Repository Public
1#!/usr/bin/env python32# =============================================================================3# SP BOUCHER | SOFTWARE & RESEARCH4# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING5# =============================================================================6#7# PROJECT METADATA8# -----------------------------------------------------------------------------9# Project : Food·Ka10# File : scripts/gen_connector_docs.py11# Module : scripts12# Repository : https://git.spboucher.ai/food-ka13# Created : 2026-08-1814# Last Modified : 2026-08-1815#16# =============================================================================17# AUTHOR & PROFESSIONAL AFFILIATION18# =============================================================================19#20# Author : Simon-Pierre Boucher21# Position : Professor of Finance22# Institution : Université du Québec en Outaouais (UQO)23# Department : Département des sciences administratives24# Organization : SP Boucher25#26# Website : https://spboucher.ai27# Git : https://git.spboucher.ai28#29# =============================================================================30# OFFICIAL CONTACT DIRECTORY31# =============================================================================32#33# General : info@spboucher.ai34# Professional : contact@spboucher.ai35# Direct : simon@spboucher.ai36# Research : research@spboucher.ai37# Development : dev@spboucher.ai38# Support : support@spboucher.ai39# Security/Admin : admin@spboucher.ai40# Notifications : notifications@spboucher.ai41#42# Preferred Contact: contact@spboucher.ai43#44# =============================================================================45# COPYRIGHT & INTELLECTUAL PROPERTY46# =============================================================================47#48# Copyright (c) 202649# Simon-Pierre Boucher50#51# All rights reserved where applicable.52#53# This file is governed by the applicable project license,54# copyright notices, institutional agreements and relevant law.55#56# Unless expressly authorized by the applicable license or57# rights holder, copying, redistribution, sublicensing,58# publication and commercial exploitation are not permitted.59#60# Existing third-party rights and notices remain unaffected.61#62# =============================================================================63# CONFIDENTIALITY & SECURITY64# =============================================================================65#66# Classification : Public67# Distribution : Public repository; use is governed by the project license68# Security Contact : admin@spboucher.ai69#70# Access to this source does not independently grant permission71# to redistribute or disclose confidential materials.72#73# Do not embed credentials, private keys, access tokens,74# certificates or confidential personal information.75#76# =============================================================================77# LICENSE & MAINTENANCE78# =============================================================================79#80# License : None specified (no license file in this repository)81# Maintainer : Simon-Pierre Boucher82# Technical Contact: dev@spboucher.ai83#84# =============================================================================85# END OF SP BOUCHER SOURCE HEADER86# =============================================================================8788# -----------------------------------------------------------------------------89# Food-Ka — Agrégateur de produits d'épicerie (province de Québec)90# Auteur : Simon-Pierre Boucher — contact@spboucher.ai91# scripts/gen_connector_docs.py : documentation standardisée des connecteurs92#93# Génère docs/connecteurs/ (INDEX.md + une fiche par FAMILLE de connecteurs +94# fiches transverses) en croisant :95# 1. data/sources.json — registre des sources (61 bannières) ;96# 2. le code des connecteurs — familles par héritage de classe97# (FlippConnector, ShopifyConnector, WooCommerceConnector…), en-têtes98# « mécanique » des modules, merchant_id/flyer_name_filter des99# circulaires, backends, plafonds env (FOODKA_*) ;100# 3. la BD live data/foodka.db — volumétrie, complétude par champ,101# dernier sync et erreurs (sync_log), matching inter-bannières102# (product_links), nutrition OFF (off_cache), historique de prix.103#104# Rejouable à volonté (BD ouverte en lecture seule, docs régénérés) :105# .venv/bin/python3 scripts/gen_connector_docs.py106# -----------------------------------------------------------------------------107from __future__ import annotations108109import datetime110import json111import re112import sqlite3113import sys114from collections import Counter, OrderedDict115from pathlib import Path116117ROOT = Path(__file__).resolve().parent.parent118sys.path.insert(0, str(ROOT))119120DB_PATH = ROOT / "data" / "foodka.db"121SOURCES_PATH = ROOT / "data" / "sources.json"122CONNECTORS_DIR = ROOT / "foodka" / "connectors"123OUT_DIR = ROOT / "docs" / "connecteurs"124125# Champs de complétude (produits actifs) : libellé -> expression SQL "rempli"126FIELDS = OrderedDict([127 ("Prix", "price IS NOT NULL"),128 ("Prix régulier", "regular_price IS NOT NULL"),129 ("Format (size_label)", "size_label IS NOT NULL AND size_label != ''"),130 ("Prix unitaire", "unit_price IS NOT NULL"),131 ("Marque", "brand IS NOT NULL AND brand != ''"),132 ("Images", "images IS NOT NULL AND images NOT IN ('', '[]')"),133 ("Nutrition OFF (details.off)", "details LIKE '%\"off\"%'"),134])135136# --- Définition des familles : (slug, titre, module socle éventuel, gotchas) --137FAMILIES = OrderedDict([138 ("flipp-proximite", {139 "title": "Circulaires Flipp — épiceries de proximité (catalogue = circulaire)",140 "base": "_flipp.py",141 "gotchas": [142 "Le paramètre d'URL de l'API backflipp ne filtre PAS par marchand : "143 "filtrer côté client sur `merchant_id`.",144 "`flyer_name_filter` écarte les cahiers parasites du même merchant "145 "(ex. Supermarché PA : « Weekly Flyer » vs « Nature Flyer »).",146 "Tri des circulaires candidates par `valid_from` croissant : en cas "147 "de chevauchement (semaine courante + semaine à venir), on prend la "148 "courante.",149 "Les items Flipp n'ont ni SKU, ni catégorie, ni unité : "150 "`external_id` = slug stable marque+nom+format (continuité du "151 "price_log d'une semaine à l'autre), catégorie déduite du nom.",152 "Le `flyer_id` change chaque semaine — toujours résolu dynamiquement "153 "via /flipp/flyers (une circulaire provinciale par bannière : un "154 "poste montréalais suffit).",155 ]}),156 ("flyers-grandes-bannieres", {157 "title": "Circulaires Flipp — grandes bannières (complément rabais du catalogue)",158 "base": "_flipp.py",159 "gotchas": [160 "Chaque source `*_flyer` complète la source catalogue de la même "161 "bannière (metro / metro_flyer) : le matching inter-bannières les "162 "traite comme UNE bannière.",163 "`flyer_name_filter` est indispensable ici : les grands merchants "164 "publient plusieurs cahiers (Metro « Metrogo! », Costco cahiers non "165 "alimentaires, Walmart livrets thématiques…).",166 "Tri `valid_from` croissant pour choisir la circulaire de la semaine "167 "courante ; flyer_id résolu à chaque sync.",168 ]}),169 ("scrapfly-asp", {170 "title": "Catalogues derrière anti-bot — Scrapfly (ASP)",171 "base": None,172 "gotchas": [173 "Chaque requête passe par Scrapfly en mode ASP (anti-scraping "174 "protection) : coût par appel — les plafonds de pagination par "175 "allée/catégorie bornent le budget de chaque sync.",176 "Metro et Super C partagent le socle `_metro.py` (tuiles rendues "177 "serveur, pagination « <allée>-page-N ») ; Maxi, Provigo et Club "178 "Entrepôt partagent `_loblaw.py` (grille complète dans "179 "`__NEXT_DATA__`).",180 ]}),181 ("render-js", {182 "title": "Catalogues SPA — Scrapfly avec rendu JavaScript",183 "base": None,184 "gotchas": [185 "Le rendu JavaScript Scrapfly est encore plus coûteux que l'ASP "186 "simple : nombre de pages par catégorie plafonné, syncs espacés.",187 ]}),188 ("shopify", {189 "title": "Boutiques Shopify — /products.json ouvert",190 "base": "_shopify.py",191 "gotchas": [192 "Catalogue public JSON sans anti-bot : "193 "/products.json?limit=250&page=N (pagination plafonnée par "194 "garde-fou).",195 "Le format vient des variantes ; prix unitaire recalculé "196 "(normalize.unit_price) quand la taille est parsable.",197 ]}),198 ("woocommerce", {199 "title": "Épiceries WooCommerce — Store API ouverte",200 "base": "_woocommerce.py",201 "gotchas": [202 "Prix en unités mineures (cents) : « 1299 » + "203 "currency_minor_unit=2 -> 12,99 $.",204 "/wp-json/wc/store/v1/products?per_page=100&page=N, pagination "205 "plafonnée par garde-fou.",206 ]}),207 ("html", {208 "title": "Catalogues HTML rendus serveur ou API directe — requests",209 "base": None,210 "gotchas": [211 "Sites sans anti-bot : parsing HTML/sitemap direct (HubSpot, "212 "Magento 2, k-eCommerce, SSR maison).",213 "SAQ : API GraphQL Adobe Live Search "214 "(catalog-service.adobe.io) appelée en direct avec la clé "215 "publique du storefront — tout est dans la réponse liste, "216 "aucune page détail ; catégorie unique « Alcool », exclue du "217 "matching (matching.EXCLUDED_SOURCES).",218 ]}),219 ("iga-api", {220 "title": "IGA — API Voilà (Sobeys Québec)",221 "base": None,222 "gotchas": [223 "Voie principale : API REST publique des promotions de voila.ca "224 "(JSON complet, curseur, sans anti-bot) ; complément optionnel par "225 "recherche SPA rendue via Scrapfly (render_js).",226 "`regionId` public requis par l'API (région de livraison Québec).",227 ]}),228 ("non-connectables", {229 "title": "Sources recensées non connectables",230 "base": None,231 "gotchas": []}),232])233234HISTORIQUE = """\235## Historique des vagues (2026-08-18)236237| Commit | Contenu |238|---|---|239| `afdb2e6` | Enrichissement connecteurs + robustesse DB (audit 2026-08-18) |240| `a45aeb4` | Vague 2 : circulaires grandes bannières + comparateur inter-bannières + nutrition Open Food Facts |241| `114aa76` | Matching : MAX_BLOCK 400 → 3000 (marques maison des circulaires ; fenêtre triée de 30 = coût linéaire) |242| `2e52f7c` | Vague 3 : SAQ (API GraphQL directe, « Alcool », hors matching) + 6 circulaires Flipp (Pharmaprix, Jean Coutu, Brunet, Uniprix — rayons alimentaires seulement ; Adonis, Avril) + Metro 4 pages sur 3 allées prioritaires |243"""244245246# --------------------------------------------------------------------------- #247# Introspection du code248# --------------------------------------------------------------------------- #249250def get_registry():251 import foodka.connectors as reg252 return reg.CONNECTORS253254255def classify(source: dict, registry) -> str:256 if source.get("status") == "non connectable":257 return "non-connectables"258 sid = source["id"]259 if sid == "iga":260 return "iga-api"261 cls = registry.get(sid)262 bases = {b.__name__ for b in cls.__mro__} if cls else set()263 if "FlippConnector" in bases:264 return "flyers-grandes-bannieres" if sid.endswith("_flyer") else "flipp-proximite"265 if "ShopifyConnector" in bases:266 return "shopify"267 if "WooStoreConnector" in bases:268 return "woocommerce"269 tech = source.get("tech", "")270 if "Flipp" in tech: # connecteur Flipp sur mesure hors socle271 return "flyers-grandes-bannieres" if sid.endswith("_flyer") else "flipp-proximite"272 if "WooCommerce" in tech: # ex. akhavan : Store API, impl. sur mesure273 return "woocommerce"274 if "rendu JavaScript" in tech:275 return "render-js"276 if "Scrapfly" in tech:277 return "scrapfly-asp"278 return "html"279280281def module_header(path: Path, marker: str | None = None) -> str:282 """Bloc de commentaires du haut du fichier, rendu en citation Markdown.283 Si `marker` est donné, on démarre à la ligne qui commence par ce texte."""284 lines, started = [], marker is None285 for raw in path.read_text(encoding="utf-8").splitlines():286 if not raw.startswith("#") or raw.startswith("#!"):287 if raw.startswith("#!"):288 continue289 break290 body = raw.lstrip("#").strip()291 if not started:292 if marker and body.startswith(marker):293 started = True294 lines.append(body)295 continue296 if set(body) <= {"-"} and len(body) > 10:297 break298 lines.append(body)299 if not lines:300 return "_(pas d'en-tête trouvé)_"301 return "\n".join("> " + l for l in lines)302303304def source_module_header(sid: str, registry) -> str:305 cls = registry.get(sid)306 if not cls:307 return "_(pas de connecteur)_"308 mod = cls.__module__.rsplit(".", 1)[-1]309 path = CONNECTORS_DIR / f"{mod}.py"310 # démarrer après les 2 lignes standard (titre projet + auteur)311 text = path.read_text(encoding="utf-8").splitlines()312 lines, seen_author = [], False313 for raw in text:314 if not raw.startswith("#"):315 break316 body = raw.lstrip("#").strip()317 if set(body) <= {"-"} and len(body) > 10:318 if seen_author and lines:319 break320 continue321 if body.startswith("Auteur :"):322 seen_author = True323 continue324 if body.startswith("Food-Ka —"):325 continue326 if seen_author:327 lines.append(body)328 return "\n".join("> " + l for l in lines) if lines else "_(pas d'en-tête)_"329330331def detect_caps(sid: str, registry) -> str:332 cls = registry.get(sid)333 if not cls:334 return "—"335 mod = cls.__module__.rsplit(".", 1)[-1]336 src = (CONNECTORS_DIR / f"{mod}.py").read_text(encoding="utf-8")337 caps = sorted(set(re.findall(r"FOODKA_[A-Z_]+", src)))338 hard = sorted(set(re.findall(r"(?:MAX|LIMIT)_[A-Z_]+\s*=\s*\d+",339 src)))[:3]340 out = caps + [h.replace(" ", "") for h in hard]341 return ", ".join(f"`{c}`" for c in out) if out else "—"342343344# --------------------------------------------------------------------------- #345# BD live346# --------------------------------------------------------------------------- #347348def q1(db, sql, args=()):349 return db.execute(sql, args).fetchone()350351352def completeness(db, source_ids: list[str]) -> tuple[int, OrderedDict]:353 if not source_ids:354 return 0, OrderedDict((l, 0.0) for l in FIELDS)355 ph = ",".join("?" * len(source_ids))356 parts = ", ".join(f"SUM(CASE WHEN {expr} THEN 1 ELSE 0 END)"357 for expr in FIELDS.values())358 row = q1(db, f"SELECT COUNT(*), {parts} FROM products "359 f"WHERE active = 1 AND source IN ({ph})", source_ids)360 n = row[0] or 0361 out = OrderedDict()362 for (label, _), filled in zip(FIELDS.items(), row[1:]):363 out[label] = (100.0 * (filled or 0) / n) if n else 0.0364 return n, out365366367def source_stats(db, sid: str) -> dict:368 tot, act, sale = q1(db, "SELECT COUNT(*), SUM(active), "369 "SUM(active = 1 AND on_sale = 1) FROM products "370 "WHERE source = ?", (sid,))371 last = q1(db, "SELECT ts, ok, found, message FROM sync_log "372 "WHERE source = ? ORDER BY ts DESC LIMIT 1", (sid,))373 errs = q1(db, "SELECT COUNT(*) FROM (SELECT ok FROM sync_log "374 "WHERE source = ? ORDER BY ts DESC LIMIT 10) WHERE ok = 0",375 (sid,))[0]376 return {"total": tot or 0, "active": act or 0, "sale": sale or 0,377 "last": last, "errs10": errs}378379380def fmt_ts(ts) -> str:381 if not ts:382 return "—"383 return datetime.datetime.fromtimestamp(ts).strftime("%Y-%m-%d %H:%M")384385386def recent_errors(db, source_ids: list[str], limit=8) -> list[tuple]:387 if not source_ids:388 return []389 ph = ",".join("?" * len(source_ids))390 return db.execute(391 f"SELECT source, ts, message FROM sync_log "392 f"WHERE ok = 0 AND source IN ({ph}) ORDER BY ts DESC LIMIT ?",393 (*source_ids, limit)).fetchall()394395396# --------------------------------------------------------------------------- #397# Rendu des fiches398# --------------------------------------------------------------------------- #399400def nfmt(n: int) -> str:401 return f"{n:,}".replace(",", " ")402403404def render_family_fiche(db, slug: str, members: list[dict], registry) -> str:405 meta = FAMILIES[slug]406 sids = [s["id"] for s in members]407 n, comp = completeness(db, sids)408409 lines = [f"# Famille `{slug}` — {meta['title']}", "",410 "_Généré automatiquement par `scripts/gen_connector_docs.py` — ne pas éditer à la main._",411 "", "## Vue d'ensemble", "",412 f"- **Sources membres** : {len(members)}"]413 if slug != "non-connectables":414 act = q1(db, "SELECT COALESCE(SUM(active), 0) FROM products WHERE source IN "415 f"({','.join('?' * len(sids))})", sids)[0]416 lines.append(f"- **Produits actifs (BD)** : {nfmt(act)}")417 if meta["base"]:418 lines.append(f"- **Socle commun** : `foodka/connectors/{meta['base']}`")419420 if meta["base"]:421 lines += ["", f"## Mécanique du socle (`{meta['base']}`)", "",422 module_header(CONNECTORS_DIR / meta["base"],423 f"connectors/{meta['base']}"), ""]424425 # ---- tableau des membres426 if slug == "non-connectables":427 lines += ["", "## Sources", "",428 "| Source | Nom | Tech | Pourquoi non connectable |",429 "|---|---|---|---|"]430 for s in sorted(members, key=lambda x: x["id"]):431 lines.append(f"| `{s['id']}` | {s['name']} | {s.get('tech', '')} | "432 f"{(s.get('notes') or '').replace('|', '—')} |")433 lines.append("")434 return "\n".join(lines)435436 if slug in ("flipp-proximite", "flyers-grandes-bannieres"):437 header = ("| Source | Nom | merchant_id | flyer_name_filter | Région | "438 "Produits actifs | En rabais | Dernier sync | Statut |")439 sep = "|---|---|---|---|---|---|---|---|---|"440 else:441 header = ("| Source | Nom | Tech | Région | Produits actifs | "442 "En rabais | Dernier sync | Statut |")443 sep = "|---|---|---|---|---|---|---|---|"444 lines += ["## Sources membres (BD live)", "", header, sep]445446 for s in sorted(members, key=lambda x: x["id"]):447 st = source_stats(db, s["id"])448 last = st["last"]449 when = fmt_ts(last[0]) if last else "jamais"450 status = ("OK" if last and last[1] else "ERREUR") + \451 (f" ({last[2] or 0} trouvés)" if last else "")452 if slug in ("flipp-proximite", "flyers-grandes-bannieres"):453 cls = registry.get(s["id"])454 mid = getattr(cls, "merchant_id", "—") if cls else "—"455 filt = getattr(cls, "flyer_name_filter", "") if cls else ""456 lines.append(f"| `{s['id']}` | {s['name']} | {mid} | "457 f"{('`' + filt + '`') if filt else '—'} | "458 f"{s.get('region', '—')} | {st['active']} | "459 f"{st['sale']} | {when} | {status} |")460 else:461 lines.append(f"| `{s['id']}` | {s['name']} | "462 f"{(s.get('tech') or '—').replace('|', '—')} | "463 f"{s.get('region', '—')} | {st['active']} | "464 f"{st['sale']} | {when} | {status} |")465 lines.append("")466467 # ---- complétude468 lines += [f"## Complétude des champs (produits actifs, N = {nfmt(n)})", "",469 "| Champ | % rempli |", "|---|---|"]470 lines += [f"| {label} | {pct:.1f} % |" for label, pct in comp.items()]471 lines.append("")472473 # ---- gotchas474 if meta["gotchas"]:475 lines += ["## Gotchas", ""]476 lines += [f"- {g}" for g in meta["gotchas"]]477 lines.append("")478479 # ---- mécanique par source (familles sans socle unique)480 if not meta["base"] and slug != "iga-api":481 lines += ["## Mécanique par source (en-têtes des modules)", ""]482 for s in sorted(members, key=lambda x: x["id"]):483 lines += [f"### `{s['id']}` — {s['name']}", "",484 f"Plafonds/env : {detect_caps(s['id'], registry)}", "",485 source_module_header(s["id"], registry), ""]486 elif slug == "iga-api":487 lines += ["## Mécanique (`foodka/connectors/iga.py`)", "",488 source_module_header("iga", registry), ""]489490 errs = recent_errors(db, sids)491 if errs:492 lines += ["## Erreurs de synchronisation récentes (sync_log, ok = 0)", "",493 "| Source | Quand | Message |", "|---|---|---|"]494 for sid, ts, msg in errs:495 lines.append(f"| `{sid}` | {fmt_ts(ts)} | "496 f"{(msg or '').replace('|', '—')[:160]} |")497 lines.append("")498 else:499 lines += ["## Erreurs de synchronisation récentes", "",500 "Aucune erreur dans le sync_log pour les sources de cette famille.", ""]501 return "\n".join(lines)502503504def render_transverse_matching(db) -> str:505 groups, uids = q1(db, "SELECT COUNT(DISTINCT group_id), COUNT(*) FROM product_links")506 dist = db.execute(507 "SELECT n, COUNT(*) FROM (SELECT group_id, COUNT(*) n FROM product_links "508 "GROUP BY group_id) GROUP BY n ORDER BY n").fetchall()509 top_src = db.execute(510 "SELECT p.source, COUNT(*) c FROM product_links l "511 "JOIN products p ON p.uid = l.uid GROUP BY p.source "512 "ORDER BY c DESC LIMIT 10").fetchall()513 lines = ["# Transverse — Matching inter-bannières (`product_links`)", "",514 "_Généré automatiquement par `scripts/gen_connector_docs.py`._", "",515 "## Mécanique (`foodka/matching.py`)", "",516 module_header(ROOT / "foodka" / "matching.py", "matching.py"), "",517 "## État live", "",518 f"- **Groupes de produits identiques** : {nfmt(groups)}",519 f"- **Produits rapprochés** : {nfmt(uids)}",520 "- **Règles conservatrices** : marque non vide et strictement égale ; "521 "format identique (quantité + unité de base) ; similarité de noms "522 "nettoyés ≥ 0,86 (0,95 sans format) ; un groupe couvre ≥ 2 bannières "523 "distinctes (`*_flyer` = même bannière que son catalogue).",524 "- **Garde-fous perf** : MAX_BLOCK 3000, comparaisons en fenêtre "525 "triée de 30 (coût linéaire ; rebuild mesuré à ~7 s).",526 "", "## Taille des groupes", "",527 "| Produits par groupe | Groupes |", "|---|---|"]528 lines += [f"| {n} | {c} |" for n, c in dist]529 lines += ["", "## Sources les plus rapprochées", "",530 "| Source | Produits dans un groupe |", "|---|---|"]531 lines += [f"| `{s}` | {c} |" for s, c in top_src]532 lines += ["", "Reconstruit après chaque cycle d'ingestion (table repartie "533 "de zéro : idempotent).", ""]534 return "\n".join(lines)535536537def render_transverse_nutrition(db) -> str:538 tot, found = q1(db, "SELECT COUNT(*), COALESCE(SUM(found), 0) FROM off_cache")539 enriched = q1(db, "SELECT COUNT(*) FROM products WHERE active = 1 "540 "AND details LIKE '%\"off\"%'")[0]541 lines = ["# Transverse — Nutrition Open Food Facts (`off_cache`)", "",542 "_Généré automatiquement par `scripts/gen_connector_docs.py`._", "",543 "## Mécanique (`foodka/nutrition.py`)", "",544 module_header(ROOT / "foodka" / "nutrition.py", "nutrition.py"), "",545 "## État live", "",546 f"- **Clés cherchées (cache)** : {nfmt(tot)} — "547 f"dont {nfmt(found)} correspondances trouvées "548 f"({100.0 * found / tot:.0f} % de hit)" if tot else549 "- **Cache vide**",550 f"- **Produits actifs enrichis (`details.off`)** : {nfmt(enriched)}",551 "- **Budget** : 100 requêtes/cycle par défaut, throttle 6 s "552 "(limite OFF : 10 recherches/min) + 1 s entre recherche et fiche "553 "produit.",554 "- **Priorisation** : produits avec marque, non encore cherchés "555 "(le cache est la vérité : vider `off_cache` pour re-tenter).",556 "- **Gotcha** : l'ancien `cgi/search.pl` OFF répond 503 (déprécié) "557 "— utiliser search.openfoodfacts.org (search-a-licious) + "558 "/api/v2/product/{code} pour les ingrédients.", ""]559 return "\n".join(lines)560561562def render_transverse_pricelog(db) -> str:563 rows, uids, t0, t1 = q1(db, "SELECT COUNT(*), COUNT(DISTINCT uid), "564 "MIN(ts), MAX(ts) FROM price_log")565 multi = q1(db, "SELECT COUNT(*) FROM (SELECT uid FROM price_log "566 "GROUP BY uid HAVING COUNT(DISTINCT price) > 1)")[0]567 lines = ["# Transverse — Historique de prix (`price_log`)", "",568 "_Généré automatiquement par `scripts/gen_connector_docs.py`._", "",569 "## Mécanique", "",570 "À chaque cycle d'ingestion, tout changement de prix observé est "571 "journalisé : `(uid, ts, price)` — `price` NULL = produit retiré "572 "de l'affichage. C'est la matière première des tendances de prix "573 "et des graphiques d'historique ; la continuité repose sur des "574 "`external_id` stables (d'où les slugs marque+nom+format des "575 "circulaires Flipp).", "",576 "## État live", "",577 f"- **Observations** : {nfmt(rows)}",578 f"- **Produits suivis** : {nfmt(uids)}",579 f"- **Produits avec au moins un changement de prix** : {nfmt(multi)}",580 f"- **Période couverte** : {fmt_ts(t0)} → {fmt_ts(t1)}", ""]581 return "\n".join(lines)582583584def render_index(db, groups: OrderedDict, sources: list[dict]) -> str:585 total, active = q1(db, "SELECT COUNT(*), SUM(active) FROM products")586 links = q1(db, "SELECT COUNT(DISTINCT group_id) FROM product_links")[0]587 off = q1(db, "SELECT COUNT(*) FROM products WHERE active = 1 "588 "AND details LIKE '%\"off\"%'")[0]589 plog = q1(db, "SELECT COUNT(*) FROM price_log")[0]590 now = datetime.datetime.now().strftime("%Y-%m-%d %H:%M")591 n_conn = sum(1 for s in sources if s.get("connector"))592593 lines = ["# Food-Ka — Documentation des connecteurs", "",594 f"_Générée le {now} par `scripts/gen_connector_docs.py`"595 " (rejouable : `.venv/bin/python3 scripts/gen_connector_docs.py`)._",596 "", "## Vue d'ensemble", "",597 f"- **Sources recensées** : {len(sources)} (registre "598 f"`data/sources.json`) — dont {n_conn} connectées",599 f"- **Produits en base** : {nfmt(total)} — dont {nfmt(active)} actifs",600 f"- **Groupes inter-bannières** : {nfmt(links)} "601 "(voir [matching](transverse-matching.md))",602 f"- **Produits enrichis Open Food Facts** : {nfmt(off)} "603 "(voir [nutrition](transverse-nutrition-off.md))",604 f"- **Observations de prix** : {nfmt(plog)} "605 "(voir [price_log](transverse-price-log.md))",606 "", "## Fiches par famille de connecteurs", "",607 "| Famille | Fiche | Sources | Produits actifs |",608 "|---|---|---|---|"]609 for slug, members in groups.items():610 sids = [s["id"] for s in members]611 act = q1(db, "SELECT COALESCE(SUM(active), 0) FROM products "612 f"WHERE source IN ({','.join('?' * len(sids))})", sids)[0] \613 if sids else 0614 lines.append(f"| `{slug}` | [{slug}.md]({slug}.md) | {len(members)} | "615 f"{nfmt(act)} |")616617 lines += ["", "## Fiches transverses", "",618 "| Sujet | Fiche |", "|---|---|",619 "| Matching inter-bannières (product_links) | [transverse-matching.md](transverse-matching.md) |",620 "| Nutrition Open Food Facts (off_cache) | [transverse-nutrition-off.md](transverse-nutrition-off.md) |",621 "| Historique de prix (price_log) | [transverse-price-log.md](transverse-price-log.md) |",622 "", HISTORIQUE]623 return "\n".join(lines)624625626# --------------------------------------------------------------------------- #627628def main() -> None:629 sources = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]630 registry = get_registry()631 groups: OrderedDict[str, list] = OrderedDict((k, []) for k in FAMILIES)632 for s in sources:633 groups[classify(s, registry)].append(s)634635 db = sqlite3.connect(f"file:{DB_PATH}?mode=ro", uri=True)636 OUT_DIR.mkdir(parents=True, exist_ok=True)637638 for slug, members in groups.items():639 (OUT_DIR / f"{slug}.md").write_text(640 render_family_fiche(db, slug, members, registry), encoding="utf-8")641 print(f" fiche {slug}.md ({len(members)} source(s))")642643 (OUT_DIR / "transverse-matching.md").write_text(render_transverse_matching(db), encoding="utf-8")644 (OUT_DIR / "transverse-nutrition-off.md").write_text(render_transverse_nutrition(db), encoding="utf-8")645 (OUT_DIR / "transverse-price-log.md").write_text(render_transverse_pricelog(db), encoding="utf-8")646 (OUT_DIR / "INDEX.md").write_text(render_index(db, groups, sources), encoding="utf-8")647 print(f"OK — {len(groups)} fiches famille + 3 transverses + INDEX.md dans {OUT_DIR}")648649650if __name__ == "__main__":651 main()652