SPB Git

Repository Public

db.py 18.6 KB 399 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Fabri·Ka9# File             : fabrika/db.py10# Module           : fabrika11# Repository       : https://git.spboucher.ai/fabri-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-2814#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Fabri-Ka — Agrégateur de produits québécois89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# db.py : persistance SQLite — upsert avec hash de contenu, cycle de vie91#         avec délai de grâce, FTS5 pour la recherche plein-texte.92# -----------------------------------------------------------------------------93from __future__ import annotations9495import json96import sqlite397import time98from pathlib import Path99100from .schema import Product101102DB_PATH = Path(__file__).resolve().parent.parent / "data" / "fabrika.db"103104# Nombre de syncs consécutives où un produit doit être absent avant désactivation105MISS_GRACE = 2106107_SCHEMA = """108CREATE TABLE IF NOT EXISTS stores (109    id            TEXT PRIMARY KEY,      -- domaine canonique110    name          TEXT,111    url           TEXT,112    platform      TEXT,113    catalog_endpoint TEXT,114    city          TEXT,115    region        TEXT,116    origin_class  TEXT,                  -- A|B|C|D|E117    origin_confidence REAL,118    origin_evidence TEXT,119    categories    TEXT,                  -- JSON120    socials       TEXT,                  -- JSON121    discovery_sources TEXT,              -- JSON122    language      TEXT,123    enabled       INTEGER DEFAULT 1,124    last_sync     REAL,125    last_status   TEXT,126    product_count INTEGER DEFAULT 0127);128CREATE TABLE IF NOT EXISTS products (129    uid          TEXT PRIMARY KEY,130    store_id     TEXT NOT NULL,131    external_id  TEXT NOT NULL,132    url          TEXT,133    title        TEXT,134    description  TEXT,135    price        REAL,136    price_max    REAL,137    compare_at_price REAL,138    currency     TEXT,139    images       TEXT,   -- JSON140    category     TEXT,141    product_type TEXT,142    tags         TEXT,   -- JSON143    vendor       TEXT,144    available    INTEGER,145    details      TEXT,   -- JSON : avis, dimensions, matériaux, variantes…146    content_hash TEXT,147    first_seen   REAL,148    last_seen    REAL,149    active       INTEGER DEFAULT 1,150    miss_count   INTEGER DEFAULT 0,151    -- colonnes ajoutées après coup : déclarées ici aussi, sinon l'index152    -- partiel idx_products_pub_cover (WHERE listing_status=…) faisait échouer153    -- la création d'une base NEUVE (tests, réinstallation)154    listing_status   TEXT DEFAULT 'published',155    price_on_request INTEGER DEFAULT 0156);157CREATE INDEX IF NOT EXISTS idx_products_store ON products(store_id);158CREATE INDEX IF NOT EXISTS idx_products_cat ON products(category);159CREATE INDEX IF NOT EXISTS idx_products_active ON products(active);160CREATE INDEX IF NOT EXISTS idx_products_pub_cover ON products(category, store_id, price, first_seen) WHERE active=1 AND listing_status='published';161CREATE INDEX IF NOT EXISTS idx_products_fs_cover ON products(first_seen, store_id, category, price);162CREATE TABLE IF NOT EXISTS sync_log (163    ts REAL, store_id TEXT, found INTEGER, added INTEGER,164    updated INTEGER, removed INTEGER, status TEXT, message TEXT165);166CREATE VIRTUAL TABLE IF NOT EXISTS products_fts USING fts5(167    uid UNINDEXED, title, description, tags, vendor, store_name,168    tokenize = 'unicode61 remove_diacritics 2'169);170"""171172173def connect() -> sqlite3.Connection:174    DB_PATH.parent.mkdir(parents=True, exist_ok=True)175    # L'initialisation du schéma (executescript) peut être refusée pendant176    # qu'un autre processus écrit (sync massive) : on retente avec délai177    # croissant plutôt que d'échouer immédiatement.178    last_exc = None179    for attempt in range(8):180        con = sqlite3.connect(DB_PATH, timeout=60)181        con.execute("PRAGMA busy_timeout=60000")182        con.row_factory = sqlite3.Row183        try:184            con.executescript(_SCHEMA)185            # migrations additives (colonnes ajoutées après la création)186            cols = {r[1] for r in con.execute("PRAGMA table_info(products)")}187            if "details" not in cols:188                con.execute("ALTER TABLE products ADD COLUMN details TEXT")189            if "listing_status" not in cols:190                con.execute("ALTER TABLE products ADD COLUMN listing_status TEXT DEFAULT 'published'")191                con.execute("CREATE INDEX IF NOT EXISTS idx_products_listing ON products(listing_status)")192            if "price_on_request" not in cols:193                con.execute("ALTER TABLE products ADD COLUMN price_on_request INTEGER DEFAULT 0")194            scols = {r[1] for r in con.execute("PRAGMA table_info(stores)")}195            for col, typ in (("shipping_info", "TEXT"), ("email", "TEXT"),196                             ("phone", "TEXT"), ("postal_prefix", "TEXT"),197                             ("lat", "REAL"), ("lng", "REAL"),198                             ("store_kind", "TEXT"),199                             # vague 4 : certifications structurées (JSON) +200                             # détection des ateliers présumés fermés201                             ("certifications", "TEXT"),202                             ("fail_streak", "INTEGER DEFAULT 0"),203                             ("presumed_closed", "INTEGER DEFAULT 0")):204                if col not in scols:205                    con.execute(f"ALTER TABLE stores ADD COLUMN {col} {typ}")206            # auto-inscription des artisans (« Inscrire mon atelier ») :207            # quarantaine de validation, jamais publiée sans geste manuel208            con.execute("""CREATE TABLE IF NOT EXISTS inscriptions (209                id INTEGER PRIMARY KEY AUTOINCREMENT,210                ts REAL, ip TEXT, name TEXT, metier TEXT, description TEXT,211                address TEXT, website TEXT, email TEXT, phone TEXT,212                socials TEXT, photos TEXT,213                status TEXT DEFAULT 'pending',   -- pending|approved|rejected214                reviewed_at REAL, review_note TEXT)""")215            return con216        except sqlite3.OperationalError as exc:217            last_exc = exc218            con.close()219            time.sleep(1.5 * (attempt + 1))220    raise last_exc221222223def upsert_store(con: sqlite3.Connection, s: dict) -> None:224    con.execute("""225        INSERT INTO stores (id, name, url, platform, catalog_endpoint, city, region,226                            origin_class, origin_confidence, origin_evidence,227                            categories, socials, discovery_sources, language, enabled,228                            phone, postal_prefix, store_kind)229        VALUES (:id,:name,:url,:platform,:catalog_endpoint,:city,:region,230                :origin_class,:origin_confidence,:origin_evidence,231                :categories,:socials,:discovery_sources,:language,:enabled,232                :phone,:postal_prefix,:store_kind)233        ON CONFLICT(id) DO UPDATE SET234            name=excluded.name, url=excluded.url, platform=excluded.platform,235            catalog_endpoint=excluded.catalog_endpoint,236            -- city vient du géocodage (pas du registre) : ne jamais l'écraser par du vide237            city=CASE WHEN excluded.city<>'' THEN excluded.city ELSE stores.city END,238            region=excluded.region, origin_class=excluded.origin_class,239            origin_confidence=excluded.origin_confidence,240            origin_evidence=excluded.origin_evidence,241            categories=excluded.categories, socials=excluded.socials,242            discovery_sources=excluded.discovery_sources,243            language=excluded.language, enabled=excluded.enabled,244            phone=CASE WHEN excluded.phone<>'' THEN excluded.phone ELSE stores.phone END,245            postal_prefix=CASE WHEN excluded.postal_prefix<>'' THEN excluded.postal_prefix246                               ELSE stores.postal_prefix END,247            store_kind=CASE WHEN excluded.store_kind<>'' THEN excluded.store_kind248                            ELSE stores.store_kind END249    """, {250        "id": s["id"], "name": s.get("name") or s["id"], "url": s.get("url") or f"https://{s['id']}",251        "platform": s.get("platform") or "", "catalog_endpoint": s.get("catalog_endpoint") or "",252        "city": s.get("city") or "", "region": s.get("region") or "",253        "origin_class": s.get("origin_class") or "E",254        "origin_confidence": s.get("origin_confidence") or 0.0,255        "origin_evidence": s.get("origin_evidence") or "",256        "categories": json.dumps(s.get("categories") or [], ensure_ascii=False),257        "socials": json.dumps(s.get("socials") or [], ensure_ascii=False),258        "discovery_sources": json.dumps(s.get("discovery_sources") or [], ensure_ascii=False),259        "language": s.get("language") or "", "enabled": 1 if s.get("enabled", True) else 0,260        "phone": s.get("phone") or "", "postal_prefix": s.get("postal_prefix") or "",261        "store_kind": s.get("store_kind") or "",262    })263264265def sync_products(con: sqlite3.Connection, store_id: str, store_name: str,266                  products: list[Product],267                  hold_removals: bool = False,268                  force_removals: bool = False) -> tuple[int, int, int]:269    """Diff complet d'une boutique : upsert + désactivation avec délai de grâce.270271    `hold_removals=True` (passe suspecte, voir ingest.drift_verdict) : les272    produits vus sont mis à jour, mais AUCUN produit absent n'est compté273    manquant ni désactivé. `force_removals=True` (baisse confirmée après274    plusieurs passes suspectes) : les absents sont désactivés sans délai.275276    Retourne (ajoutés, modifiés, retirés)."""277    now = time.time()278    existing = {r["uid"]: (r["content_hash"], r["active"], r["miss_count"])279                for r in con.execute("SELECT uid, content_hash, active, miss_count "280                                     "FROM products WHERE store_id=?", (store_id,))}281    seen, added, updated = set(), 0, 0282    # FTS5 : uid est UNINDEXED -> chaque DELETE WHERE uid=? balaie toute la283    # table. On accumule et on supprime par lots (voir fin de fonction).284    fts_del, fts_add = [], []285    for p in products:286        p.finalize()287        uid, chash = p.uid, p.content_hash()288        if uid in seen:      # doublon dans la même source289            continue290        seen.add(uid)291        row = p.to_row()292        row.update(images=json.dumps(p.images), tags=json.dumps(p.tags, ensure_ascii=False),293                   details=json.dumps(p.details, ensure_ascii=False) if p.details else None,294                   content_hash=chash, last_seen=now,295                   available=None if p.available is None else int(p.available))296        if uid not in existing:297            row["first_seen"] = now298            con.execute("""INSERT INTO products (uid, store_id, external_id, url, title,299                description, price, price_max, compare_at_price, currency, images, category,300                product_type, tags, vendor, available, details, content_hash, first_seen,301                last_seen, active, miss_count, listing_status, price_on_request)302                VALUES (:uid,:store_id,:external_id,:url,:title,303                :description,:price,:price_max,:compare_at_price,:currency,:images,:category,304                :product_type,:tags,:vendor,:available,:details,:content_hash,:first_seen,305                :last_seen,1,0,:listing_status,:price_on_request)""", row)306            con.execute("INSERT INTO products_fts (uid, title, description, tags, vendor, store_name) "307                        "VALUES (?,?,?,?,?,?)",308                        (uid, p.title, p.description, " ".join(p.tags), p.vendor, store_name))309            added += 1310        else:311            old_hash, old_active, _ = existing[uid]312            if old_hash != chash or not old_active:313                con.execute("""UPDATE products SET url=:url, title=:title, description=:description,314                    price=:price, price_max=:price_max, compare_at_price=:compare_at_price,315                    currency=:currency, images=:images, category=:category,316                    product_type=:product_type, tags=:tags, vendor=:vendor,317                    available=:available, details=:details, content_hash=:content_hash,318                    last_seen=:last_seen, listing_status=:listing_status,319                    price_on_request=:price_on_request,320                    active=1, miss_count=0 WHERE uid=:uid""", row)321                fts_del.append(uid)322                fts_add.append((uid, p.title, p.description, " ".join(p.tags),323                                p.vendor, store_name))324                updated += 1325            else:326                con.execute("UPDATE products SET last_seen=?, miss_count=0 WHERE uid=?", (now, uid))327328    removed = 0329    for uid, (_, active, miss) in existing.items():330        if hold_removals or uid in seen or not active:331            continue332        if force_removals or miss + 1 >= MISS_GRACE:333            con.execute("UPDATE products SET active=0, miss_count=? WHERE uid=?", (miss + 1, uid))334            fts_del.append(uid)335            removed += 1336        else:337            con.execute("UPDATE products SET miss_count=? WHERE uid=?", (miss + 1, uid))338339    # purge/réinsertion FTS par lots (1 balayage par lot de 500 au lieu de N)340    for i in range(0, len(fts_del), 500):341        chunk = fts_del[i:i + 500]342        con.execute("DELETE FROM products_fts WHERE uid IN (%s)"343                    % ",".join("?" * len(chunk)), chunk)344    if fts_add:345        con.executemany("INSERT INTO products_fts (uid, title, description, tags, "346                        "vendor, store_name) VALUES (?,?,?,?,?,?)", fts_add)347348    con.execute("UPDATE stores SET last_sync=?, product_count="349                "(SELECT COUNT(*) FROM products WHERE store_id=? AND active=1 "350                "AND listing_status='published') WHERE id=?",351                (now, store_id, store_id))352    return added, updated, removed353354355def redact(text) -> str:356    """Masque toute clé d'API avant consignation (voir connectors/_resilient)."""357    from .connectors import _resilient358    return _resilient.redact(text)359360361# -- détection de dérive --------------------------------------------------------362DRIFT_WINDOW = 10        # passes réussies NON VIDES retenues pour la médiane363364365def reference_count(con, store_id: str) -> float | None:366    """Taille de référence d'un catalogue : médiane du nombre de produits vus367    lors des dernières passes réussies et NON VIDES (30 jours). Les passes à368    zéro et les passes suspectes n'entrent jamais dans la médiane : après369    quelques passes vides, la référence ne doit pas tomber à zéro et faire370    passer une panne pour l'état normal. None s'il y a moins de 3 passes."""371    rows = [r[0] for r in con.execute(372        "SELECT found FROM sync_log WHERE store_id=? AND status='ok' AND found>0 "373        "AND ts>? ORDER BY ts DESC LIMIT ?",374        (store_id, time.time() - 30 * 86400, DRIFT_WINDOW))]375    if len(rows) < 3:376        return None377    rows.sort()378    mid = len(rows) // 2379    return float(rows[mid]) if len(rows) % 2 else (rows[mid - 1] + rows[mid]) / 2.0380381382def suspect_streak(con, store_id: str) -> int:383    """Nombre de passes suspectes consécutives les plus récentes."""384    n = 0385    for (status,) in con.execute(386            "SELECT status FROM sync_log WHERE store_id=? ORDER BY ts DESC LIMIT 40",387            (store_id,)):388        if status != "suspect":389            break390        n += 1391    return n392393394def log_sync(con, store_id, found, added, updated, removed, status, message=""):395    con.execute("INSERT INTO sync_log VALUES (?,?,?,?,?,?,?,?)",396                (time.time(), store_id, found, added, updated, removed, status,397                 redact(message)[:300]))398    con.execute("UPDATE stores SET last_status=? WHERE id=?", (status, store_id))399
Files main
Menu

Theme