#!/usr/bin/env python3 """Enrichissement des produits. 1. Re-catégorisation avec le classifieur courant (mots-clés enrichis). 2. Héritage de catégorie : un produit encore « autre » hérite de la catégorie dominante de sa boutique (si ≥ 60 % des produits catégorisés de la boutique partagent une catégorie, ou si le registre assigne une catégorie source). 3. Nettoyage : entités HTML résiduelles, espaces. """ import json import os import sys from collections import Counter ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT) from fabrika import db as fdb # noqa: E402 from fabrika.schema import infer_category # noqa: E402 def main(): con = fdb.connect() # catégorie source du registre (ex. bijoux pour le balayage bijouteries) reg = json.load(open(os.path.join(ROOT, "data", "stores.json")))["stores"] reg_cat = {s["id"]: (s.get("categories") or [None])[0] for s in reg} # 1) re-catégorisation par classifieur n_reclass = 0 for r in con.execute("SELECT uid, title, description, product_type, tags, category " "FROM products").fetchall(): cat = infer_category(r["product_type"] or "", " ".join(json.loads(r["tags"] or "[]")), r["title"] or "", (r["description"] or "")[:200]) if cat != "autre" and cat != r["category"]: con.execute("UPDATE products SET category=? WHERE uid=?", (cat, r["uid"])) n_reclass += 1 con.commit() print(f"re-catégorisés par classifieur: {n_reclass}") # 2) héritage boutique pour les « autre » dominant = {} for sid, in con.execute("SELECT DISTINCT store_id FROM products WHERE active=1"): counts = Counter(dict(con.execute( "SELECT category, COUNT(*) FROM products WHERE store_id=? AND active=1 " "AND category<>'autre' GROUP BY category", (sid,)).fetchall())) total_cat = sum(counts.values()) total_all = con.execute("SELECT COUNT(*) FROM products WHERE store_id=? AND active=1", (sid,)).fetchone()[0] if counts and total_cat >= max(3, total_all * 0.25): top, n = counts.most_common(1)[0] if n / total_cat >= 0.6: dominant[sid] = top if sid not in dominant and reg_cat.get(sid): dominant[sid] = reg_cat[sid] n_inherit = 0 for sid, cat in dominant.items(): cur = con.execute("UPDATE products SET category=? WHERE store_id=? AND active=1 " "AND category='autre'", (cat, sid)) n_inherit += cur.rowcount con.commit() print(f"hérités de la boutique: {n_inherit} (boutiques avec dominante: {len(dominant)})") print(dict(con.execute("SELECT category, COUNT(*) FROM products WHERE active=1 " "GROUP BY category ORDER BY 2 DESC").fetchall())) con.close() if __name__ == "__main__": main()