SPB Git

Repository Public

db.py 29.6 KB 696 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Lou·Ka9# File             : louka/db.py10# Module           : louka11# Repository       : https://git.spboucher.ai/lou-ka12# Created          : 2026-08-0613# Last Modified    : 2026-11-0314#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# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# db.py : persistance SQLite — upsert avec détection de changements,91#         cycle de vie avec délai de grâce (2 syncs), détection de dérive,92#         cache des pages détail, cache de géocodage.93# -----------------------------------------------------------------------------94from __future__ import annotations9596import json97import sqlite398import statistics99import time100from pathlib import Path101102from .schema import Listing103104DB_PATH = Path(__file__).resolve().parent.parent / "data" / "louka.db"105106# Nombre d'exécutions consécutives où une annonce doit être absente de la107# source avant d'être désactivée (délai de grâce contre les ratés ponctuels).108MISS_GRACE = 2109110# Dérive : si une source retourne <= DRIFT_RATIO × sa médiane historique111# (médiane >= DRIFT_MIN_BASE annonces), on alerte et on suspend les retraits.112DRIFT_RATIO = 0.25113DRIFT_MIN_BASE = 8114DRIFT_HISTORY = 5115116_SCHEMA = """117CREATE TABLE IF NOT EXISTS listings (118    uid          TEXT PRIMARY KEY,119    source       TEXT NOT NULL,120    external_id  TEXT NOT NULL,121    url          TEXT,122    title        TEXT,123    address      TEXT,124    sector       TEXT,125    city         TEXT,126    unit_type    TEXT,127    bedrooms     REAL,128    bathrooms    REAL,129    price        REAL,130    price_label  TEXT,131    availability TEXT,132    availability_date TEXT,133    area_sqft    REAL,134    pets         TEXT,135    furnished    INTEGER,136    description  TEXT,137    amenities    TEXT,   -- JSON (liste de textes source)138    details      TEXT,   -- JSON (champs structurés : inclusions, parking…)139    images       TEXT,   -- JSON140    lat          REAL,141    lng          REAL,142    geocode_failed INTEGER DEFAULT 0,143    content_hash TEXT,144    first_seen   REAL,145    last_seen    REAL,146    updated_at   REAL,147    miss_count   INTEGER DEFAULT 0,148    active       INTEGER DEFAULT 1149);150CREATE INDEX IF NOT EXISTS idx_listings_source ON listings(source);151CREATE INDEX IF NOT EXISTS idx_listings_city   ON listings(city);152CREATE INDEX IF NOT EXISTS idx_listings_active ON listings(active);153CREATE INDEX IF NOT EXISTS idx_listings_geo    ON listings(lat, lng);154155CREATE TABLE IF NOT EXISTS sync_log (156    id        INTEGER PRIMARY KEY AUTOINCREMENT,157    source    TEXT,158    ts        REAL,159    found     INTEGER,160    added     INTEGER,161    updated   INTEGER,162    removed   INTEGER,163    ok        INTEGER,164    message   TEXT,165    stats     TEXT    -- JSON : taux de champs null, missed, alerte…166);167CREATE INDEX IF NOT EXISTS idx_sync_log_ts ON sync_log(ts);168169CREATE TABLE IF NOT EXISTS detail_cache (170    source      TEXT NOT NULL,171    external_id TEXT NOT NULL,172    key         TEXT,            -- hash du contenu « liste » de l'annonce173    payload     TEXT,            -- JSON opaque propre au connecteur174    fetched_at  REAL,175    PRIMARY KEY (source, external_id)176);177178CREATE TABLE IF NOT EXISTS price_log (179    uid   TEXT NOT NULL,180    ts    REAL NOT NULL,181    price REAL              -- prix observé (NULL = retiré de l'affichage)182);183CREATE INDEX IF NOT EXISTS idx_price_log_uid ON price_log(uid);184185CREATE TABLE IF NOT EXISTS poi_cache (186    coord_key   TEXT PRIMARY KEY,   -- "lat,lng" arrondi à 4 décimales (~11 m)187    lat         REAL,188    lng         REAL,189    pois        TEXT,               -- JSON : [{cat, name, dist_m}] (plus proche/catégorie)190    ts          REAL191);192193CREATE TABLE IF NOT EXISTS geocode_cache (194    address     TEXT PRIMARY KEY,   -- adresse normalisée (clé de cache)195    lat         REAL,196    lng         REAL,197    provider    TEXT,198    failed      INTEGER DEFAULT 0,199    ts          REAL200);201202CREATE TABLE IF NOT EXISTS users (203    id          INTEGER PRIMARY KEY AUTOINCREMENT,204    google_sub  TEXT UNIQUE,        -- identifiant stable Google (OpenID « sub »)205    ka_id       TEXT,               -- identifiant membre « ka-0123456789 » (unique)206    email       TEXT,207    name        TEXT,208    picture     TEXT,               -- URL de l'avatar Google209    public      INTEGER DEFAULT 0,  -- profil public /u/{ka_id} (opt-in)210    role        TEXT,               -- « locataire » | « gestionnaire » | NULL211    org_source  TEXT,               -- source réclamée (gestionnaire)212    created_at  REAL,213    last_login  REAL214);215216CREATE TABLE IF NOT EXISTS favorites (217    user_id  INTEGER NOT NULL,218    uid      TEXT NOT NULL,          -- listings.uid219    ts       REAL,220    PRIMARY KEY (user_id, uid)221);222223CREATE TABLE IF NOT EXISTS image_checks (224    url        TEXT PRIMARY KEY,   -- URL d'image vérifiée (imgcheck.py)225    status     TEXT,               -- ok | dead | small | error226    width      INTEGER,227    height     INTEGER,228    bytes      INTEGER,229    sha1       TEXT,               -- hash du contenu (doublons / placeholders)230    checked_at REAL231);232233CREATE TABLE IF NOT EXISTS env_tiles (234    tile_key   TEXT PRIMARY KEY,   -- « ty,tx » (tuiles 0,5° — voir poi.py/environment.py)235    data       TEXT,               -- JSON : routes/rails/aéro/industriel/bars/cyclable/POI236    fetched_at REAL237);238239CREATE TABLE IF NOT EXISTS kascores (240    coord_key   TEXT PRIMARY KEY,  -- « lat,lng » arrondi à 4 décimales (immeuble)241    lat REAL, lng REAL,242    walk REAL,                     -- KA Walk Score 0-100 (NULL = données insuffisantes)243    transit REAL,                  -- KA Transit Score (NULL = non desservi/inconnu)244    bike REAL,245    calme REAL,246    services REAL,247    global REAL,                   -- moyenne pondérée par défaut (voir kascores.py)248    details TEXT,                  -- JSON : détail par score (fiche + méthodologie)249    version TEXT,                  -- version du barème (recalcul si changement)250    computed_at REAL251);252253CREATE TABLE IF NOT EXISTS source_profiles (254    source_id     TEXT PRIMARY KEY,  -- id de la source (data/sources.json)255    owner_user_id INTEGER,           -- gestionnaire qui a réclamé la page256    tagline       TEXT,              -- accroche personnalisée257    description   TEXT,258    website       TEXT,259    phone         TEXT,260    email         TEXT,261    logo_url      TEXT,262    updated_at    REAL263);264265CREATE TABLE IF NOT EXISTS listing_events (266    id    INTEGER PRIMARY KEY AUTOINCREMENT,267    uid   TEXT NOT NULL,             -- listings.uid268    ts    REAL NOT NULL,269    event TEXT NOT NULL,             -- description | superficie | dispo |270                                     -- inclusions | photos | disparition |271                                     -- reapparition  (prix -> price_log)272    old   TEXT,                      -- valeur avant (JSON compact)273    new   TEXT                       -- valeur après (JSON compact)274);275CREATE INDEX IF NOT EXISTS idx_levents_uid ON listing_events(uid, ts);276277CREATE TABLE IF NOT EXISTS buildings (278    bkey        TEXT PRIMARY KEY,    -- clé d'adresse « civique|rue|ville »279                                     -- (dedup._parse_address) ou « geo:lat,lng »280    address     TEXT,                -- adresse d'affichage (la plus fréquente)281    city        TEXT,282    lat REAL, lng REAL,283    stats       TEXT,                -- JSON : unités, annonces, loyers,284                                     -- rotation, pression, gestionnaires…285    version     TEXT,                -- version du calcul (building.py)286    computed_at REAL287);288289CREATE TABLE IF NOT EXISTS recycled_cache (290    uid         TEXT PRIMARY KEY,    -- listings.uid291    matches     TEXT,                -- JSON : correspondances probables + signaux292    computed_at REAL293);294295CREATE TABLE IF NOT EXISTS managers (296    id               INTEGER PRIMARY KEY AUTOINCREMENT,297    source_id        TEXT UNIQUE,    -- id de la source (data/sources.json)298    name             TEXT,           -- nom canonique299    aliases          TEXT,           -- JSON : variantes de nom300    website          TEXT,301    phone            TEXT,302    -- résolution Google Maps (SerpApi) — voir louka/managers.py303    gmaps_place_id   TEXT,304    gmaps_data_id    TEXT,305    gmaps_name       TEXT,306    gmaps_address    TEXT,307    gmaps_rating     REAL,308    gmaps_reviews    INTEGER,        -- nombre d'avis annoncé par Google309    match_confidence REAL,           -- 0..1 (association refusée si trop faible)310    match_signals    TEXT,           -- JSON : signaux ayant fondé l'association311    resolved_at      REAL,312    resolve_failed   INTEGER DEFAULT 0,313    review_stats     TEXT,           -- JSON : distribution, tendance, thèmes314    last_synced_at   REAL315);316317CREATE TABLE IF NOT EXISTS manager_reviews (318    id                  INTEGER PRIMARY KEY AUTOINCREMENT,319    manager_id          INTEGER NOT NULL,320    external_review_id  TEXT,        -- id Google (déduplication)321    source              TEXT DEFAULT 'google_maps',322    rating              REAL,323    text                TEXT,324    published_at        TEXT,        -- ISO si dérivable325    relative_date_raw   TEXT,        -- « il y a 3 mois » (texte source)326    author_name         TEXT,327    author_review_count INTEGER,328    owner_response      TEXT,329    owner_response_date TEXT,330    source_url          TEXT,331    fetched_at          REAL,332    content_hash        TEXT,        -- déduplication de secours333    analysis            TEXT         -- JSON : topics/sentiment/severity (managers.py)334);335CREATE INDEX IF NOT EXISTS idx_mreviews_mgr ON manager_reviews(manager_id);336CREATE UNIQUE INDEX IF NOT EXISTS idx_mreviews_ext337    ON manager_reviews(manager_id, external_review_id);338"""339340# Colonnes ajoutées après la v1 — migration automatique des bases existantes.341_MIGRATIONS = {342    "listings": {343        "availability_date": "TEXT",344        "area_sqft": "REAL",345        "pets": "TEXT",346        "furnished": "INTEGER",347        "details": "TEXT",348        "geocode_failed": "INTEGER DEFAULT 0",349        "miss_count": "INTEGER DEFAULT 0",350        "dauid": "TEXT",     # aire de diffusion 2021 (stats de quartier)351        "digest": "TEXT",    # JSON louka/textmine.py (description structurée)352        "dup_of": "TEXT",    # uid de l'annonce canonique si doublon inter-sources353        "dup_sources": "TEXT",  # JSON : autres sources où l'annonce est publiée354        "bedrooms": "REAL",   # chambres fermées (convention QC : 4½ = 2)355        "bathrooms": "REAL",  # salles de bain (1.5 = salle d'eau en plus)356        "completeness": "REAL",          # score de complétude 0–100 (quality.py)357        "published": "INTEGER DEFAULT 1",  # 0 = quarantaine (sous le seuil)358        "quality_reasons": "TEXT",       # JSON : raisons de la quarantaine359        "images_ok": "TEXT",   # JSON : galerie nettoyée (imgcheck.py)360        "img_audit": "TEXT",   # JSON : traçabilité du contrôle images361        "coord_key": "TEXT",   # clé immeuble « lat,lng » 4 déc. (jointure kascores)362        "building_key": "TEXT",  # clé immeuble par adresse (buildings.bkey)363        "province": "TEXT DEFAULT 'QC'",  # « QC » | « ON » (expansion Ontario 2026-08)364    },365    "sync_log": {366        "stats": "TEXT",367    },368    "users": {369        "ka_id": "TEXT",370        "public": "INTEGER DEFAULT 0",371        "role": "TEXT",372        "org_source": "TEXT",373        "display_name": "TEXT",   # nom choisi (prime sur le nom Google)374        "avatar_url": "TEXT",     # photo téléversée (prime sur picture)375        "bio": "TEXT",376        "city": "TEXT",377        "phone": "TEXT",378        "website": "TEXT",379        "socials": "TEXT",        # JSON {instagram, facebook, x, linkedin…}380    },381}382383384def connect() -> sqlite3.Connection:385    DB_PATH.parent.mkdir(parents=True, exist_ok=True)386    con = sqlite3.connect(DB_PATH)387    con.row_factory = sqlite3.Row388    con.executescript(_SCHEMA)389    for table, cols in _MIGRATIONS.items():390        existing = {r["name"] for r in con.execute(f"PRAGMA table_info({table})")}391        for col, decl in cols.items():392            if col not in existing:393                con.execute(f"ALTER TABLE {table} ADD COLUMN {col} {decl}")394    # index sur des colonnes de migration : APRÈS les ALTER TABLE (une base395    # antérieure n'a pas encore la colonne au moment du CREATE INDEX)396    con.execute("CREATE UNIQUE INDEX IF NOT EXISTS users_ka_id ON users(ka_id)")397    con.execute("CREATE INDEX IF NOT EXISTS idx_listings_pub"398                " ON listings(active, published)")399    con.execute("CREATE INDEX IF NOT EXISTS idx_listings_coord"400                " ON listings(coord_key)")401    con.execute("CREATE INDEX IF NOT EXISTS idx_listings_bkey"402                " ON listings(building_key)")403    con.commit()404    # WAL : lectures (web) et écritures (sync, imgcheck) concurrentes sans405    # verrou global ; busy_timeout évite les « database is locked » ponctuels.406    con.execute("PRAGMA journal_mode=WAL")407    con.execute("PRAGMA busy_timeout=30000")408    return con409410411# ---------------------------------------------------------------------------412# Synchronisation d'une source413# ---------------------------------------------------------------------------414415def _drift_alert(con: sqlite3.Connection, source: str, found: int,416                 null_price_rate: float) -> str | None:417    """Détecte une dérive du connecteur (chute du volume ou des prix extraits).418419    Retourne un message d'alerte, ou None si tout est normal.420    """421    hist = con.execute(422        "SELECT found, stats FROM sync_log WHERE source=? AND ok=1"423        " ORDER BY ts DESC LIMIT ?", (source, DRIFT_HISTORY)).fetchall()424    if len(hist) < 3:425        return None426    med_found = statistics.median(r["found"] for r in hist)427    if med_found >= DRIFT_MIN_BASE and found <= DRIFT_RATIO * med_found:428        return (f"dérive: {found} annonce(s) trouvée(s) contre une médiane de "429                f"{med_found:.0f} — retraits suspendus, vérifier le connecteur")430    if found >= DRIFT_MIN_BASE and null_price_rate >= 0.8:431        rates = []432        for r in hist:433            try:434                rates.append(json.loads(r["stats"] or "{}")["null_price_rate"])435            except (KeyError, ValueError, TypeError):436                continue437        if rates and statistics.median(rates) <= 0.3:438            return (f"dérive: {null_price_rate:.0%} des annonces sans prix "439                    f"(habituellement {statistics.median(rates):.0%}) — "440                    "le format de la source a probablement changé")441    return None442443444def _j(v) -> str:445    return json.dumps(v, ensure_ascii=False)446447448def _log_events(con: sqlite3.Connection, uid: str, ts: float,449                old: sqlite3.Row, new: dict) -> None:450    """Journalise les changements observés d'une annonce (listing_events).451452    Le prix a déjà son historique dédié (price_log) — ici : description,453    superficie, disponibilité, inclusions, photos. Valeurs compactes (pas de454    texte intégral) : l'objectif est la timeline de la fiche, pas l'archive.455    """456    ev: list[tuple[str, str | None, str | None]] = []457    old_desc = (old["description"] or "").strip()458    new_desc = (new.get("description") or "").strip()459    if old_desc != new_desc and (old_desc or new_desc):460        ev.append(("description", _j({"caracteres": len(old_desc)}),461                   _j({"caracteres": len(new_desc)})))462    if (old["area_sqft"] or None) != (new.get("area_sqft") or None):463        ev.append(("superficie", _j(old["area_sqft"]), _j(new.get("area_sqft"))))464    if (old["availability_date"] or None) != (new.get("availability_date") or None):465        ev.append(("dispo", _j(old["availability_date"]),466                   _j(new.get("availability_date"))))467    try:468        inc_old = (json.loads(old["details"] or "{}") or {}).get("inclusions") or {}469        inc_new = (json.loads(new.get("details") or "{}") or {}).get("inclusions") or {}470    except (ValueError, TypeError):471        inc_old = inc_new = {}472    if inc_old != inc_new:473        keys = set(inc_old) | set(inc_new)474        diff_old = {k: inc_old.get(k) for k in keys if inc_old.get(k) != inc_new.get(k)}475        diff_new = {k: inc_new.get(k) for k in keys if inc_old.get(k) != inc_new.get(k)}476        if diff_old or diff_new:477            ev.append(("inclusions", _j(diff_old), _j(diff_new)))478    try:479        imgs_old = json.loads(old["images"] or "[]")480        imgs_new = json.loads(new.get("images") or "[]")481    except (ValueError, TypeError):482        imgs_old = imgs_new = []483    if set(imgs_old) != set(imgs_new):484        ev.append(("photos", _j({"n": len(imgs_old)}), _j({"n": len(imgs_new)})))485    if ev:486        con.executemany(487            "INSERT INTO listing_events (uid, ts, event, old, new)"488            " VALUES (?,?,?,?,?)",489            [(uid, ts, e, o, n) for e, o, n in ev])490491492def sync_source(con: sqlite3.Connection, source: str,493                listings: list[Listing]) -> dict:494    """Synchronise les annonces d'une source.495496    - nouvelle annonce  -> insertion497    - annonce modifiée  -> mise à jour (comparaison de content_hash)498    - annonce disparue  -> miss_count += 1, puis active=0 après MISS_GRACE499      exécutions consécutives (délai de grâce)500    - dérive détectée   -> alerte consignée, retraits suspendus501    """502    now = time.time()503    added = updated = 0504    seen_uids = set()505506    n = len(listings)507    null_price = sum(1 for l in listings if l.price is None)508    null_addr = sum(1 for l in listings if not l.address)509    null_price_rate = round(null_price / n, 3) if n else 0.0510511    alert = _drift_alert(con, source, n, null_price_rate)512513    for lst in listings:514        seen_uids.add(lst.uid)515        h = lst.content_hash()516        row = con.execute(517            "SELECT content_hash, price, images, description, area_sqft,"518            " availability_date, details, active FROM listings WHERE uid=?",519            (lst.uid,)).fetchone()520        # score de complétude + seuil de publication (quarantaine sous le seuil)521        from .quality import evaluate522        q_score, q_pub, q_reasons = evaluate({523            "title": lst.title,524            "price": lst.price, "address": lst.address, "city": lst.city,525            "sector": lst.sector, "lat": lst.lat, "lng": lst.lng,526            "description": lst.description, "images": lst.images,527            "unit_type": lst.unit_type, "bedrooms": lst.bedrooms,528            "bathrooms": lst.bathrooms, "availability": lst.availability,529            "availability_date": lst.availability_date,530            "area_sqft": lst.area_sqft, "amenities": lst.amenities,531            "details": lst.details, "url": lst.url,532            "province": getattr(lst, "province", None) or "QC"})533        params = dict(534            uid=lst.uid, source=lst.source, external_id=lst.external_id,535            url=lst.url, title=lst.title, address=lst.address,536            sector=lst.sector, city=lst.city,537            province=(getattr(lst, "province", None) or "QC"),538            unit_type=lst.unit_type,539            bedrooms=lst.bedrooms, bathrooms=lst.bathrooms,540            price=lst.price, price_label=lst.price_label,541            availability=lst.availability,542            availability_date=lst.availability_date,543            area_sqft=lst.area_sqft, pets=lst.pets,544            furnished=(None if lst.furnished is None else int(lst.furnished)),545            description=lst.description,546            digest=(json.dumps(lst.digest, ensure_ascii=False)547                    if getattr(lst, "digest", None) else None),548            amenities=json.dumps(lst.amenities, ensure_ascii=False),549            details=json.dumps(lst.details, ensure_ascii=False),550            images=json.dumps(lst.images, ensure_ascii=False),551            lat=lst.lat, lng=lst.lng, content_hash=h, now=now,552            completeness=q_score, published=int(q_pub),553            quality_reasons=(json.dumps(q_reasons, ensure_ascii=False)554                             if q_reasons else None),555        )556        if row is None:557            con.execute(558                """INSERT INTO listings (uid, source, external_id, url, title,559                   address, sector, city, province, unit_type, bedrooms,560                   bathrooms, price, price_label,561                   availability, availability_date, area_sqft, pets, furnished,562                   description, digest, amenities, details, images, lat, lng,563                   content_hash, first_seen, last_seen, updated_at,564                   miss_count, active, completeness, published,565                   quality_reasons)566                   VALUES (:uid,:source,:external_id,:url,:title,:address,567                   :sector,:city,:province,:unit_type,:bedrooms,:bathrooms,568                   :price,:price_label,:availability,569                   :availability_date,:area_sqft,:pets,:furnished,570                   :description,:digest,:amenities,:details,:images,:lat,:lng,571                   :content_hash,:now,:now,:now,0,1,572                   :completeness,:published,:quality_reasons)""", params)573            if lst.price is not None:   # prix initial = point de départ de l'historique574                con.execute("INSERT INTO price_log (uid, ts, price) VALUES (?,?,?)",575                            (lst.uid, now, lst.price))576            added += 1577        elif row["content_hash"] != h:578            # COALESCE : ne jamais écraser des coordonnées géocodées par null579            con.execute(580                """UPDATE listings SET url=:url, title=:title,581                   address=:address, sector=:sector, city=:city,582                   province=:province,583                   unit_type=:unit_type, bedrooms=:bedrooms,584                   bathrooms=:bathrooms, price=:price,585                   price_label=:price_label, availability=:availability,586                   availability_date=:availability_date,587                   area_sqft=:area_sqft, pets=:pets, furnished=:furnished,588                   description=:description, digest=:digest,589                   amenities=:amenities, details=:details, images=:images,590                   lat=COALESCE(:lat, lat), lng=COALESCE(:lng, lng),591                   content_hash=:content_hash, last_seen=:now,592                   updated_at=:now, miss_count=0, active=1,593                   completeness=:completeness, published=:published,594                   quality_reasons=:quality_reasons595                   WHERE uid=:uid""", params)596            if (row["images"] or "[]") != params["images"]:597                # galerie modifiée : invalider l'audit d'images (imgcheck.py)598                con.execute("UPDATE listings SET images_ok=NULL, img_audit=NULL"599                            " WHERE uid=?", (lst.uid,))600            if lst.price != row["price"]:   # changement de prix -> historique601                con.execute("INSERT INTO price_log (uid, ts, price) VALUES (?,?,?)",602                            (lst.uid, now, lst.price))603            # timeline de la fiche : changements observés (hors prix)604            _log_events(con, lst.uid, now, row, params)605            if not row["active"]:606                con.execute("INSERT INTO listing_events (uid, ts, event, old, new)"607                            " VALUES (?,?,?,?,?)",608                            (lst.uid, now, "reapparition", None, None))609            updated += 1610        else:611            if not row["active"]:612                con.execute("INSERT INTO listing_events (uid, ts, event, old, new)"613                            " VALUES (?,?,?,?,?)",614                            (lst.uid, now, "reapparition", None, None))615            con.execute(616                "UPDATE listings SET last_seen=?, miss_count=0, active=1 WHERE uid=?",617                (now, lst.uid))618619    # Annonces de cette source qui n'apparaissent plus : délai de grâce,620    # puis désactivation. Suspendu si une dérive est détectée.621    removed = missed = 0622    if not alert:623        for r in con.execute(624                "SELECT uid, miss_count FROM listings WHERE source=? AND active=1",625                (source,)).fetchall():626            if r["uid"] in seen_uids:627                continue628            missed += 1629            if r["miss_count"] + 1 >= MISS_GRACE:630                con.execute(631                    "UPDATE listings SET active=0, miss_count=?, updated_at=?"632                    " WHERE uid=?", (r["miss_count"] + 1, now, r["uid"]))633                con.execute("INSERT INTO listing_events (uid, ts, event, old, new)"634                            " VALUES (?,?,?,?,?)",635                            (r["uid"], now, "disparition", None, None))636                removed += 1637            else:638                con.execute("UPDATE listings SET miss_count=miss_count+1 WHERE uid=?",639                            (r["uid"],))640641    stats = {642        "null_price_rate": null_price_rate,643        "null_address_rate": round(null_addr / n, 3) if n else 0.0,644        "missed": missed,645    }646    if alert:647        stats["alert"] = alert648    con.execute(649        "INSERT INTO sync_log (source, ts, found, added, updated, removed, ok,"650        " message, stats) VALUES (?,?,?,?,?,?,1,?,?)",651        (source, now, n, added, updated, removed, alert or "ok",652         json.dumps(stats, ensure_ascii=False)))653    con.commit()654    out = {"source": source, "found": n, "added": added,655           "updated": updated, "removed": removed}656    if alert:657        out["alert"] = alert658    return out659660661def log_failure(con: sqlite3.Connection, source: str, message: str) -> None:662    con.execute(663        "INSERT INTO sync_log (source, ts, found, added, updated, removed, ok, message)"664        " VALUES (?,?,0,0,0,0,0,?)", (source, time.time(), message))665    con.commit()666667668# ---------------------------------------------------------------------------669# Cache des pages détail (« détail si nouveau/modifié »)670# ---------------------------------------------------------------------------671672def get_cached_detail(con: sqlite3.Connection, source: str,673                      external_id: str, key: str) -> dict | None:674    """Payload détail mis en cache si la clé (hash liste) n'a pas changé."""675    row = con.execute(676        "SELECT key, payload FROM detail_cache WHERE source=? AND external_id=?",677        (source, external_id)).fetchone()678    if row and row["key"] == key and row["payload"]:679        try:680            return json.loads(row["payload"])681        except ValueError:682            return None683    return None684685686def put_cached_detail(con: sqlite3.Connection, source: str,687                      external_id: str, key: str, payload: dict) -> None:688    con.execute(689        "INSERT INTO detail_cache (source, external_id, key, payload, fetched_at)"690        " VALUES (?,?,?,?,?)"691        " ON CONFLICT(source, external_id) DO UPDATE SET"692        " key=excluded.key, payload=excluded.payload, fetched_at=excluded.fetched_at",693        (source, external_id, key, json.dumps(payload, ensure_ascii=False),694         time.time()))695    con.commit()696
Files main
Menu

Theme