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/enrich_collections.py11# Description : Phase 2 — taxonomie métier réelle des boutiques Shopify12# via /collections.json.13# Module : scripts14# Repository : https://git.spboucher.ai/fabri-ka15# Created : 2026-08-1916# Last Modified : 2026-08-1917#18# =============================================================================19# AUTHOR & PROFESSIONAL AFFILIATION20# =============================================================================21#22# Author : Simon-Pierre Boucher23# Position : Professor of Finance24# Institution : Université du Québec en Outaouais (UQO)25# Department : Département des sciences administratives26# Organization : SP Boucher27#28# Website : https://spboucher.ai29# Git : https://git.spboucher.ai30#31# =============================================================================32# OFFICIAL CONTACT DIRECTORY33# =============================================================================34#35# General : info@spboucher.ai36# Professional : contact@spboucher.ai37# Direct : simon@spboucher.ai38# Research : research@spboucher.ai39# Development : dev@spboucher.ai40# Support : support@spboucher.ai41# Security/Admin : admin@spboucher.ai42# Notifications : notifications@spboucher.ai43#44# Preferred Contact: contact@spboucher.ai45#46# =============================================================================47# COPYRIGHT & INTELLECTUAL PROPERTY48# =============================================================================49#50# Copyright (c) 202651# Simon-Pierre Boucher52#53# All rights reserved where applicable.54#55# This file is governed by the applicable project license,56# copyright notices, institutional agreements and relevant law.57#58# Unless expressly authorized by the applicable license or59# rights holder, copying, redistribution, sublicensing,60# publication and commercial exploitation are not permitted.61#62# Existing third-party rights and notices remain unaffected.63#64# =============================================================================65# CONFIDENTIALITY & SECURITY66# =============================================================================67#68# Classification : Public69# Distribution : Public repository; use is governed by the project license70# Security Contact : admin@spboucher.ai71#72# Access to this source does not independently grant permission73# to redistribute or disclose confidential materials.74#75# Do not embed credentials, private keys, access tokens,76# certificates or confidential personal information.77#78# =============================================================================79# LICENSE & MAINTENANCE80# =============================================================================81#82# License : None specified (no license file in this repository)83# Maintainer : Simon-Pierre Boucher84# Technical Contact: dev@spboucher.ai85#86# =============================================================================87# END OF SP BOUCHER SOURCE HEADER88# =============================================================================8990"""Phase 2 — taxonomie métier réelle des boutiques Shopify via /collections.json.91921 requête par boutique Shopify productive (curl, throttle global 0,7 s) :93la liste des collections (titres + handles + published) est la taxonomie94métier déclarée par le marchand. On la mappe vers la taxonomie Fabri-Ka95(infer_category sur les titres de collections) pour :9697 - assigner des catégories boutique (registre + DB) quand il n'y en a pas ;98 - alimenter l'héritage de catégorie d'enrich_products.py (produits « autre ») ;99 - consigner la table de correspondance collection -> catégorie100 (data/collections_taxonomy.json, rejouable et auditable).101102WooCommerce : PAS de requête réseau — la Store API renvoie déjà les103catégories par produit (champ product_type), l'endpoint104/wc/store/v1/products/categories serait redondant (décision consignée).105106Cache : data/enrich_cache/collections/<dom>.json.107Usage : .venv/bin/python scripts/enrich_collections.py [--cap 700]108"""109import argparse110import concurrent.futures as cf111import json112import os113import subprocess114import sys115import threading116import time117from collections import Counter118119ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))120sys.path.insert(0, ROOT)121CACHE = os.path.join(ROOT, "data", "enrich_cache", "collections")122os.makedirs(CACHE, exist_ok=True)123124from fabrika import db as fdb # noqa: E402125from fabrika.schema import infer_category # noqa: E402126127UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "128 "(KHTML, like Gecko) Chrome/126 Safari/537.36")129130_LOCK = threading.Lock()131_last = [0.0]132133# titres de collections sans signal métier134NOISE = {"accueil", "home", "all", "tous", "tout", "frontpage", "nouveautés",135 "nouveautes", "new", "soldes", "sale", "promotions", "promo",136 "cadeaux", "gifts", "idées cadeaux", "best sellers", "meilleurs vendeurs"}137138139def fetch_collections(dom: str, base: str) -> dict:140 cpath = os.path.join(CACHE, dom + ".json")141 if os.path.exists(cpath):142 return json.load(open(cpath))143 with _LOCK:144 wait = 0.7 - (time.time() - _last[0])145 if wait > 0:146 time.sleep(wait)147 _last[0] = time.time()148 rec = {"domain": dom, "collections": [], "checked_at": time.strftime("%Y-%m-%d")}149 for attempt in range(4): # retry 429 avec backoff long150 p = subprocess.run(["curl", "-sS", "--compressed", "-L", "--max-time", "25",151 "-A", UA, "-w", "\n%{http_code}",152 f"{base}/collections.json?limit=250"],153 capture_output=True, text=True, errors="replace")154 body, _, code = p.stdout.rpartition("\n")155 if code == "200":156 try:157 cols = json.loads(body).get("collections", [])158 rec["collections"] = [{"handle": c.get("handle", ""),159 "title": c.get("title", ""),160 "products_count": c.get("products_count")}161 for c in cols]162 rec.pop("error", None)163 except Exception as exc:164 rec["error"] = str(exc)[:120]165 break166 rec["error"] = f"HTTP {code}"167 if code != "429":168 break169 time.sleep(10 * (attempt + 1))170 json.dump(rec, open(cpath, "w"), ensure_ascii=False)171 return rec172173174def main():175 ap = argparse.ArgumentParser()176 ap.add_argument("--cap", type=int, default=700)177 ap.add_argument("--retry-errors", action="store_true",178 help="purge du cache les fiches en erreur (ex. 429) avant la passe")179 args = ap.parse_args()180181 if args.retry_errors:182 import glob183 n = 0184 for f in glob.glob(os.path.join(CACHE, "*.json")):185 try:186 if json.load(open(f)).get("error"):187 os.remove(f); n += 1188 except Exception:189 pass190 print(f"[collections] {n} caches en erreur purgés")191192 con = fdb.connect()193 rows = [dict(r) for r in con.execute(194 "SELECT id, url FROM stores WHERE platform='shopify' AND product_count>0 "195 "ORDER BY product_count DESC LIMIT ?", (args.cap,))]196 con.close()197 print(f"[collections] {len(rows)} boutiques Shopify ciblées", flush=True)198199 results, done = [], 0200 with cf.ThreadPoolExecutor(4) as ex:201 for rec in ex.map(lambda s: fetch_collections(s["id"], (s["url"] or "").rstrip("/")), rows):202 results.append(rec)203 done += 1204 if done % 100 == 0:205 print(f" {done}/{len(rows)}", flush=True)206207 # table de correspondance collection -> catégorie Fabri-Ka (consignée)208 mapping = {}209 store_cats = {}210 n_cols = 0211 for rec in results:212 cats = Counter()213 for c in rec.get("collections", []):214 title = (c.get("title") or "").strip()215 if not title or title.lower() in NOISE:216 continue217 n_cols += 1218 cat = infer_category(title)219 mapping[title] = cat220 if cat != "autre":221 cats[cat] += max(1, int(c.get("products_count") or 1))222 if cats:223 store_cats[rec["domain"]] = [k for k, _ in cats.most_common(3)]224225 json.dump({"generated": time.strftime("%Y-%m-%d"),226 "note": "titres de collections Shopify -> taxonomie Fabri-Ka (infer_category)",227 "mapping": dict(sorted(mapping.items()))},228 open(os.path.join(ROOT, "data", "collections_taxonomy.json"), "w"),229 ensure_ascii=False, indent=1)230 print(f"[collections] {n_cols} collections vues, {len(mapping)} mappées, "231 f"{len(store_cats)} boutiques avec catégories déduites")232233 # registre + DB : catégories boutique si absentes234 reg_path = os.path.join(ROOT, "data", "stores.json")235 reg = json.load(open(reg_path))236 n_reg = 0237 con = fdb.connect()238 for s in reg["stores"]:239 cats = store_cats.get(s["id"])240 if cats and not s.get("categories"):241 s["categories"] = cats242 con.execute("UPDATE stores SET categories=? WHERE id=?",243 (json.dumps(cats, ensure_ascii=False), s["id"]))244 n_reg += 1245 con.commit(); con.close()246 json.dump(reg, open(reg_path, "w"), ensure_ascii=False, indent=1)247 print(f"[collections] catégories boutique assignées (registre+DB) : {n_reg}")248249250if __name__ == "__main__":251 main()252