SPB Git

Repository Public

stats.py 53.2 KB 1,182 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/stats.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1713# Last Modified    : 2026-08-2414#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# Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# stats.py : tableau de bord analytique /api/stats/dashboard + rapport PDF91#   /api/stats/report. Toutes les valeurs viennent de la base92#   (listings, price_log, sync_log) — AUCUNE statistique inventée : une93#   mesure indisponible est simplement omise (le front affiche un état vide).94#   v2 : sparklines KPI, jauges (géolocalisation, photos, publiable),95#   multi-courbes (prix médian par type / grande ville), barres empilées96#   (nouvelles inscriptions par bannière), distributions (prix, superficie,97#   année de construction), heatmap horaire 7×24, tableaux quarantaine &98#   bannières, records enrichis.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import json103import statistics104import threading105import time106import unicodedata107from datetime import date, datetime, timedelta108from pathlib import Path109from zoneinfo import ZoneInfo110111from . import db112from . import public, villes113from .public import PUBLIC_EVER114115TZ = ZoneInfo("America/Toronto")116SQFT_PER_M2 = 10.7639104117ROOT = Path(__file__).resolve().parent.parent118SOURCES_PATH = ROOT / "data" / "sources.json"119120# Position vs estimation Vrai-Prix (mêmes seuils que le fair value Lou-Ka) :121# sous le marché si écart <= -8 %, au-dessus si >= +8 % ; les écarts hors122# (-50 %, +100 %) sont presque toujours des erreurs de lecture -> ignorés.123FV_SEUIL_SOUS = public.VP_SOUS / 100.0124FV_SEUIL_SUR = public.VP_SUR / 100.0125FV_DEV_BOUNDS = (public.VP_BOUNDS[0] / 100.0, public.VP_BOUNDS[1] / 100.0)126# bornes de plausibilité des prix de vente résidentiels (journal de prix) :127# les écarts extrêmes sont des erreurs de source, pas de vraies baisses.128PRICE_MIN, PRICE_MAX = 25_000, 50_000_000129130# Même règle de visibilité que le reste de l'API (immoka/public.py).131# Sans la condition « active » : chaque requête la pose elle-même (active=1 pour132# l'inventaire, active=0 pour les retraits). Avec PUBLIC tel quel, toutes les133# mesures sur les retraits étaient vides (délai par ville, retraits, tension).134VISIBLE = " AND " + PUBLIC_EVER135136PERIOD_LABELS = {137    "auj": "Aujourd'hui", "7j": "7 jours", "30j": "30 jours",138    "3m": "3 mois", "6m": "6 mois", "12m": "12 mois",139    "annee": "Année en cours", "tout": "Toute la période",140}141142# --- cache serveur (>= 5 min par période, contrat SPEC) -----------------------143_CACHE: dict[str, tuple[float, dict]] = {}144_CACHE_TTL = 300145_CACHE_LOCK = threading.Lock()146_KEY_LOCKS: dict[str, threading.Lock] = {}147148149# --- utilitaires --------------------------------------------------------------150def _today() -> date:151    return datetime.now(TZ).date()152153154def _iso(d: date) -> str:155    return d.isoformat()156157158def _parse(d: str) -> date | None:159    try:160        return date.fromisoformat(d[:10])161    except (ValueError, TypeError):162        return None163164165# autres écritures acceptées pour une période166_PERIOD_ALIASES = {"90j": "3m", "180j": "6m", "365j": "12m", "1a": "12m", "an": "12m"}167168169def _epoch(d: date) -> float:170    """Minuit local (heure de l'Est) du jour donné, en epoch."""171    return datetime(d.year, d.month, d.day, tzinfo=TZ).timestamp()172173174def resolve_period(period: str | None, frm: str | None, to: str | None,175                   data_start: date) -> tuple[date, date, str]:176    today = _today()177    f, t = _parse(frm or ""), _parse(to or "")178    if f and t:179        if t < f:180            f, t = t, f181        return f, t, f"{_iso(f)} → {_iso(t)}"182    p = (period or "30j").lower()183    p = _PERIOD_ALIASES.get(p, p)184    spans = {"7j": 6, "30j": 29, "3m": 89, "6m": 181, "12m": 364}185    if p == "auj":186        return today, today, PERIOD_LABELS["auj"]187    if p == "annee":188        return date(today.year, 1, 1), today, PERIOD_LABELS["annee"]189    if p == "tout":190        return data_start, today, PERIOD_LABELS["tout"]191    days = spans.get(p, 29)192    label = PERIOD_LABELS.get(p, PERIOD_LABELS["30j"])193    return today - timedelta(days=days), today, label194195196def _v(raw) -> str:197    """Ville normalisée (immoka/villes.py)."""198    return villes.label(raw or "")199200201def _by_ville(rows) -> dict[str, int]:202    out: dict[str, int] = {}203    for r in rows:204        v = _v(r["city"])205        if v:206            out[v] = out.get(v, 0) + r["n"]207    return out208209210def _fold(s: str) -> str:211    return "".join(c for c in unicodedata.normalize("NFKD", s.lower().strip())212                   if not unicodedata.combining(c))213214215def _median(vals: list[float]) -> float | None:216    # défensif : la DB peut contenir des prix NULL — on les écarte217    vals = [v for v in vals if isinstance(v, (int, float))]218    return statistics.median(vals) if vals else None219220221def _fmt_money(v: float) -> str:222    return f"{round(v):,}".replace(",", " ") + " $"223224225def _fmt_pct(cur: float, prev: float) -> float | None:226    if prev <= 0:227        return None228    return round((cur - prev) / prev * 100.0, 1)229230231def _daterange(a: date, b: date):232    d = a233    while d <= b:234        yield d235        d += timedelta(days=1)236237238def _source_names() -> dict[str, str]:239    """id -> nom lisible depuis data/sources.json (repli : id brut)."""240    try:241        reg = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]242        return {s["id"]: s.get("name") or s["id"] for s in reg}243    except (OSError, ValueError, KeyError, TypeError):244        return {}245246247# Familles de connecteurs (mêmes règles que web._FRANCHISES — dupliquées ici248# pour éviter l'import circulaire web ⇄ stats)249_FAMILLES = [250    ("RE/MAX", lambda s: s == "remax_quebec" or s.startswith("remax_ag_")),251    ("Via Capitale", lambda s: s == "via_capitale" or s.startswith("via_ag_")),252    ("Century 21", lambda s: s == "century21" or s.startswith("c21_ag_")),253    ("Royal LePage", lambda s: s == "royal_lepage"),254    ("Groupe Sutton", lambda s: s == "sutton"),255    ("Keller Williams", lambda s: s.startswith("kw_")),256    ("DuProprio", lambda s: s == "duproprio"),257    ("Vendre.ca", lambda s: s == "vendre_ag_ca"),258]259260261def _famille_of(source: str, names: dict[str, str]) -> str:262    for name, match in _FAMILLES:263        if match(source):264            return name265    return names.get(source, source)266267268def _downsample(pts: list[dict], keep: int = 40) -> list[dict]:269    """Réduit une série de points {t,v} à <= keep points (sparklines)."""270    if len(pts) <= keep:271        return pts272    step = (len(pts) - 1) / (keep - 1)273    return [pts[round(i * step)] for i in range(keep)]274275276# Libellés lisibles des motifs de quarantaine/anomalies (quality.py)277_MOTIFS_QUALITE = {278    "quarantaine": "Sous le seuil de publication",279    "sans_image": "Sans image (secours affiché)",280    "prix_hors_bornes": "Prix hors bornes",281    "superficie_improbable": "Superficie improbable",282    "terrain_improbable": "Terrain improbable",283    "chambres_improbables": "Chambres improbables",284    "sdb_improbables": "Salles de bain improbables",285    "chambres_vs_type": "Chambres vs type incohérents",286    "annee_invalide": "Année de construction invalide",287    "prix_pi2_extreme": "Prix au pi² extrême",288}289290291# --- calcul du tableau de bord ------------------------------------------------292def _compute(frm_q: str | None, to_q: str | None, period: str | None) -> dict:293    con = db.connect()294    try:295        return _compute_con(con, frm_q, to_q, period)296    finally:297        con.close()298299300def _compute_con(con, frm_q, to_q, period) -> dict:301    today = _today()302    row = con.execute("SELECT MIN(first_seen) m FROM listings").fetchone()303    data_start = (datetime.fromtimestamp(row["m"], TZ).date()304                  if row and row["m"] else today)305306    # Le premier jour d'observation (2026-08-12) a vu entrer tout l'inventaire307    # d'un coup : ces ~58 000 inscriptions ne sont pas des « nouvelles ». Toutes308    # les mesures de nouveautés (first_seen) partent du lendemain.309    obs_min = _epoch(data_start + timedelta(days=1))310    con.create_function("obs_min", 0, lambda: obs_min, deterministic=True)311312    frm, to, label = resolve_period(period, frm_q, to_q, data_start)313    to = min(to, today)314    # fenêtre observée : la collecte a commencé le data_start — les séries315    # sont bornées à ce qui a réellement été mesuré (rien d'extrapolé).316    s_frm = max(frm, data_start)317    s_to = max(to, s_frm)318    ep_frm, ep_to = _epoch(s_frm), _epoch(s_to + timedelta(days=1))319    ndays = (s_to - s_frm).days + 1320    # période précédente de même longueur (pour les deltas)321    p_frm, p_to = s_frm - timedelta(days=ndays), s_frm - timedelta(days=1)322    # deltas seulement si la période précédente a été observée EN ENTIER —323    # comparer à une fenêtre tronquée fausserait les variations.324    prev_ok = p_frm >= data_start325    ep_pfrm, ep_pto = _epoch(p_frm), _epoch(p_to + timedelta(days=1))326327    # ---- reconstruction « annonces actives par jour » (événements) ----------328    actives_by_day: dict[str, int] = {}329    deltas: dict[date, int] = {}330    for r in con.execute(331            "SELECT date(first_seen,'unixepoch','localtime') fs,"332            " date(last_seen,'unixepoch','localtime') ls, active"333            " FROM listings WHERE 1=1" + VISIBLE):334        d0 = _parse(r["fs"])335        if d0 is None:336            continue337        deltas[d0] = deltas.get(d0, 0) + 1338        if not r["active"]:339            d1 = (_parse(r["ls"]) or d0) + timedelta(days=1)340            deltas[d1] = deltas.get(d1, 0) - 1341    run = 0342    for d in _daterange(data_start, today):343        run += deltas.get(d, 0)344        actives_by_day[_iso(d)] = run345346    # ---- KPI -----------------------------------------------------------------347    snap = con.execute(348        "SELECT COUNT(*) n, AVG(price) avg_p,"349        " 0 cities"350        " FROM listings WHERE active=1" + VISIBLE).fetchone()351    prices = [r["price"] for r in con.execute(352        "SELECT price FROM listings WHERE active=1" + VISIBLE)]353    med_price = _median(prices)354    ppm2 = [r["v"] for r in con.execute(355        "SELECT price/(area_sqft/" + str(SQFT_PER_M2) + ") v FROM listings"356        " WHERE active=1 AND area_sqft>=200" + VISIBLE)]357    med_ppm2 = _median(ppm2)358    n_ppm2 = len(ppm2)359360    new_cur = con.execute(361        "SELECT COUNT(*) n FROM listings WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?"362        + VISIBLE, (ep_frm, ep_to)).fetchone()["n"]363    new_prev = con.execute(364        "SELECT COUNT(*) n FROM listings WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?"365        + VISIBLE, (ep_pfrm, ep_pto)).fetchone()["n"] if prev_ok else 0366    gone_cur = con.execute(367        "SELECT COUNT(*) n FROM listings WHERE active=0 AND last_seen>=?"368        " AND last_seen<?" + VISIBLE, (ep_frm, ep_to)).fetchone()["n"]369    gone_prev = con.execute(370        "SELECT COUNT(*) n FROM listings WHERE active=0 AND last_seen>=?"371        " AND last_seen<?" + VISIBLE, (ep_pfrm, ep_pto)).fetchone()["n"] if prev_ok else 0372    conn_cur = con.execute(373        "SELECT COUNT(DISTINCT source) n FROM sync_log WHERE ok=1 AND ts>=?"374        " AND ts<?", (ep_frm, ep_to)).fetchone()["n"]375376    act_now = snap["n"]377    act_prev = actives_by_day.get(_iso(p_to)) if prev_ok else None378379    def kpi(id_, lbl, val, unit="", dpct=None):380        k = {"id": id_, "label": lbl, "value": val, "unit": unit}381        if dpct is not None:382            k["delta_pct"] = dpct383            k["direction"] = "up" if dpct >= 0 else "down"384        return k385386    kpis = [387        kpi("actives", "Annonces actives", act_now, "",388            _fmt_pct(act_now, act_prev) if act_prev else None),389        kpi("nouvelles", "Nouvelles annonces (période)", new_cur, "",390            _fmt_pct(new_cur, new_prev) if prev_ok and new_prev else None),391        kpi("retirees", "Vendues / retirées (période)", gone_cur, "",392            _fmt_pct(gone_cur, gone_prev) if prev_ok and gone_prev else None),393    ]394    if snap["avg_p"]:395        kpis.append(kpi("prix_moyen", "Prix moyen demandé",396                        round(snap["avg_p"]), "$"))397    if med_price:398        kpis.append(kpi("prix_median", "Prix médian demandé",399                        round(med_price), "$"))400    if med_ppm2 and n_ppm2 >= 100:401        kpis.append(kpi("prix_m2",402                        f"Prix médian au m² ({n_ppm2:,} annonces avec superficie)".replace(",", " "),403                        round(med_ppm2), "$/m²"))404    # prix au pi² déclaré à la source (details.prix_pi2) — médiane405    ppi2 = [r["v"] for r in con.execute(406        "SELECT CAST(json_extract(details,'$.prix_pi2') AS REAL) v"407        " FROM listings WHERE active=1" + VISIBLE +408        " AND CAST(json_extract(details,'$.prix_pi2') AS REAL)"409        " BETWEEN 30 AND 10000")]410    med_ppi2 = _median(ppi2)411    if med_ppi2 and len(ppi2) >= 100:412        kpis.append(kpi(413            "prix_pi2",414            f"Prix médian au pi² ({len(ppi2):,} annonces le déclarant)".replace(",", " "),415            round(med_ppi2), "$/pi²"))416    # jours sur le marché (annonces actives) — médiane depuis first_seen417    now_ts = time.time()418    dom = [max((now_ts - r["fs"]) / 86400.0, 0.0) for r in con.execute(419        "SELECT first_seen fs FROM listings WHERE active=1" + VISIBLE)]420    med_dom = _median(dom)421    if med_dom is not None and dom:422        kpis.append(kpi("jours_marche", "Jours sur le marché (médiane, actives)",423                        round(med_dom, 1), "j"))424    # baisses de prix observées dans la période (journal price_log) —425    # une entrée par annonce, bornes de plausibilité (voir en tête de fichier)426    drops = con.execute(427        """SELECT l.city city, MAX(p1.price - p2.price) amt,428                  date(MAX(p2.ts),'unixepoch','localtime') dt429           FROM price_log p1430           JOIN price_log p2 ON p2.uid = p1.uid AND p2.ts > p1.ts431           JOIN listings l ON l.uid = p1.uid432           WHERE p2.ts>=? AND p2.ts<? AND p2.price < p1.price433             AND p1.price BETWEEN ? AND ? AND p2.price BETWEEN ? AND ?434             AND p2.price >= p1.price * 0.5 AND l.dup_hidden=0 AND l.published=1435           GROUP BY l.uid ORDER BY amt DESC""",436        (ep_frm, ep_to, PRICE_MIN, PRICE_MAX, PRICE_MIN, PRICE_MAX)).fetchall()437    kpis.append(kpi("baisses_prix", "Baisses de prix observées (période)",438                    len(drops)))439    # qualité des données (quality.py) : score moyen + quarantaine440    qual = con.execute(441        "SELECT ROUND(AVG(quality_score),1) c FROM listings WHERE active=1"442        + VISIBLE).fetchone()443    quar = con.execute(444        "SELECT COUNT(*) n FROM listings"445        " WHERE active=1 AND dup_hidden=0 AND published=0").fetchone()["n"]446    if qual["c"] is not None:447        kpis.append(kpi("qualite", "Score de qualité moyen des fiches",448                        qual["c"], "/100"))449        kpis.append(kpi("quarantaine", "Annonces en quarantaine (qualité)",450                        quar))451    # position des prix vs estimation Vrai-Prix (juste valeur) — un seul452    # balayage réutilisé par le KPI, l'anneau et le tableau par ville453    fv_rows = con.execute(454        f"SELECT city, price, {public.VP_VALUE_SQL} vp, {public.VP_LOW_SQL} lo,"455        f" {public.VP_HIGH_SQL} hi"456        " FROM listings WHERE active=1" + VISIBLE +457        f" AND {public.VP_VALUE_SQL} > 0"458        " AND price BETWEEN ? AND ?", (PRICE_MIN, PRICE_MAX)).fetchall()459    fv_sous = fv_marche = fv_sur = 0460    fv_city: dict[str, list[float]] = {}461    for r in fv_rows:462        # la règle unique du verdict (immoka/public.py), écart en fraction463        pct, verdict = public.verdict(r["price"], r["vp"], r["lo"], r["hi"])464        if verdict is None:465            continue466        dev = pct / 100.0467        if verdict == "sous":468            fv_sous += 1469        elif verdict == "sur":470            fv_sur += 1471        else:472            fv_marche += 1473        if _v(r["city"]):474            fv_city.setdefault(_v(r["city"]), []).append(dev)475    fv_n = fv_sous + fv_marche + fv_sur476    if fv_n:477        kpis.append(kpi("sous_marche", "Annonces sous l'estimation Vrai-Prix",478                        fv_sous))479    kpis.append(kpi("villes", "Villes couvertes", len(villes.index()["by_label"])))480    kpis.append(kpi("connecteurs", "Connecteurs actifs (période)", conn_cur))481    # indice de tension : retraits / nouvelles entrées (mesuré, pas modélisé)482    if new_cur >= 50:483        kpis.append(kpi("tension", "Tension — retraits / nouvelles",484                        round(100.0 * gone_cur / new_cur, 1), "%"))485486    # ---- jauges (v2) : couvertures mesurées sur les annonces publiées --------487    gauges: list[dict] = []488    if act_now:489        g_geo = con.execute(490            "SELECT COUNT(*) n FROM listings WHERE active=1"491            " AND lat IS NOT NULL AND lng IS NOT NULL" + VISIBLE).fetchone()["n"]492        g_photo = con.execute(493            "SELECT COUNT(*) n FROM listings WHERE active=1"494            " AND images IS NOT NULL AND images<>'' AND images<>'[]'"495            + VISIBLE).fetchone()["n"]496        g_vp = con.execute(497            "SELECT COUNT(*) n FROM listings WHERE active=1" + VISIBLE +498            " AND CAST(json_extract(vraiprix,'$.value') AS REAL) > 0"499        ).fetchone()["n"]500        gauges.append({"id": "geoloc", "label": "Fiches géolocalisées",501                       "value": round(100.0 * g_geo / act_now, 1),502                       "max": 100, "unit": "%"})503        gauges.append({"id": "photos", "label": "Fiches avec photos",504                       "value": round(100.0 * g_photo / act_now, 1),505                       "max": 100, "unit": "%"})506        if g_vp:507            gauges.append({"id": "vraiprix",508                           "label": "Fiches avec estimation Vrai-Prix",509                           "value": round(100.0 * g_vp / act_now, 1),510                           "max": 100, "unit": "%"})511    act_all = con.execute(512        "SELECT COUNT(*) n FROM listings WHERE active=1 AND dup_hidden=0"513    ).fetchone()["n"]514    if act_all:515        gauges.append({"id": "publiable",516                       "label": "Hors quarantaine (qualité publiable)",517                       "value": round(100.0 * (act_all - quar) / act_all, 1),518                       "max": 100, "unit": "%"})519    if qual["c"] is not None:520        gauges.append({"id": "completude",521                       "label": "Complétude moyenne des fiches (0–100)",522                       "value": qual["c"], "max": 100})523524    # ---- séries quotidiennes ---------------------------------------------------525    days = [_iso(d) for d in _daterange(s_frm, s_to)]526    new_by_day = {r["d"]: r["n"] for r in con.execute(527        "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"528        " FROM listings WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE +529        " GROUP BY d", (ep_frm, ep_to))}530    gone_by_day = {r["d"]: r["n"] for r in con.execute(531        "SELECT date(last_seen,'unixepoch','localtime') d, COUNT(*) n"532        " FROM listings WHERE active=0 AND last_seen>=? AND last_seen<?"533        + VISIBLE + " GROUP BY d", (ep_frm, ep_to))}534    series = []535    if len(days) >= 2:536        series = [537            {"id": "actives", "title": "Annonces actives par jour",538             "unit": "annonces", "kind": "line",539             "points": [{"t": d, "v": actives_by_day.get(d, 0)} for d in days]},540            {"id": "nouvelles", "title": "Nouvelles annonces par jour",541             "unit": "annonces", "kind": "bar",542             "points": [{"t": d, "v": new_by_day.get(d, 0)} for d in days]},543            {"id": "retraits", "title": "Retraits (vendues / retirées) par jour",544             "unit": "annonces", "kind": "bar",545             "points": [{"t": d, "v": gone_by_day.get(d, 0)} for d in days]},546        ]547        # prix médian demandé des nouvelles inscriptions (jours à >= 3 entrées548        # seulement — rien d'interpolé, l'axe saute les jours creux)549        med_day: list[dict] = []550        day_prices: dict[str, list[float]] = {}551        for r in con.execute(552                "SELECT date(first_seen,'unixepoch','localtime') d, price"553                " FROM listings WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE +554                " AND price BETWEEN ? AND ?",555                (ep_frm, ep_to, PRICE_MIN, PRICE_MAX)):556            day_prices.setdefault(r["d"], []).append(r["price"])557        for d in days:558            ps = day_prices.get(d)559            if ps and len(ps) >= 3:560                med_day.append({"t": d, "v": round(statistics.median(ps))})561        if len(med_day) >= 5:562            series.append({563                "id": "prix_median_nouvelles",564                "title": "Prix médian demandé des nouvelles inscriptions"565                         " (jours à ≥ 3 entrées)",566                "unit": "$", "kind": "area", "points": med_day})567        # comparaison période précédente (même longueur) : seulement si elle568        # a réellement été observée en entier (rien d'extrapolé)569        if prev_ok:570            pdays = [_iso(d) for d in _daterange(p_frm, p_to)]571            series[0]["compare"] = [{"t": d, "v": actives_by_day.get(d, 0)}572                                    for d in pdays]573            cmp_new = {r["d"]: r["n"] for r in con.execute(574                "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"575                " FROM listings WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE +576                " GROUP BY d", (ep_pfrm, ep_pto))}577            series[1]["compare"] = [{"t": d, "v": cmp_new.get(d, 0)}578                                    for d in pdays]579580    # ---- sparklines des KPI (v2) — mêmes données que les séries ---------------581    if len(days) >= 2:582        conn_day = {r["d"]: r["n"] for r in con.execute(583            "SELECT date(ts,'unixepoch','localtime') d,"584            " COUNT(DISTINCT source) n FROM sync_log"585            " WHERE ok=1 AND ts>=? AND ts<? GROUP BY d", (ep_frm, ep_to))}586        sparks = {587            "actives": [{"t": d, "v": actives_by_day.get(d, 0)} for d in days],588            "nouvelles": [{"t": d, "v": new_by_day.get(d, 0)} for d in days],589            "retirees": [{"t": d, "v": gone_by_day.get(d, 0)} for d in days],590            "connecteurs": [{"t": d, "v": conn_day.get(d, 0)} for d in days],591        }592        for k in kpis:593            sp = sparks.get(k["id"])594            if sp and any(p["v"] for p in sp):595                k["spark"] = _downsample(sp)596597    # ---- multi-courbes (v2) : prix médian des nouvelles inscriptions ----------598    # Buckets quotidiens (<= 45 j) ou hebdomadaires ; un bucket n'est gardé que599    # si CHAQUE groupe y compte >= 3 inscriptions (axes alignés, rien d'inventé).600    def _multiserie(id_, title, group_sql, top_n):601        weekly = ndays > 45602        bucket_sql = ("strftime('%Y-%m-%d', first_seen, 'unixepoch',"603                      " 'localtime', 'weekday 1', '-6 days')" if weekly else604                      "date(first_seen,'unixepoch','localtime')")605        rows = con.execute(606            f"SELECT {group_sql} g, {bucket_sql} b, price FROM listings"607            " WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE +608            f" AND price BETWEEN ? AND ? AND {group_sql} <> ''",609            (ep_frm, ep_to, PRICE_MIN, PRICE_MAX)).fetchall()610        vol: dict[str, int] = {}611        data: dict[str, dict[str, list[float]]] = {}612        for r in rows:613            if "/" in r["g"]:       # libellés composites de sources ("Laval /614                continue            # North Shore") — bruit, pas une vraie ville615            vol[r["g"]] = vol.get(r["g"], 0) + 1616            data.setdefault(r["g"], {}).setdefault(r["b"], []).append(r["price"])617        groups = [g for g, _ in sorted(vol.items(), key=lambda kv: -kv[1])[:top_n]]618        if len(groups) < 2:619            return None620        buckets = sorted({b for g in groups for b in data[g]621                          if all(len(data[gg].get(b, [])) >= 3 for gg in groups)})622        if len(buckets) < 4:623            return None624        return {"id": id_, "title": title + (" (semaines)" if weekly else ""),625                "unit": "$",626                "series": [{"label": g, "points": [627                    {"t": b, "v": round(statistics.median(data[g][b]))}628                    for b in buckets]} for g in groups]}629630    multiseries = []631    ms_type = _multiserie(632        "prix_type", "Prix médian des nouvelles inscriptions par type",633        "property_type", 3)634    if ms_type:635        multiseries.append(ms_type)636    ms_ville = _multiserie(637        "prix_ville", "Prix médian des nouvelles inscriptions — grandes villes",638        "city", 4)639    if ms_ville:640        multiseries.append(ms_ville)641642    # ---- barres empilées (v2) : nouvelles inscriptions par bannière -----------643    names = _source_names()644    stacked = []645    if len(days) >= 2:646        weekly_st = ndays > 60647        bucket_st = ("strftime('%Y-%m-%d', first_seen, 'unixepoch',"648                     " 'localtime', 'weekday 1', '-6 days')" if weekly_st else649                     "date(first_seen,'unixepoch','localtime')")650        fam_day: dict[str, dict[str, int]] = {}651        fam_tot: dict[str, int] = {}652        for r in con.execute(653                f"SELECT source s, {bucket_st} b, COUNT(*) n FROM listings"654                " WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE +655                " GROUP BY source, b", (ep_frm, ep_to)):656            fam = _famille_of(r["s"], names)657            fam_day.setdefault(fam, {})658            fam_day[fam][r["b"]] = fam_day[fam].get(r["b"], 0) + r["n"]659            fam_tot[fam] = fam_tot.get(fam, 0) + r["n"]660        if fam_tot:661            top_fams = [f for f, _ in662                        sorted(fam_tot.items(), key=lambda kv: -kv[1])[:5]]663            others = [f for f in fam_day if f not in top_fams]664            keys = top_fams + (["Autres"] if others else [])665            buckets_st = sorted({b for d_ in fam_day.values() for b in d_})666            pts = []667            for b in buckets_st:668                vals = [fam_day[f].get(b, 0) for f in top_fams]669                if others:670                    vals.append(sum(fam_day[f].get(b, 0) for f in others))671                pts.append({"t": b, "values": vals})672            if len(pts) >= 2:673                stacked.append({674                    "id": "ajouts_bannieres",675                    "title": "Nouvelles inscriptions par bannière"676                             + (" (semaines)" if weekly_st else ""),677                    "unit": "inscriptions", "keys": keys, "points": pts})678679    # ---- distributions (v2) : prix, superficie, année de construction ---------680    distributions = []681    price_bins = [("< 100 k$", 0, 100e3)] + [682        (f"{i}00–{i+1}00 k$", i * 100e3, (i + 1) * 100e3) for i in range(1, 10)683    ] + [("1–1,5 M$", 1e6, 1.5e6), ("1,5–2 M$", 1.5e6, 2e6),684         ("2 M$ +", 2e6, None)]685    bins_p = []686    for lbl, lo, hi in price_bins:687        q = ("SELECT COUNT(*) n FROM listings WHERE active=1 AND price>=?"688             + VISIBLE)689        args: list = [lo]690        if hi is not None:691            q += " AND price<?"692            args.append(hi)693        bins_p.append({"label": lbl,694                       "value": con.execute(q, args).fetchone()["n"]})695    if sum(b["value"] for b in bins_p):696        distributions.append({697            "id": "prix", "unit": "annonces",698            "title": "Distribution des prix demandés (annonces actives)",699            "bins": bins_p})700    area_bins = [("< 500", 100, 500), ("500–1 000", 500, 1000),701                 ("1 000–1 500", 1000, 1500), ("1 500–2 000", 1500, 2000),702                 ("2 000–2 500", 2000, 2500), ("2 500–3 000", 2500, 3000),703                 ("3 000–4 000", 3000, 4000), ("4 000 +", 4000, 20000)]704    bins_a = [{"label": f"{lbl} pi²",705               "value": con.execute(706                   "SELECT COUNT(*) n FROM listings WHERE active=1"707                   " AND area_sqft>=? AND area_sqft<?" + VISIBLE,708                   (lo, hi)).fetchone()["n"]}709              for lbl, lo, hi in area_bins]710    if sum(b["value"] for b in bins_a) >= 100:711        distributions.append({712            "id": "superficie", "unit": "annonces",713            "title": "Distribution des superficies habitables (renseignées)",714            "bins": bins_a})715    yr_now = today.year716    year_bins = ([("< 1900", 1600, 1900), ("1900–1949", 1900, 1950)] +717                 [(f"{d}–{d+9}", d, d + 10) for d in range(1950, 2020, 10)] +718                 [("2020 +", 2020, yr_now + 2)])719    bins_y = [{"label": lbl,720               "value": con.execute(721                   "SELECT COUNT(*) n FROM listings WHERE active=1"722                   " AND year_built>=? AND year_built<?" + VISIBLE,723                   (lo, hi)).fetchone()["n"]}724              for lbl, lo, hi in year_bins]725    if sum(b["value"] for b in bins_y) >= 100:726        distributions.append({727            "id": "annee", "unit": "annonces",728            "title": "Distribution des années de construction (renseignées)",729            "bins": bins_y})730731    # ---- heatmap horaire (v2) : détection des nouvelles annonces (7×24) -------732    # first_seen = moment où la synchronisation a détecté l'annonce — c'est le733    # rythme réel d'alimentation de la plateforme (8 dernières semaines).734    h56 = _epoch(max(data_start, s_to - timedelta(days=55)))735    hourly_cells = [736        {"dow": (int(r["w"]) + 6) % 7, "hour": int(r["h"]), "value": r["n"]}737        for r in con.execute(738            "SELECT strftime('%w', first_seen,'unixepoch','localtime') w,"739            " strftime('%H', first_seen,'unixepoch','localtime') h, COUNT(*) n"740            " FROM listings WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE +741            " GROUP BY w, h", (h56, _epoch(s_to + timedelta(days=1))))]742    hourly = ({"title": "Détection de nouvelles annonces par heure"743                        " (8 dernières semaines)", "cells": hourly_cells}744              if len(hourly_cells) >= 12 else None)745746    # ---- répartitions (photo des annonces actives) -----------------------------747    types = [{"label": r["t"] or "Autre / non précisé", "value": r["n"]}748             for r in con.execute(749                 "SELECT property_type t, COUNT(*) n FROM listings"750                 " WHERE active=1" + VISIBLE +751                 " GROUP BY property_type ORDER BY n DESC LIMIT 9")]752    ranges = [("Moins de 200 k$", 0, 200e3), ("200 – 300 k$", 200e3, 300e3),753              ("300 – 400 k$", 300e3, 400e3), ("400 – 500 k$", 400e3, 500e3),754              ("500 – 750 k$", 500e3, 750e3), ("750 k$ – 1 M$", 750e3, 1e6),755              ("1 – 2 M$", 1e6, 2e6), ("2 M$ et plus", 2e6, None)]756    price_items = []757    for lbl, lo, hi in ranges:758        q = "SELECT COUNT(*) n FROM listings WHERE active=1 AND price>=?" + VISIBLE759        args: list = [lo]760        if hi is not None:761            q += " AND price<?"762            args.append(hi)763        price_items.append({"label": lbl,764                            "value": con.execute(q, args).fetchone()["n"]})765    # nouvelles inscriptions de la période par fourchette + delta honnête766    # (vs période précédente entièrement observée seulement)767    new_price_items = []768    for lbl, lo, hi in ranges:769        base = ("SELECT COUNT(*) n FROM listings WHERE first_seen>=?"770                " AND first_seen<? AND price>=?" + VISIBLE)771        args_c: list = [ep_frm, ep_to, lo]772        args_p: list = [ep_pfrm, ep_pto, lo]773        if hi is not None:774            base += " AND price<?"775            args_c.append(hi)776            args_p.append(hi)777        n_c = con.execute(base, args_c).fetchone()["n"]778        item = {"label": lbl, "value": n_c}779        if prev_ok:780            n_p = con.execute(base, args_p).fetchone()["n"]781            if n_p:782                item["delta_pct"] = _fmt_pct(n_c, n_p)783        new_price_items.append(item)784    beds = [{"label": ("8 chambres et +" if r["b"] >= 8785                       else f"{int(r['b'])} chambre" + ("s" if r["b"] > 1 else "")),786             "value": r["n"]}787            for r in con.execute(788                "SELECT MIN(bedrooms,8) b, COUNT(*) n FROM listings"789                " WHERE active=1 AND bedrooms IS NOT NULL" + VISIBLE +790                " GROUP BY MIN(bedrooms,8) ORDER BY b")]791    names = _source_names()792    by_source = [{"label": names.get(r["s"], r["s"]), "value": r["n"]}793                 for r in con.execute(794                     "SELECT source s, COUNT(*) n FROM listings"795                     " WHERE active=1" + VISIBLE +796                     " GROUP BY source ORDER BY n DESC LIMIT 12")]797    breakdowns = []798    if fv_n:799        breakdowns.append({800            "id": "fairvalue",801            "title": "Position des prix demandés vs estimation Vrai-Prix",802            "kind": "donut", "items": [803                {"label": "Sous le marché", "value": fv_sous},804                {"label": "Dans le marché", "value": fv_marche},805                {"label": "Au-dessus du marché", "value": fv_sur}]})806    breakdowns += [807        {"id": "types", "title": "Répartition par type de propriété",808         "kind": "donut", "items": types},809        {"id": "prix", "title": "Répartition par fourchette de prix demandé",810         "kind": "bar", "items": price_items},811    ]812    if sum(i["value"] for i in new_price_items):813        breakdowns.append({814            "id": "prix_nouvelles",815            "title": "Nouvelles inscriptions par fourchette de prix (période)",816            "kind": "bar", "items": new_price_items})817    if beds:818        breakdowns.append({"id": "chambres",819                           "title": "Répartition par nombre de chambres (renseignées)",820                           "kind": "bar", "items": beds})821    if by_source:822        breakdowns.append({"id": "sources",823                           "title": "Top sources (annonces actives)",824                           "kind": "bar", "items": by_source})825826    # ---- géographie : par région (fusion accents/casse, libellé le + fréquent)827    reg_counts: dict[str, dict[str, int]] = {}828    for r in con.execute(829            "SELECT region, COUNT(*) n FROM listings WHERE active=1"830            " AND region<>''" + VISIBLE + " GROUP BY region"):831        raw = (r["region"] or "").strip()832        key = _fold(raw)833        if not key or key.isdigit():834            continue835        reg_counts.setdefault(key, {})[raw] = reg_counts.get(key, {}).get(raw, 0) + r["n"]836    geo_items = []837    for key, variants in reg_counts.items():838        best_variant = max(variants, key=variants.get)839        geo_items.append({"label": best_variant, "value": sum(variants.values())})840    geo_items.sort(key=lambda x: -x["value"])841    geo = ({"title": "Annonces actives par région", "items": geo_items[:14]}842           if geo_items else None)843844    # ---- heatmap : nouvelles annonces par jour (26 dernières semaines max) ----845    h_frm = max(data_start, s_to - timedelta(days=181))846    hm = [{"date": r["d"], "value": r["n"]} for r in con.execute(847        "SELECT date(first_seen,'unixepoch','localtime') d, COUNT(*) n"848        " FROM listings WHERE first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE +849        " GROUP BY d", (_epoch(h_frm), _epoch(s_to + timedelta(days=1))))]850    heatmap = ({"title": "Nouvelles annonces par jour", "cells": hm}851               if len(hm) >= 2 else None)852853    # ---- tableaux ---------------------------------------------------------------854    # Top villes : actives, prix moyen/médian, nouvelles sur la période + delta855    city_prices: dict[str, list[float]] = {}856    for r in con.execute(857            "SELECT city, price FROM listings WHERE active=1 AND city<>''"858            + VISIBLE):859        if _v(r["city"]):860            city_prices.setdefault(_v(r["city"]), []).append(r["price"])861    new_city = _by_ville(con.execute(862        "SELECT city, COUNT(*) n FROM listings WHERE city<>''"863        " AND first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE + " GROUP BY city",864        (ep_frm, ep_to)))865    new_city_prev = _by_ville(con.execute(866        "SELECT city, COUNT(*) n FROM listings WHERE city<>''"867        " AND first_seen>=MAX(?, obs_min()) AND first_seen<?" + VISIBLE + " GROUP BY city",868        (ep_pfrm, ep_pto))) if prev_ok else {}869    gone_city = _by_ville(con.execute(870        "SELECT city, COUNT(*) n FROM listings WHERE active=0 AND city<>''"871        " AND last_seen>=? AND last_seen<?" + VISIBLE + " GROUP BY city",872        (ep_frm, ep_to)))873    top = sorted(city_prices.items(), key=lambda kv: -len(kv[1]))[:50]874    top_rows = []875    for city, ps in top:876        n_new = new_city.get(city, 0)877        n_prev = new_city_prev.get(city, 0)878        net = n_new - gone_city.get(city, 0)879        d = _fmt_pct(n_new, n_prev) if prev_ok and n_prev else None880        pn = [v for v in ps if isinstance(v, (int, float))]  # prix NULL écartés881        top_rows.append([882            city, len(ps),883            _fmt_money(sum(pn) / len(pn)) if pn else "—",884            _fmt_money(statistics.median(pn)) if pn else "—", n_new,885            f"{'+' if net >= 0 else ''}{net}",886            (f"{'+' if d >= 0 else ''}{str(d).replace('.', ',')} %"887             if d is not None else "—"),888        ])889    tables = [{890        "id": "top_villes", "title": "Top villes",891        "columns": ["Ville", "Actives", "Prix moyen", "Prix médian",892                    "Nouvelles (période)", "Δ net (période)", "Var. nouvelles"],893        "rows": top_rows,894    }]895    # Top sources : actives, prix moyen, nouvelles, qualité, quarantaine, synchro896    top_srcs = con.execute(897        """SELECT source s, COUNT(*) n,898                  AVG(CASE WHEN price>0 THEN price END) avg_p,899                  SUM(CASE WHEN first_seen>=MAX(?, obs_min()) AND first_seen<? THEN 1 ELSE 0 END) new_n,900                  ROUND(AVG(quality_score),0) qual901           FROM listings WHERE active=1""" + VISIBLE +902        " GROUP BY source ORDER BY n DESC LIMIT 50", (ep_frm, ep_to)).fetchall()903    quar_src = {r["s"]: r["n"] for r in con.execute(904        "SELECT source s, COUNT(*) n FROM listings"905        " WHERE active=1 AND dup_hidden=0 AND published=0 GROUP BY source")}906    last_sync = {r["source"]: r["ts"] for r in con.execute(907        "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 GROUP BY source")}908    if top_srcs:909        src_rows = []910        for r in top_srcs:911            ls = last_sync.get(r["s"])912            src_rows.append([913                names.get(r["s"], r["s"]), r["n"],914                _fmt_money(r["avg_p"]) if r["avg_p"] else "—",915                r["new_n"],916                f"{r['qual']:.0f} /100" if r["qual"] is not None else "—",917                quar_src.get(r["s"], 0),918                (datetime.fromtimestamp(ls, TZ).strftime("%Y-%m-%d %H:%M")919                 if ls else "—")])920        tables.append({921            "id": "top_sources", "title": "Top sources & courtiers",922            "columns": ["Source", "Annonces actives", "Prix moyen",923                        "Nouvelles (période)", "Qualité", "Quarantaine",924                        "Dernière synchro"],925            "rows": src_rows})926    # Délai de présence (retirées de la période) par ville927    dur_city: dict[str, list[float]] = {}928    for r in con.execute(929            "SELECT city, (last_seen-first_seen)/86400.0 d FROM listings"930            " WHERE active=0 AND city<>'' AND last_seen>=? AND last_seen<?"931            + VISIBLE, (ep_frm, ep_to)):932        if _v(r["city"]):933            dur_city.setdefault(_v(r["city"]), []).append(max(r["d"], 0.0))934    dur_rows = []935    for city, ds in sorted(dur_city.items(), key=lambda kv: -len(kv[1]))[:50]:936        if len(ds) < 3:937            continue938        dur_rows.append([939            city, len(ds),940            str(round(sum(ds) / len(ds), 1)).replace(".", ","),941            str(round(statistics.median(ds), 1)).replace(".", ","),942        ])943    if dur_rows:944        tables.append({945            "id": "delai_villes",946            "title": "Délai de présence avant retrait, par ville (période)",947            "columns": ["Ville", "Retirées", "Délai moyen (j)", "Délai médian (j)"],948            "rows": dur_rows,949        })950    # Écart moyen à l'estimation Vrai-Prix par ville (volume suffisant)951    fv_rows_city = []952    for city, devs in sorted(fv_city.items(), key=lambda kv: -len(kv[1]))[:25]:953        if len(devs) < 50:954            continue955        dev_pct = round(100.0 * sum(devs) / len(devs), 1)956        fv_rows_city.append([957            city, len(devs),958            f"{'+' if dev_pct >= 0 else ''}{str(dev_pct).replace('.', ',')} %",959            sum(1 for d in devs if d <= FV_SEUIL_SOUS)])960    if fv_rows_city:961        tables.append({962            "id": "fv_villes",963            "title": "Écart à l'estimation Vrai-Prix par ville",964            "columns": ["Ville", "Annonces évaluées", "Écart moyen",965                        "Sous le marché"],966            "rows": fv_rows_city})967    # Couche qualité : anomalies & quarantaine par motif (quality.py)968    anomalies: dict[str, int] = {}969    for r in con.execute(970            "SELECT quality_issues FROM listings WHERE active=1"971            " AND dup_hidden=0 AND quality_issues IS NOT NULL"):972        try:973            for issue in json.loads(r["quality_issues"]):974                key = issue.split(":")[0]975                anomalies[key] = anomalies.get(key, 0) + 1976        except ValueError:977            continue978    if anomalies and act_all:979        tables.append({980            "id": "quarantaine_motifs",981            "title": "Couche qualité — anomalies et quarantaine par motif",982            "columns": ["Motif", "Annonces touchées", "% des actives"],983            "rows": [[_MOTIFS_QUALITE.get(k, k), v,984                      str(round(100.0 * v / act_all, 1)).replace(".", ",") + " %"]985                     for k, v in sorted(anomalies.items(), key=lambda kv: -kv[1])],986        })987    # Bannières / familles de connecteurs : volume, nouvelles, prix, fraîcheur988    fam_info: dict[str, dict] = {}989    for r in con.execute(990            "SELECT source s, price p FROM listings WHERE active=1" + VISIBLE):991        e = fam_info.setdefault(_famille_of(r["s"], names),992                                {"srcs": set(), "prices": [], "new": 0,993                                 "sync": None})994        e["srcs"].add(r["s"])995        e["prices"].append(r["p"])996    for r in con.execute(997            "SELECT source s, COUNT(*) n FROM listings WHERE first_seen>=?"998            " AND first_seen<?" + VISIBLE + " GROUP BY source",999            (ep_frm, ep_to)):1000        fam = _famille_of(r["s"], names)1001        if fam in fam_info:1002            fam_info[fam]["new"] += r["n"]1003    for src, ts in last_sync.items():1004        fam = _famille_of(src, names)1005        if fam in fam_info:1006            e = fam_info[fam]1007            e["sync"] = max(e["sync"] or 0, ts)1008    if fam_info:1009        fam_rows = []1010        for fam, e in sorted(fam_info.items(),1011                             key=lambda kv: -len(kv[1]["prices"]))[:30]:1012            fam_rows.append([1013                fam, len(e["srcs"]), len(e["prices"]), e["new"],1014                (_fmt_money(statistics.median(pn))1015                 if (pn := [v for v in e["prices"]1016                            if isinstance(v, (int, float))]) else "—"),1017                (datetime.fromtimestamp(e["sync"], TZ).strftime("%Y-%m-%d %H:%M")1018                 if e["sync"] else "—")])1019        tables.append({1020            "id": "familles",1021            "title": "Bannières & familles de connecteurs",1022            "columns": ["Bannière / famille", "Connecteurs", "Annonces actives",1023                        "Nouvelles (période)", "Prix médian",1024                        "Dernière synchro"],1025            "rows": fam_rows})10261027    # ---- records & faits marquants ---------------------------------------------1028    records = []1029    if new_by_day:1030        best = max(new_by_day.items(), key=lambda kv: kv[1])1031        records.append({"label": "Jour record de nouvelles annonces",1032                        "value": f"{best[1]:,} annonces".replace(",", " "),1033                        "date": best[0]})1034    if gone_by_day:1035        worst = max(gone_by_day.items(), key=lambda kv: kv[1])1036        records.append({"label": "Jour record de retraits",1037                        "value": f"{worst[1]:,} annonces".replace(",", " "),1038                        "date": worst[0]})1039    fast = con.execute(1040        "SELECT city, address, (last_seen-first_seen)/86400.0 d,"1041        " date(last_seen,'unixepoch','localtime') dt FROM listings"1042        " WHERE active=0 AND last_seen>=? AND last_seen<?"1043        " AND last_seen-first_seen>=3600"           # >= 1 h : écarte les artefacts de sync1044        + VISIBLE + " ORDER BY (last_seen-first_seen) ASC LIMIT 1",1045        (ep_frm, ep_to)).fetchone()1046    if fast:1047        d = fast["d"]1048        val = (f"{round(d * 24, 1)} h" if d < 1 else f"{round(d, 1)} j").replace(".", ",")1049        records.append({"label": "Retrait le plus rapide (mise en ligne → retrait)",1050                        "value": val + (f" · {fast['city']}" if fast["city"] else ""),1051                        "date": fast["dt"]})1052    if drops:  # balayage price_log fait plus haut (KPI baisses_prix)1053        drop = drops[0]1054        records.append({"label": "Plus forte baisse de prix demandé",1055                        "value": "−" + _fmt_money(drop["amt"]) +1056                                 (f" · {drop['city']}" if drop["city"] else ""),1057                        "date": drop["dt"]})1058    if new_city:1059        c, n = max(new_city.items(), key=lambda kv: kv[1])1060        records.append({"label": "Ville la plus active (nouvelles annonces)",1061                        "value": f"{c} — {n:,} annonces".replace(",", " ")})1062    if top_srcs:1063        src = max(top_srcs, key=lambda r: r["new_n"])1064        if src["new_n"]:1065            records.append({"label": "Source la plus active (nouvelles annonces)",1066                            "value": f"{names.get(src['s'], src['s'])}"1067                                     f" — {src['new_n']:,}".replace(",", " ")})1068    top_price = con.execute(1069        "SELECT city, price FROM listings WHERE active=1" + VISIBLE +1070        " AND price BETWEEN ? AND ? ORDER BY price DESC LIMIT 1",1071        (PRICE_MIN, PRICE_MAX)).fetchone()1072    if top_price:1073        records.append({"label": "Inscription active la plus chère",1074                        "value": _fmt_money(top_price["price"]) +1075                                 (f" · {top_price['city']}"1076                                  if top_price["city"] else "")})1077    med_cities = {c: statistics.median(pn) for c, ps in city_prices.items()1078                  if len(pn := [v for v in ps1079                                if isinstance(v, (int, float))]) >= 30}1080    if med_cities:1081        c_hi = max(med_cities, key=med_cities.get)1082        c_lo = min(med_cities, key=med_cities.get)1083        records.append({"label": "Ville la plus chère (prix médian, ≥ 30 annonces)",1084                        "value": f"{c_hi} — {_fmt_money(med_cities[c_hi])}"})1085        records.append({"label": "Ville la plus abordable (prix médian, ≥ 30 annonces)",1086                        "value": f"{c_lo} — {_fmt_money(med_cities[c_lo])}"})1087    big_area = con.execute(1088        "SELECT city, area_sqft a FROM listings WHERE active=1" + VISIBLE +1089        " AND area_sqft BETWEEN 100 AND 50000"1090        " ORDER BY area_sqft DESC LIMIT 1").fetchone()1091    if big_area:1092        records.append({"label": "Plus grande superficie habitable (plausible)",1093                        "value": f"{round(big_area['a']):,} pi²".replace(",", " ") +1094                                 (f" · {big_area['city']}"1095                                  if big_area["city"] else "")})1096    if fam_info:1097        fam_big = max(fam_info.items(), key=lambda kv: len(kv[1]["srcs"]))1098        if len(fam_big[1]["srcs"]) > 1:1099            records.append({"label": "Bannière au plus grand réseau agrégé",1100                            "value": f"{fam_big[0]} — "1101                                     f"{len(fam_big[1]['srcs'])} connecteurs"})11021103    out = {1104        "updated": datetime.now(TZ).isoformat(timespec="seconds"),1105        # `from` = début RÉEL des données de la période (une période « 12 mois »1106        # demandée alors que l'observation a commencé il y a 3 mois commence au1107        # premier jour observé) ; `requested_from` = début demandé.1108        "period": {"from": _iso(s_frm), "to": _iso(to), "label": label,1109                   "requested_from": _iso(frm), "truncated": s_frm > frm,1110                   "days": ndays,1111                   "observed_from": _iso(data_start),1112                   "new_listings_from": _iso(data_start + timedelta(days=1))},1113        "kpis": kpis,1114        "series": series,1115        "breakdowns": breakdowns,1116        "tables": tables,1117        "records": records,1118    }1119    if gauges:1120        out["gauges"] = gauges1121    if multiseries:1122        out["multiseries"] = multiseries1123    if stacked:1124        out["stacked"] = stacked1125    if distributions:1126        out["distributions"] = distributions1127    if geo:1128        out["geo"] = geo1129    if heatmap:1130        out["heatmap"] = heatmap1131    if hourly:1132        out["hourly"] = hourly1133    try:1134        from . import statsextra, statsfiche1135        pnls = statsfiche.panels(con) + statsextra.panels(con)1136        if pnls:1137            out["panels"] = pnls1138    except Exception:1139        pass1140    return out114111421143def dashboard(period: str | None = None, frm: str | None = None,1144              to: str | None = None) -> dict:1145    key = f"{period or ''}|{frm or ''}|{to or ''}"1146    now = time.time()1147    with _CACHE_LOCK:1148        hit = _CACHE.get(key)1149        if hit and now - hit[0] < _CACHE_TTL:1150            return hit[1]1151        lock = _KEY_LOCKS.setdefault(key, threading.Lock())11521153    def _fill() -> dict:1154        data = _compute(frm, to, period)1155        with _CACHE_LOCK:1156            _CACHE[key] = (time.time(), data)1157            # garder le cache borné1158            if len(_CACHE) > 64:1159                for k in sorted(_CACHE, key=lambda k: _CACHE[k][0])[:32]:1160                    _CACHE.pop(k, None)1161                    _KEY_LOCKS.pop(k, None)1162        return data11631164    # Le calcul complet prend ~25 s sur 76 000 inscriptions. Valeur périmée1165    # (moins d'une journée) : on la sert tout de suite et UN fil la recalcule1166    # en arrière-plan. Aucune valeur : un seul fil calcule, les autres attendent.1167    if hit and now - hit[0] < 86400:1168        if lock.acquire(blocking=False):1169            def _bg():1170                try:1171                    _fill()1172                finally:1173                    lock.release()1174            threading.Thread(target=_bg, daemon=True).start()1175        return hit[1]1176    with lock:1177        with _CACHE_LOCK:1178            hit = _CACHE.get(key)1179        if hit and time.time() - hit[0] < _CACHE_TTL:1180            return hit[1]1181        return _fill()1182
Files main
Menu

Theme