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_products.py11# Description : Enrichissement des produits.12# Module : scripts13# Repository : https://git.spboucher.ai/fabri-ka14# Created : 2026-08-1215# Last Modified : 2026-08-1816#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"""Enrichissement des produits.90911. Re-catégorisation avec le classifieur courant (mots-clés enrichis).922. Héritage de catégorie : un produit encore « autre » hérite de la catégorie93 dominante de sa boutique (si ≥ 60 % des produits catégorisés de la boutique94 partagent une catégorie, ou si le registre assigne une catégorie source).953. Nettoyage : entités HTML résiduelles, espaces.96"""97import json98import os99import sys100from collections import Counter101102ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))103sys.path.insert(0, ROOT)104from fabrika import db as fdb # noqa: E402105from fabrika.schema import infer_category, details_signal_text # noqa: E402106107108def main():109 con = fdb.connect()110111 # catégorie source du registre (ex. bijoux pour le balayage bijouteries)112 reg = json.load(open(os.path.join(ROOT, "data", "stores.json")))["stores"]113 reg_cat = {s["id"]: (s.get("categories") or [None])[0] for s in reg}114115 # 1) re-catégorisation par classifieur116 n_reclass = 0117 for r in con.execute("SELECT uid, title, description, product_type, tags, category, details "118 "FROM products").fetchall():119 try:120 det = json.loads(r["details"]) if r["details"] else {}121 except Exception:122 det = {}123 cat = infer_category(r["product_type"] or "", " ".join(json.loads(r["tags"] or "[]")),124 r["title"] or "", (r["description"] or "")[:200],125 details_signal_text(det))126 if cat != "autre" and cat != r["category"]:127 con.execute("UPDATE products SET category=? WHERE uid=?", (cat, r["uid"]))128 n_reclass += 1129 con.commit()130 print(f"re-catégorisés par classifieur: {n_reclass}")131132 # 2) héritage boutique pour les « autre »133 dominant = {}134 for sid, in con.execute("SELECT DISTINCT store_id FROM products WHERE active=1"):135 counts = Counter(dict(con.execute(136 "SELECT category, COUNT(*) FROM products WHERE store_id=? AND active=1 "137 "AND category<>'autre' GROUP BY category", (sid,)).fetchall()))138 total_cat = sum(counts.values())139 total_all = con.execute("SELECT COUNT(*) FROM products WHERE store_id=? AND active=1",140 (sid,)).fetchone()[0]141 if counts and total_cat >= max(3, total_all * 0.25):142 top, n = counts.most_common(1)[0]143 if n / total_cat >= 0.6:144 dominant[sid] = top145 if sid not in dominant and reg_cat.get(sid):146 dominant[sid] = reg_cat[sid]147 n_inherit = 0148 for sid, cat in dominant.items():149 cur = con.execute("UPDATE products SET category=? WHERE store_id=? AND active=1 "150 "AND category='autre'", (cat, sid))151 n_inherit += cur.rowcount152 con.commit()153 print(f"hérités de la boutique: {n_inherit} (boutiques avec dominante: {len(dominant)})")154155 print(dict(con.execute("SELECT category, COUNT(*) FROM products WHERE active=1 "156 "GROUP BY category ORDER BY 2 DESC").fetchall()))157 con.close()158159160if __name__ == "__main__":161 main()162