Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/web.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0613# Last Modified : 2026-11-0314#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# web.py : API FastAPI (JSON) + service du frontend React (frontend/dist)91# -----------------------------------------------------------------------------92from __future__ import annotations9394import json95import threading96import time97from pathlib import Path9899from fastapi import Body, FastAPI, HTTPException, Query100from fastapi.middleware.cors import CORSMiddleware101from fastapi.middleware.gzip import GZipMiddleware102from fastapi.responses import FileResponse103from fastapi.staticfiles import StaticFiles104105from . import db106107ROOT = Path(__file__).resolve().parent.parent108SOURCES_PATH = ROOT / "data" / "sources.json"109FRONTEND_DIST = ROOT / "frontend" / "dist"110111app = FastAPI(title="Lou-Ka API", version="2.0",112 description="Agrégateur de logements à louer — province de Québec")113app.add_middleware(CORSMiddleware, allow_origins=["*"],114 allow_methods=["*"], allow_headers=["*"])115app.add_middleware(GZipMiddleware, minimum_size=1000)116117# annuaire des déménageurs du Québec118from . import demenageurs # noqa: E402119app.include_router(demenageurs.router)120121122def _row_to_dict(row) -> dict:123 d = dict(row)124 d["amenities"] = json.loads(d.get("amenities") or "[]")125 d["images"] = json.loads(d.get("images") or "[]")126 # galerie nettoyée par le contrôle qualité (imgcheck.py) : liens morts,127 # minuscules, placeholders et doublons retirés — prime sur la galerie brute128 imgs_ok = d.pop("images_ok", None)129 if imgs_ok:130 try:131 cleaned = json.loads(imgs_ok)132 if isinstance(cleaned, list):133 d["images"] = cleaned134 except (ValueError, TypeError):135 pass136 d.pop("img_audit", None)137 d["details"] = json.loads(d.get("details") or "{}")138 # autres plateformes où l'annonce est aussi publiée (badge « aussi sur… »)139 if d.get("dup_sources"):140 try:141 d["dup_sources"] = json.loads(d["dup_sources"])142 except (ValueError, TypeError):143 d["dup_sources"] = []144 if d.get("furnished") is not None:145 d["furnished"] = bool(d["furnished"])146 return d147148149@app.get("/api/listings")150def list_listings(151 city: str | None = None,152 sector: str | None = None,153 unit_type: str | None = None,154 source: str | None = None,155 price_max: float | None = None,156 price_min: float | None = None,157 pets: str | None = None, # "oui" -> oui OU conditions158 furnished: int | None = None, # 1 / 0159 available_by: str | None = None, # ISO : dispo maintenant ou avant date160 area_min: float | None = None, # superficie minimale (pi²)161 q: str | None = None,162 deal: str | None = None, # sous | marche | sur (fair value)163 kascore_min: float | None = None, # KA Score global minimal164 sort: str | None = None, # "deal" affaires | "ka" KA Score165 active: int = 1,166 limit: int = Query(500, le=2000),167 offset: int = 0,168):169 con = db.connect()170 sql = ("SELECT listings.*, fv.fv AS fv, fv.fv_low, fv.fv_high,"171 " fv.deviation AS fv_deviation, fv.verdict AS fv_verdict,"172 " fv.confidence AS fv_confidence," + _KS_COLS +173 " FROM listings LEFT JOIN fairvalue fv USING (uid)" + _KS_JOIN +174 " WHERE dup_of IS NULL") # doublons masqués175 args: list = []176 if active in (0, 1):177 sql += " AND active=?"; args.append(active)178 if active == 1: # quarantaine qualité : jamais dans les résultats publics179 sql += " AND published=1"180 if city:181 sql += " AND city=?"; args.append(city)182 if sector:183 sql += " AND sector LIKE ?"; args.append(f"%{sector}%")184 if unit_type:185 sql += " AND unit_type=?"; args.append(unit_type)186 if source:187 sql += " AND source=?"; args.append(source)188 if price_max is not None:189 sql += " AND price IS NOT NULL AND price<=?"; args.append(price_max)190 if price_min is not None:191 sql += " AND price IS NOT NULL AND price>=?"; args.append(price_min)192 if pets == "oui":193 sql += " AND pets IN ('oui','conditions')"194 elif pets:195 sql += " AND pets=?"; args.append(pets)196 if furnished in (0, 1):197 sql += " AND furnished=?"; args.append(furnished)198 if available_by:199 # « now » trié après les dates ISO : comparaison explicite200 sql += " AND (availability_date='now' OR (availability_date IS NOT NULL" \201 " AND availability_date<=?))"202 args.append(available_by)203 if area_min is not None:204 sql += " AND area_sqft IS NOT NULL AND area_sqft>=?"; args.append(area_min)205 if q:206 sql += " AND (title LIKE ? OR address LIKE ? OR sector LIKE ?)"207 args += [f"%{q}%"] * 3208 if deal in ("sous", "marche", "sur"):209 sql += " AND fv.verdict=?"; args.append(deal)210 if kascore_min is not None:211 sql += " AND ks.global IS NOT NULL AND ks.global>=?"212 args.append(kascore_min)213 total = con.execute(f"SELECT COUNT(*) c FROM ({sql})", args).fetchone()["c"]214 if sort == "deal": # meilleures affaires d'abord (écart le plus négatif)215 sql += (" ORDER BY fv.deviation IS NULL, fv.deviation ASC,"216 " price IS NULL, price ASC LIMIT ? OFFSET ?")217 elif sort == "ka": # meilleurs emplacements d'abord (KA Score global)218 sql += (" ORDER BY ks.global IS NULL, ks.global DESC,"219 " price IS NULL, price ASC LIMIT ? OFFSET ?")220 elif sort == "prix":221 sql += " ORDER BY price IS NULL, price ASC LIMIT ? OFFSET ?"222 else: # défaut : les plus récentes d'abord223 sql += " ORDER BY first_seen DESC, price IS NULL, price ASC LIMIT ? OFFSET ?"224 args += [limit, offset]225 rows = [_row_to_dict(r) for r in con.execute(sql, args).fetchall()]226 con.close()227 return {"total": total, "count": len(rows), "listings": rows}228229230@app.get("/api/listings.geojson")231def listings_geojson(232 city: str | None = None,233 sector: str | None = None,234 unit_type: str | None = None,235 source: str | None = None,236 price_max: float | None = None,237 price_min: float | None = None,238 pets: str | None = None,239 furnished: int | None = None,240 available_by: str | None = None,241 area_min: float | None = None,242 q: str | None = None,243 bbox: str | None = None,244 limit: int = Query(3000, le=8000),245):246 """Annonces géolocalisées au format GeoJSON (mêmes filtres que /api/listings).247248 Léger par conception : seuls les champs nécessaires aux marqueurs et aux249 fiches de la carte sont inclus (1 photo, pas de description).250251 Ka Maps : `bbox=ouest,sud,est,nord` restreint au rectangle visible252 (index idx_listings_geo) ; `limit` plafonne la réponse. La collection253 porte deux membres additionnels : `totalGeocoded` (annonces géolocalisées254 correspondant aux filtres) et `totalMatching` (avec ou sans coordonnées),255 pour afficher « N résultats sans position sur la carte ».256 """257 con = db.connect()258 sql = ("SELECT uid, title, address, price, price_label, unit_type,"259 " availability_date, source, city, sector, area_sqft, images,"260 " images_ok, lat, lng, fv.verdict AS fv_verdict,"261 " fv.deviation AS fv_deviation"262 " FROM listings LEFT JOIN fairvalue fv USING (uid)"263 " WHERE active=1 AND published=1 AND dup_of IS NULL"264 " AND lat IS NOT NULL AND lng IS NOT NULL")265 args: list = []266 if bbox:267 try:268 west, south, east, north = (float(v) for v in bbox.split(","))269 except ValueError:270 raise HTTPException(400, "bbox attendu : ouest,sud,est,nord")271 sql += " AND lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?"272 args += [south, north, west, east]273 if city:274 sql += " AND city=?"; args.append(city)275 if sector:276 sql += " AND sector LIKE ?"; args.append(f"%{sector}%")277 if unit_type:278 sql += " AND unit_type=?"; args.append(unit_type)279 if source:280 sql += " AND source=?"; args.append(source)281 if price_max is not None:282 sql += " AND price IS NOT NULL AND price<=?"; args.append(price_max)283 if price_min is not None:284 sql += " AND price IS NOT NULL AND price>=?"; args.append(price_min)285 if pets == "oui":286 sql += " AND pets IN ('oui','conditions')"287 elif pets:288 sql += " AND pets=?"; args.append(pets)289 if furnished in (0, 1):290 sql += " AND furnished=?"; args.append(furnished)291 if available_by:292 sql += " AND (availability_date='now' OR (availability_date IS NOT NULL" \293 " AND availability_date<=?))"294 args.append(available_by)295 if area_min is not None:296 sql += " AND area_sqft IS NOT NULL AND area_sqft>=?"; args.append(area_min)297 if q:298 sql += " AND (title LIKE ? OR address LIKE ? OR sector LIKE ?)"299 args += [f"%{q}%"] * 3300301 total_geo = con.execute(f"SELECT COUNT(*) c FROM ({sql})", args).fetchone()["c"]302 # Même requête sans l'exigence de coordonnées ni le bbox : mesure les303 # annonces filtrées invisibles sur la carte (affordance « sans position »).304 sql_all = sql.replace(" AND lat IS NOT NULL AND lng IS NOT NULL", "")305 args_all = list(args)306 if bbox:307 sql_all = sql_all.replace(" AND lat BETWEEN ? AND ? AND lng BETWEEN ? AND ?", "")308 del args_all[0:4]309 total_all = con.execute(f"SELECT COUNT(*) c FROM ({sql_all})", args_all).fetchone()["c"]310311 sql += " ORDER BY first_seen DESC LIMIT ?"312 args.append(limit)313314 features = []315 for r in con.execute(sql, args).fetchall():316 # galerie nettoyée si auditée (même vide : les images brutes sont317 # alors toutes mortes/placeholder — le frontend affiche le visuel318 # de secours Lou-Ka plutôt qu'une image cassée)319 images = json.loads((r["images_ok"] if r["images_ok"] is not None320 else r["images"]) or "[]")321 features.append({322 "type": "Feature",323 "geometry": {"type": "Point", "coordinates": [r["lng"], r["lat"]]},324 "properties": {325 "uid": r["uid"], "title": r["title"], "address": r["address"],326 "price": r["price"],327 "price_label": r["price_label"], "unit_type": r["unit_type"],328 "availability_date": r["availability_date"],329 "source": r["source"], "city": r["city"], "sector": r["sector"],330 "area_sqft": r["area_sqft"],331 "fv_verdict": r["fv_verdict"], "fv_deviation": r["fv_deviation"],332 "image": images[0] if images else None,333 },334 })335 con.close()336 return {"type": "FeatureCollection", "features": features,337 "totalGeocoded": total_geo, "totalMatching": total_all}338339340# --- Recherche unifiée liste + carte -----------------------------------------341# Une seule vérité partagée : la même requête sert la page de liste ET les342# points de la carte, dans la même réponse. Le compteur affiché en tête de343# liste est par construction égal au nombre de points envoyés à la carte.344345_SEARCH_SORTS = {346 "prix": " ORDER BY price IS NULL, price ASC",347 "prix_desc": " ORDER BY price IS NULL, price DESC",348 "recent": " ORDER BY first_seen DESC, price IS NULL, price ASC",349 "deal": (" ORDER BY fv.deviation IS NULL, fv.deviation ASC,"350 " price IS NULL, price ASC"),351 "ka": (" ORDER BY ks.global IS NULL, ks.global DESC,"352 " price IS NULL, price ASC"),353}354355# colonnes KA Scores jointes aux annonces (pastilles + tri + fiche)356_KS_COLS = (" ks.walk AS ks_walk, ks.transit AS ks_transit,"357 " ks.bike AS ks_bike, ks.calme AS ks_calme,"358 " ks.services AS ks_services, ks.global AS ks_global")359_KS_JOIN = " LEFT JOIN kascores ks ON ks.coord_key = listings.coord_key"360_FV_CODES = {"sous": "s", "marche": "m", "sur": "o"}361362363def _parse_poly(poly: str) -> list[tuple[float, float]]:364 """`poly=lng,lat;lng,lat;…` → liste de sommets (≥ 3) ou HTTP 400."""365 try:366 pts = [tuple(float(v) for v in p.split(",")) for p in poly.split(";") if p]367 except ValueError:368 raise HTTPException(400, "poly attendu : lng,lat;lng,lat;…")369 if len(pts) < 3 or any(len(p) != 2 for p in pts):370 raise HTTPException(400, "poly : au moins 3 sommets lng,lat")371 return pts # type: ignore[return-value]372373374def _point_in_poly(lng: float, lat: float, ring: list[tuple[float, float]]) -> bool:375 """Ray casting — même algorithme que ka-maps (utils/geo.pointInPolygon)."""376 inside = False377 j = len(ring) - 1378 for i in range(len(ring)):379 xi, yi = ring[i]380 xj, yj = ring[j]381 if (yi > lat) != (yj > lat) and lng < (xj - xi) * (lat - yi) / (yj - yi) + xi:382 inside = not inside383 j = i384 return inside385386387@app.get("/api/search")388def search_unified(389 city: str | None = None,390 sector: str | None = None,391 unit_type: str | None = None,392 source: str | None = None,393 price_max: float | None = None,394 price_min: float | None = None,395 pets: str | None = None,396 furnished: int | None = None,397 available_by: str | None = None,398 area_min: float | None = None,399 q: str | None = None,400 deal: str | None = None, # sous | marche | sur (juste valeur)401 bbox: str | None = None, # ouest,sud,est,nord (zone visible carte)402 poly: str | None = None, # lng,lat;… (zone dessinée)403 kascore_min: float | None = None, # KA Score global minimal (0-100)404 sort: str = "recent", # recent (défaut) | prix | prix_desc | deal | ka405 page: int = 1,406 page_size: int = Query(20, ge=1, le=100),407 include: str = "tout", # tout | liste (points inchangés côté client)408):409 """Recherche synchronisée liste ↔ carte (une réponse = les deux vues).410411 Retourne `total` (compteur partagé), `listings` (la page demandée) et412 `points` (TOUS les points correspondants, format compact413 [uid, lng, lat, prix, verdict]) — triés selon `sort`, si bien que la414 position d'un point dans `points` donne directement sa page de liste.415 Seules les annonces géolocalisées participent (la règle d'or : chaque416 annonce de la liste est visible sur la carte) ; `unpositioned` compte417 les annonces filtrées sans coordonnées, pour l'afficher honnêtement.418 """419 if sort not in _SEARCH_SORTS:420 raise HTTPException(400, f"sort inconnu : {sort}")421 ring = _parse_poly(poly) if poly else None422423 con = db.connect()424 sql = (" FROM listings LEFT JOIN fairvalue fv USING (uid)" + _KS_JOIN +425 " WHERE dup_of IS NULL AND active=1 AND published=1"426 " AND listings.lat IS NOT NULL AND listings.lng IS NOT NULL")427 args: list = []428 if bbox:429 try:430 west, south, east, north = (float(v) for v in bbox.split(","))431 except ValueError:432 raise HTTPException(400, "bbox attendu : ouest,sud,est,nord")433 sql += (" AND listings.lat BETWEEN ? AND ?"434 " AND listings.lng BETWEEN ? AND ?")435 args += [south, north, west, east]436 if ring:437 # préfiltre SQL par l'emprise du polygone, appartenance exacte en aval438 lngs = [p[0] for p in ring]; lats = [p[1] for p in ring]439 sql += (" AND listings.lat BETWEEN ? AND ?"440 " AND listings.lng BETWEEN ? AND ?")441 args += [min(lats), max(lats), min(lngs), max(lngs)]442 if city:443 sql += " AND city=?"; args.append(city)444 if sector:445 sql += " AND sector LIKE ?"; args.append(f"%{sector}%")446 if unit_type:447 sql += " AND unit_type=?"; args.append(unit_type)448 if source:449 sql += " AND source=?"; args.append(source)450 if price_max is not None:451 sql += " AND price IS NOT NULL AND price<=?"; args.append(price_max)452 if price_min is not None:453 sql += " AND price IS NOT NULL AND price>=?"; args.append(price_min)454 if pets == "oui":455 sql += " AND pets IN ('oui','conditions')"456 elif pets:457 sql += " AND pets=?"; args.append(pets)458 if furnished in (0, 1):459 sql += " AND furnished=?"; args.append(furnished)460 if available_by:461 sql += " AND (availability_date='now' OR (availability_date IS NOT NULL" \462 " AND availability_date<=?))"463 args.append(available_by)464 if area_min is not None:465 sql += " AND area_sqft IS NOT NULL AND area_sqft>=?"; args.append(area_min)466 if q:467 sql += " AND (title LIKE ? OR address LIKE ? OR sector LIKE ?)"468 args += [f"%{q}%"] * 3469 if deal in ("sous", "marche", "sur"):470 sql += " AND fv.verdict=?"; args.append(deal)471 if kascore_min is not None:472 sql += " AND ks.global IS NOT NULL AND ks.global>=?"473 args.append(kascore_min)474475 rows = con.execute(476 "SELECT uid, listings.lng AS lng, listings.lat AS lat, price,"477 " fv.verdict AS v" + sql + _SEARCH_SORTS[sort],478 args).fetchall()479 if ring:480 rows = [r for r in rows if _point_in_poly(r["lng"], r["lat"], ring)]481 total = len(rows)482483 # points compacts : [uid, lng, lat, prix, verdict] — l'index dans ce484 # tableau détermine la page (points et liste partagent le même tri)485 points = [[r["uid"], round(r["lng"], 6), round(r["lat"], 6), r["price"],486 _FV_CODES.get(r["v"] or "", None)] for r in rows]487488 # page demandée, ramenée dans les bornes si les filtres l'ont dépassée489 last = max(1, -(-total // page_size))490 page = min(max(1, page), last)491 page_uids = [r["uid"] for r in rows[(page - 1) * page_size: page * page_size]]492493 listings: list[dict] = []494 if page_uids:495 marks = ",".join("?" * len(page_uids))496 by_uid = {r["uid"]: _row_to_dict(r) for r in con.execute(497 "SELECT listings.*, fv.fv AS fv, fv.fv_low, fv.fv_high,"498 " fv.deviation AS fv_deviation, fv.verdict AS fv_verdict,"499 " fv.confidence AS fv_confidence," + _KS_COLS +500 " FROM listings LEFT JOIN fairvalue fv USING (uid)" + _KS_JOIN +501 f" WHERE uid IN ({marks})", page_uids).fetchall()}502 listings = [by_uid[u] for u in page_uids if u in by_uid]503504 # annonces filtrées mais sans coordonnées (affichage honnête, hors carte)505 sql_nogeo = sql.replace(506 " AND listings.lat IS NOT NULL AND listings.lng IS NOT NULL",507 " AND (listings.lat IS NULL OR listings.lng IS NULL)", 1)508 args_nogeo = list(args)509 for spatial in (bbox, poly):510 if spatial:511 sql_nogeo = sql_nogeo.replace(512 " AND listings.lat BETWEEN ? AND ?"513 " AND listings.lng BETWEEN ? AND ?", "", 1)514 del args_nogeo[0:4]515 unpositioned = con.execute("SELECT COUNT(*) c" + sql_nogeo,516 args_nogeo).fetchone()["c"]517 con.close()518519 return {520 "total": total, "page": page, "page_size": page_size, "sort": sort,521 "listings": listings,522 "points": points if include != "liste" else None,523 "unpositioned": unpositioned,524 }525526527# --- Miniatures optimisées (WebP, taille écran) ------------------------------528# Sert les images des annonces redimensionnées et compressées (perf mobile) :529# /api/img?u=<url>&w=480. Seules les URLs déjà vérifiées par le contrôle530# qualité (table image_checks) sont proxifiées — pas de proxy ouvert. Si531# l'URL n'est pas (encore) connue : 404, le frontend retombe sur l'original.532_IMG_WIDTHS = (160, 480, 800, 1280)533_IMG_CACHE = ROOT / "data" / "imgcache"534535536@app.get("/api/img")537def img_thumbnail(u: str, w: int = 480):538 import hashlib539 import requests as _rq540 from fastapi.responses import Response541 w = min(_IMG_WIDTHS, key=lambda x: abs(x - w))542 if not u.startswith(("http://", "https://")):543 raise HTTPException(400, "URL invalide")544 key = hashlib.sha1(u.encode()).hexdigest()545 _IMG_CACHE.mkdir(parents=True, exist_ok=True)546 path = _IMG_CACHE / f"{key}_{w}.webp"547 headers = {"Cache-Control": "public, max-age=2592000, immutable"}548 if path.exists():549 return Response(path.read_bytes(), media_type="image/webp",550 headers=headers)551 con = db.connect()552 known = con.execute("SELECT status FROM image_checks WHERE url=?",553 (u,)).fetchone()554 con.close()555 if known is None or known["status"] not in ("ok",):556 raise HTTPException(404, "image inconnue du contrôle qualité")557 try:558 resp = _rq.get(u, timeout=12, headers={"User-Agent": "LouKaImg/1.0"})559 resp.raise_for_status()560 from io import BytesIO561 from PIL import Image, ImageOps562 img = Image.open(BytesIO(resp.content))563 img = ImageOps.exif_transpose(img)564 if img.mode not in ("RGB", "L"):565 img = img.convert("RGB")566 if img.width > w:567 img = img.resize((w, max(1, round(img.height * w / img.width))),568 Image.LANCZOS)569 buf = BytesIO()570 img.save(buf, "WEBP", quality=80, method=4)571 data = buf.getvalue()572 path.write_bytes(data)573 return Response(data, media_type="image/webp", headers=headers)574 except HTTPException:575 raise576 except Exception:577 raise HTTPException(404, "image irrécupérable")578579580@app.get("/api/listings/{uid}/pdf")581def listing_pdf(uid: str):582 """Fiche de propriété PDF (photos, prix, quartier, QR) — voir pdfgen.py."""583 from fastapi.responses import Response584 from . import pdfgen585 data = pdfgen.fiche_pdf(uid)586 if data is None:587 raise HTTPException(404, "Annonce introuvable")588 nom = uid.replace(":", "-")589 return Response(content=data, media_type="application/pdf", headers={590 "Content-Disposition": f'attachment; filename="louka-fiche-{nom}.pdf"'})591592593@app.get("/api/stats/rapport.pdf")594def rapport_marche_pdf():595 """Rapport global du marché locatif (PDF multi-pages)."""596 from fastapi.responses import Response597 from . import pdfgen598 return Response(content=pdfgen.rapport_pdf(), media_type="application/pdf",599 headers={"Content-Disposition":600 'attachment; filename="louka-rapport-marche.pdf"'})601602603@app.get("/api/fairvalue/{uid}")604def fairvalue_detail(uid: str):605 """Analyse de prix Lou-Ka : juste valeur, fourchette, confiance,606 distribution du segment (voir louka/fairvalue.py)."""607 from . import fairvalue608 d = fairvalue.explain(uid)609 if d is None:610 raise HTTPException(404, "Pas d'estimation pour cette annonce")611 return d612613614@app.get("/api/hydro")615def hydro_at(adresse: str, solve: int = 0, uid: str | None = None,616 lat: float | None = None, lng: float | None = None):617 """Estimation du coût d'électricité à une adresse (Hydro-Québec).618 Par défaut cache seulement (aucun captcha) ; solve=1 force le calcul.619 uid/lat/lng permettent la lecture cache par annonce et la dérivation du620 code postal (adresses sans CP)."""621 from . import hydro622 return hydro.estimate(adresse=adresse, uid=uid, lat=lat, lng=lng,623 solve=bool(solve))624625626@app.get("/api/commerces")627def commerces_at(lat: float, lng: float):628 """Grands commerces + métro/bus les plus proches (Mapbox / OSM)."""629 from . import commerces630 return commerces.nearby(lat, lng)631632633@app.get("/api/air")634def air_at(lat: float, lng: float):635 """Qualité de l'air : station RSQAQ la plus proche (MELCCFP)."""636 from . import air637 d = air.lookup(lat, lng)638 if d is None:639 raise HTTPException(404, "Base qualité de l'air non disponible")640 return d641642643@app.get("/api/gaz")644def gaz_at(lat: float, lng: float, limit: int = 5):645 """Stations-service à proximité et prix courants (gazquebec.ca).646 `limit` (défaut 5, max 60) : la fiche demande la liste complète pour son647 panneau « Voir les N stations »."""648 from . import gaz649 return gaz.nearby(lat, lng, limit=max(1, min(limit, 60)))650651652@app.get("/api/inondation")653def inondation_at(lat: float, lng: float):654 """Risque d'inondation à l'adresse (BDZI, gouv. du Québec) —655 bloc « Risque d'inondation » de la fiche."""656 from . import inondation657 d = inondation.lookup(lat, lng)658 if d is None:659 raise HTTPException(404, "Base des zones inondables non disponible")660 return d661662663@app.get("/api/rdl")664def rdl_nearby(lat: float, lng: float, radius: int = 600, limit: int = 12):665 """Loyers déclarés au Registre des loyers (registre-des-loyers.ca)666 autour d'un point — bloc « Registre des loyers » de la fiche.667 `limit` (défaut 12, max 300) : nombre de déclarations retournées dans668 `items` ; la fiche demande la liste complète pour son panneau669 « Voir les N loyers comparables »."""670 from . import rdl671 radius = max(100, min(radius, 2000))672 d = rdl.nearby(lat, lng, radius, limit=max(1, min(limit, 300)))673 if d is None:674 raise HTTPException(404, "Registre des loyers non disponible")675 return d676677678@app.get("/api/tal")679def tal_history(address: str, city: str | None = None):680 """Historique au Tribunal administratif du logement (décisions SOQUIJ)681 à l'adresse de l'annonce — bloc « Historique TAL » de la fiche.682 Une adresse jamais vérifiée est mise en file prioritaire (status pending)."""683 from . import tal684 return tal.lookup(address, city)685686687@app.get("/api/listings/{uid}/historique")688def listing_history(uid: str):689 """Historique Lou-Ka : timeline des observations réelles (prix, texte,690 photos, disponibilité, retraits/retours) — voir louka/history.py."""691 from . import history692 out = history.timeline(uid)693 if out is None:694 raise HTTPException(404, "Annonce introuvable")695 return out696697698@app.get("/api/listings/{uid}/cout-reel")699def listing_cout_reel(uid: str):700 """Coût réel mensuel : loyer + frais non inclus ligne par ligne, chaque701 poste étiqueté included/observed/estimated/unknown — louka/coutreel.py."""702 from . import coutreel703 out = coutreel.compute(uid)704 if out is None:705 raise HTTPException(404, "Annonce introuvable")706 return out707708709@app.get("/api/listings/{uid}/recyclees")710def listing_recycled(uid: str):711 """Annonces antérieures probables du même logement (score multi-signaux,712 inférence explicable) — louka/recycled.py."""713 from . import recycled714 return recycled.lookup(uid)715716717@app.get("/api/immeuble")718def immeuble_fiche(bkey: str):719 """Passeport de l'immeuble (stats précalculées par building.rollup)."""720 from . import building721 out = building.fiche(bkey)722 if out is None:723 raise HTTPException(404, "Immeuble inconnu")724 return out725726727@app.get("/api/managers")728def managers_directory():729 """Annuaire de tous les gestionnaires immobiliers recensés (connectés730 ou non) : inventaire actif, loyers, villes, note Google — louka/directory.py."""731 from . import directory732 return directory.compute()733734735@app.get("/api/managers/{source_id}")736def manager_fiche(source_id: str):737 """Fiche du gestionnaire (source directe) + avis Google synchronisés en738 base — aucun appel SerpApi au chargement de page (louka/managers.py)."""739 from . import managers740 out = managers.fiche(source_id)741 if out is None:742 raise HTTPException(404, "Gestionnaire inconnu")743 return out744745746@app.get("/api/listings/{uid}")747def get_listing(uid: str):748 con = db.connect()749 row = con.execute(750 "SELECT listings.*, fv.fv AS fv, fv.fv_low, fv.fv_high,"751 " fv.deviation AS fv_deviation, fv.verdict AS fv_verdict,"752 " fv.confidence AS fv_confidence"753 " FROM listings LEFT JOIN fairvalue fv USING (uid)"754 " WHERE uid=?", (uid,)).fetchone()755 d = None756 if row is not None:757 d = _row_to_dict(row)758 # commodités de proximité (cache par immeuble, voir louka/poi.py)759 if d.get("lat") is not None and d.get("lng") is not None:760 key = f"{round(d['lat'], 4)},{round(d['lng'], 4)}"761 poi_row = con.execute(762 "SELECT pois FROM poi_cache WHERE coord_key=?", (key,)).fetchone()763 d["poi"] = json.loads(poi_row["pois"]) if poi_row else []764 else:765 d["poi"] = []766 # KA Scores de l'immeuble (Walk/Transit/Bike/Calme/Services + global)767 if d.get("coord_key"):768 ks = con.execute(769 "SELECT walk, transit, bike, calme, services, global AS glob,"770 " details, version, computed_at FROM kascores WHERE coord_key=?",771 (d["coord_key"],)).fetchone()772 if ks is not None:773 d["kascores"] = {774 "walk": ks["walk"], "transit": ks["transit"],775 "bike": ks["bike"], "calme": ks["calme"],776 "services": ks["services"], "global": ks["glob"],777 "details": json.loads(ks["details"] or "{}"),778 "version": ks["version"], "computed_at": ks["computed_at"],779 }780 # statistiques de quartier (recensement, proximité, chaleur, criminalité)781 from . import quartier782 dauid = d.get("dauid")783 d["quartier"] = quartier.fiche_quartier(784 d.get("lat"), d.get("lng"), d.get("city") or "",785 dauid if dauid and dauid != "hors-zone" else None)786 # passeport de l'immeuble (stats précalculées) + score hiver787 if d.get("building_key"):788 from . import building789 d["immeuble"] = building.fiche(d["building_key"], con)790 else:791 d["immeuble"] = None792 from . import hiver793 d["hiver"] = hiver.score(d.get("lat"), d.get("lng"), con)794 # description structurée + historique de prix795 d["digest"] = json.loads(d["digest"]) if d.get("digest") else None796 d["price_history"] = [dict(r) for r in con.execute(797 "SELECT ts, price FROM price_log WHERE uid=? ORDER BY ts DESC LIMIT 6",798 (uid,)).fetchall()]799 con.close()800 if d is None:801 raise HTTPException(404, "Annonce introuvable")802 return d803804805@app.get("/api/scores/stats")806@app.get("/api/kascores/stats")807def kascores_stats():808 """Couverture, moyennes et version du barème — page « Scores »."""809 from . import kascores810 return kascores.stats()811812813@app.get("/api/facets")814def facets(city: str | None = None):815 """Valeurs distinctes pour construire les filtres du frontend.816817 `city` (optionnel) restreint la liste des quartiers à cette ville —818 utilisé par le sélecteur « Quartier » dépendant de « Ville ».819 """820 con = db.connect()821 sector_sql = ("SELECT DISTINCT sector FROM listings"822 " WHERE active=1 AND published=1 AND dup_of IS NULL"823 " AND sector<>''")824 sector_args: list = []825 if city:826 sector_sql += " AND city=?"827 sector_args.append(city)828 out = {829 "cities": [r["city"] for r in con.execute(830 "SELECT DISTINCT city FROM listings WHERE active=1 AND published=1"831 " AND dup_of IS NULL AND city<>'' ORDER BY city")],832 "sectors": [r["sector"] for r in con.execute(833 sector_sql + " ORDER BY sector", sector_args)],834 "unit_types": [r["unit_type"] for r in con.execute(835 "SELECT DISTINCT unit_type FROM listings WHERE active=1 AND published=1"836 " AND dup_of IS NULL AND unit_type<>'' ORDER BY unit_type")],837 "sources": [dict(r) for r in con.execute(838 "SELECT source, COUNT(*) n FROM listings WHERE active=1 AND published=1"839 " AND dup_of IS NULL GROUP BY source ORDER BY n DESC")],840 }841 con.close()842 return out843844845@app.get("/api/version")846def api_version():847 """Version de l'API : les clients natifs s'en servent pour vérifier qu'ils848 parlent bien à Lou-Ka v2 (annuaire, lumières, noms de sources)."""849 from . import __version__850 return {"api": 2, "version": __version__, "name": "Lou-Ka"}851852853@app.get("/api/lights")854def lights():855 """Densité des logements disponibles (cellules ~1 km) + principales villes856 — carte d'accueil. Voir louka/lights.py."""857 from . import lights as _lights858 return _lights.compute()859860861@app.get("/api/sources/names")862def source_names():863 """Identifiant de source → nom lisible (léger : cartes d'annonces)."""864 from . import lights as _lights865 return _lights.source_names()866867868@app.get("/api/sources")869def sources():870 registry = json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]871 con = db.connect()872 counts = {r["source"]: r["n"] for r in con.execute(873 "SELECT source, COUNT(*) n FROM listings WHERE active=1 AND published=1"874 " GROUP BY source")}875 last = {r["source"]: r["ts"] for r in con.execute(876 "SELECT source, MAX(ts) ts FROM sync_log WHERE ok=1 GROUP BY source")}877 con.close()878 for s in registry:879 s["active_listings"] = counts.get(s["id"], 0)880 s["last_sync"] = last.get(s["id"])881 return {"sources": registry}882883884# Villes de la grande région de Montréal (le reste de la province est885# compté dans « autres » — Outaouais, Estrie, Mauricie, Est-du-Québec…)886_VILLES_GM = (887 "Montréal", "Montréal-Est", "Laval", "Longueuil", "Brossard", "Terrebonne",888 "Mascouche", "Repentigny", "Boucherville", "Saint-Lambert", "Westmount",889 "Côte Saint-Luc", "Dorval", "Pointe-Claire", "Verdun", "LaSalle", "Anjou",890 "Saint-Constant", "Delson", "Candiac", "Châteauguay", "Chambly",891 "Sainte-Julie", "Varennes", "Belœil", "McMasterville", "Mont-Saint-Hilaire",892 "Saint-Basile-le-Grand", "Saint-Bruno-de-Montarville", "Boisbriand",893 "Richelieu", "Beauharnois", "Salaberry-de-Valleyfield", "Vaudreuil-Dorion",894 "Kirkland", "Beaconsfield", "Dollard-des-Ormeaux", "Mont-Royal", "Outremont",895)896897898# Agrégats listings de /api/stats : 2 scans plein-table sur la base de 5 Go.899# Même panne que l'accueil (2026-11-03) : moniteur + healthchecks empilaient900# ces scans à froid et saturaient le threadpool anyio. Single-flight : un seul901# thread recalcule, les appels concurrents servent la version précédente.902_STATS_TTL = 300 # secondes903_STATS_CACHE: dict = {"ts": 0.0, "data": None}904_STATS_LOCK = threading.Lock()905906907def _stats_aggregates() -> dict:908 cached = _STATS_CACHE["data"]909 if cached is not None and time.time() - _STATS_CACHE["ts"] < _STATS_TTL:910 return cached911 if not _STATS_LOCK.acquire(blocking=cached is None):912 return cached # recalcul déjà en cours : servir la version précédente913 try:914 cached = _STATS_CACHE["data"]915 if cached is not None and time.time() - _STATS_CACHE["ts"] < _STATS_TTL:916 return cached # rempli pendant l'attente du verrou917 con = db.connect()918 try:919 gm = ",".join("?" * len(_VILLES_GM))920 row = con.execute(921 f"""SELECT COUNT(*) total,922 SUM(CASE WHEN city='Québec' THEN 1 ELSE 0 END) quebec,923 SUM(CASE WHEN city='Lévis' THEN 1 ELSE 0 END) levis,924 SUM(CASE WHEN city IN ({gm}) THEN 1 ELSE 0 END) montreal,925 SUM(CASE WHEN city NOT IN ('Québec','Lévis') AND city NOT IN ({gm})926 THEN 1 ELSE 0 END) autres,927 COUNT(DISTINCT source) sources,928 AVG(price) avg_price929 FROM listings WHERE active=1 AND published=1 AND dup_of IS NULL""",930 list(_VILLES_GM) + list(_VILLES_GM)).fetchone()931 # qualité des données : complétude moyenne + quarantaine (quality.py)932 qual = con.execute(933 """SELECT ROUND(AVG(completeness),1) avg_completeness,934 SUM(published=1) publiees, SUM(published=0) quarantaine935 FROM listings WHERE active=1"""936 ).fetchone()937 finally:938 con.close()939 data = {"row": dict(row), "quality": dict(qual)}940 _STATS_CACHE.update(ts=time.time(), data=data)941 return data942 finally:943 _STATS_LOCK.release()944945946@app.get("/api/stats")947def stats(syncs_since_h: float | None = None):948 """Stats globales + journal de synchronisation.949950 `syncs_since_h` (optionnel) : fenêtre en heures pour `recent_syncs` — le951 moniteur central (api-ka) polle aux 2 h et les 20 dernières entrées ne952 couvrent que ~11 min d'activité sur ~200 sources (fausses alertes953 « stale »). Avec le paramètre : toutes les entrées des N dernières heures954 (max 4000) ; s'il y en a moins de 20, on retombe sur les 20 dernières955 toutes époques confondues. Sans le paramètre : comportement historique956 inchangé (LIMIT 20).957 """958 agg = _stats_aggregates()959 con = db.connect()960 log: list[dict] = []961 if syncs_since_h is not None:962 import time as _time963 cutoff = _time.time() - syncs_since_h * 3600964 log = [dict(r) for r in con.execute(965 "SELECT * FROM sync_log WHERE ts >= ? ORDER BY ts DESC LIMIT 4000",966 (cutoff,))]967 if syncs_since_h is None or len(log) < 20:968 log = [dict(r) for r in con.execute(969 "SELECT * FROM sync_log ORDER BY ts DESC LIMIT 20")]970 con.close()971 # Sources en pause (ex. pause Ontario 2026-08-27) déclarées au moniteur972 # central api-ka via `disabled_sources` : il les retire de la supervision973 # au lieu de les flagger « stale » et de missionner des agents pour rien.974 disabled = [975 s["id"]976 for s in json.loads(SOURCES_PATH.read_text(encoding="utf-8"))["sources"]977 if (s.get("status") or "").startswith(("pause", "inactif", "retir"))978 ]979 return {**agg["row"], "quality": agg["quality"], "recent_syncs": log,980 "disabled_sources": disabled}981982983@app.get("/api/stats/detailed")984def stats_detailed():985 """Agrégats du marché (source unique : louka/marketstats.py)."""986 from . import marketstats987 return marketstats.compute()988989990# --- Tableau de bord et rapports statistiques ---------------------------------991REPORT_SITE = {"id": "lou-ka", "wordmark": "Lou-Ka", "accent": "#245B48",992 "domain": "lou-ka.com", "tagline": "Ouvrez la porte à votre prochain chez-vous"}993_PERIODES_VALIDES = {"auj", "7j", "30j", "3m", "6m", "12m", "annee", "tout"}994995996@app.get("/api/stats/dashboard")997def stats_dashboard(period: str = "30j",998 from_: str | None = Query(None, alias="from"),999 to: str | None = None):1000 """Tableau de bord analytique (KPI, séries, répartitions, tableaux…)."""1001 from . import statsdash1002 if period not in _PERIODES_VALIDES and not (from_ and to):1003 period = "30j"1004 return statsdash.compute(period, from_, to)100510061007@app.get("/api/stats/report")1008def stats_report(period: str = "30j",1009 from_: str | None = Query(None, alias="from"),1010 to: str | None = None,1011 mode: str = "complet"):1012 """Rapport statistique PDF Lou-Ka — 5 modes :1013 complet | synthese | tendances | repartitions | donnees (inconnu → complet)."""1014 from fastapi.responses import Response1015 from . import reportpdf, statsdash1016 if period not in _PERIODES_VALIDES:1017 period = "perso" if (from_ and to) else "30j"1018 if mode not in reportpdf.REPORT_MODES:1019 mode = "complet"1020 dash = statsdash.compute(period if period != "perso" else "30j",1021 from_, to)1022 site = REPORT_SITE1023 data = reportpdf.MarketReport(site=site, dashboard=dash, mode=mode).build()1024 fname = reportpdf.filename("lou-ka", period, mode)1025 return Response(content=data, media_type="application/pdf",1026 headers={"Content-Disposition":1027 f'attachment; filename="{fname}"'})1028102910301031@app.get("/api/stats/catalog")1032def stats_catalog(period: str = "30j",1033 from_: str | None = Query(None, alias="from"),1034 to: str | None = None):1035 """v3 — blocs composables pour le constructeur de rapports personnalisés."""1036 from . import reportpdf, statsdash1037 if period not in _PERIODES_VALIDES and not (from_ and to):1038 period = "30j"1039 dash = statsdash.compute(period if period in _PERIODES_VALIDES else "30j",1040 from_, to)1041 return {"updated": dash.get("updated"), "period": dash.get("period"),1042 "blocks": reportpdf.catalog(dash)}104310441045@app.post("/api/stats/report/custom")1046def stats_report_custom(spec: dict = Body(...)):1047 """v3 — rapport PDF personnalisé : {"title", "period", "from", "to",1048 "blocks": [{"key": "series:…", "render": "bar"}, …]} (SPEC.md §3bis)."""1049 from fastapi.responses import Response1050 from . import reportpdf, statsdash1051 period = str(spec.get("period") or "30j")1052 from_ = str(spec.get("from") or "") or None1053 to = str(spec.get("to") or "") or None1054 if period not in _PERIODES_VALIDES:1055 period = "perso" if (from_ and to) else "30j"1056 dash = statsdash.compute(period if period != "perso" else "30j",1057 from_, to)1058 known = {b["key"] for b in reportpdf.catalog(dash)}1059 blocks = [b for b in (spec.get("blocks") or [])1060 if isinstance(b, dict) and b.get("key") in known][:40]1061 if not blocks:1062 raise HTTPException(400, "Aucun bloc valide dans la composition")1063 site = REPORT_SITE1064 data = reportpdf.MarketReport(1065 site=site, dashboard=dash, mode=reportpdf.CUSTOM_MODE,1066 spec={"title": str(spec.get("title") or "")[:80], "blocks": blocks},1067 ).build()1068 fname = reportpdf.filename("lou-ka", period, reportpdf.CUSTOM_MODE)1069 return Response(content=data, media_type="application/pdf",1070 headers={"Content-Disposition":1071 f'attachment; filename="{fname}"'})107210731074# --- Frontend React (build Vite) --------------------------------------------1075if FRONTEND_DIST.exists():1076 app.mount("/assets", StaticFiles(directory=FRONTEND_DIST / "assets"), name="assets")10771078 # référencement : SSR des routes publiques, robots.txt, sitemaps, 410.1079 # Inclus AVANT le catch-all — l'ordre d'enregistrement fait foi.1080 from . import seo # noqa: E4021081 app.include_router(seo.router)10821083 @app.middleware("http")1084 async def _cache_headers(request, call_next):1085 """Politique de cache : les bundles hachés (/assets/…) sont immuables,1086 mais index.html doit TOUJOURS être revalidé — sinon les navigateurs1087 gardent une vieille version de l'app après un déploiement."""1088 resp = await call_next(request)1089 path = request.url.path1090 if path.startswith("/assets/"):1091 resp.headers["Cache-Control"] = "public, max-age=31536000, immutable"1092 elif "text/html" in (resp.headers.get("content-type") or ""):1093 resp.headers["Cache-Control"] = "no-cache"1094 return resp10951096 # routes de l'app rendues uniquement côté client (privées ou volatiles) —1097 # tout autre chemin inconnu renvoie index.html avec un statut 404 : le1098 # routeur React affiche sa page « introuvable », les moteurs de recherche1099 # voient un vrai 404 (fin des soft-404).1100 _CLIENT_ROUTES = {"recherche", "favoris", "comparer", "contact",1101 "juste-valeur", "scores", "gestionnaires", "a-propos", "lab"}1102 _CLIENT_PREFIXES = ()11031104 @app.get("/{full_path:path}")1105 def spa(full_path: str):1106 target = FRONTEND_DIST / full_path1107 if full_path and target.is_file():1108 return FileResponse(target)1109 known = (full_path in _CLIENT_ROUTES1110 or any(full_path == p.rstrip("/") or full_path.startswith(p)1111 for p in _CLIENT_PREFIXES))1112 return FileResponse(FRONTEND_DIST / "index.html",1113 status_code=200 if known else 404,1114 headers={"Cache-Control": "no-cache"})1115