SPB Git

spb/fabri-ka Public

Agrégateur de produits québécois — www.fabri-ka.com

HTML 57.9% Python 18.6% TypeScript 15.6% CSS 7.8%
2.9 KB · 70 lines python
Raw Blame History
1#!/usr/bin/env python32"""Enrichissement des produits.341. Re-catégorisation avec le classifieur courant (mots-clés enrichis).52. Héritage de catégorie : un produit encore « autre » hérite de la catégorie6   dominante de sa boutique (si ≥ 60 % des produits catégorisés de la boutique7   partagent une catégorie, ou si le registre assigne une catégorie source).83. Nettoyage : entités HTML résiduelles, espaces.9"""10import json11import os12import sys13from collections import Counter1415ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))16sys.path.insert(0, ROOT)17from fabrika import db as fdb  # noqa: E40218from fabrika.schema import infer_category  # noqa: E402192021def main():22    con = fdb.connect()2324    # catégorie source du registre (ex. bijoux pour le balayage bijouteries)25    reg = json.load(open(os.path.join(ROOT, "data", "stores.json")))["stores"]26    reg_cat = {s["id"]: (s.get("categories") or [None])[0] for s in reg}2728    # 1) re-catégorisation par classifieur29    n_reclass = 030    for r in con.execute("SELECT uid, title, description, product_type, tags, category "31                         "FROM products").fetchall():32        cat = infer_category(r["product_type"] or "", " ".join(json.loads(r["tags"] or "[]")),33                             r["title"] or "", (r["description"] or "")[:200])34        if cat != "autre" and cat != r["category"]:35            con.execute("UPDATE products SET category=? WHERE uid=?", (cat, r["uid"]))36            n_reclass += 137    con.commit()38    print(f"re-catégorisés par classifieur: {n_reclass}")3940    # 2) héritage boutique pour les « autre »41    dominant = {}42    for sid, in con.execute("SELECT DISTINCT store_id FROM products WHERE active=1"):43        counts = Counter(dict(con.execute(44            "SELECT category, COUNT(*) FROM products WHERE store_id=? AND active=1 "45            "AND category<>'autre' GROUP BY category", (sid,)).fetchall()))46        total_cat = sum(counts.values())47        total_all = con.execute("SELECT COUNT(*) FROM products WHERE store_id=? AND active=1",48                                (sid,)).fetchone()[0]49        if counts and total_cat >= max(3, total_all * 0.25):50            top, n = counts.most_common(1)[0]51            if n / total_cat >= 0.6:52                dominant[sid] = top53        if sid not in dominant and reg_cat.get(sid):54            dominant[sid] = reg_cat[sid]55    n_inherit = 056    for sid, cat in dominant.items():57        cur = con.execute("UPDATE products SET category=? WHERE store_id=? AND active=1 "58                          "AND category='autre'", (cat, sid))59        n_inherit += cur.rowcount60    con.commit()61    print(f"hérités de la boutique: {n_inherit} (boutiques avec dominante: {len(dominant)})")6263    print(dict(con.execute("SELECT category, COUNT(*) FROM products WHERE active=1 "64                           "GROUP BY category ORDER BY 2 DESC").fetchall()))65    con.close()666768if __name__ == "__main__":69    main()70