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/recategorize.py11# Description : Vague 2 — recatégorisation des produits existants avec les12# signaux `details`.13# Module : scripts14# Repository : https://git.spboucher.ai/fabri-ka15# Created : 2026-08-1816# Last Modified : 2026-08-1817#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"""Vague 2 — recatégorisation des produits existants avec les signaux `details`.9192Le classifieur (schema.infer_category) tient maintenant compte des options93Shopify et des attributs WooCommerce (matériaux, formats…) stockés dans la94colonne `details` depuis la vague 1. La sync n'actualise la catégorie que95lorsque le hash de contenu change ; ce script applique la nouvelle logique96rétroactivement à tous les produits actifs.9798Usage : python3 scripts/recategorize.py [--dry-run]99"""100import argparse101import json102import os103import sys104105ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))106sys.path.insert(0, ROOT)107108from fabrika import db as fdb # noqa: E402109from fabrika.schema import infer_category, details_signal_text # noqa: E402110111112def main():113 ap = argparse.ArgumentParser()114 ap.add_argument("--dry-run", action="store_true")115 args = ap.parse_args()116117 con = fdb.connect()118 cur = con.execute("SELECT uid, category, product_type, tags, title, "119 "substr(description,1,200) AS descr, details "120 "FROM products WHERE active=1")121 updates, scanned = [], 0122 while True:123 rows = cur.fetchmany(5000)124 if not rows:125 break126 for r in rows:127 scanned += 1128 tags = ""129 try:130 tags = " ".join(json.loads(r["tags"] or "[]"))131 except Exception:132 pass133 details = {}134 try:135 details = json.loads(r["details"]) if r["details"] else {}136 except Exception:137 pass138 new = infer_category(r["product_type"] or "", tags, r["title"] or "",139 r["descr"] or "", details_signal_text(details))140 # jamais de rétrogradation vers « autre » : beaucoup de141 # catégories sont héritées de la boutique (enrich_products.py)142 if new != "autre" and new != (r["category"] or ""):143 updates.append((new, r["uid"]))144 print(f"[recat] {scanned} produits actifs analysés, {len(updates)} changements")145 if args.dry_run or not updates:146 from collections import Counter147 c = Counter(u[0] for u in updates)148 print("[recat] top nouvelles catégories:", dict(c.most_common(10)))149 con.close()150 return151 con.close()152 import sqlite3, time153 done = 0154 for i in range(0, len(updates), 2000):155 batch = updates[i:i + 2000]156 for attempt in range(20): # la sync massive peut tenir le verrou > 60 s157 try:158 wcon = fdb.connect()159 wcon.executemany("UPDATE products SET category=? WHERE uid=?", batch)160 wcon.commit(); wcon.close()161 done += len(batch)162 break163 except sqlite3.OperationalError as exc:164 print(f" [recat] verrou ({exc}), attente… ({attempt+1})", flush=True)165 time.sleep(15)166 else:167 raise SystemExit("[recat] verrou persistant, abandon")168 print(f"[recat] {done} catégories mises à jour")169170171if __name__ == "__main__":172 main()173