Repository Public
1# -----------------------------------------------------------------------------2# Auto-Ka v2 — véhicules d'occasion à vendre au Québec3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# web.py : API v2 (FastAPI). Application autonome : aucun compte, aucune5# session, aucun favori côté serveur. Tout est en lecture ; tous les endpoints6# de liste, de carte, de comptage et de statistiques lisent le même catalogue7# (autoka/public.py), d'où des totaux qui concordent par construction.8# -----------------------------------------------------------------------------9from __future__ import annotations1011import hashlib12import io13import json14import os15import re16import threading17import time18from collections import Counter, OrderedDict, defaultdict19from pathlib import Path20from urllib.parse import urlsplit2122from fastapi import Body, FastAPI, HTTPException, Query, Request23from fastapi.middleware.cors import CORSMiddleware24from fastapi.middleware.gzip import GZipMiddleware25from fastapi.responses import JSONResponse, Response2627from . import __version__, db, public, seo, stats28from .public import carte, catalogue, cle, slugify2930ROOT = Path(__file__).resolve().parent.parent31NOINDEX = os.environ.get("AUTOKA_NOINDEX", "").strip() not in ("", "0", "false")3233app = FastAPI(title="Auto-Ka API", version=__version__, docs_url="/api/docs",34 redoc_url=None, openapi_url="/api/openapi.json",35 description="Véhicules d'occasion à vendre au Québec — API v2")36app.add_middleware(CORSMiddleware, allow_origins=["*"],37 allow_methods=["GET", "POST", "OPTIONS"], allow_headers=["*"])38app.add_middleware(GZipMiddleware, minimum_size=1024)394041@app.middleware("http")42async def _entetes(request: Request, call_next):43 t0 = time.perf_counter()44 resp = await call_next(request)45 resp.headers["Server-Timing"] = f"app;dur={(time.perf_counter() - t0) * 1000:.1f}"46 if NOINDEX:47 resp.headers["X-Robots-Tag"] = "noindex, nofollow"48 return resp495051def _json(payload, status: int = 200, max_age: int = 60) -> Response:52 return Response(json.dumps(payload, ensure_ascii=False, separators=(",", ":")),53 status_code=status, media_type="application/json",54 headers={"Cache-Control": f"public, max-age={max_age}"})555657# --- mémo par instantané ------------------------------------------------------------58_MEMO_MAX = 400596061def _memo(cat, espace: str, clef, fabrique, maxi: int = _MEMO_MAX):62 """Résultat gardé pour la durée d'un instantané du catalogue (LRU)."""63 store: OrderedDict = cat.calcul("lru:" + espace, OrderedDict)64 hit = store.get(clef)65 if hit is not None:66 try:67 store.move_to_end(clef)68 except KeyError:69 pass70 return hit71 val = fabrique()72 store[clef] = val73 while len(store) > maxi:74 try:75 store.popitem(last=False)76 except KeyError:77 break78 return val798081# =============================================================================82# /api/version, /api/public83# =============================================================================84@app.get("/api/version")85def api_version():86 cat = catalogue()87 return {88 "api": 2, "version": __version__, "name": "Auto-Ka",89 "contact": "contact@spboucher.ai",90 "generated_at": cat.ts, "refresh_seconds": public.REFRESH,91 "public_listings": len(cat.items),92 "kinds": dict(Counter(v["kind"] for v in cat.items)),93 "verdict": public.verdict_methode(),94 "sorts": list(_SORTS), "page_size_max": PAGE_MAX,95 "noindex": NOINDEX,96 }979899@app.get("/api/public")100def api_public():101 """La règle « public », mesurée : combien d'annonces sont publiques et102 pourquoi les autres ne le sont pas."""103 cat = catalogue()104 return _json({105 "generated_at": cat.ts, "build_seconds": cat.duree,106 "rows_in_database": cat.total_base, "active": cat.actives,107 "public": len(cat.items),108 "excluded": cat.actives - len(cat.items),109 "excluded_by_reason": [110 {"code": k, "n": n, "label": public.RAISONS[k]}111 for k, n in sorted(cat.raisons.items(), key=lambda kv: -kv[1])],112 "thresholds": {113 "price_min": public.PRIX_MIN, "price_max": public.PRIX_MAX,114 "payment_max": public.PAIEMENT_MAX, "payment_age_years": public.PAIEMENT_AGE,115 "km_max": public.KM_MAX, "year_min": public.ANNEE_MIN,116 "year_max": public.ANNEE + 1, "stale_days": public.PERIME_JOURS},117 "data_quality": cat.mesures,118 "rule": [119 "active (encore affichée par sa source) et confirmée depuis moins de "120 f"{public.PERIME_JOURS} jours",121 "un vrai véhicule à vendre : ni transfert de bail, ni location, ni pièce, "122 "ni prix « à partir de » d'un financement",123 "prix plausible (plancher par type, plafond, paiement déguisé écarté)",124 "marque et modèle reconnus, année plausible",125 "au moins une photo, ou au moins quatre caractéristiques",126 "au Québec",127 "sans doublon : même NIV ; puis même concessionnaire + marque + modèle + "128 "année + kilométrage + prix ; puis même marque + modèle + année + "129 "kilométrage + prix entre sources différentes",130 ],131 })132133134# =============================================================================135# Filtres136# =============================================================================137def _csv(v: str | None) -> list[str]:138 return [x.strip() for x in (v or "").split(",") if x.strip()]139140141_FUEL_ALIAS = {142 "electrique": ("Électrique",), "ev": ("Électrique",),143 "hybride": ("Hybride", "Hybride rechargeable"),144 "hybride-simple": ("Hybride",),145 "hybride-rechargeable": ("Hybride rechargeable",), "phev": ("Hybride rechargeable",),146 "electrifie": ("Électrique", "Hybride", "Hybride rechargeable"),147 "essence": ("Essence",), "diesel": ("Diesel",),148}149_DRIVE_ALIAS = {"integrale-4x4": "Intégrale / 4x4", "awd": "Intégrale / 4x4",150 "4x4": "Intégrale / 4x4", "integrale": "Intégrale / 4x4",151 "traction": "Traction", "fwd": "Traction",152 "propulsion": "Propulsion", "rwd": "Propulsion"}153_VERDICTS = {"excellent", "bon", "marche", "eleve"}154_VCODE = {v: k for k, v in public.VERDICT_CODES.items()}155_KINDS = ("auto", "moto", "scooter")156157158def _int(v, nom: str) -> int | None:159 if v is None:160 return None161 try:162 return int(float(v))163 except (TypeError, ValueError):164 raise HTTPException(400, f"{nom} : entier attendu")165166167def _num(v, nom: str) -> float | None:168 if v is None:169 return None170 try:171 return float(v)172 except (TypeError, ValueError):173 raise HTTPException(400, f"{nom} : nombre attendu")174175176def _flag(v) -> bool:177 return str(v or "").lower() in ("1", "true", "oui", "yes")178179180class Filtres:181 """Filtres de recherche décodés. Chaque dimension est un prédicat ; les182 facettes comptent en ignorant la dimension qu'elles décrivent."""183184 def __init__(self, p: dict) -> None:185 cat = catalogue()186 self.preds: dict[str, object] = {}187 self.centre: tuple[float, float] | None = None188 g = lambda k: (p.get(k) if p.get(k) not in (None, "") else None) # noqa: E731189190 kind = (g("kind") or "auto").lower()191 if kind not in ("tous", "all"):192 if kind not in _KINDS:193 raise HTTPException(400, f"kind inconnu : {kind} (auto, moto, scooter, tous)")194 self.preds["kind"] = lambda v, k=kind: v["kind"] == k195196 makes = {cle(x) for x in _csv(g("make"))}197 if makes:198 self.preds["make"] = lambda v, s=makes: cle(v["make"]) in s199 models = {cle(x) for x in _csv(g("model"))}200 if models:201 self.preds["model"] = lambda v, s=models: v["_mdk"] in s202 trim = g("trim")203 if trim:204 t = public._ascii(trim).lower()205 self.preds["trim"] = lambda v, t=t: t in public._ascii(v["trim"]).lower()206207 ymin, ymax = _int(g("year_min"), "year_min"), _int(g("year_max"), "year_max")208 if ymin is not None or ymax is not None:209 lo, hi = ymin or 0, ymax or 9999210 self.preds["year"] = lambda v, lo=lo, hi=hi: lo <= v["year"] <= hi211 pmin, pmax = _num(g("price_min"), "price_min"), _num(g("price_max"), "price_max")212 if pmin is not None or pmax is not None:213 lo, hi = pmin or 0, pmax if pmax is not None else 1e12214 self.preds["price"] = lambda v, lo=lo, hi=hi: lo <= v["price"] <= hi215 kmin, kmax = _num(g("km_min"), "km_min"), _num(g("km_max"), "km_max")216 if kmin is not None or kmax is not None:217 lo, hi = kmin or 0, kmax if kmax is not None else 1e12218 self.preds["km"] = lambda v, lo=lo, hi=hi: (219 v["mileage_km"] is not None and lo <= v["mileage_km"] <= hi)220221 bodies = {cle(x) for x in _csv(g("body_type"))}222 if bodies:223 self.preds["body_type"] = lambda v, s=bodies: cle(v["body_type"]) in s224 fuels: set[str] = set()225 for x in _csv(g("fuel")):226 fuels.update(_FUEL_ALIAS.get(slugify(x), (x,)))227 if fuels:228 fk = {cle(x) for x in fuels}229 self.preds["fuel"] = lambda v, s=fk: cle(v["fuel"]) in s230 tr = {cle(x) for x in _csv(g("transmission"))}231 if tr:232 self.preds["transmission"] = lambda v, s=tr: cle(v["transmission"]) in s233 dr = {cle(_DRIVE_ALIAS.get(slugify(x), x)) for x in _csv(g("drivetrain"))}234 if dr:235 self.preds["drivetrain"] = lambda v, s=dr: cle(v["drivetrain"]) in s236 col = {cle(x) for x in _csv(g("color"))}237 if col:238 self.preds["color"] = lambda v, s=col: cle(v["color"]) in s239240 cities = {cle(public.ville_propre(x.replace("-", " ")) or x) for x in _csv(g("city"))}241 if cities:242 self.preds["city"] = lambda v, s=cities: cle(v["city"]) in s243 regions = {cle(x) for x in _csv(g("region"))}244 if regions:245 self.preds["region"] = lambda v, s=regions: cle(v["region"]) in s246247 lat, lng = _num(g("lat"), "lat"), _num(g("lng"), "lng")248 rayon = _num(g("radius_km"), "radius_km")249 pres = g("near")250 if pres and (lat is None or lng is None):251 e = cat.villes.get(slugify(public.ville_propre(pres.replace("-", " ")) or pres))252 if e is None or e["lat"] is None:253 raise HTTPException(400, f"near : ville inconnue ou sans position ({pres})")254 lat, lng = e["lat"], e["lng"]255 if lat is not None and lng is not None:256 self.centre = (lat, lng)257 if rayon is not None:258 if not (0 < rayon <= 2000):259 raise HTTPException(400, "radius_km doit être entre 0 et 2000")260 hav = public.haversine261 dlat = rayon / 111.0262 self.preds["geo"] = lambda v, a=lat, b=lng, r=rayon, d=dlat: (263 v["lat"] is not None and abs(v["lat"] - a) <= d264 and hav(a, b, v["lat"], v["lng"]) <= r)265 bbox = g("bbox")266 if bbox:267 try:268 w, s_, e_, n = (float(x) for x in bbox.split(","))269 except ValueError:270 raise HTTPException(400, "bbox attendu : ouest,sud,est,nord")271 prev = self.preds.get("geo")272 self.preds["geo"] = lambda v, w=w, s_=s_, e_=e_, n=n, prev=prev: (273 v["lat"] is not None and s_ <= v["lat"] <= n and w <= v["lng"] <= e_274 and (prev is None or prev(v)))275276 dealer = g("dealer")277 if dealer:278 dk = {slugify(x, 60) for x in _csv(dealer)}279 self.preds["dealer"] = lambda v, s=dk: v["_dk"] in s280 src = set(_csv(g("source")))281 if src:282 self.preds["source"] = lambda v, s=src: v["source"] in s283 vd = {_VCODE.get(x, x) for x in _csv(g("verdict"))}284 if vd:285 if vd - _VERDICTS - {"aucun"}:286 raise HTTPException(400, "verdict : excellent, bon, marche, eleve, aucun")287 self.preds["verdict"] = lambda v, s=vd: (v["_vc"] or "aucun") in s288 st = set(_csv(g("status")))289 if st:290 self.preds["status"] = lambda v, s=st: v["status"] in s291 seller = g("seller")292 if seller in ("particulier", "concessionnaire"):293 want = seller == "particulier"294 self.preds["seller"] = lambda v, w=want: v["private_seller"] is w295 elif seller:296 raise HTTPException(400, "seller : particulier ou concessionnaire")297 if _flag(g("price_drop")):298 self.preds["drop"] = lambda v: bool(v["price_change"]) and v["price_change"]["delta"] < 0299 if _flag(g("with_photo")):300 self.preds["photo"] = lambda v: v["n_img"] > 0301 dmax = _int(g("days_max"), "days_max")302 if dmax is not None:303 self.preds["days"] = lambda v, d=dmax: v["days_listed"] <= d304 q = g("q")305 if q:306 mots = [m for m in public._ascii(q).lower().split() if m][:8]307 if mots:308 self.preds["q"] = lambda v, ms=mots: all(m in v["_q"] for m in ms)309310 def filtrer(self, items: list[dict]) -> list[dict]:311 fs = list(self.preds.values())312 if not fs:313 return items314 return [v for v in items if all(f(v) for f in fs)]315316317_PARAMS = ("kind", "make", "model", "trim", "year_min", "year_max", "price_min",318 "price_max", "km_min", "km_max", "body_type", "fuel", "transmission",319 "drivetrain", "color", "city", "region", "near", "lat", "lng", "radius_km",320 "bbox", "dealer", "source", "verdict", "status", "seller", "price_drop",321 "with_photo", "days_max", "q")322323324def _filtres(request) -> Filtres:325 qp = request.query_params326 return Filtres({k: qp.get(k) for k in _PARAMS})327328329def _clef_requete(request) -> tuple:330 return tuple(sorted((k, v) for k, v in request.query_params.items()331 if k in _PARAMS and v != ""))332333334# =============================================================================335# /api/search — recherche unifiée liste + carte336# =============================================================================337PAGE_MAX = 100338_SORTS = {339 "recent": lambda v: -(v["first_seen"] or 0),340 "price_asc": lambda v: v["price"],341 "price_desc": lambda v: -v["price"],342 "km_asc": lambda v: v["mileage_km"] if v["mileage_km"] is not None else 1e12,343 "km_desc": lambda v: -(v["mileage_km"] or -1),344 "year_desc": lambda v: (-v["year"], v["price"]),345 "year_asc": lambda v: (v["year"], v["price"]),346 "deal": lambda v: (v["price_verdict"]["deviation_pct"] if v["price_verdict"] else 1e9),347 "drop": lambda v: (v["price_change"]["pct"] if v["price_change"] else 1e9),348 "distance": None,349}350_POINTS_FORMAT = ["lat", "lng", "n", "price_min", "price_median", "city", "dealer_id", "uid"]351352353def _points(res: list[dict]) -> list[list]:354 """Points de carte : un par POSITION (les véhicules d'un même commerce355 partagent ses coordonnées)."""356 g: dict[tuple, list] = defaultdict(list)357 for v in res:358 if v["lat"] is not None:359 g[(v["lat"], v["lng"])].append(v)360 out = []361 for (lat, lng), vs in g.items():362 prix = sorted(x["price"] for x in vs)363 dealers = {x["dealer_id"] for x in vs}364 out.append([lat, lng, len(vs), int(prix[0]), int(prix[len(prix) // 2]),365 vs[0]["city"], next(iter(dealers)) if len(dealers) == 1 else None,366 vs[0]["uid"] if len(vs) == 1 else None])367 out.sort(key=lambda p: -p[2])368 return out369370371def _recherche(cat, request, f: Filtres, sort: str) -> dict:372 def fabrique():373 res = f.filtrer(cat.items)374 if sort == "distance":375 if f.centre is None:376 raise HTTPException(400, "sort=distance exige lat et lng (ou near)")377 a, b = f.centre378 hav = public.haversine379 res = sorted(res, key=lambda v: hav(a, b, v["lat"], v["lng"])380 if v["lat"] is not None else 1e9)381 else:382 res = sorted(res, key=_SORTS[sort])383 return {"res": res, "points": None,384 "unpositioned": sum(1 for v in res if v["lat"] is None)}385 # une entrée garde la liste triée entière (jusqu'à 47 000 références) : LRU court386 return _memo(cat, "search", (_clef_requete(request), sort), fabrique, maxi=48)387388389@app.get("/api/search")390def search(request: Request, sort: str = "recent", page: int = 1,391 page_size: int = 24, points: int = 0):392 """Recherche unifiée : une page de résultats, le total et (points=1) les393 points de carte de TOUS les résultats."""394 if sort not in _SORTS:395 raise HTTPException(400, "sort inconnu : " + ", ".join(_SORTS))396 if page < 1 or not (1 <= page_size <= PAGE_MAX):397 raise HTTPException(400, f"page >= 1 et 1 <= page_size <= {PAGE_MAX}")398 cat = catalogue()399 f = _filtres(request)400 r = _recherche(cat, request, f, sort)401 res = r["res"]402 total = len(res)403 debut = (page - 1) * page_size404 cartes = [carte(v) for v in res[debut:debut + page_size]]405 if f.centre is not None:406 a, b = f.centre407 for c in cartes:408 c["distance_km"] = (round(public.haversine(a, b, c["lat"], c["lng"]), 1)409 if c["lat"] is not None else None)410 out = {"total": total, "page": page, "page_size": page_size,411 "pages": (total + page_size - 1) // page_size, "sort": sort,412 "unpositioned": r["unpositioned"], "generated_at": cat.ts,413 "listings": cartes}414 if points:415 if r["points"] is None:416 r["points"] = _points(res)417 out["points"] = r["points"]418 out["points_format"] = _POINTS_FORMAT419 return _json(out)420421422@app.get("/api/count")423def count(request: Request):424 """Nombre de résultats pour des filtres (bouton « Voir N véhicules »)."""425 cat = catalogue()426 f = _filtres(request)427 n = _memo(cat, "count", _clef_requete(request), lambda: (len(f.filtrer(cat.items)),))428 return _json({"total": n[0], "generated_at": cat.ts})429430431# =============================================================================432# /api/facets433# =============================================================================434_FACETTES = {435 "kind": lambda v: v["kind"], "make": lambda v: v["make"],436 "model": lambda v: v["model"], "body_type": lambda v: v["body_type"],437 "fuel": lambda v: v["fuel"], "transmission": lambda v: v["transmission"],438 "drivetrain": lambda v: v["drivetrain"], "color": lambda v: v["color"],439 "city": lambda v: v["city"], "region": lambda v: v["region"],440 "source": lambda v: v["source"], "status": lambda v: v["status"],441 "verdict": lambda v: v["_vc"] or "aucun", "year": lambda v: v["year"],442 "dealer": lambda v: v["_dk"],443}444445446def _plage(vals: list[float]) -> dict:447 if not vals:448 return {"min": None, "max": None, "median": None}449 vals = sorted(vals)450 return {"min": int(vals[0]), "max": int(vals[-1]), "median": int(vals[len(vals) // 2])}451452453def _facettes(cat, f: Filtres) -> dict:454 preds = list(f.preds.items())455 compte: dict[str, Counter] = {d: Counter() for d in _FACETTES}456 total = 0457 prix: list[float] = []458 kms: list[float] = []459 for v in cat.items:460 rate = None461 ok = True462 for dim, fn in preds:463 if not fn(v):464 if rate is not None:465 ok = False466 break467 rate = dim468 if not ok:469 continue470 if rate is None:471 total += 1472 prix.append(v["price"])473 if v["mileage_km"] is not None:474 kms.append(v["mileage_km"])475 for d, val in _FACETTES.items():476 compte[d][val(v)] += 1477 elif rate in compte:478 compte[rate][_FACETTES[rate](v)] += 1479480 def liste(d, limite=None, tri_valeur=False):481 it = [(k, n) for k, n in compte[d].items() if k not in (None, "")]482 it.sort(key=(lambda kv: kv[0]) if tri_valeur else (lambda kv: (-kv[1], str(kv[0]))))483 return [{"value": k, "n": n} for k, n in it[:limite]]484 reg = cat.sources485 annees = [k for k in compte["year"] if k]486 return {487 "total": total, "generated_at": cat.ts,488 "kinds": liste("kind"),489 "makes": [dict(x, slug=slugify(x["value"])) for x in liste("make")],490 "models": [dict(x, slug=slugify(x["value"])) for x in liste("model", 400)],491 "body_types": liste("body_type"), "fuels": liste("fuel"),492 "transmissions": liste("transmission"), "drivetrains": liste("drivetrain"),493 "colors": liste("color"),494 "regions": [dict(x, slug=slugify(x["value"])) for x in liste("region")],495 "cities": [dict(x, slug=slugify(x["value"])) for x in liste("city", 600)],496 "sources": [dict(x, name=(reg.get(x["value"]) or {}).get("name", x["value"]))497 for x in liste("source")],498 "statuses": liste("status"),499 "verdicts": [dict(x, label=public.VERDICT_LIBELLES.get(x["value"], "Sans verdict"))500 for x in liste("verdict")],501 "years": liste("year", None, True),502 "dealers": [dict(x, name=(cat.dealers.get(x["value"]) or {}).get("name", x["value"]))503 for x in liste("dealer", 60)],504 "unknown": {d: compte[d].get("", 0) + compte[d].get(None, 0)505 for d in ("body_type", "fuel", "transmission", "drivetrain", "color",506 "city", "region", "dealer")},507 "ranges": {"price": _plage(prix), "mileage_km": _plage(kms),508 "year": {"min": min(annees, default=None), "max": max(annees, default=None)}},509 "verdict_thresholds": public.verdict_methode()["seuils_pct"],510 }511512513@app.get("/api/facets")514def facets(request: Request):515 """Valeurs et comptes de chaque filtre, DÉPENDANTS des filtres actifs :516 chaque facette est comptée en ignorant son propre filtre (avec make=Honda,517 `makes` liste toujours toutes les marques et `models` les modèles Honda)."""518 cat = catalogue()519 f = _filtres(request)520 return _json(_memo(cat, "facets", _clef_requete(request), lambda: _facettes(cat, f)))521522523# =============================================================================524# /api/listings/{uid} — fiche525# =============================================================================526def _ligne(uid: str):527 con = db.connect_ro()528 try:529 row = con.execute("SELECT * FROM vehicles WHERE uid=?", (uid,)).fetchone()530 hist = [dict(r) for r in con.execute(531 "SELECT ts, price FROM price_log WHERE uid=? ORDER BY ts", (uid,))] if row else []532 finally:533 con.close()534 return row, hist535536537def _json_col(val, defaut):538 try:539 out = json.loads(val) if val else defaut540 return out if isinstance(out, type(defaut)) else defaut541 except ValueError:542 return defaut543544545def _score(v: dict, n_images: int, description: str, features: list) -> dict:546 """Score composite (0-100) : prix, kilométrage, qualité de la fiche, fraîcheur."""547 parts: list[dict] = []548 vd = v.get("price_verdict")549 if vd:550 s = max(0, min(100, round(50 - vd["deviation_pct"] * 2.5)))551 parts.append({"key": "prix", "label": "Prix face au marché", "score": s, "weight": 40})552 if v.get("mileage_km") is not None and v.get("year"):553 age = max(public.ANNEE - v["year"], 0.5)554 ratio = v["mileage_km"] / (age * stats.KM_PAR_AN)555 parts.append({"key": "km", "label": "Kilométrage pour l'âge",556 "score": max(0, min(100, round(100 - (ratio - 0.4) * 100))), "weight": 25})557 complet = sum((n_images >= 5, bool(description), bool(features),558 len(v.get("vin") or "") == 17, bool(v.get("has_carfax")),559 v.get("mileage_km") is not None,560 bool(v.get("transmission")) and bool(v.get("fuel")),561 v.get("lat") is not None))562 parts.append({"key": "fiche", "label": "Qualité de la fiche",563 "score": round(complet / 8 * 100), "weight": 20})564 jours = v.get("days_listed") or 0565 parts.append({"key": "fraicheur", "label": "Fraîcheur de l'annonce",566 "score": max(0, min(100, round(100 - jours * 100 / 90))), "weight": 15})567 tw = sum(p["weight"] for p in parts)568 return {"overall": round(sum(p["score"] * p["weight"] for p in parts) / tw),569 "parts": parts, "km_per_year_reference": stats.KM_PAR_AN}570571572def _similaires(cat, v: dict, n: int = 8) -> list[dict]:573 comps = [x for x in cat.items574 if x["make"] == v["make"] and x["_mdk"] == v["_mdk"] and x["uid"] != v["uid"]575 and x["kind"] == v["kind"]]576 if len(comps) < n:577 comps += [x for x in cat.items578 if x["kind"] == v["kind"] and x["body_type"] and x["body_type"] == v["body_type"]579 and x["make"] != v["make"] and abs(x["price"] - v["price"]) <= 0.15 * v["price"]580 and abs(x["year"] - v["year"]) <= 2][: 3 * n]581 comps.sort(key=lambda x: (x["make"] != v["make"], abs(x["year"] - v["year"]),582 abs(x["price"] - v["price"])))583 return [carte(x) for x in comps[:n]]584585586def _nuage(cat, v: dict) -> list[dict]:587 """Comparables du verdict (prix bruts et kilométrage) pour le graphique."""588 comps = cat.marche.get((v["make"], v["_mdk"], public._motorisation(v["fuel"])), ())589 span = (v["price_verdict"] or {}).get("year_span", 1)590 pts = [{"uid": u, "year": y, "mileage_km": int(k), "price": int(p)}591 for y, k, p, u in comps if abs(y - v["year"]) <= span and u != v["uid"]]592 if len(pts) > 200:593 pas = len(pts) / 200.0594 pts = [pts[int(i * pas)] for i in range(200)]595 return pts596597598_VIN_FILE: set[str] = set()599_VIN_LOCK = threading.Lock()600601602def _vin_info(vin: str):603 """Fiche constructeur : servie du cache ; sinon décodée en arrière-plan604 (la fiche n'attend pas la NHTSA) — `vin_info` vaut alors null et605 `vin_info_pending` true ; /api/vin/{niv} attend la réponse."""606 from . import vindecode607 if len(vin or "") != 17:608 return None, False609 info = vindecode.decode_v2(vin, reseau=False)610 if info is not None or vindecode.en_cache(vin):611 return info, False612 with _VIN_LOCK:613 if vin in _VIN_FILE or len(_VIN_FILE) > 50:614 return None, True615 _VIN_FILE.add(vin)616617 def tache():618 try:619 vindecode.decode_v2(vin, reseau=True)620 finally:621 with _VIN_LOCK:622 _VIN_FILE.discard(vin)623 threading.Thread(target=tache, daemon=True).start()624 return None, True625626627def fiche(uid: str) -> dict | None:628 """Tout ce qu'on sait d'une annonce (publique ou non, active ou retirée)."""629 cat = catalogue()630 row, hist = _ligne(uid)631 if row is None:632 return None633 r = dict(row)634 images = [public.image_propre(u) for u in _json_col(r.get("images"), []) if isinstance(u, str)]635 features = [x for x in _json_col(r.get("features"), []) if isinstance(x, str)]636 details = _json_col(r.get("details"), {})637 pub = cat.par_uid.get(uid)638 if pub is not None:639 v = carte(pub)640 v.update({k: pub[k] for k in ("interior_color", "engine", "doors", "seats",641 "price_label", "updated_at", "offers",642 "title_raw", "make_raw", "model_raw", "city_raw",643 "color_raw", "fuel_raw")})644 v["public"] = True645 v["exclusion"] = None646 base = pub647 else:648 # annonce retirée ou écartée : normalisation minimale, jamais de verdict649 kind = r.get("kind") or "auto"650 mk, ok = public.marque(r.get("make"), kind)651 mdl = public.modele_propre(mk, r.get("model"))652 if ok and mdl and mk in cat.modeles:653 mdl, _reste = cat.modeles[mk].resoudre(mdl)654 ville = public.ville_propre(r.get("city"))655 titre = " ".join(str(x) for x in (r.get("year"), mk, mdl) if x) or (r.get("title") or "")656 code = "inactive" if not r.get("active") else cat.exclues.get(uid, "perimee")657 v = {658 "uid": uid, "source": r["source"], "url": r.get("url"), "kind": kind,659 "title": titre, "title_raw": r.get("title") or "", "make": mk, "model": mdl,660 "make_raw": r.get("make") or "", "model_raw": r.get("model") or "",661 "trim": r.get("trim") or "", "year": r.get("year"), "price": r.get("price"),662 "price_label": r.get("price_label") or "", "mileage_km": r.get("mileage_km"),663 "transmission": public.transmission(r.get("transmission")),664 "fuel": public.carburant(r.get("fuel")), "fuel_raw": r.get("fuel") or "",665 "drivetrain": public.rouage(r.get("drivetrain")),666 "body_type": public.carrosserie(r.get("body_type"), kind),667 "color": public.couleur(r.get("exterior_color")),668 "color_raw": r.get("exterior_color") or "",669 "exterior_color": r.get("exterior_color") or "",670 "interior_color": r.get("interior_color") or "", "engine": r.get("engine") or "",671 "doors": r.get("doors"), "seats": r.get("seats"), "vin": r.get("vin") or "",672 "stock_number": r.get("stock_number") or "",673 "dealer_name": r.get("dealer_name") or "", "dealer_id": None,674 "city": ville, "city_raw": r.get("city") or "",675 "region": public.region_canon(r.get("region")),676 "lat": r.get("lat"), "lng": r.get("lng"),677 "n_img": len(images), "img": images[0] if images else None,678 "n_feat": len(features), "has_carfax": bool(r.get("carfax_url")),679 "first_seen": r.get("first_seen"), "last_seen": r.get("last_seen"),680 "updated_at": r.get("updated_at"), "status": "occasion",681 "private_seller": details.get("forsaleby") == "particulier",682 "price_verdict": None, "price_change": None, "offers": [],683 "offers_count": 0,684 "source_name": (cat.sources.get(r["source"]) or {}).get("name", r["source"]),685 "slug": slugify(titre), "days_listed": None,686 "make_slug": slugify(mk), "model_slug": slugify(mdl),687 "city_slug": slugify(ville) if ville else None,688 "public": False,689 "exclusion": {"code": code, "label": public.RAISONS.get(code, code)},690 }691 v["path"] = f"/vehicule/{public._quote(uid)}/{v['slug']}"692 base = None693 v["active"] = bool(r.get("active"))694 v["description"] = (r.get("description") or "").strip()695 v["features"] = features696 v["images"] = images697 v["carfax_url"] = r.get("carfax_url") or ""698 v["details"] = details699 v["price_history"] = hist700 v["dealer"] = cat.dealers.get(v.get("dealer_id") or "")701 if base is not None:702 v["similar"] = _similaires(cat, base)703 v["market_points"] = _nuage(cat, base) if base["price_verdict"] else []704 v["score"] = _score(base, len(images), v["description"], features)705 else:706 v["similar"], v["market_points"], v["score"] = [], [], None707 # rappels de sécurité (Transports Canada) : marque, modèle, année708 try:709 from . import recalls as recalls_mod710 con = db.connect_ro()711 try:712 rc = recalls_mod.for_vehicle(con, v["make"], v["model"], v["year"], ensure=False)713 finally:714 con.close()715 v["recalls"] = {"checked": bool(v["make"] and v["model"] and v["year"]),716 "count": len(rc), "items": rc[:40]}717 except Exception: # noqa: BLE001718 v["recalls"] = {"checked": False, "count": 0, "items": []}719 info, attente = _vin_info(v.get("vin") or "")720 v["vin_info"] = info721 v["vin_info_pending"] = attente722 v["links"] = {"page": v["path"], "pdf": f"/api/listings/{public._quote(uid)}/pdf",723 "source": v.get("url")}724 return v725726727@app.get("/api/listings/{uid}")728def get_listing(uid: str):729 v = fiche(uid)730 if v is None:731 raise HTTPException(404, "Annonce introuvable")732 return _json(v, max_age=30)733734735@app.get("/api/listings/{uid}/recalls")736def listing_recalls(uid: str):737 v = fiche(uid)738 if v is None:739 raise HTTPException(404, "Annonce introuvable")740 return _json({"uid": uid, "make": v["make"], "model": v["model"], "year": v["year"],741 **v["recalls"]})742743744_PDF_CACHE: dict = {}745_PDF_LOCK = threading.Lock()746747748@app.get("/api/listings/{uid}/pdf")749def listing_pdf(uid: str):750 v = fiche(uid)751 if v is None:752 raise HTTPException(404, "Annonce introuvable")753 from . import fichepdf754 clef = (uid, v.get("updated_at"), v.get("price"))755 with _PDF_LOCK:756 hit = _PDF_CACHE.get(clef)757 if hit is None or time.time() - hit[0] > 900:758 # la première génération télécharge la photo (≈ 2 s) ; ensuite c'est le cache759 hit = (time.time(), fichepdf.construire(v))760 with _PDF_LOCK:761 _PDF_CACHE[clef] = hit762 while len(_PDF_CACHE) > 48:763 _PDF_CACHE.pop(next(iter(_PDF_CACHE)))764 pdf = hit[1]765 nom = f"auto-ka-{v['slug']}-{hashlib.md5(uid.encode()).hexdigest()[:6]}.pdf"766 return Response(content=pdf, media_type="application/pdf",767 headers={"Content-Disposition": f'inline; filename="{nom}"',768 "Cache-Control": "public, max-age=300"})769770771# =============================================================================772# NIV et rappels773# =============================================================================774@app.get("/api/vin/{vin}")775def vin_decode(vin: str):776 """Décodage d'un NIV (vPIC de la NHTSA, mis en cache)."""777 from . import vindecode778 vin = vin.strip().upper()779 if not public._VIN_RE.match(vin):780 raise HTTPException(400, "NIV invalide : 17 caractères, sans I, O ni Q")781 info = vindecode.decode_v2(vin, reseau=True)782 cat = catalogue()783 annonces = [carte(v) for v in cat.items if v["vin"] == vin]784 return _json({"vin": vin, "decoded": info is not None, "info": info or {},785 "listings": annonces}, max_age=3600)786787788@app.get("/api/recalls")789def recalls(make: str, model: str, year: int):790 """Rappels de sécurité de Transports Canada pour une marque, un modèle, une année."""791 from . import recalls as recalls_mod792 mk, _ok = public.marque(make, "auto")793 con = db.connect_ro()794 try:795 rc = recalls_mod.for_vehicle(con, mk or make, model, year, ensure=False)796 finally:797 con.close()798 return _json({"make": mk or make, "model": model, "year": year, "count": len(rc),799 "recalls": rc, "source": "Transports Canada — base de données des rappels"},800 max_age=3600)801802803# =============================================================================804# Concessionnaires805# =============================================================================806@app.get("/api/concessionnaires")807def concessionnaires(q: str | None = None, region: str | None = None,808 city: str | None = None, make: str | None = None,809 sort: str = "listings", page: int = 1, page_size: int = 60):810 """Annuaire des concessionnaires et marchands qui ont au moins une annonce publique."""811 cat = catalogue()812 if not (1 <= page_size <= 2000) or page < 1:813 raise HTTPException(400, "page >= 1 et 1 <= page_size <= 2000")814 lst = list(cat.dealers.values())815 if q:816 k = public._ascii(q).lower()817 lst = [d for d in lst if k in public._ascii(d["name"] + " " + d["city"]).lower()]818 if region:819 lst = [d for d in lst if cle(d["region"]) == cle(region)]820 if city:821 ck = cle(public.ville_propre(city.replace("-", " ")) or city)822 lst = [d for d in lst if cle(d["city"]) == ck]823 if make:824 mk = cle(make)825 lst = [d for d in lst if any(cle(m["make"]) == mk for m in d["makes"])]826 if sort == "name":827 lst.sort(key=lambda d: public._ascii(d["name"]).lower())828 else:829 lst.sort(key=lambda d: (-d["listings"], d["name"]))830 total = len(lst)831 debut = (page - 1) * page_size832 return _json({833 "total": total, "page": page, "page_size": page_size,834 "listings_total": sum(d["listings"] for d in lst),835 "private_listings": sum(1 for v in cat.items if v["private_seller"]),836 "generated_at": cat.ts,837 "dealers": lst[debut:debut + page_size]})838839840@app.get("/api/concessionnaires/{dealer_id}")841def concessionnaire(dealer_id: str, sort: str = "recent", page: int = 1, page_size: int = 24):842 out = page_concessionnaire(catalogue(), dealer_id, sort, page, page_size)843 if out is None:844 raise HTTPException(404, "Concessionnaire introuvable")845 return _json(out)846847848def page_concessionnaire(cat, dealer_id: str, sort: str = "recent", page: int = 1,849 page_size: int = 24) -> dict | None:850 d = cat.dealers.get(dealer_id)851 if d is None:852 return None853 if sort not in _SORTS or sort == "distance":854 raise HTTPException(400, "sort inconnu")855 if page < 1 or not (1 <= page_size <= PAGE_MAX):856 raise HTTPException(400, f"page >= 1 et 1 <= page_size <= {PAGE_MAX}")857 inv = sorted((v for v in cat.items if v["_dk"] == dealer_id), key=_SORTS[sort])858 debut = (page - 1) * page_size859 return {860 **d, "total": len(inv), "page": page, "page_size": page_size,861 "pages": (len(inv) + page_size - 1) // page_size,862 "price": _plage([v["price"] for v in inv]),863 "body_types": [{"value": k, "n": n} for k, n in864 Counter(v["body_type"] for v in inv if v["body_type"]).most_common()],865 "verdicts": dict(Counter(v["_vc"] or "aucun" for v in inv)),866 "source_names": [{"id": s, "name": (cat.sources.get(s) or {}).get("name", s),867 "url": (cat.sources.get(s) or {}).get("url")} for s in d["sources"]],868 "listings": [carte(v) for v in inv[debut:debut + page_size]],869 "search": {"kind": "tous", "dealer": dealer_id},870 "generated_at": cat.ts}871872873# =============================================================================874# Pages par marque, par modèle, par ville, par région875# =============================================================================876def _resume(vs: list[dict]) -> dict:877 prix = sorted(v["price"] for v in vs)878 kms = sorted(v["mileage_km"] for v in vs if v["mileage_km"] is not None)879 ans = [v["year"] for v in vs]880 return {"n": len(vs),881 "price_median": int(prix[len(prix) // 2]) if prix else None,882 "price_min": int(prix[0]) if prix else None,883 "price_max": int(prix[-1]) if prix else None,884 "km_median": int(kms[len(kms) // 2]) if kms else None,885 "year_min": min(ans) if ans else None, "year_max": max(ans) if ans else None}886887888_PREFIXE = {"auto": "/usagees", "moto": "/motos", "scooter": "/scooters"}889890891def index_marques(cat) -> dict:892 def fabrique():893 par: dict[tuple, list] = defaultdict(list)894 for v in cat.items:895 par[(v["kind"], v["make"])].append(v)896 out: dict[str, list] = {k: [] for k in _KINDS}897 for (kind, mk), vs in par.items():898 out[kind].append({"make": mk, "slug": slugify(mk),899 "path": f"{_PREFIXE[kind]}/{slugify(mk)}",900 **_resume(vs), "models": len({v["model"] for v in vs})})901 for k in out:902 out[k].sort(key=lambda m: -m["n"])903 return out904 return cat.calcul("marques", fabrique)905906907@app.get("/api/marques")908def marques(kind: str = "auto"):909 cat = catalogue()910 if kind not in _KINDS:911 raise HTTPException(400, "kind : auto, moto ou scooter")912 lst = index_marques(cat)[kind]913 return _json({"kind": kind, "total": len(lst),914 "listings_total": sum(m["n"] for m in lst), "makes": lst,915 "generated_at": cat.ts})916917918def trouver_marque(cat, slug: str, kind: str = "auto"):919 k = cle(public._MAKE_ALIAS.get(cle(slug), slug))920 for m in index_marques(cat)[kind]:921 if cle(m["make"]) == k:922 return m923 return None924925926def page_marque(cat, slug: str, kind: str = "auto") -> dict | None:927 m = trouver_marque(cat, slug, kind)928 if m is None:929 return None930931 def fabrique():932 vs = [v for v in cat.items if v["kind"] == kind and v["make"] == m["make"]]933 par: dict[str, list] = defaultdict(list)934 for v in vs:935 par[v["model"]].append(v)936 modeles = [{"model": md, "slug": slugify(md),937 "path": (f"/usagees/{m['slug']}/{slugify(md)}" if kind == "auto" else None),938 **_resume(x)} for md, x in par.items()]939 modeles.sort(key=lambda x: -x["n"])940 return {941 **m, "kind": kind, "models": modeles,942 "years": [{"value": y, "n": n} for y, n in sorted(Counter(v["year"] for v in vs).items())],943 "body_types": [{"value": k, "n": n} for k, n in944 Counter(v["body_type"] for v in vs if v["body_type"]).most_common()],945 "fuels": [{"value": k, "n": n} for k, n in946 Counter(v["fuel"] for v in vs if v["fuel"]).most_common()],947 "regions": [{"value": k, "slug": slugify(k), "n": n} for k, n in948 Counter(v["region"] for v in vs if v["region"]).most_common()],949 "verdicts": dict(Counter(v["_vc"] or "aucun" for v in vs)),950 "listings": [carte(v) for v in sorted(vs, key=_SORTS["recent"])[:24]],951 "search": {"kind": kind, "make": m["make"]}, "generated_at": cat.ts}952 return cat.calcul(f"marque:{kind}:{m['slug']}", fabrique)953954955@app.get("/api/marques/{slug}")956def marque_detail(slug: str, kind: str = "auto"):957 cat = catalogue()958 if kind not in _KINDS:959 raise HTTPException(400, "kind : auto, moto ou scooter")960 out = page_marque(cat, slug, kind)961 if out is None:962 raise HTTPException(404, "Marque sans annonce publique")963 return _json(out)964965966def page_modele(cat, make_slug: str, model_slug: str) -> dict | None:967 m = trouver_marque(cat, make_slug, "auto")968 if m is None:969 return None970 mk = cle(model_slug)971 vs = [v for v in cat.items if v["kind"] == "auto" and v["make"] == m["make"] and v["_mdk"] == mk]972 if not vs:973 return None974 modele = vs[0]["model"]975976 def fabrique():977 par_an: dict[int, list] = defaultdict(list)978 for v in vs:979 par_an[v["year"]].append(v)980 return {981 "make": m["make"], "make_slug": m["slug"], "model": modele,982 "slug": slugify(modele), "path": f"/usagees/{m['slug']}/{slugify(modele)}",983 **_resume(vs),984 "by_year": [{"year": y, **_resume(x)} for y, x in sorted(par_an.items())],985 "trims": [{"value": k, "n": n} for k, n in986 Counter(v["trim"] for v in vs if v["trim"]).most_common(30)],987 "fuels": [{"value": k, "n": n} for k, n in988 Counter(v["fuel"] for v in vs if v["fuel"]).most_common()],989 "regions": [{"value": k, "slug": slugify(k), "n": n} for k, n in990 Counter(v["region"] for v in vs if v["region"]).most_common()],991 "verdicts": dict(Counter(v["_vc"] or "aucun" for v in vs)),992 "depreciation": stats.depreciation(cat, m["make"], modele),993 "listings": [carte(v) for v in sorted(vs, key=_SORTS["recent"])[:24]],994 "search": {"kind": "auto", "make": m["make"], "model": modele},995 "generated_at": cat.ts}996 return cat.calcul(f"modele:{m['slug']}:{mk}", fabrique)997998999@app.get("/api/marques/{slug}/{model_slug}")1000def modele_detail(slug: str, model_slug: str):1001 out = page_modele(catalogue(), slug, model_slug)1002 if out is None:1003 raise HTTPException(404, "Modèle sans annonce publique")1004 return _json(out)100510061007def index_villes(cat) -> list[dict]:1008 def fabrique():1009 par: dict[str, list] = defaultdict(list)1010 for v in cat.items:1011 if v["city"] and v["kind"] == "auto":1012 par[v["city_slug"]].append(v)1013 out = []1014 for slug, vs in par.items():1015 e = cat.villes[slug]1016 out.append({"city": e["name"], "slug": slug, "path": f"/ville/{slug}",1017 "region": e["region"], "lat": e["lat"], "lng": e["lng"],1018 **_resume(vs),1019 "dealers": len({v["_dk"] for v in vs if v["_dk"]})})1020 out.sort(key=lambda x: -x["n"])1021 return out1022 return cat.calcul("villes", fabrique)102310241025@app.get("/api/villes")1026def villes(min: int = 1, region: str | None = None):1027 cat = catalogue()1028 lst = [c for c in index_villes(cat) if c["n"] >= min]1029 if region:1030 lst = [c for c in lst if cle(c["region"]) == cle(region)]1031 sans = sum(1 for v in cat.items if v["kind"] == "auto" and not v["city"])1032 return _json({"total": len(lst), "listings_total": sum(c["n"] for c in lst),1033 "no_city": sans, "cities": lst, "generated_at": cat.ts})103410351036def trouver_ville(cat, slug: str):1037 k = cle(public.ville_propre(slug.replace("-", " ")) or slug)1038 for c in index_villes(cat):1039 if cle(c["city"]) == k:1040 return c1041 return None104210431044def page_ville(cat, slug: str) -> dict | None:1045 c = trouver_ville(cat, slug)1046 if c is None:1047 return None10481049 def fabrique():1050 vs = [v for v in cat.items if v["kind"] == "auto" and v["city_slug"] == c["slug"]]1051 dl = Counter(v["_dk"] for v in vs if v["_dk"])1052 proches = []1053 if c["lat"] is not None:1054 for o in index_villes(cat):1055 if o["slug"] != c["slug"] and o["lat"] is not None:1056 d = public.haversine(c["lat"], c["lng"], o["lat"], o["lng"])1057 if d <= 40:1058 proches.append({"city": o["city"], "slug": o["slug"], "path": o["path"],1059 "n": o["n"], "distance_km": round(d, 1)})1060 proches.sort(key=lambda x: x["distance_km"])1061 return {1062 **c,1063 "makes": [{"value": k, "slug": slugify(k), "n": n} for k, n in1064 Counter(v["make"] for v in vs).most_common(30)],1065 "body_types": [{"value": k, "n": n} for k, n in1066 Counter(v["body_type"] for v in vs if v["body_type"]).most_common()],1067 "verdicts": dict(Counter(v["_vc"] or "aucun" for v in vs)),1068 "top_dealers": [dict(cat.dealers[k], n_here=n) for k, n in dl.most_common(12)1069 if k in cat.dealers],1070 "nearby": proches[:12],1071 "listings": [carte(v) for v in sorted(vs, key=_SORTS["recent"])[:24]],1072 "search": {"kind": "auto", "city": c["city"]}, "generated_at": cat.ts}1073 return cat.calcul(f"ville:{c['slug']}", fabrique)107410751076@app.get("/api/villes/{slug}")1077def ville_detail(slug: str):1078 out = page_ville(catalogue(), slug)1079 if out is None:1080 raise HTTPException(404, "Ville sans annonce publique")1081 return _json(out)108210831084def index_regions(cat) -> dict:1085 def fabrique():1086 par: dict[str, list] = defaultdict(list)1087 for v in cat.items:1088 if v["kind"] == "auto":1089 par[v["region"]].append(v)1090 out = [{"region": r, "slug": slugify(r), "path": f"/region/{slugify(r)}",1091 **_resume(vs), "cities": len({v["city"] for v in vs if v["city"]})}1092 for r, vs in par.items() if r]1093 out.sort(key=lambda x: -x["n"])1094 return {"total": len(out), "listings_total": sum(x["n"] for x in out),1095 "no_region": len(par.get("", [])), "regions": out, "generated_at": cat.ts}1096 return cat.calcul("regions", fabrique)109710981099@app.get("/api/regions")1100def regions():1101 return _json(index_regions(catalogue()))110211031104# =============================================================================1105# Carte : densité1106# =============================================================================1107@app.get("/api/lights")1108def lights(kind: str = "auto", cell: float = 0.05):1109 """Densité de l'inventaire : un point [lat, lng, n] par cellule de `cell`1110 degrés. Sert de fond de carte."""1111 cat = catalogue()1112 if cell not in (0.02, 0.05, 0.1, 0.25):1113 raise HTTPException(400, "cell : 0.02, 0.05, 0.1 ou 0.25")1114 if kind not in _KINDS + ("tous",):1115 raise HTTPException(400, "kind : auto, moto, scooter ou tous")11161117 def fabrique():1118 g: Counter = Counter()1119 n = sans = 01120 for v in cat.items:1121 if kind == "tous" or v["kind"] == kind:1122 if v["lat"] is None:1123 sans += 11124 continue1125 g[(round(round(v["lat"] / cell) * cell, 3),1126 round(round(v["lng"] / cell) * cell, 3))] += 11127 n += 11128 pts = [[a, b, c] for (a, b), c in g.items()]1129 pts.sort(key=lambda p: -p[2])1130 return {"kind": kind, "cell_deg": cell, "total": n, "unpositioned": sans,1131 "cells": len(pts), "max": pts[0][2] if pts else 0,1132 "format": ["lat", "lng", "n"], "points": pts, "generated_at": cat.ts}1133 return _json(cat.calcul(f"lights:{kind}:{cell}", fabrique), max_age=300)113411351136# =============================================================================1137# Sources1138# =============================================================================1139def _etat_sources() -> dict:1140 con = db.connect_ro()1141 try:1142 derniers = {r["source"]: dict(r) for r in con.execute(1143 """SELECT s.source, s.ts, s.found, s.ok, s.message FROM sync_log s1144 JOIN (SELECT source, MAX(id) id FROM sync_log GROUP BY source) m ON m.id=s.id""")}1145 dernier_ok = {r["source"]: r["ts"] for r in con.execute(1146 "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 AND found>0 GROUP BY source")}1147 finally:1148 con.close()1149 return {"derniers": derniers, "ok": dernier_ok}115011511152def index_sources(cat) -> dict:1153 def fabrique():1154 etat = _etat_sources()1155 pub = Counter(v["source"] for v in cat.items)1156 now = time.time()1157 out = []1158 for sid, s in cat.sources.items():1159 d = etat["derniers"].get(sid) or {}1160 ok_ts = etat["ok"].get(sid)1161 if (s.get("status") or "actif") != "actif":1162 sante = "fermee"1163 elif not d:1164 sante = "jamais"1165 elif not d.get("ok"):1166 sante = "en_panne"1167 elif d.get("message") not in (None, "ok"):1168 sante = "en_alerte"1169 elif not d.get("found"):1170 sante = "vide"1171 elif ok_ts and now - ok_ts > 2 * 86400:1172 sante = "en_retard"1173 else:1174 sante = "ok"1175 out.append({1176 "id": sid, "name": s.get("name", sid), "url": s.get("url"),1177 "city": s.get("city", ""), "region": s.get("region", ""),1178 "type": s.get("type", "direct"),1179 "public_listings": pub.get(sid, 0),1180 "last_sync": d.get("ts"), "last_success": ok_ts,1181 "last_found": d.get("found"), "health": sante})1182 out.sort(key=lambda x: (-x["public_listings"], x["name"]))1183 return {"total": len(out), "listings_total": sum(x["public_listings"] for x in out),1184 "health": dict(Counter(x["health"] for x in out)),1185 "sources": out, "generated_at": cat.ts}1186 return cat.calcul("sources", fabrique)118711881189@app.get("/api/sources")1190def sources():1191 """Sources suivies, annonces publiques de chacune et santé de la collecte."""1192 return _json(index_sources(catalogue()))119311941195@app.get("/api/sources/names")1196def source_names():1197 cat = catalogue()1198 return _json({sid: s.get("name", sid) for sid, s in cat.sources.items()}, max_age=3600)119912001201# =============================================================================1202# Statistiques de marché1203# =============================================================================1204@app.get("/api/stats")1205def stats_apercu():1206 cat = catalogue()1207 return _json(cat.calcul("stats:apercu", lambda: stats.apercu(cat)))120812091210@app.get("/api/stats/marche")1211def stats_marche(make: str | None = None, model: str | None = None, min: int = 5):1212 """Prix médians par marque, par modèle et par année."""1213 cat = catalogue()1214 return _json(_memo(cat, "stats", ("marche", cle(make), cle(model), min),1215 lambda: stats.marche(cat, make, model, min)))121612171218@app.get("/api/stats/depreciation")1219def stats_depreciation(make: str | None = None, model: str | None = None):1220 cat = catalogue()1221 return _json(_memo(cat, "stats", ("dep", cle(make), cle(model)),1222 lambda: stats.depreciation(cat, make, model)))122312241225@app.get("/api/stats/baisses")1226def stats_baisses(days: int = 30, limit: int = 24):1227 cat = catalogue()1228 if not (1 <= days <= 365 and 1 <= limit <= 100):1229 raise HTTPException(400, "1 <= days <= 365 et 1 <= limit <= 100")1230 return _json(_memo(cat, "stats", ("baisses", days, limit),1231 lambda: stats.baisses(cat, days, limit)))123212331234@app.get("/api/stats/electriques")1235def stats_electriques():1236 cat = catalogue()1237 return _json(cat.calcul("stats:ev", lambda: stats.electriques(cat)))123812391240@app.get("/api/stats/delais")1241def stats_delais(make: str | None = None, days: int = 90):1242 """Délais avant retrait (≈ délai de vente) des annonces retirées récemment."""1243 if not (7 <= days <= 365):1244 raise HTTPException(400, "7 <= days <= 365")1245 return _json(stats.delais(make, days), max_age=600)124612471248REPORT_SITE = {"wordmark": "Auto-Ka", "accent": "#1F3A5F", "domain": "www.auto-ka.com",1249 "tagline": "Véhicules d'occasion · tout le Québec · toujours à jour"}125012511252def _dash(period, from_, to):1253 from . import statsdash1254 try:1255 return statsdash.dashboard(period, from_, to)1256 except ValueError:1257 raise HTTPException(400, "Dates invalides (format attendu : AAAA-MM-JJ)")125812591260@app.get("/api/stats/dashboard")1261def stats_dashboard(period: str = "30j", from_: str | None = Query(None, alias="from"),1262 to: str | None = None):1263 """Tableau de bord analytique par période (cache 5 min)."""1264 return _json(_dash(period, from_, to), max_age=120)126512661267@app.get("/api/stats/report")1268def stats_report(period: str = "30j", from_: str | None = Query(None, alias="from"),1269 to: str | None = None, mode: str = "complet"):1270 """Rapport PDF du marché — 5 modes : complet, synthese, tendances, repartitions, donnees."""1271 from . import rapportpdf1272 dash = _dash(period, from_, to)1273 mode = mode if mode in rapportpdf.REPORT_MODES else "complet"1274 pdf = rapportpdf.Rapport(site=REPORT_SITE, dashboard=dash, mode=mode).build()1275 nom = rapportpdf.filename("auto-ka", period, mode)1276 return Response(content=pdf, media_type="application/pdf",1277 headers={"Content-Disposition": f'attachment; filename="{nom}"'})127812791280@app.get("/api/stats/catalog")1281def stats_catalog(period: str = "30j", from_: str | None = Query(None, alias="from"),1282 to: str | None = None):1283 from . import rapportpdf1284 dash = _dash(period, from_, to)1285 return _json({"updated": dash.get("updated"), "period": dash.get("period"),1286 "blocks": rapportpdf.catalog(dash)})128712881289@app.post("/api/stats/report/custom")1290def stats_report_custom(spec: dict = Body(...)):1291 """Rapport PDF composé : {"title", "period", "from", "to", "blocks": [{"key", "render"}]}."""1292 from . import rapportpdf1293 period = str(spec.get("period") or "30j")1294 dash = _dash(period, str(spec.get("from") or "") or None, str(spec.get("to") or "") or None)1295 connus = {b["key"] for b in rapportpdf.catalog(dash)}1296 blocs = [b for b in (spec.get("blocks") or [])1297 if isinstance(b, dict) and b.get("key") in connus][:40]1298 if not blocs:1299 raise HTTPException(400, "Aucun bloc valide dans la composition")1300 pdf = rapportpdf.Rapport(site=REPORT_SITE, dashboard=dash, mode=rapportpdf.CUSTOM_MODE,1301 spec={"title": str(spec.get("title") or "")[:80],1302 "blocks": blocs}).build()1303 nom = rapportpdf.filename("auto-ka", period, rapportpdf.CUSTOM_MODE)1304 return Response(content=pdf, media_type="application/pdf",1305 headers={"Content-Disposition": f'attachment; filename="{nom}"'})130613071308# =============================================================================1309# /api/img — miniatures WebP en cache1310# =============================================================================1311_IMG_WIDTHS = (160, 320, 480, 800, 1280, 1920)1312_IMG_CACHE = ROOT / "data" / "imgcache"1313_IMG_MAX = 15 * 1024 * 10241314_HOTES: dict = {"ts": 0.0, "set": set()}131513161317def _hotes_images() -> set[str]:1318 """Hôtes d'images vus dans les annonces actives (liste blanche de /api/img)."""1319 if _HOTES["set"] and time.time() - _HOTES["ts"] < 1800:1320 return _HOTES["set"]1321 hs: set[str] = set()1322 con = db.connect_ro()1323 try:1324 for (u,) in con.execute(1325 "SELECT DISTINCT substr(json_extract(images,'$[0]'),1,90) FROM vehicles"1326 " WHERE active=1 AND json_valid(images)"):1327 if u:1328 h = urlsplit(u).hostname1329 if h:1330 hs.add(h.lower())1331 finally:1332 con.close()1333 _HOTES.update(ts=time.time(), set=hs)1334 return hs133513361337def _hote_permis(h: str) -> bool:1338 hs = _hotes_images()1339 if h in hs:1340 return True1341 if re.fullmatch(r"[\d.:]+|localhost", h) or "." not in h:1342 return False1343 # autres sous-domaines d'un CDN déjà connu (img1., img2., cdn-3.…)1344 base = "." + ".".join(h.split(".")[-2:])1345 return any(x.endswith(base) for x in hs)134613471348@app.get("/api/img")1349def img(u: str, w: int = 480):1350 """Miniature WebP d'une photo d'annonce, ramenée à `w` pixels de large et1351 gardée en cache sur disque. Seuls les hôtes d'images des annonces sont acceptés."""1352 import requests1353 from PIL import Image1354 if w not in _IMG_WIDTHS:1355 raise HTTPException(400, "w : " + ", ".join(str(x) for x in _IMG_WIDTHS))1356 parts = urlsplit(u)1357 host = (parts.hostname or "").lower()1358 if parts.scheme not in ("http", "https") or not host:1359 raise HTTPException(400, "URL d'image invalide")1360 if not _hote_permis(host):1361 raise HTTPException(403, "Hôte d'image non autorisé")1362 nom = hashlib.sha1(f"{w}|{u}".encode()).hexdigest()1363 chemin = _IMG_CACHE / nom[:2] / (nom + ".webp")1364 entetes = {"Cache-Control": "public, max-age=2592000, immutable"}1365 if chemin.is_file():1366 return Response(chemin.read_bytes(), media_type="image/webp", headers=entetes)1367 try:1368 r = requests.get(u.replace(" ", "%20"), timeout=12, stream=True,1369 allow_redirects=False, headers={1370 "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "1371 "(KHTML, like Gecko) Chrome/126 Safari/537.36",1372 "Accept": "image/avif,image/webp,image/*,*/*;q=0.8",1373 "Referer": f"{parts.scheme}://{host}/"})1374 if r.status_code != 200:1375 raise HTTPException(404, f"Image indisponible chez la source (HTTP {r.status_code})")1376 brut = r.raw.read(_IMG_MAX + 1, decode_content=True)1377 if len(brut) > _IMG_MAX:1378 raise HTTPException(413, "Image trop lourde")1379 im = Image.open(io.BytesIO(brut))1380 im.load()1381 except HTTPException:1382 raise1383 except Exception: # noqa: BLE0011384 raise HTTPException(404, "Image illisible ou indisponible")1385 if im.mode not in ("RGB", "RGBA"):1386 im = im.convert("RGBA" if "A" in im.getbands() else "RGB")1387 if im.width > w:1388 im = im.resize((w, max(1, round(im.height * w / im.width))), Image.LANCZOS)1389 tampon = io.BytesIO()1390 im.save(tampon, "WEBP", quality=78, method=4)1391 data = tampon.getvalue()1392 try:1393 chemin.parent.mkdir(parents=True, exist_ok=True)1394 tmp = chemin.with_suffix(f".{os.getpid()}.{threading.get_ident()}.tmp")1395 tmp.write_bytes(data)1396 tmp.replace(chemin)1397 except OSError:1398 pass1399 return Response(data, media_type="image/webp", headers=entetes)140014011402# =============================================================================1403# Routes retirées avec la v1 (comptes, KA ID, favoris serveur, formats v1)1404# =============================================================================1405_RETIREES = {1406 "/api/vehicles": "/api/search", "/api/vehicles/{uid}": "/api/listings/{uid}",1407 "/api/vehicles/{uid}/recalls": "/api/listings/{uid}/recalls",1408 "/api/dealers": "/api/concessionnaires", "/api/stats/detailed": "/api/stats",1409 "/api/stats/rapport.pdf": "/api/stats/report",1410}141114121413def _retiree(remplace: str | None):1414 def handler():1415 return JSONResponse({"detail": "Route retirée avec la v1 d'Auto-Ka.",1416 "replaced_by": remplace}, status_code=410)1417 return handler141814191420for _chemin, _rempl in _RETIREES.items():1421 app.add_api_route(_chemin, _retiree(_rempl), methods=["GET"], include_in_schema=False)1422for _chemin in ("/api/sync", "/api/auth/{reste:path}", "/api/kaid/{reste:path}",1423 "/api/favorites", "/api/favorites/{reste:path}", "/api/me",1424 "/ka/{reste:path}", "/me", "/logout", "/profil", "/doc", "/doc/{reste:path}"):1425 app.add_api_route(_chemin, _retiree(None), methods=["GET", "POST", "PUT", "DELETE"],1426 include_in_schema=False)142714281429@app.get("/api/{reste:path}", include_in_schema=False)1430def api_inconnue(reste: str):1431 raise HTTPException(404, "Endpoint inconnu — voir /api/docs")143214331434# =============================================================================1435# Pages rendues par le serveur (référencement) — en dernier : attrape-tout1436# =============================================================================1437app.include_router(seo.router)143814391440# =============================================================================1441# Démarrage : catalogue + préchauffage1442# =============================================================================1443class _Requete:1444 """Requête minimale (préchauffage) : mêmes clefs de cache qu'une vraie."""14451446 def __init__(self, **q):1447 self.query_params = q144814491450def _prechauffer(cat) -> None:1451 """Calcule d'avance ce que les premières visites demanderont."""1452 for q in ({}, {"kind": "moto"}, {"kind": "tous"}):1453 r = _Requete(**q)1454 f = Filtres({k: q.get(k) for k in _PARAMS})1455 _memo(cat, "facets", _clef_requete(r), lambda f=f: _facettes(cat, f))1456 for s in ("recent", "price_asc"):1457 _recherche(cat, r, f, s)["points"] = None1458 index_marques(cat)1459 index_villes(cat)1460 index_regions(cat)1461 index_sources(cat)1462 cat.calcul("stats:apercu", lambda: stats.apercu(cat))1463 cat.calcul("stats:ev", lambda: stats.electriques(cat))1464 try:1465 stats.copie_analytique(cat)1466 except Exception: # noqa: BLE0011467 import traceback1468 traceback.print_exc()146914701471public.apres_reconstruction(_prechauffer)147214731474@app.on_event("startup")1475def _demarrage() -> None:1476 public.demarrer()1477 _hotes_images()1478 threading.Thread(target=stats.prechauffer_tableau, daemon=True).start()1479