Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : Fabri·Ka10# File : scripts/backfill_quality.py11# Description : Phase 2 — backfill qualité (2026-08-19).12# Module : scripts13# Repository : https://git.spboucher.ai/fabri-ka14# Created : 2026-08-1915# Last Modified : 2026-08-1916#17# =============================================================================18# AUTHOR & PROFESSIONAL AFFILIATION19# =============================================================================20#21# Author : Simon-Pierre Boucher22# Position : Professor of Finance23# Institution : Université du Québec en Outaouais (UQO)24# Department : Département des sciences administratives25# Organization : SP Boucher26#27# Website : https://spboucher.ai28# Git : https://git.spboucher.ai29#30# =============================================================================31# OFFICIAL CONTACT DIRECTORY32# =============================================================================33#34# General : info@spboucher.ai35# Professional : contact@spboucher.ai36# Direct : simon@spboucher.ai37# Research : research@spboucher.ai38# Development : dev@spboucher.ai39# Support : support@spboucher.ai40# Security/Admin : admin@spboucher.ai41# Notifications : notifications@spboucher.ai42#43# Preferred Contact: contact@spboucher.ai44#45# =============================================================================46# COPYRIGHT & INTELLECTUAL PROPERTY47# =============================================================================48#49# Copyright (c) 202650# Simon-Pierre Boucher51#52# All rights reserved where applicable.53#54# This file is governed by the applicable project license,55# copyright notices, institutional agreements and relevant law.56#57# Unless expressly authorized by the applicable license or58# rights holder, copying, redistribution, sublicensing,59# publication and commercial exploitation are not permitted.60#61# Existing third-party rights and notices remain unaffected.62#63# =============================================================================64# CONFIDENTIALITY & SECURITY65# =============================================================================66#67# Classification : Public68# Distribution : Public repository; use is governed by the project license69# Security Contact : admin@spboucher.ai70#71# Access to this source does not independently grant permission72# to redistribute or disclose confidential materials.73#74# Do not embed credentials, private keys, access tokens,75# certificates or confidential personal information.76#77# =============================================================================78# LICENSE & MAINTENANCE79# =============================================================================80#81# License : None specified (no license file in this repository)82# Maintainer : Simon-Pierre Boucher83# Technical Contact: dev@spboucher.ai84#85# =============================================================================86# END OF SP BOUCHER SOURCE HEADER87# =============================================================================8889"""Phase 2 — backfill qualité (2026-08-19).9091Applique aux données DÉJÀ en base les règles désormais appliquées à92l'ingestion (schema.py) :93941. Produits :95 - prix placeholders (999 999 $…) -> price=NULL + price_on_request=1 ;96 - produits sans prix -> price_on_request=1 ;97 - prix > 100 000 $ -> quarantine:prix_hors_bornes ;98 - titre vide -> quarantine:titre_vide ;99 - cartes-cadeaux / ateliers-cours / abonnements / billets / produits test100 -> excluded:<raison> (marqués, jamais supprimés, réintégrables).1012. Boutiques :102 - renommage des noms génériques d'annuaire (« Créateurs », « Complices »…)103 et des groupes dupliqués via og:site_name du cache d'enrichissement104 (data/enrich_cache/<dom>.json) — registre + DB + réindexation FTS ;105 - store_kind (fabricant / revendeur / collectif / hors_mission) :106 * revendeur : origin_evidence du registre contenant « revend » +107 liste curée (marques tierces dominantes constatées en base) ;108 * collectif : boutiques multi-créateurs connues ;109 * hors_mission : transport/billetterie (produits exclus en masse).110 - postal_prefix recopié du registre vers la DB (upsert le maintient ensuite).111112Idempotent ; usage : .venv/bin/python scripts/backfill_quality.py [--dry-run]113"""114import argparse115import json116import os117import re118import sys119120ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))121sys.path.insert(0, ROOT)122123from fabrika import db as fdb # noqa: E402124from fabrika.schema import classify_listing, is_placeholder_price, PRICE_SANE_MAX # noqa: E402125126REG_PATH = os.path.join(ROOT, "data", "stores.json")127ENRICH_CACHE = os.path.join(ROOT, "data", "enrich_cache")128129# Noms de boutiques génériques hérités des rubriques d'annuaires130BAD_SITE_NAMES = {"your site title", "site title", "home", "home page",131 "accueil", "untitled", "my site", "mon site"}132133GENERIC_NAMES = {"créateurs", "createurs", "producteurs/transformateurs",134 "producteurs", "transformateurs", "complices", "accueil",135 "home", "boutique", "produits", "shop", "menu", "à propos"}136137# revendeurs constatés (marques tierces dominantes dans le catalogue :138# Tissot, BIBS, Rieker, Natural Factors, Pacsafe… — voir 05-ENRICHISSEMENT-RAPPORT)139CURATED_REVENDEUR = {140 "lamaisondubleuet.com", "mondeavie.ca", "lesptitsmosus.com",141 "grenierboutique.ca", "yellowshoes.com", "bijouteriejodoin.com",142 "eugeneallard.com", "remorquetrailer.com", "doggoboutique.ca",143 "boiteavins.com",144}145# boutiques multi-créateurs (vendor = fabricant réel)146CURATED_COLLECTIF = {"paperole.com", "signelocal.com", "wachiya.com",147 "galerieiris.com"}148# hors mission fabricant (transport, activités, billetterie)149CURATED_HORS_MISSION = {"traversiers.com", "rtcbq.com", "raftingmomentum.com"}150151152def main():153 ap = argparse.ArgumentParser()154 ap.add_argument("--dry-run", action="store_true")155 args = ap.parse_args()156157 con = fdb.connect()158159 # ------------------------------------------------------------------ produits160 stats = {"placeholder": 0, "on_request": 0, "quarantine_prix": 0,161 "quarantine_titre": 0}162 excl = {}163 updates = []164 for r in con.execute("SELECT uid, title, product_type, price, price_max, "165 "details, listing_status, price_on_request FROM products"):166 uid, title, ptype, price = r["uid"], r["title"] or "", r["product_type"] or "", r["price"]167 new_price, new_pmax = price, r["price_max"]168 details = r["details"]169 on_req = 0170 if new_price is not None and new_price <= 0: # 0 $ n'est pas un prix171 new_price = None172 if new_pmax is not None and new_pmax <= 0:173 new_pmax = None174 if is_placeholder_price(new_price) or is_placeholder_price(new_pmax):175 try:176 d = json.loads(details) if details else {}177 except Exception:178 d = {}179 d["price_placeholder"] = new_price or new_pmax180 details = json.dumps(d, ensure_ascii=False)181 new_price = new_pmax = None182 stats["placeholder"] += 1183 if new_price is None:184 on_req = 1185 status = classify_listing(title, ptype)186 if status == "published":187 if not title.strip():188 status = "quarantine:titre_vide"189 stats["quarantine_titre"] += 1190 elif new_price is not None and new_price > PRICE_SANE_MAX:191 status = "quarantine:prix_hors_bornes"192 stats["quarantine_prix"] += 1193 else:194 excl[status] = excl.get(status, 0) + 1195 if on_req:196 stats["on_request"] += 1197 if (status != (r["listing_status"] or "published")198 or on_req != (r["price_on_request"] or 0)199 or new_price != price):200 updates.append((new_price, new_pmax, details, status, on_req, uid))201202 print(f"[produits] placeholders neutralisés : {stats['placeholder']} | "203 f"sur devis (price_on_request) : {stats['on_request']} | "204 f"quarantaine prix : {stats['quarantine_prix']} | "205 f"quarantaine titre : {stats['quarantine_titre']}")206 print(f"[produits] exclusions : {json.dumps(excl, ensure_ascii=False)}")207 print(f"[produits] lignes à modifier : {len(updates)}")208 if not args.dry_run:209 con.executemany("UPDATE products SET price=?, price_max=?, details=?, "210 "listing_status=?, price_on_request=? WHERE uid=?", updates)211 con.commit()212213 # ------------------------------------------------- boutiques : renommage214 reg = json.load(open(REG_PATH))215 by_id = {s["id"]: s for s in reg["stores"]}216 from collections import Counter217 name_counts = Counter((s.get("name") or "").strip().lower() for s in reg["stores"])218 renamed = []219 for s in reg["stores"]:220 cur = (s.get("name") or "").strip()221 low = cur.lower()222 generic = low in GENERIC_NAMES or (name_counts[low] >= 3 and len(low) < 40)223 if not generic:224 continue225 cpath = os.path.join(ENRICH_CACHE, s["id"] + ".json")226 if not os.path.exists(cpath):227 continue228 try:229 site_name = (json.load(open(cpath)).get("site_name") or "").strip()230 except Exception:231 continue232 import html as _html233 site_name = re.sub(r"\s+", " ", _html.unescape(site_name)).strip()[:80]234 if site_name.lower() in BAD_SITE_NAMES:235 continue236 if (site_name and site_name.lower() not in GENERIC_NAMES237 and site_name.lower() != low and len(site_name) >= 3):238 renamed.append((s["id"], cur, site_name))239 s["name"] = site_name240 print(f"[boutiques] renommées via og:site_name : {len(renamed)}")241 for sid, old, new in renamed[:15]:242 print(f" {sid}: «{old}» -> «{new}»")243244 # ------------------------------------------------- boutiques : store_kind245 kinds = {}246 for s in reg["stores"]:247 sid = s["id"]248 ev = (s.get("origin_evidence") or "").lower()249 kind = ""250 if sid in CURATED_HORS_MISSION:251 kind = "hors_mission"252 elif sid in CURATED_COLLECTIF:253 kind = "collectif"254 elif sid in CURATED_REVENDEUR or "revend" in ev:255 kind = "revendeur"256 if kind:257 s["store_kind"] = kind258 kinds[kind] = kinds.get(kind, 0) + 1259 print(f"[boutiques] store_kind : {json.dumps(kinds, ensure_ascii=False)}")260261 if args.dry_run:262 print("[dry-run] aucun écrit")263 return264265 json.dump(reg, open(REG_PATH, "w"), ensure_ascii=False, indent=1)266267 # DB : noms, store_kind, postal_prefix, phone268 for sid, _, new in renamed:269 con.execute("UPDATE stores SET name=? WHERE id=?", (new, sid))270 for s in reg["stores"]:271 con.execute("UPDATE stores SET store_kind=COALESCE(NULLIF(?,''), store_kind), "272 "postal_prefix=COALESCE(NULLIF(?,''), postal_prefix), "273 "phone=COALESCE(NULLIF(?,''), phone) WHERE id=?",274 (s.get("store_kind") or "", s.get("postal_prefix") or "",275 s.get("phone") or "", s["id"]))276277 # produits des boutiques hors mission -> exclus en masse278 for sid in CURATED_HORS_MISSION:279 cur = con.execute("UPDATE products SET listing_status='excluded:hors_mission' "280 "WHERE store_id=? AND listing_status='published'", (sid,))281 if cur.rowcount:282 print(f"[hors-mission] {sid}: {cur.rowcount} produits exclus")283284 # réindexation FTS (store_name) des boutiques renommées avec produits285 n_fts = 0286 for sid, _, new in renamed:287 rows = con.execute("SELECT uid, title, description, tags, vendor FROM products "288 "WHERE store_id=? AND active=1", (sid,)).fetchall()289 if not rows:290 continue291 uids = [r["uid"] for r in rows]292 for i in range(0, len(uids), 500):293 chunk = uids[i:i + 500]294 con.execute("DELETE FROM products_fts WHERE uid IN (%s)"295 % ",".join("?" * len(chunk)), chunk)296 con.executemany(297 "INSERT INTO products_fts (uid, title, description, tags, vendor, store_name) "298 "VALUES (?,?,?,?,?,?)",299 [(r["uid"], r["title"], r["description"],300 " ".join(json.loads(r["tags"] or "[]")), r["vendor"], new) for r in rows])301 n_fts += len(rows)302 print(f"[fts] {n_fts} produits réindexés (nouveau nom de boutique)")303304 # product_count recalculé (publiés seulement)305 con.execute("UPDATE stores SET product_count=(SELECT COUNT(*) FROM products "306 "WHERE store_id=stores.id AND active=1 AND listing_status='published')")307 con.commit()308 con.close()309 print("[backfill] terminé")310311312if __name__ == "__main__":313 main()314