SPB Git

Repository Public

ingest.py 5.8 KB 155 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Auto·Ka9# File             : autoka/ingest.py10# Module           : autoka11# Repository       : https://git.spboucher.ai/auto-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# Auto-Ka — Agrégateur de voitures usagées à vendre (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) = inventaire à jour92# -----------------------------------------------------------------------------93from __future__ import annotations9495import sys96import time97import traceback9899from . import db100from .connectors import CONNECTORS101102103def run(sources: list[str] | None = None) -> list[dict]:104    """Exécute l'ingestion pour toutes les sources (ou celles demandées)."""105    con = db.connect()106    results = []107    targets = sources or list(CONNECTORS.keys())108    for sid in targets:109        cls = CONNECTORS.get(sid)110        if cls is None:111            print(f"[auto-ka] connecteur inconnu : {sid}", file=sys.stderr)112            continue113        t0 = time.time()114        print(f"[auto-ka] sync {sid} ...")115        try:116            vehicles = cls().fetch()117            finalized, dropped = [], 0118            for veh in vehicles:119                try:120                    finalized.append(veh.finalize())121                except Exception:  # une annonce malformée ne bloque pas la source122                    dropped += 1123            stats = db.sync_source(con, sid, finalized)124            stats["seconds"] = round(time.time() - t0, 1)125            if dropped:126                stats["dropped"] = dropped127            if stats.get("alert"):128                print(f"[auto-ka]   ⚠ ALERTE {sid} : {stats['alert']}")129            print(f"[auto-ka]   {stats}")130            results.append(stats)131        except Exception as exc:  # robustesse : une source ne bloque pas les autres132            db.log_failure(con, sid, f"{exc}")133            traceback.print_exc()134            results.append({"source": sid, "error": str(exc)})135    # dédoublonnage inter-sources par VIN — recalculé après chaque cycle136    try:137        from . import dedup138        dedup.recompute(con)139    except Exception:140        traceback.print_exc()141    con.close()142    return results143144145def watch(interval_seconds: int = 7200) -> None:146    """Boucle de rafraîchissement périodique (pseudo-webhook par sondage)."""147    while True:148        run()149        print(f"[auto-ka] prochaine synchronisation dans {interval_seconds}s")150        time.sleep(interval_seconds)151152153if __name__ == "__main__":154    run(sys.argv[1:] or None)155
Files main
Menu

Theme