SPB Git

Repository Public

web.py 53.5 KB 1,267 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/web.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-1213# Last Modified    : 2026-09-0714#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 maisons à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# web.py : API FastAPI (JSON) v2 autonome + service du frontend (frontend/dist)91# -----------------------------------------------------------------------------92from __future__ import annotations9394import json95import os96import threading97import time98from pathlib import Path99100from fastapi import Body, FastAPI, HTTPException, Query, Request101from fastapi.middleware.cors import CORSMiddleware102from fastapi.middleware.gzip import GZipMiddleware103from fastapi.responses import FileResponse, Response104from fastapi.staticfiles import StaticFiles105106from . import db, public, seo, villes107from .public import (PUBLIC, VP_CODES, VP_HIGH_SQL, VP_LOW_SQL,108                     VP_VALUE_SQL)109from . import stats as kastats110111ROOT = Path(__file__).resolve().parent.parent112SOURCES_PATH = ROOT / "data" / "sources.json"113# Frontend : build Vite (React) si présent, sinon la page statique de secours.114FRONTEND_DIST = ROOT / "frontend" / "dist"115FRONTEND_DIR = FRONTEND_DIST if FRONTEND_DIST.exists() else ROOT / "frontend"116117app = FastAPI(title="Immo-Ka API", version="2.0",118              description="Agrégateur de propriétés à vendre — province de Québec")119app.add_middleware(CORSMiddleware, allow_origins=["*"],120                   allow_methods=["*"], allow_headers=["*"])121# les points de la carte pèsent plusieurs Mo — la compression est vitale122app.add_middleware(GZipMiddleware, minimum_size=1024)123124# préproduction : jamais indexée (IMMOKA_NOINDEX=1 dans .env)125if os.environ.get("IMMOKA_NOINDEX") == "1":126    @app.middleware("http")127    async def _noindex(request: Request, call_next):128        resp = await call_next(request)129        resp.headers["X-Robots-Tag"] = "noindex, nofollow"130        return resp131132# annuaire des déménageurs du Québec133from . import demenageurs  # noqa: E402134app.include_router(demenageurs.router)135# annuaire des inspecteurs en bâtiment du Québec136from . import inspecteurs  # noqa: E402137app.include_router(inspecteurs.router)138# annuaire des bannières & courtiers (registre OACIQ)139from . import bannieres  # noqa: E402140app.include_router(bannieres.router)141# moteur hypothécaire — taux réels multibanques + calculateur canadien,142# voir immoka/mortgage/ (docs/mortgage-engine.md)143from .mortgage import api as mortgage_api  # noqa: E402144app.include_router(mortgage_api.router)145146# Une inscription est PUBLIQUE si elle est active, publiée (seuil de qualité147# de immoka/quality.py), sans doublon (dédup Centris + adresse, colonnes148# dup_hidden / dup_of pré-calculées par db.refresh_dedup) et au Québec.149# La règle vit dans immoka/public.py ; tous les endpoints l'appliquent,150# leurs totaux concordent. La fiche par uid reste accessible.151DEDUP_CLAUSE = " AND " + PUBLIC152153# --- Cache à un seul fil -------------------------------------------------------154# Les agrégats lourds (facettes, recherche, annuaire) sont calculés une fois155# puis servis de la mémoire. Un seul fil recalcule à l'expiration ; les autres156# requêtes reçoivent la valeur précédente au lieu de s'empiler sur SQLite.157_MEMO: dict[str, tuple[float, object]] = {}158_MEMO_LOCKS: dict[str, threading.Lock] = {}159_MEMO_GUARD = threading.Lock()160_MEMO_MAX = 96161162163def _memo(key: str, ttl: float, build):164    now = time.time()165    hit = _MEMO.get(key)166    if hit and now - hit[0] < ttl:167        return hit[1]168    with _MEMO_GUARD:169        lock = _MEMO_LOCKS.setdefault(key, threading.Lock())170    if not lock.acquire(blocking=hit is None):171        return hit[1]          # un autre fil recalcule : valeur précédente172    try:173        hit = _MEMO.get(key)174        if hit and time.time() - hit[0] < ttl:175            return hit[1]176        val = build()177        if len(_MEMO) >= _MEMO_MAX:      # purge des entrées les plus anciennes178            for k, _ in sorted(_MEMO.items(), key=lambda kv: kv[1][0])[:_MEMO_MAX // 4]:179                _MEMO.pop(k, None)180                _MEMO_LOCKS.pop(k, None)181        _MEMO[key] = (time.time(), val)182        return val183    finally:184        lock.release()185186187def _json(payload, status: int = 200) -> Response:188    """Réponse JSON sérialisée directement (les grosses réponses évitent le189    passage par jsonable_encoder de FastAPI, coûteux sur 70 000 points)."""190    return Response(json.dumps(payload, ensure_ascii=False, separators=(",", ":")),191                    media_type="application/json", status_code=status)192193194def _source_name(source: str | None) -> str:195    from . import lights as _lights196    return _lights.source_names().get(source or "", "") if source else ""197198199def _row_to_dict(row) -> dict:200    d = dict(row)201    d["features"] = json.loads(d.get("features") or "[]")202    d["images"] = json.loads(d.get("images") or "[]")203    d["details"] = json.loads(d.get("details") or "{}")204    if d.get("vraiprix"):205        try:206            d["vraiprix"] = json.loads(d["vraiprix"]) or None207        except (ValueError, TypeError):208            d["vraiprix"] = None209    # verdict Vrai-Prix : écart du prix demandé vs l'estimation (immoka/public.py)210    vp = d["vraiprix"] if isinstance(d.get("vraiprix"), dict) else {}211    dev, verdict = public.verdict(d.get("price"), vp.get("value"),212                                  vp.get("low"), vp.get("high"))213    d["vp_value"] = vp.get("value")214    d["vp_low"], d["vp_high"] = vp.get("low"), vp.get("high")215    d["vp_deviation"], d["vp_verdict"] = dev, verdict216    # l'estimation est-elle cohérente avec sa propre fourchette ? (sinon : pas de verdict)217    d["vp_ok"] = public.estimate_ok(vp.get("value"), vp.get("low"), vp.get("high")) \218        if vp.get("value") else None219    # région administrative normalisée (le champ `region` brut varie par source)220    d["region_name"] = public.region_of(d.get("region"), d.get("city"))221    # ville normalisée (immoka/villes.py) ; le libellé de la source reste dans222    # `city_raw`, et le secteur qu'il contenait complète `sector` s'il est vide223    d["city_raw"] = d.get("city") or ""224    d["city"], sec = villes.normalize(d["city_raw"])225    if d.get("address"):226        d["address"] = villes.clean_address(d["address"], d["city_raw"])227    if sec and not d.get("sector"):228        d["sector"] = sec229    # anomalies de qualité : toujours un tableau230    qi = d.get("quality_issues")231    if isinstance(qi, str):232        try:233            qi = json.loads(qi)234        except ValueError:235            qi = [qi]236    d["quality_issues"] = qi if isinstance(qi, list) else []237    # « courtier » qui n'est que le nom de la source ou de l'agence : pas un courtier238    bn = (d.get("broker_name") or "").strip()239    if bn:240        from . import directory241        kb = villes.key(bn)242        sn = _source_name(d.get("source"))243        if kb in {villes.key(sn), villes.key(sn.split("(")[0]),244                  villes.key(directory.franchise_of_source(d.get("source") or "") or ""),245                  villes.key(d.get("agency") or "")} or "particuliers" in kb:246            d["broker_name"] = None247    # jours sur le marché (depuis la 1re observation par Immo-Ka ; la date248    # d'inscription de la source, si connue, est dans details.listed_at)249    if d.get("first_seen"):250        d["days_on_market"] = max(0, int((time.time() - d["first_seen"]) // 86400))251    return d252253254# --- Filtres communs (liste, carte, recherche) --------------------------------255def _csv(v: str | None) -> list[str]:256    return [x.strip() for x in v.split(",") if x.strip()] if v else []257258259def _where(*, city=None, sector=None, region=None, property_type=None,260           source=None, agency=None, price_min=None, price_max=None,261           bedrooms_min=None, bathrooms_min=None, area_min=None, area_max=None,262           lot_min=None, year_min=None, year_max=None, q=None) -> tuple[str, list]:263    """Clause WHERE des inscriptions publiques + filtres. `city`,264    `property_type` et `source` acceptent plusieurs valeurs séparées par des265    virgules. `city` est une ville normalisée ; `agency` est une égalité."""266    sql, args = " WHERE " + PUBLIC, []267268    def _multi(col: str, value: str | None):269        nonlocal sql270        vals = _csv(value)271        if len(vals) == 1:272            sql += f" AND {col}=?"273            args.append(vals[0])274        elif vals:275            sql += f" AND {col} IN ({','.join('?' * len(vals))})"276            args.extend(vals)277278    if city:279        # ville canonique → toutes les écritures de la colonne (immoka/villes.py)280        vals: list[str] = []281        for c in _csv(city):282            vals += villes.raws(c) or [c]283        vals = list(dict.fromkeys(vals))284        sql += f" AND city IN ({','.join('?' * len(vals))})"285        args.extend(vals)286    _multi("property_type", property_type)287    _multi("source", source)288    if sector:289        # le secteur est parfois dans le libellé de ville (« Gatineau (Hull) »)290        sql += " AND (sector LIKE ? OR city LIKE ?)"291        args += [f"%{sector}%", f"%{sector}%"]292    if region:293        clause, rargs = public.region_clause(region)294        sql += clause; args.extend(rargs)295    if agency:296        # égalité exacte, insensible à la casse (pas de recherche partielle)297        sql += " AND agency=? COLLATE NOCASE"; args.append(agency.strip())298    if price_max is not None:299        sql += " AND price IS NOT NULL AND price<=?"; args.append(price_max)300    if price_min is not None:301        sql += " AND price IS NOT NULL AND price>=?"; args.append(price_min)302    if bedrooms_min is not None:303        sql += " AND bedrooms IS NOT NULL AND bedrooms>=?"; args.append(bedrooms_min)304    if bathrooms_min is not None:305        sql += " AND bathrooms IS NOT NULL AND bathrooms>=?"; args.append(bathrooms_min)306    if area_min is not None:307        sql += " AND area_sqft IS NOT NULL AND area_sqft>=?"; args.append(area_min)308    if area_max is not None:309        sql += " AND area_sqft IS NOT NULL AND area_sqft<=?"; args.append(area_max)310    if lot_min is not None:311        sql += " AND lot_sqft IS NOT NULL AND lot_sqft>=?"; args.append(lot_min)312    if year_min is not None:313        sql += " AND year_built IS NOT NULL AND year_built>=?"; args.append(year_min)314    if year_max is not None:315        sql += " AND year_built IS NOT NULL AND year_built<=?"; args.append(year_max)316    if q:317        sql += (" AND (title LIKE ? OR address LIKE ? OR city LIKE ?"318                " OR sector LIKE ? OR mls LIKE ?)")319        args += [f"%{q}%"] * 5320    return sql, args321322323def _bbox(bbox: str) -> tuple[str, list]:324    try:325        west, south, east, north = (float(v) for v in bbox.split(","))326    except ValueError:327        raise HTTPException(400, "bbox attendu : ouest,sud,est,nord")328    return " AND lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?", [south, north, west, east]329330331_LIST_SORTS = {332    "price_asc": " ORDER BY price IS NULL, price ASC",333    "price_desc": " ORDER BY price IS NULL, price DESC",334    "recent": " ORDER BY first_seen DESC",335}336337338@app.get("/api/listings")339def list_listings(340    city: str | None = None,341    sector: str | None = None,342    region: str | None = None,343    property_type: str | None = None,344    source: str | None = None,345    agency: str | None = None,346    price_max: float | None = None,347    price_min: float | None = None,348    bedrooms_min: int | None = None,349    bathrooms_min: int | None = None,350    area_min: float | None = None,       # superficie habitable minimale (pi²)351    area_max: float | None = None,352    lot_min: float | None = None,        # terrain minimal (pi²)353    year_min: int | None = None,354    year_max: int | None = None,355    q: str | None = None,356    sort: str = "price_asc",             # price_asc | price_desc | recent357    limit: int = Query(500, le=2000),358    offset: int = 0,359):360    """Liste paginée (historique v1). Le nouveau frontend utilise /api/search."""361    where, args = _where(362        city=city, sector=sector, region=region, property_type=property_type,363        source=source, agency=agency, price_min=price_min, price_max=price_max,364        bedrooms_min=bedrooms_min, bathrooms_min=bathrooms_min,365        area_min=area_min, area_max=area_max, lot_min=lot_min,366        year_min=year_min, year_max=year_max, q=q)367    con = db.connect()368    total = con.execute("SELECT COUNT(*) c FROM listings" + where, args).fetchone()["c"]369    order = _LIST_SORTS.get(sort, _LIST_SORTS["price_asc"])370    rows = [_row_to_dict(r) for r in con.execute(371        "SELECT * FROM listings" + where + order + " LIMIT ? OFFSET ?",372        args + [limit, offset]).fetchall()]373    con.close()374    return {"total": total, "count": len(rows), "listings": rows}375376377# --- Recherche unifiée liste + carte -----------------------------------------378# Une seule vérité partagée : la même requête sert la page de liste ET les379# points de la carte, dans la même réponse. Le compteur affiché en tête de380# liste est par construction égal au nombre de points envoyés à la carte.381382_SEARCH_SORTS = {383    "recent": " ORDER BY first_seen DESC, price IS NULL, price ASC",384    "prix": " ORDER BY price IS NULL, price ASC",385    "prix_desc": " ORDER BY price IS NULL, price DESC",386    "superficie": " ORDER BY area_sqft IS NULL, area_sqft DESC, price IS NULL, price ASC",387    "deal": " ORDER BY price IS NULL, price ASC",   # reclassé par écart Vrai-Prix388}389_SEARCH_TTL = 120          # secondes : les données bougent au rythme du veilleur390391392def _parse_poly(poly: str) -> list[tuple[float, float]]:393    """`poly=lng,lat;lng,lat;…` → liste de sommets (≥ 3) ou HTTP 400."""394    try:395        pts = [tuple(float(v) for v in p.split(",")) for p in poly.split(";") if p]396    except ValueError:397        raise HTTPException(400, "poly attendu : lng,lat;lng,lat;…")398    if len(pts) < 3 or any(len(p) != 2 for p in pts):399        raise HTTPException(400, "poly : au moins 3 sommets lng,lat")400    return pts  # type: ignore[return-value]401402403def _point_in_poly(lng: float, lat: float, ring: list[tuple[float, float]]) -> bool:404    """Ray casting (même algorithme que Lou-Ka)."""405    inside = False406    j = len(ring) - 1407    for i in range(len(ring)):408        xi, yi = ring[i]409        xj, yj = ring[j]410        if (yi > lat) != (yj > lat) and lng < (xj - xi) * (lat - yi) / (yj - yi) + xi:411            inside = not inside412        j = i413    return inside414415416def _search_set(where: str, args: list, bbox: str | None, poly: str | None,417                deal: str | None, sort: str) -> dict:418    """Résultat complet d'une recherche (tous les points triés + compteur des419    inscriptions sans coordonnées), mis en cache par jeu de filtres : changer420    de page ne refait pas la requête."""421    ring = _parse_poly(poly) if poly else None422    spatial, sargs = "", []423    if bbox:424        spatial, sargs = _bbox(bbox)425    if ring:426        lngs = [p[0] for p in ring]; lats = [p[1] for p in ring]427        spatial += " AND lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?"428        sargs += [min(lats), max(lats), min(lngs), max(lngs)]429430    def build() -> dict:431        con = db.connect()432        try:433            rows = con.execute(434                f"SELECT uid, lng, lat, price, {VP_VALUE_SQL} AS vpv,"435                f" {VP_LOW_SQL} AS vpl, {VP_HIGH_SQL} AS vph FROM listings"436                + where + " AND lat IS NOT NULL AND lng IS NOT NULL" + spatial437                + _SEARCH_SORTS[sort], args + sargs).fetchall()438            nogeo = con.execute(439                f"SELECT price, {VP_VALUE_SQL} AS vpv, {VP_LOW_SQL} AS vpl,"440                f" {VP_HIGH_SQL} AS vph FROM listings" + where441                + " AND (lat IS NULL OR lng IS NULL)", args).fetchall()442        finally:443            con.close()444        items = []445        for r in rows:446            if ring and not _point_in_poly(r["lng"], r["lat"], ring):447                continue448            dev, verdict = public.verdict(r["price"], r["vpv"], r["vpl"], r["vph"])449            if deal and verdict != deal:450                continue451            items.append((r["uid"], r["lng"], r["lat"], r["price"], verdict, dev))452        if sort == "deal":453            # meilleures affaires d'abord : plus grand rabais vs l'estimation454            items.sort(key=lambda t: (t[5] is None, t[5] if t[5] is not None else 0.0))455        unpositioned = sum(456            1 for r in nogeo457            if not deal or public.verdict(r["price"], r["vpv"], r["vpl"],458                                          r["vph"])[1] == deal)459        points = [[t[0], round(t[1], 6), round(t[2], 6), t[3], VP_CODES.get(t[4] or "")]460                  for t in items]461        return {"uids": [t[0] for t in items],462                "points_json": json.dumps(points, ensure_ascii=False,463                                          separators=(",", ":")),464                "unpositioned": unpositioned}465466    key = "search:" + json.dumps([where, args, bbox, poly, deal, sort],467                                 ensure_ascii=False, default=str)468    return _memo(key, _SEARCH_TTL, build)469470471@app.get("/api/search")472def search_unified(473    city: str | None = None,474    sector: str | None = None,475    region: str | None = None,        # région administrative (nom ou code 01–17)476    property_type: str | None = None,477    source: str | None = None,478    agency: str | None = None,479    price_max: float | None = None,480    price_min: float | None = None,481    bedrooms_min: int | None = None,482    bathrooms_min: int | None = None,483    area_min: float | None = None,    # superficie habitable (pi²)484    area_max: float | None = None,485    lot_min: float | None = None,     # terrain (pi²)486    year_min: int | None = None,487    year_max: int | None = None,488    q: str | None = None,489    deal: str | None = None,          # sous | marche | sur (verdict Vrai-Prix)490    bbox: str | None = None,          # ouest,sud,est,nord (zone visible carte)491    poly: str | None = None,          # lng,lat;… (zone dessinée)492    sort: str = "recent",             # recent | prix | prix_desc | deal | superficie493    page: int = 1,494    page_size: int = Query(20, ge=1, le=100),495    include: str = "tout",            # tout | liste (points inchangés côté client)496):497    """Recherche synchronisée liste ↔ carte (une réponse = les deux vues).498499    Retourne `total` (compteur partagé), `listings` (la page demandée) et500    `points` (TOUS les points correspondants, format compact501    [uid, lng, lat, prix, verdict]) — triés selon `sort`, si bien que la502    position d'un point dans `points` donne directement sa page de liste.503    Seules les inscriptions géolocalisées participent (chaque inscription de504    la liste est visible sur la carte) ; `unpositioned` compte les505    inscriptions filtrées sans coordonnées, pour l'afficher honnêtement.506    """507    if sort not in _SEARCH_SORTS:508        raise HTTPException(400, f"sort inconnu : {sort}")509    if deal is not None and deal not in VP_CODES:510        raise HTTPException(400, "deal attendu : sous | marche | sur")511    where, args = _where(512        city=city, sector=sector, region=region, property_type=property_type,513        source=source, agency=agency, price_min=price_min, price_max=price_max,514        bedrooms_min=bedrooms_min, bathrooms_min=bathrooms_min,515        area_min=area_min, area_max=area_max, lot_min=lot_min,516        year_min=year_min, year_max=year_max, q=q)517    res = _search_set(where, args, bbox, poly, deal, sort)518    uids = res["uids"]519    total = len(uids)520521    # page demandée, ramenée dans les bornes si les filtres l'ont dépassée522    last = max(1, -(-total // page_size))523    page = min(max(1, page), last)524    page_uids = uids[(page - 1) * page_size: page * page_size]525526    listings: list[dict] = []527    if page_uids:528        con = db.connect()529        marks = ",".join("?" * len(page_uids))530        by_uid = {r["uid"]: _row_to_dict(r) for r in con.execute(531            f"SELECT * FROM listings WHERE uid IN ({marks})", page_uids).fetchall()}532        con.close()533        listings = [by_uid[u] for u in page_uids if u in by_uid]534535    head = json.dumps({"total": total, "page": page, "page_size": page_size,536                       "pages": last, "sort": sort, "unpositioned": res["unpositioned"],537                       "listings": listings},538                      ensure_ascii=False, separators=(",", ":"))539    points = res["points_json"] if include != "liste" else "null"540    return Response(head[:-1] + ',"points":' + points + "}",541                    media_type="application/json")542543544# --- Miniatures optimisées (WebP, taille écran) ------------------------------545# Sert les images des inscriptions redimensionnées et compressées (perf546# mobile) : /api/img?u=<url>&w=480. Seules les URLs validées par l'audit des547# images (table image_audit, ok=1) sont relayées — pas de proxy ouvert. URL548# inconnue de l'audit : 404, le client retombe sur l'image d'origine.549_IMG_WIDTHS = (160, 480, 800, 1280)550_IMG_CACHE = ROOT / "data" / "imgcache"551552553@app.get("/api/img")554def img_thumbnail(u: str, w: int = 480):555    import hashlib556    import requests as _rq557    w = min(_IMG_WIDTHS, key=lambda x: abs(x - w))558    if not u.startswith(("http://", "https://")):559        raise HTTPException(400, "URL invalide")560    key = hashlib.sha1(u.encode()).hexdigest()561    _IMG_CACHE.mkdir(parents=True, exist_ok=True)562    path = _IMG_CACHE / f"{key}_{w}.webp"563    headers = {"Cache-Control": "public, max-age=2592000, immutable"}564    if path.exists():565        return Response(path.read_bytes(), media_type="image/webp", headers=headers)566    con = db.connect()567    known = con.execute("SELECT ok FROM image_audit WHERE url=?", (u,)).fetchone()568    con.close()569    if known is None or not known["ok"]:570        raise HTTPException(404, "image inconnue de l'audit des images")571    try:572        resp = _rq.get(u, timeout=12, headers={"User-Agent": "ImmoKaImg/2.0"})573        resp.raise_for_status()574        from io import BytesIO575        from PIL import Image, ImageOps576        img = Image.open(BytesIO(resp.content))577        img = ImageOps.exif_transpose(img)578        if img.mode not in ("RGB", "L"):579            img = img.convert("RGB")580        if img.width > w:581            img = img.resize((w, max(1, round(img.height * w / img.width))),582                             Image.LANCZOS)583        buf = BytesIO()584        img.save(buf, "WEBP", quality=80, method=4)585        data = buf.getvalue()586        tmp = path.with_name(f"{path.name}.{threading.get_ident()}.tmp")587        tmp.write_bytes(data)588        tmp.replace(path)589        return Response(data, media_type="image/webp", headers=headers)590    except HTTPException:591        raise592    except Exception:593        raise HTTPException(404, "image irrécupérable")594595596# Hydro : `solve=1` résout un captcha PAYANT chez Hydro-Québec. L'endpoint est597# public : le calcul à la demande n'est permis que pour une inscription connue598# (`uid`), une fois par inscription et par jour, et dans la limite d'un plafond599# horaire global (IMMOKA_HYDRO_SOLVES_PER_HOUR, défaut 12 ; 0 = désactivé). Le600# résultat est gardé 6 mois par adresse (immoka/hydro.py). Au-delà du plafond,601# la réponse est celle du cache, avec `en_attente`.602_HYDRO_LOCK = threading.Lock()603_HYDRO_SOLVES: list[float] = []          # horodatages des calculs de la dernière heure604_HYDRO_TRIED: dict[str, float] = {}      # uid → dernier essai605606607@app.get("/api/hydro")608def hydro_at(adresse: str, solve: int = 0, uid: str | None = None,609             lat: float | None = None, lng: float | None = None):610    """Estimation du coût d'électricité à une adresse (Hydro-Québec).611    Par défaut cache seulement (aucun captcha). `solve=1` demande le calcul :612    il exige un `uid` d'inscription et reste plafonné (voir ci-dessus)."""613    from . import hydro614    cached = hydro.estimate(adresse=adresse, uid=uid, lat=lat, lng=lng, solve=False)615    if not solve or cached.get("disponible") or not cached.get("en_attente"):616        return cached617618    def refuse(raison: str) -> dict:619        return {**cached, "raison": raison, "calcul_refuse": True}620621    cap = int(os.environ.get("IMMOKA_HYDRO_SOLVES_PER_HOUR", "12") or 0)622    if cap <= 0:623        return refuse("calcul à la demande désactivé")624    if not uid:625        return refuse("uid requis pour le calcul à la demande")626    con = db.connect()627    row = con.execute("SELECT address, lat, lng FROM listings WHERE uid=? AND active=1",628                      (uid,)).fetchone()629    con.close()630    if row is None:631        return refuse("inscription inconnue")632    now = time.time()633    with _HYDRO_LOCK:634        _HYDRO_SOLVES[:] = [t for t in _HYDRO_SOLVES if now - t < 3600]635        if now - _HYDRO_TRIED.get(uid, 0) < 86400:636            return refuse("déjà demandé pour cette inscription aujourd'hui")637        if len(_HYDRO_SOLVES) >= cap:638            return refuse("plafond horaire atteint")639        _HYDRO_SOLVES.append(now)640        _HYDRO_TRIED[uid] = now641        if len(_HYDRO_TRIED) > 5000:642            for k in [k for k, t in _HYDRO_TRIED.items() if now - t > 86400]:643                _HYDRO_TRIED.pop(k, None)644    # l'adresse et les coordonnées viennent de l'inscription, pas de la requête645    out = hydro.estimate(adresse=row["address"] or adresse, uid=uid,646                         lat=row["lat"], lng=row["lng"], solve=True)647    if out.get("cache"):                 # servi du cache : rien n'a été dépensé648        with _HYDRO_LOCK:649            if now in _HYDRO_SOLVES:650                _HYDRO_SOLVES.remove(now)651    return out652653654@app.get("/api/commerces")655def commerces_at(lat: float, lng: float):656    """Grands commerces + métro/bus les plus proches (Mapbox / OSM)."""657    from . import commerces658    return commerces.nearby(lat, lng)659660661@app.get("/api/air")662def air_at(lat: float, lng: float):663    """Qualité de l'air : station RSQAQ la plus proche (MELCCFP)."""664    from . import air665    d = air.lookup(lat, lng)666    if d is None:667        raise HTTPException(404, "Base qualité de l'air non disponible")668    return d669670671@app.get("/api/gaz")672def gaz_at(lat: float, lng: float, limit: int = 5):673    """Stations-service à proximité et prix courants (gazquebec.ca).674    `limit` (défaut 5, max 60) : la fiche demande la liste complète pour son675    panneau « Voir les N stations »."""676    from . import gaz677    return gaz.nearby(lat, lng, limit=max(1, min(limit, 60)))678679680@app.get("/api/inondation")681def inondation_at(lat: float, lng: float):682    """Risque d'inondation à l'adresse (BDZI, gouv. du Québec) —683    bloc « Risque d'inondation » de la fiche."""684    from . import inondation685    d = inondation.lookup(lat, lng)686    if d is None:687        raise HTTPException(404, "Base des zones inondables non disponible")688    return d689690691@app.get("/api/listings/{uid}")692def get_listing(uid: str):693    con = db.connect()694    row = con.execute("SELECT * FROM listings WHERE uid=?", (uid,)).fetchone()695    d = None696    if row is not None:697        d = _row_to_dict(row)698        # historique de prix (baisses/hausses du prix demandé)699        d["price_history"] = [dict(r) for r in con.execute(700            "SELECT ts, price FROM price_log WHERE uid=? ORDER BY ts DESC LIMIT 10",701            (uid,)).fetchall()]702        # commodités de proximité (cache par immeuble, voir immoka/poi.py)703        if d.get("lat") is not None and d.get("lng") is not None:704            key = f"{round(d['lat'], 4)},{round(d['lng'], 4)}"705            poi_row = con.execute(706                "SELECT pois FROM poi_cache WHERE coord_key=?", (key,)).fetchone()707            d["poi"] = json.loads(poi_row["pois"]) if poi_row else []708        else:709            d["poi"] = []710        # autres publications de la même propriété (doublons masqués par la711        # dédup, rattachés via dup_of) — pour la box « Aussi publiée sur… »712        d["duplicates"] = [dict(r) for r in con.execute(713            "SELECT uid, source, url, broker_name, agency, price_label"714            " FROM listings WHERE dup_of=? AND active=1 ORDER BY source",715            (uid,)).fetchall()]716        # statistiques de quartier (recensement, proximité, chaleur, criminalité)717        from . import quartier718        dauid = d.get("dauid")719        d["quartier"] = quartier.fiche_quartier(720            d.get("lat"), d.get("lng"), d.get("city") or "",721            dauid if dauid and dauid != "hors-zone" else None)722        # visible dans la recherche ? (sinon : retirée, en quarantaine, doublon)723        d["public"] = con.execute(724            f"SELECT 1 FROM listings WHERE uid=? AND {PUBLIC}",725            (uid,)).fetchone() is not None726    con.close()727    if d is None:728        raise HTTPException(404, "Propriété introuvable")729    return d730731732@app.get("/api/listings/{uid}/pdf")733def listing_pdf(uid: str):734    """Fiche PDF complète de la propriété (immoka/pdffiche.py) — reflète tous735    les blocs de la fiche web : prix + verdict Vrai-Prix, photos, description,736    caractéristiques, pièces, analyses, environnement, quartier, QR."""737    from . import pdffiche738    data = pdffiche.fiche_pdf(uid)739    if data is None:740        raise HTTPException(404, "Propriété introuvable")741    safe = uid.replace(":", "-").replace("/", "-")742    return Response(743        content=data, media_type="application/pdf",744        headers={"Content-Disposition":745                 f'attachment; filename="immo-ka_fiche_{safe}.pdf"'})746747748@app.get("/api/listings.geojson")749def listings_geojson(750    city: str | None = None,751    sector: str | None = None,752    region: str | None = None,753    property_type: str | None = None,754    source: str | None = None,755    agency: str | None = None,756    price_max: float | None = None,757    price_min: float | None = None,758    bedrooms_min: int | None = None,759    bathrooms_min: int | None = None,760    area_min: float | None = None,761    area_max: float | None = None,762    lot_min: float | None = None,763    year_min: int | None = None,764    year_max: int | None = None,765    q: str | None = None,766    bbox: str | None = None,767    limit: int = Query(3000, le=8000),768):769    """Propriétés géolocalisées (marqueurs de carte, champs allégés) — format770    historique v1 ; le nouveau frontend utilise `points` de /api/search.771772    `bbox=ouest,sud,est,nord` restreint au rectangle visible (index773    idx_listings_geo) ; `limit` plafonne la réponse ; la collection porte774    `totalGeocoded` (géolocalisées correspondantes) et `totalMatching`775    (avec ou sans coordonnées). Mêmes filtres que /api/search.776    """777    where, args = _where(778        city=city, sector=sector, region=region, property_type=property_type,779        source=source, agency=agency, price_min=price_min, price_max=price_max,780        bedrooms_min=bedrooms_min, bathrooms_min=bathrooms_min,781        area_min=area_min, area_max=area_max, lot_min=lot_min,782        year_min=year_min, year_max=year_max, q=q)783    geo, gargs = " AND lat IS NOT NULL AND lng IS NOT NULL", []784    if bbox:785        clause, gargs = _bbox(bbox)786        geo += clause787    con = db.connect()788    total_all = con.execute("SELECT COUNT(*) c FROM listings" + where,789                            args).fetchone()["c"]790    total_geo = con.execute("SELECT COUNT(*) c FROM listings" + where + geo,791                            args + gargs).fetchone()["c"]792    features = []793    for r in con.execute(794            "SELECT uid, title, address, price, price_label, property_type,"795            " bedrooms, bathrooms, source, city, sector, images, lat, lng, vraiprix,"796            " json_extract(COALESCE(details,'{}'),'$.cover_thumb') AS cover_thumb"797            " FROM listings" + where + geo798            + " ORDER BY price IS NULL, price ASC LIMIT ?",799            args + gargs + [limit]).fetchall():800        images = json.loads(r["images"] or "[]")801        try:802            vpj = json.loads(r["vraiprix"]) or {}803        except (TypeError, ValueError):804            vpj = {}805        vp_val = vpj.get("value")806        ville, sec = villes.normalize(r["city"])807        features.append({808            "type": "Feature",809            "geometry": {"type": "Point", "coordinates": [r["lng"], r["lat"]]},810            "properties": {811                "uid": r["uid"],812                "title": None if r["address"] else r["title"],813                "address": r["address"],814                "price": r["price"], "price_label": r["price_label"],815                "property_type": r["property_type"], "bedrooms": r["bedrooms"],816                "bathrooms": r["bathrooms"], "source": r["source"],817                "city": ville, "sector": r["sector"] or sec or "",818                # miniature légère pour le popup mobile si le connecteur en a une819                "image": r["cover_thumb"] or (images[0] if images else None),820                "vp": vp_val,821                "vp_verdict": public.verdict(r["price"], vp_val, vpj.get("low"),822                                             vpj.get("high"))[1],823            },824        })825    con.close()826    return _json({"type": "FeatureCollection", "features": features,827                  "totalGeocoded": total_geo, "totalMatching": total_all})828829830@app.get("/api/facets")831def facets(city: str | None = None):832    """Valeurs des filtres, avec le nombre d'inscriptions publiques de chacune.833834    `city` (optionnel) restreint la liste des secteurs à cette ville."""835    def build() -> dict:836        from . import lights as _lights837        names = _lights.source_names()838        vidx = villes.index()839        con = db.connect()840        try:841            sector_sql = (f"SELECT sector, COUNT(*) n FROM listings WHERE {PUBLIC}"842                          " AND sector<>''")843            sector_args: list = []844            if city:845                rv = villes.raws(city) or [city]846                sector_sql += f" AND city IN ({','.join('?' * len(rv))})"847                sector_args += rv848            price = con.execute(849                f"SELECT COUNT(*) total, MIN(price) lo, MAX(price) hi FROM listings"850                f" WHERE {PUBLIC} AND {public.PRICE_OK}").fetchone()851            total = con.execute(852                f"SELECT COUNT(*) c FROM listings WHERE {PUBLIC}").fetchone()["c"]853            out = {854                "total": total,855                "cities": [{"city": lab, "n": e["n"]} for lab, e in sorted(856                    vidx["by_label"].items(), key=lambda kv: (-kv[1]["n"], kv[0]))],857                "no_city": vidx["no_city"],858                "sectors": [dict(r) for r in con.execute(859                    sector_sql + " GROUP BY sector ORDER BY n DESC, sector LIMIT 500",860                    sector_args)],861                "property_types": [dict(r) for r in con.execute(862                    f"SELECT property_type, COUNT(*) n FROM listings WHERE {PUBLIC}"863                    " AND property_type<>'' GROUP BY property_type"864                    " ORDER BY n DESC, property_type")],865                "sources": [{"source": r["source"], "n": r["n"],866                             "name": names.get(r["source"], r["source"])}867                            for r in con.execute(868                    f"SELECT source, COUNT(*) n FROM listings WHERE {PUBLIC}"869                    " GROUP BY source ORDER BY n DESC")],870                "regions": [{"region": k, "n": v} for k, v in sorted(871                    public.region_index()["counts"].items(), key=lambda kv: -kv[1])],872                "price": {"min": price["lo"], "max": price["hi"]},873                "deals": list(VP_CODES),874                "verdict_thresholds": public.verdict_thresholds(),875                "sorts": list(_SEARCH_SORTS),876            }877        finally:878            con.close()879        return out880    return _json(_memo("facets:" + (city or ""), 300, build))881882883@app.get("/api/version")884def api_version():885    """Version de l'API : les clients natifs s'en servent pour vérifier qu'ils886    parlent bien à Immo-Ka v2 (recherche unifiée, lumières, annuaire)."""887    from . import __version__888    return {"api": 2, "version": __version__, "name": "Immo-Ka",889            "verdict_thresholds": public.verdict_thresholds()}890891892@app.get("/api/lights")893def lights():894    """Densité des propriétés à vendre (cellules ~1 km) + principales villes895    — carte d'accueil. Voir immoka/lights.py."""896    from . import lights as _lights897    return _json(_lights.compute())898899900@app.get("/api/sources/names")901def source_names():902    """Identifiant de source → nom lisible (léger : cartes d'inscriptions)."""903    from . import lights as _lights904    return _lights.source_names()905906907@app.get("/api/sources")908def sources():909    """Registre des sources avec leur inventaire PUBLIC (mêmes règles que la910    recherche) et leur dernière synchronisation réussie."""911    def build() -> dict:912        registry = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]913        con = db.connect()914        try:915            counts = {r["source"]: r["n"] for r in con.execute(916                f"SELECT source, COUNT(*) n FROM listings WHERE {PUBLIC}"917                " GROUP BY source")}918            last = {r["source"]: r["ts"] for r in con.execute(919                "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 AND found>0"920                " GROUP BY source")}921        finally:922            con.close()923        known = set()924        for s in registry:925            known.add(s["id"])926            s["active_listings"] = counts.get(s["id"], 0)927            s["last_sync"] = last.get(s["id"])928        # sous-agences générées (RE/MAX, Via Capitale, Century 21…) absentes du929        # registre : listées à part pour que la somme égale le total public930        from . import lights as _lights931        names = _lights.source_names()932        others = [{"id": sid, "name": names.get(sid, sid), "active_listings": n,933                   "last_sync": last.get(sid)}934                  for sid, n in sorted(counts.items(), key=lambda kv: -kv[1])935                  if sid not in known]936        return {"total": sum(counts.values()), "sources": registry, "others": others}937    return _json(_memo("sources", 300, build))938939940# Rattachement d'une source à sa bannière (franchise) pour le regroupement.941_FRANCHISES = [942    ("RE/MAX", lambda s: s == "remax_quebec" or s.startswith("remax_ag_")),943    ("Via Capitale", lambda s: s == "via_capitale" or s.startswith("via_ag_")),944    ("Century 21", lambda s: s == "century21" or s.startswith("c21_ag_")),945    ("Royal LePage", lambda s: s == "royal_lepage"),946    ("Groupe Sutton", lambda s: s == "sutton"),947    ("Keller Williams", lambda s: s.startswith("kw_")),948    ("DuProprio", lambda s: s == "duproprio"),949]950951952def _franchise_of(source: str, source_names: dict) -> str:953    for name, match in _FRANCHISES:954        if match(source):955            return name956    return source_names.get(source, source)   # agence indépendante = elle-même957958959@app.get("/api/agencies")960def agencies():961    """Arbre bannière → sous-agences (bureaux) avec le nombre d'inscriptions.962963    Alimente la page « Sources » de l'app : chaque bannière est éclatée par964    sous-agence via le champ `agency` (bureau). Dédupliqué (n° Centris)."""965    con = db.connect()966    registry = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]967    source_names = {s["id"]: s["name"] for s in registry}968    rows = con.execute(969        "SELECT source, COALESCE(NULLIF(agency,''), '') agency, COUNT(*) n"970        " FROM listings WHERE active=1" + DEDUP_CLAUSE +971        " GROUP BY source, agency").fetchall()972    con.close()973    tree: dict[str, dict] = {}974    for r in rows:975        fr = _franchise_of(r["source"], source_names)976        node = tree.setdefault(fr, {"franchise": fr, "total": 0, "agencies": {}})977        node["total"] += r["n"]978        # nom de sous-agence : le bureau (agency) sinon le nom de la source979        label = r["agency"] or source_names.get(r["source"], r["source"])980        a = node["agencies"].setdefault(label, {"name": label, "count": 0,981                                                 "sources": set()})982        a["count"] += r["n"]983        a["sources"].add(r["source"])984    out = []985    for node in tree.values():986        ags = sorted(node["agencies"].values(), key=lambda x: -x["count"])987        for a in ags:988            a["sources"] = sorted(a["sources"])989        out.append({"franchise": node["franchise"], "total": node["total"],990                    "sub_agencies": len(ags), "agencies": ags})991    out.sort(key=lambda x: -x["total"])992    return {"franchises": out}993994995@app.get("/api/agences")996def agences_directory():997    """Annuaire des agences (registre OACIQ) et des bannières de courtage :998    inventaire actif, prix médian, villes, courtiers — immoka/directory.py."""999    from . import directory1000    return _json(directory.compute())100110021003@app.get("/api/agences/{agency_id}")1004def agence_detail(agency_id: str):1005    """Une agence de l'annuaire, avec la liste de ses courtiers."""1006    from . import directory1007    a = directory.agency(agency_id)1008    if a is None:1009        raise HTTPException(404, "Agence inconnue")1010    return a101110121013@app.get("/api/stats")1014def stats(syncs_since_h: float | None = None):1015    """Chiffres globaux, écart Vrai-Prix par bannière, qualité des données1016    et journal de synchronisation récent (cache 60 s)."""1017    return _json(_memo(f"stats:{syncs_since_h}", 60,1018                       lambda: _stats_build(syncs_since_h)))101910201021def _stats_build(syncs_since_h: float | None = None) -> dict:1022    con = db.connect()1023    row = con.execute(1024        """SELECT COUNT(*) total,1025                  COUNT(DISTINCT source) sources,1026                  COUNT(DISTINCT city) cities,1027                  AVG(price) avg_price,1028                  MIN(price) min_price,1029                  MAX(price) max_price1030           FROM listings WHERE active=1""" + DEDUP_CLAUSE).fetchone()1031    # Fenêtre de synchronisations pour la supervision :1032    # sans paramètre, comportement historique (20 dernières entrées) ; avec1033    # ?syncs_since_h=<heures>, toutes les entrées de la fenêtre (borne 4000) —1034    # évite les fausses alertes « stale » quand 100+ sources synchronisent1035    # plus de 20 fois entre deux sondages.1036    log: list[dict] = []1037    if syncs_since_h is not None:1038        cutoff = time.time() - syncs_since_h * 36001039        log = [dict(r) for r in con.execute(1040            "SELECT * FROM sync_log WHERE ts >= ?"1041            " ORDER BY ts DESC LIMIT 4000", (cutoff,))]1042    if len(log) < 20:1043        log = [dict(r) for r in con.execute(1044            "SELECT * FROM sync_log ORDER BY ts DESC LIMIT 20")]10451046    # --- écart prix demandé vs estimation Vrai-Prix, par bannière -----------1047    registry = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]1048    source_names = {s["id"]: s["name"] for s in registry}1049    # Sources volontairement sans sync (retirées ou en pause dans le registre) :1050    # publiées à la supervision via `disabled_sources`.1051    disabled_sources = sorted(1052        s["id"] for s in registry if s.get("status") in ("inactif", "pause"))1053    # écarts au Vrai-Prix par bannière — même règle que le verdict des fiches1054    # (immoka/public.py : seuils ±8 %, estimation dans sa fourchette, −50…+100 %)1055    deltas: dict[str, list[float]] = {}1056    for r in con.execute(1057            f"SELECT source, price, {VP_VALUE_SQL} vp, {VP_LOW_SQL} lo, {VP_HIGH_SQL} hi"1058            " FROM listings WHERE active=1" + DEDUP_CLAUSE +1059            " AND price IS NOT NULL AND price > 0"1060            " AND vraiprix LIKE '%estimation%'"):1061        d = public.deviation(r["price"], r["vp"], r["lo"], r["hi"])1062        if d is not None:1063            deltas.setdefault(_franchise_of(r["source"], source_names), []).append(d)1064    con.close()10651066    def _agg(name: str, ds: list[float]) -> dict:1067        ds = sorted(ds)1068        n = len(ds)1069        med = ds[n // 2] if n % 2 else (ds[n // 2 - 1] + ds[n // 2]) / 21070        sur = round(100 * sum(1 for d in ds if d >= public.VP_SUR) / n, 1)1071        sous = round(100 * sum(1 for d in ds if d <= public.VP_SOUS) / n, 1)1072        marche = round(100 - sur - sous, 1)1073        return {1074            "banniere": name, "n": n,1075            "median_delta_pct": round(med, 1),1076            "p25": round(ds[n // 4], 1), "p75": round(ds[(3 * n) // 4], 1),1077            "pct_sur": sur, "pct_marche": marche, "pct_sous": sous,1078            # anciens noms (v1) : mêmes valeurs, mêmes seuils que ci-dessus1079            "pct_sur10": sur, "pct_juste": marche, "pct_sous5": sous,1080        }10811082    tous = [d for ds in deltas.values() for d in ds]1083    vraiprix = {1084        "ensemble": _agg("Toutes bannières", tous) if tous else None,1085        "bannieres": sorted(1086            (_agg(k, v) for k, v in deltas.items() if len(v) >= 30),1087            key=lambda x: -x["median_delta_pct"]),1088    }1089    # qualité des données : complétude, quarantaine, anomalies (par connecteur)1090    from . import quality1091    con2 = db.connect()1092    try:1093        qualite = quality.summary(con2)1094    finally:1095        con2.close()1096    out_row = dict(row)1097    out_row["cities"] = len(villes.index()["by_label"])1098    return {**out_row, "vraiprix": vraiprix, "qualite": qualite,1099            "disabled_sources": disabled_sources, "recent_syncs": log}110011011102# --- Tableau de bord et rapports statistiques ---------------------------------1103REPORT_SITE = {"wordmark": "Immo-Ka", "accent": "#D12C37",1104               "domain": "www.immo-ka.com",1105               "tagline": "Toutes les propriétés à vendre au Québec"}1106@app.get("/api/stats/dashboard")1107def stats_dashboard(1108    period: str | None = Query(None),1109    from_: str | None = Query(None, alias="from"),1110    to: str | None = Query(None),1111):1112    """Tableau de bord analytique (cache 5 min)."""1113    return kastats.dashboard(period, from_, to)111411151116@app.get("/api/stats/report")1117def stats_report(1118    period: str = Query("30j"),1119    from_: str | None = Query(None, alias="from"),1120    to: str | None = Query(None),1121    mode: str = Query("complet"),1122):1123    """Rapport statistique PDF Immo-Ka (immoka/reportpdf.py)."""1124    from . import reportpdf1125    dash = kastats.dashboard(period, from_, to)1126    site = REPORT_SITE1127    pdf = reportpdf.MarketReport(1128        site=site, dashboard=dash,1129        mode="synthese" if mode == "synthese" else "complet").build()1130    return Response(1131        content=pdf, media_type="application/pdf",1132        headers={"Content-Disposition":1133                 f'attachment; filename="{reportpdf.filename("immo-ka", period)}"'})1134113511361137@app.get("/api/stats/catalog")1138def stats_catalog(1139    period: str = Query("30j"),1140    from_: str | None = Query(None, alias="from"),1141    to: str | None = Query(None),1142):1143    """v3 — blocs composables pour le constructeur de rapports personnalisés."""1144    from . import reportpdf1145    dash = kastats.dashboard(period, from_, to)1146    return {"updated": dash.get("updated"), "period": dash.get("period"),1147            "blocks": reportpdf.catalog(dash)}114811491150@app.post("/api/stats/report/custom")1151def stats_report_custom(spec: dict = Body(...)):1152    """v3 — rapport PDF personnalisé : {"title", "period", "from", "to",1153    "blocks": [{"key": "series:…", "render": "bar"}, …]} (SPEC.md §3bis)."""1154    from . import reportpdf1155    period = str(spec.get("period") or "30j")1156    dash = kastats.dashboard(period, str(spec.get("from") or "") or None,1157                             str(spec.get("to") or "") or None)1158    site = REPORT_SITE1159    known = {b["key"] for b in reportpdf.catalog(dash)}1160    blocks = [b for b in (spec.get("blocks") or [])1161              if isinstance(b, dict) and b.get("key") in known][:40]1162    if not blocks:1163        raise HTTPException(400, "Aucun bloc valide dans la composition")1164    pdf = reportpdf.MarketReport(1165        site=site, dashboard=dash, mode=reportpdf.CUSTOM_MODE,1166        spec={"title": str(spec.get("title") or "")[:80], "blocks": blocks},1167    ).build()1168    fname = reportpdf.filename("immo-ka", period, reportpdf.CUSTOM_MODE)1169    return Response(1170        content=pdf, media_type="application/pdf",1171        headers={"Content-Disposition": f'attachment; filename="{fname}"'})11721173# --- Référencement : robots, sitemaps, résolution de slugs (voir immoka/seo.py)1174@app.get("/robots.txt")1175def robots():1176    return seo.robots_txt()117711781179@app.get("/sitemap.xml")1180def sitemap():1181    return seo.sitemap_index()118211831184@app.get("/sitemaps/{name}")1185def sitemap_part(name: str):1186    return seo.sitemap_file(name)118711881189@app.get("/api/seo/resolve")1190def seo_resolve(ville: str | None = None, type: str | None = None):1191    """Slug d'URL programmatique → valeurs exactes (pages /a-vendre du SPA)."""1192    out = seo.resolve_slugs(ville, type)1193    if out is None:1194        raise HTTPException(404, "Slug inconnu")1195    return out119611971198@app.get("/api/seo/villes")1199def seo_villes(min: int = 1):1200    """Villes ayant des propriétés à vendre (pages /a-vendre/{slug})."""1201    return _json(seo.api_villes(min))120212031204@app.get("/api/seo/ville/{slug}")1205def seo_ville(slug: str, type: str | None = None):1206    """Données d'une page de ville : statistiques, types, secteurs,1207    inscriptions récentes, villes voisines."""1208    out = seo.api_ville(slug, type)1209    if out is None:1210        raise HTTPException(404, "Ville ou type inconnu")1211    return _json(out)121212131214# --- Préchauffage ----------------------------------------------------------1215# Au démarrage, un fil d'arrière-plan calcule une fois les agrégats lourds1216# (lumières, facettes, annuaire, villes, tableau de bord ~25 s) : le premier1217# visiteur ne paie pas le calcul à froid.1218def _warm() -> None:1219    from . import directory, lights as _lights1220    for job in (villes.index, _lights.compute, _lights.source_names, public.region_index,1221                facets, sources, directory.compute, seo.registry,1222                seo.api_villes, search_unified_warm, _warm_villes,1223                lambda: kastats.dashboard(None, None, None),1224                lambda: kastats.dashboard("30j", None, None),1225                lambda: kastats.dashboard("7j", None, None),1226                lambda: kastats.dashboard("3m", None, None)):1227        try:1228            job()1229        except Exception:  # noqa: BLE001 — jamais bloquant1230            pass123112321233def _warm_villes() -> None:1234    """Pages des plus grandes villes (les plus demandées, les plus lentes à froid)."""1235    for v in seo.api_villes()["villes"][:10]:1236        seo.api_ville(v["slug"])123712381239def search_unified_warm() -> None:1240    where, args = _where()1241    _search_set(where, args, None, None, None, "recent")124212431244if os.environ.get("IMMOKA_NO_WARM") != "1":1245    threading.Thread(target=_warm, daemon=True).start()124612471248# --- Frontend statique -------------------------------------------------------1249if FRONTEND_DIR.exists():12501251    if (FRONTEND_DIR / "assets").is_dir():1252        app.mount("/assets", StaticFiles(directory=FRONTEND_DIR / "assets"), name="assets")12531254    @app.get("/{full_path:path}")1255    def spa(full_path: str, request: Request):1256        target = FRONTEND_DIR / full_path1257        if full_path and target.is_file():1258            return FileResponse(target)1259        # rendu SEO côté serveur : HTML complet par route (meta, JSON-LD,1260        # contenu d'indexation dans #root que l'app remplace au montage). Ne doit JAMAIS1261        # casser l'app → repli sur l'index brut à la moindre erreur.1262        try:1263            return seo.render_for_path("/" + full_path,1264                                       dict(request.query_params))1265        except Exception:1266            return FileResponse(FRONTEND_DIR / "index.html")1267
Files main
Menu

Theme