SPB Git

Repository Public

ingest.py 6.8 KB 178 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Food·Ka9# File             : foodka/ingest.py10# Module           : foodka11# Repository       : https://git.spboucher.ai/food-ka12# Created          : 2026-08-1213# Last Modified    : 2026-08-1814#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# Food-Ka — Agrégateur de produits d'épicerie (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# ingest.py : pipeline d'ingestion — exécute les connecteurs et synchronise91#             la base (ajouts / mises à jour / retraits) = contenu toujours à jour92# -----------------------------------------------------------------------------93from __future__ import annotations9495import sys96import time97import traceback9899from . import db100from .connectors import CONNECTORS101from .connectors._resilient import redact102103104def _log(msg: str, err: bool = False) -> None:105    """Ligne de journal : sans clé d'API (redact) et vidée tout de suite.106107    Sous PM2 la sortie est un tube : sans `flush`, Python la retient par blocs108    et le journal paraissait arrêté pendant des jours alors que le veilleur109    tournait (constat du 2026-11-26).110    """111    print(redact(msg), file=sys.stderr if err else sys.stdout, flush=True)112113114def run(sources: list[str] | None = None) -> list[dict]:115    """Exécute l'ingestion pour toutes les sources (ou celles demandées)."""116    con = db.connect()117    results = []118    targets = sources or list(CONNECTORS.keys())119    for sid in targets:120        cls = CONNECTORS.get(sid)121        if cls is None:122            _log(f"[food-ka] connecteur inconnu : {sid}", err=True)123            continue124        t0 = time.time()125        _log(f"[food-ka] sync {sid} ...")126        try:127            connector = cls()128            products = connector.fetch()129            finalized, dropped = [], 0130            for prod in products:131                try:132                    finalized.append(prod.finalize())133                except Exception:  # un produit malformé ne bloque pas la source134                    dropped += 1135            stats = db.sync_source(con, sid, finalized)136            stats["seconds"] = round(time.time() - t0, 1)137            if dropped:138                stats["dropped"] = dropped139            via = getattr(connector, "via_counts", None)140            if via:141                stats["via"] = dict(via)142            if stats.get("alert"):143                _log(f"[food-ka]   ⚠ ALERTE {sid} : {stats['alert']}")144            _log(f"[food-ka]   {stats}")145            results.append(stats)146        except Exception as exc:  # robustesse : une source ne bloque pas les autres147            db.log_failure(con, sid, redact(f"{exc}")[:500])148            _log(traceback.format_exc(), err=True)149            results.append({"source": sid, "error": redact(str(exc))})150151    # post-cycle 1 : rapprochement inter-bannières (table product_links)152    try:153        from . import matching154        _log(f"[food-ka] matching : {matching.rebuild(con)}")155    except Exception:              # l'enrichissement n'est jamais bloquant156        _log(traceback.format_exc(), err=True)157    # post-cycle 2 : nutrition Open Food Facts (details.off, budget 100/cycle)158    try:159        from . import nutrition160        _log(f"[food-ka] nutrition : {nutrition.enrich(con, budget=100)}")161    except Exception:162        _log(traceback.format_exc(), err=True)163164    con.close()165    return results166167168def watch(interval_seconds: int = 3600) -> None:169    """Boucle de rafraîchissement périodique (pseudo-webhook par sondage)."""170    while True:171        run()172        _log(f"[food-ka] prochaine synchronisation dans {interval_seconds}s")173        time.sleep(interval_seconds)174175176if __name__ == "__main__":177    run(sys.argv[1:] or None)178
Files main
Menu

Theme