Repository Public
1# =============================================================================2# SP BOUCHER | SOFTWARE & RESEARCH3# ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project : Lou·Ka9# File : louka/pdfgen.py10# Module : louka11# Repository : https://git.spboucher.ai/lou-ka12# Created : 2026-08-0913# Last Modified : 2026-08-2414#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author : Simon-Pierre Boucher20# Position : Professor of Finance21# Institution : Université du Québec en Outaouais (UQO)22# Department : Département des sciences administratives23# Organization : SP Boucher24#25# Website : https://spboucher.ai26# Git : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General : info@spboucher.ai33# Professional : contact@spboucher.ai34# Direct : simon@spboucher.ai35# Research : research@spboucher.ai36# Development : dev@spboucher.ai37# Support : support@spboucher.ai38# Security/Admin : admin@spboucher.ai39# Notifications : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification : Public66# Distribution : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License : None specified (no license file in this repository)80# Maintainer : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Lou-Ka — Agrégateur de logements à louer (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# pdfgen.py : génération PDF à l'identité visuelle officielle Lou-Ka91# - fiche_pdf(uid) : fiche de propriété complète — tout ce que montre la92# fiche web : photos, prix + analyse Lou-Ka (juste valeur, histogramme),93# chips, description structurée, inclusions, coût réel mensuel,94# historique Lou-Ka (+ vies antérieures), passeport de l'immeuble,95# gestionnaire (fiche Google + avis synchronisés), registre des loyers,96# historique TAL, inondation, qualité de l'air, coût d'électricité,97# commerces/transport, essence, KA Scores, score hiver, quartier,98# à proximité, QR99# - rapport_pdf() : rapport global du marché (totaux, régions, histogramme100# des loyers, types, villes, gestionnaires)101# Palette identique au site : blanc #ffffff, marine #0b1330, orange #ff6a00,102# bleu vif #2258ff, gris pâle #f2f2f2. Polices de base (Helvetica) stylées103# par la mise en page — aucune dépendance de police externe.104# -----------------------------------------------------------------------------105from __future__ import annotations106107import io108import json109import math110import time111112import qrcode113import requests114from reportlab.lib.colors import HexColor115from reportlab.lib.pagesizes import letter116from reportlab.lib.utils import ImageReader117from reportlab.pdfgen import canvas as rl_canvas118119from . import db120121# --- palette Lou-Ka (identité officielle) ------------------------------------122PAPER = HexColor("#ffffff")123SURFACE = HexColor("#ffffff")124INK = HexColor("#0b1330") # bleu marine profond125INK2 = HexColor("#3e4560")126INK3 = HexColor("#8a90a5")127GREEN = HexColor("#2258ff") # accent secondaire : bleu vif128GREEN_DEEP = HexColor("#0b1330")129LIME = HexColor("#ff6a00") # accent d'action : orange vif130LIME_SOFT = HexColor("#fff1e6")131AMBER = HexColor("#ff6a00")132AMBER_SOFT = HexColor("#fff1e6")133134PAGE_W, PAGE_H = letter135M = 40 # marge136IMG_TIMEOUT = 6137UA = "LouKaBot/1.0 (+https://www.lou-ka.com/bot; contact@spboucher.ai)"138139POI_LABELS = {140 "epicerie": "Épicerie", "depanneur": "Dépanneur", "pharmacie": "Pharmacie",141 "ecole": "École", "garderie": "Garderie", "parc": "Parc", "bus": "Arrêt de bus",142 "metro": "Métro", "gym": "Gym", "cafe": "Café", "clinique": "Clinique",143 "hopital": "Hôpital", "bibliotheque": "Bibliothèque",144}145PROX_LABELS = [146 ("prox_epicerie", "Épiceries"), ("prox_transport", "Transport en commun"),147 ("prox_parc", "Parcs"), ("prox_ecole_prim", "Écoles primaires"),148 ("prox_sante", "Soins de santé"), ("prox_pharmacie", "Pharmacies"),149]150151NBSP = " "152153154def _fmt_money(v) -> str:155 return f"{v:,.0f}".replace(",", f"{NBSP}") + f"{NBSP}$" if v is not None else "—"156157158def _fmt_dist(m_: float) -> str:159 return (f"{round(m_ / 10) * 10}{NBSP}m" if m_ < 1000160 else f"{m_ / 1000:.1f}".replace(".", ",") + f"{NBSP}km")161162163def _marche(m_: float) -> str:164 return f"≈{NBSP}{max(1, round(m_ * 1.3 / 80))}{NBSP}min à pied"165166167def _fetch_image(url: str) -> ImageReader | None:168 try:169 r = requests.get(url, timeout=IMG_TIMEOUT, headers={"User-Agent": UA})170 r.raise_for_status()171 raw = r.content172 try:173 # les photos source dépassent parfois 5 Mo chacune : sans174 # redimensionnement le PDF grimpe à 30 Mo175 from PIL import Image176 im = Image.open(io.BytesIO(raw))177 im.thumbnail((1200, 1200))178 buf = io.BytesIO()179 im.convert("RGB").save(buf, "JPEG", quality=82)180 buf.seek(0)181 return ImageReader(buf)182 except Exception:183 return ImageReader(io.BytesIO(raw))184 except Exception:185 return None186187188class _Style:189 """Petits composants du style « éditorial sharp » sur un canvas."""190191 def __init__(self, c: rl_canvas.Canvas):192 self.c = c193194 def fond(self):195 self.c.setFillColor(PAPER)196 self.c.rect(0, 0, PAGE_W, PAGE_H, stroke=0, fill=1)197198 def logo(self, x: float, y: float, taille: float = 22):199 """Wordmark Lou·Ka : « Lou » encre + boîte encre avec « Ka » lime."""200 c = self.c201 c.setFont("Helvetica-Bold", taille)202 c.setFillColor(INK)203 c.drawString(x, y, "Lou")204 w = c.stringWidth("Lou", "Helvetica-Bold", taille)205 bw = c.stringWidth("Ka", "Helvetica-Bold", taille) + 8206 c.saveState()207 c.translate(x + w + 3 + bw / 2, y + taille * 0.32)208 c.rotate(-3)209 c.setFillColor(INK)210 c.roundRect(-bw / 2, -taille * 0.62, bw, taille * 1.15, 4, stroke=0, fill=1)211 c.setFillColor(LIME)212 c.drawCentredString(0, -taille * 0.30, "Ka")213 c.restoreState()214 return x + w + 6 + bw215216 def entete(self, titre: str):217 c = self.c218 self.logo(M, PAGE_H - M - 16)219 c.setFont("Courier-Bold", 8)220 c.setFillColor(INK3)221 c.drawRightString(PAGE_W - M, PAGE_H - M - 6,222 titre.upper())223 c.drawRightString(PAGE_W - M, PAGE_H - M - 16,224 time.strftime("GÉNÉRÉ LE %Y-%m-%d · WWW.LOU-KA.COM"))225 c.setStrokeColor(INK)226 c.setLineWidth(2)227 c.line(M, PAGE_H - M - 26, PAGE_W - M, PAGE_H - M - 26)228 return PAGE_H - M - 40 # y de départ du contenu229230 def pied(self, texte: str, page: int | None = None):231 c = self.c232 c.setStrokeColor(INK)233 c.setLineWidth(1)234 c.line(M, M + 16, PAGE_W - M, M + 16)235 c.setFont("Helvetica", 6.5)236 c.setFillColor(INK3)237 c.drawString(M, M + 6, texte[:150])238 if page:239 c.setFont("Courier-Bold", 7)240 c.drawRightString(PAGE_W - M, M + 6, f"P.{page}")241242 def pilule(self, x: float, y: float, texte: str, fg=LIME, bg=INK,243 stroke=None, taille: float = 8) -> float:244 """Chip arrondie ; retourne le x suivant."""245 c = self.c246 w = c.stringWidth(texte, "Helvetica-Bold", taille) + 14247 c.setFillColor(bg)248 if stroke:249 c.setStrokeColor(stroke)250 c.setLineWidth(1.2)251 c.roundRect(x, y, w, taille + 9, (taille + 9) / 2,252 stroke=1 if stroke else 0, fill=1)253 c.setFillColor(fg)254 c.setFont("Helvetica-Bold", taille)255 c.drawString(x + 7, y + 5, texte)256 return x + w + 6257258 def titre_section(self, y: float, texte: str) -> float:259 c = self.c260 c.setFont("Helvetica-Bold", 12.5)261 c.setFillColor(INK)262 c.drawString(M, y, texte)263 c.setStrokeColor(LIME)264 c.setLineWidth(3)265 w = c.stringWidth(texte, "Helvetica-Bold", 12.5)266 c.line(M, y - 4, M + w, y - 4)267 return y - 18268269 def paragraphe(self, x: float, y: float, texte: str, largeur: float,270 taille: float = 8.5, couleur=INK2, interligne: float = 11.5,271 max_lignes: int = 100) -> float:272 """Texte multi-lignes avec découpe aux mots ; retourne le y suivant."""273 c = self.c274 c.setFont("Helvetica", taille)275 c.setFillColor(couleur)276 mots = texte.split()277 ligne = ""278 n = 0279 for mot in mots:280 essai = (ligne + " " + mot).strip()281 if c.stringWidth(essai, "Helvetica", taille) <= largeur:282 ligne = essai283 else:284 c.drawString(x, y, ligne)285 y -= interligne286 n += 1287 ligne = mot288 if n >= max_lignes - 1:289 ligne += " …"290 break291 if ligne:292 c.drawString(x, y, ligne)293 y -= interligne294 return y295296 def tuile(self, x: float, y: float, w: float, h: float,297 val: str, lab: str):298 """Tuile KPI blanche à ombre décalée (x, y = coin inférieur gauche)."""299 c = self.c300 c.setFillColor(INK)301 c.roundRect(x + 2.5, y - 2.5, w, h, 5, stroke=0, fill=1)302 c.setFillColor(SURFACE)303 c.setStrokeColor(INK)304 c.setLineWidth(1.2)305 c.roundRect(x, y, w, h, 5, stroke=1, fill=1)306 c.setFont("Helvetica-Bold", 12)307 c.setFillColor(INK)308 c.drawString(x + 8, y + h - 20, str(val))309 c.setFont("Courier", 6.2)310 c.setFillColor(INK3)311 c.drawString(x + 8, y + 7, lab.upper()[: max(4, int(w / 4.2))])312313314# ---------------------------------------------------------------------------315# Fiche de propriété316# ---------------------------------------------------------------------------317318_MOIS = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet",319 "août", "septembre", "octobre", "novembre", "décembre"]320321322def _fmt_mois(d: str | None) -> str:323 """« 2017-11-04 » → « novembre 2017 » (sinon la valeur telle quelle)."""324 if not d:325 return "—"326 try:327 an, mois = d[:7].split("-")328 return f"{_MOIS[int(mois) - 1]} {an}"329 except Exception:330 return d331332333def _fmt_ts(ts, jour: bool = False) -> str:334 """Timestamp unix → « 6 août 2026 » (jour=True) ou « août 2026 »."""335 if not ts:336 return "—"337 t = time.localtime(ts)338 mois = f"{_MOIS[t.tm_mon - 1]} {t.tm_year}"339 return f"{t.tm_mday} {mois}" if jour else mois340341342_VERDICTS = {343 "sous": ("Sous le marché", GREEN_DEEP, LIME_SOFT, GREEN),344 "marche": ("Dans le marché", INK2, SURFACE, INK),345 "sur": ("Au-dessus du marché", HexColor("#8a5a12"), AMBER_SOFT, AMBER),346}347348_PIED_FICHE = ("Données de l'annonce publiée par le gestionnaire — Lou-Ka est "349 "un agrégateur indépendant. Enrichissements (analyse de prix, "350 "registre, TAL, environnement) fournis à titre indicatif, sans "351 "valeur juridique.")352353def fiche_pdf(uid: str) -> bytes | None:354 """PDF de la fiche du logement `uid` — reflète TOUS les blocs de la fiche355 web : prix + analyse Lou-Ka, photos, description, inclusions, registre des356 loyers, historique TAL, risque d'inondation, qualité de l'air, coût357 d'électricité, commerces/transport, essence, KA Scores, quartier,358 à proximité, références + QR. None si introuvable."""359 con = db.connect()360 row = con.execute("SELECT * FROM listings WHERE uid=?", (uid,)).fetchone()361 if row is None:362 con.close()363 return None364 l = dict(row)365 l["amenities"] = json.loads(l.get("amenities") or "[]")366 l["images"] = json.loads(l.get("images") or "[]")367 l["details"] = json.loads(l.get("details") or "{}")368 l["digest"] = json.loads(l["digest"]) if l.get("digest") else None369 poi = []370 quartier = None371 if l.get("lat") is not None:372 key = f"{round(l['lat'], 4)},{round(l['lng'], 4)}"373 pr = con.execute("SELECT pois FROM poi_cache WHERE coord_key=?", (key,)).fetchone()374 poi = json.loads(pr["pois"]) if pr else []375 from . import quartier as qmod376 dauid = l.get("dauid")377 quartier = qmod.fiche_quartier(l["lat"], l["lng"], l.get("city") or "",378 dauid if dauid and dauid != "hors-zone" else None)379 reg = json.loads((db.DB_PATH.parent / "sources.json").read_text("utf-8"))["sources"]380 src_name = next((s["name"] for s in reg if s["id"] == l["source"]), l["source"])381 kasc = None382 if l.get("coord_key"):383 kr = con.execute("SELECT walk, transit, bike, calme, services,"384 " global AS glob FROM kascores WHERE coord_key=?",385 (l["coord_key"],)).fetchone()386 if kr is not None:387 kasc = dict(kr)388 price_history = [dict(r) for r in con.execute(389 "SELECT ts, price FROM price_log WHERE uid=? ORDER BY ts DESC LIMIT 6",390 (uid,)).fetchall()]391 con.close()392393 # --- enrichissements de la fiche (mêmes modules que les blocs du site) ---394 lat, lng = l.get("lat"), l.get("lng")395 geo = lat is not None and lng is not None396397 def _safe(fn, *a, **k):398 try:399 return fn(*a, **k)400 except Exception:401 return None402403 from . import air as air_mod404 from . import commerces as com_mod405 from . import fairvalue as fv_mod406 from . import gaz as gaz_mod407 from . import hydro as hydro_mod408 from . import inondation as inon_mod409 from . import rdl as rdl_mod410 from . import tal as tal_mod411 fv = _safe(fv_mod.explain, uid)412 rdl_d = _safe(rdl_mod.nearby, lat, lng) if geo else None413 tal_d = (_safe(tal_mod.lookup, l["address"], l.get("city"))414 if l.get("address") else None)415 inon = _safe(inon_mod.lookup, lat, lng) if geo else None416 air_d = _safe(air_mod.lookup, lat, lng) if geo else None417 gaz_d = _safe(gaz_mod.nearby, lat, lng) if geo else None418 com = _safe(com_mod.nearby, lat, lng) if geo else None419 hyd = _safe(hydro_mod.estimate, adresse=l.get("address") or "",420 uid=uid, lat=lat, lng=lng, solve=False)421 # dossier d'intelligence locative (mêmes modules que les blocs du site)422 from . import building as bld_mod423 from . import coutreel as cr_mod424 from . import history as hist_mod425 from . import hiver as hiv_mod426 from . import managers as mgr_mod427 from . import recycled as rec_mod428 cout = _safe(cr_mod.compute, uid)429 histo = _safe(hist_mod.timeline, uid)430 recyc = _safe(rec_mod.lookup, uid)431 imm = (_safe(bld_mod.fiche, l["building_key"])432 if l.get("building_key") else None)433 hiv = _safe(hiv_mod.score, lat, lng) if geo else None434 gest = _safe(mgr_mod.fiche, l["source"])435436 buf = io.BytesIO()437 c = rl_canvas.Canvas(buf, pagesize=letter)438 c.setTitle(f"Lou-Ka — {l.get('title') or l.get('address')}")439 s = _Style(c)440 s.fond()441 y = s.entete("Fiche logement")442 page = [1]443444 def saut_page() -> float:445 s.pied(_PIED_FICHE, page[0])446 c.showPage()447 page[0] += 1448 s.fond()449 return s.entete("Fiche logement · suite")450451 def place(y_: float, besoin: float) -> float:452 """Saute de page si `besoin` points ne tiennent plus sous y_."""453 return saut_page() if (y_ - besoin) < M + 34 else y_454455 # --- bloc prix + badge marché (verdict du modèle Lou-Ka en priorité)456 prix_txt = (_fmt_money(l["price"]) + f"{NBSP}/ mois") if l.get("price") \457 else (l.get("price_label") or "Prix sur demande")458 c.setFont("Helvetica-Bold", 30)459 c.setFillColor(INK)460 c.drawString(M, y - 24, prix_txt)461 loyer_secteur = (quartier or {}).get("demographie", {}).get("loyer_moyen") \462 if quartier else None463 bx = M + c.stringWidth(prix_txt, "Helvetica-Bold", 30) + 14464 if l.get("price") and fv and fv.get("verdict") in _VERDICTS:465 dev = fv.get("deviation") or 0466 pct = f"{'+' if dev > 0 else '−'}{abs(round(dev * 100))}{NBSP}%"467 lab, fg, bg, stk = _VERDICTS[fv["verdict"]]468 s.pilule(bx, y - 22, f"{pct} vs juste valeur · {lab}", fg, bg, stk)469 elif l.get("price") and loyer_secteur:470 delta = (l["price"] - loyer_secteur) / loyer_secteur471 pct = f"{'+' if delta > 0 else '−'}{abs(round(delta * 100))}{NBSP}%"472 if delta <= -0.15:473 s.pilule(bx, y - 22, f"{pct} vs secteur · Bon deal", GREEN_DEEP, LIME_SOFT, GREEN)474 elif delta <= 0.10:475 s.pilule(bx, y - 22, f"{pct} vs secteur · Dans le marché", INK2, SURFACE, INK)476 else:477 s.pilule(bx, y - 22, f"{pct} vs secteur · Au-dessus du marché",478 HexColor("#8a5a12"), AMBER_SOFT, AMBER)479 y -= 44480481 # --- titre + adresse482 c.setFont("Helvetica-Bold", 13)483 c.setFillColor(INK)484 c.drawString(M, y, (l.get("title") or l.get("address") or "")[:80])485 y -= 14486 c.setFont("Helvetica", 9)487 c.setFillColor(INK2)488 loc = " · ".join(x for x in (l.get("address"), l.get("sector"), l.get("city"))489 if x and x != l.get("title"))490 c.drawString(M, y, loc[:110])491 y -= 20492493 # --- chips clés494 x = M495 chips = []496 if l.get("unit_type"):497 chips.append(l["unit_type"])498 ad = l.get("availability_date")499 if ad == "now":500 chips.append("Libre maintenant")501 elif ad:502 chips.append(f"Dispo {ad}")503 if l.get("area_sqft"):504 chips.append(f"{round(l['area_sqft'])}{NBSP}pi²")505 if l.get("furnished"):506 chips.append("Meublé")507 if l.get("pets"):508 chips.append({"oui": "Animaux acceptés", "non": "Animaux refusés",509 "conditions": "Animaux sous conditions"}.get(l["pets"], l["pets"]))510 if l["details"].get("floor") is not None:511 chips.append(f"{l['details']['floor']}e étage")512 for chip in chips[:7]:513 x = s.pilule(x, y - 6, chip)514 y -= 30515516 # --- photos : 1 grande + 3 vignettes517 imgs = [im for im in (_fetch_image(u) for u in l["images"][:4]) if im]518 if imgs:519 big_h = 170520 big_w = big_h * 16 / 10.5521 c.setStrokeColor(INK)522 c.setLineWidth(1.5)523 try:524 c.drawImage(imgs[0], M, y - big_h, big_w, big_h,525 preserveAspectRatio=True, anchor="c", mask="auto")526 except Exception:527 pass528 c.rect(M, y - big_h, big_w, big_h, stroke=1, fill=0)529 tx = M + big_w + 10530 th = (big_h - 16) / 3531 for i, im in enumerate(imgs[1:4]):532 ty = y - (i + 1) * th - i * 8533 try:534 c.drawImage(im, tx, ty, PAGE_W - M - tx, th,535 preserveAspectRatio=True, anchor="c", mask="auto")536 c.rect(tx, ty, PAGE_W - M - tx, th, stroke=1, fill=0)537 except Exception:538 pass539 y -= big_h + 18540541 # --- « En bref » (digest) sur bandeau lime542 dg = l.get("digest")543 if dg and dg.get("en_bref"):544 c.setFillColor(LIME_SOFT)545 c.setStrokeColor(GREEN)546 c.setLineWidth(1.2)547 c.roundRect(M, y - 40, PAGE_W - 2 * M, 44, 6, stroke=1, fill=1)548 s.paragraphe(M + 10, y - 8, "EN BREF — " + dg["en_bref"],549 PAGE_W - 2 * M - 20, taille=8.5, couleur=GREEN_DEEP,550 max_lignes=3)551 y -= 54552553 # --- description (2-3 sections max) | inclusions en colonne droite554 col_g = PAGE_W * 0.56 - M555 y_desc = s.titre_section(y, "Description")556 if dg and dg.get("sections"):557 for sec in dg["sections"][:3]:558 c.setFont("Helvetica-Bold", 9)559 c.setFillColor(INK)560 c.drawString(M, y_desc, sec["titre"][:60])561 y_desc -= 12562 y_desc = s.paragraphe(M, y_desc, sec["texte"], col_g, max_lignes=6)563 y_desc -= 4564 if y_desc < 150:565 break566 elif l.get("description"):567 y_desc = s.paragraphe(M, y_desc, l["description"], col_g, max_lignes=16)568569 xr = M + col_g + 24570 y_incl = s_titre_droite(c, y, xr, "Inclusions et commodités")571 d = l["details"]572 badges = []573 inc = d.get("inclusions") or {}574 for k, lab in (("heating", "Chauffage inclus"), ("electricity", "Électricité incluse"),575 ("hot_water", "Eau chaude incluse"), ("internet", "Internet inclus")):576 if inc.get(k):577 badges.append(lab)578 app = d.get("appliances") or {}579 if app.get("dishwasher"):580 badges.append("Lave-vaisselle")581 if app.get("washer_dryer"):582 badges.append("Laveuse-sécheuse")583 for k, lab in (("ac", "Climatisation"), ("elevator", "Ascenseur"),584 ("balcony", "Balcon"), ("pool", "Piscine"), ("gym", "Gym"),585 ("laundry", "Buanderie"), ("storage", "Rangement")):586 if d.get(k):587 badges.append(lab)588 if (d.get("parking") or {}).get("available"):589 badges.append("Stationnement")590 if l.get("furnished"):591 badges.append("Meublé")592 c.setFont("Helvetica", 8.5)593 for b in badges[:12]:594 c.setFillColor(GREEN)595 c.drawString(xr, y_incl, "✓")596 c.setFillColor(INK2)597 c.drawString(xr + 12, y_incl, b)598 y_incl -= 12599 autres = [a for a in l["amenities"]600 if not any(b.lower() in a.lower() or a.lower() in b.lower() for b in badges)]601 for a in autres[: max(0, 14 - len(badges))]:602 c.setFillColor(INK3)603 c.drawString(xr + 12, y_incl, a[:38])604 y_incl -= 11605606 y = min(y_desc, y_incl) - 16607608 # --- Analyse de prix Lou-Ka (juste valeur, fourchette, distribution)609 if fv and fv.get("fv"):610 hist = fv.get("histogram") or []611 y = place(y, 168 if hist else 92)612 y = s.titre_section(y, "Analyse de prix Lou-Ka")613 jv = _fmt_money(round(fv["fv"]))614 c.setFont("Helvetica-Bold", 17)615 c.setFillColor(INK)616 c.drawString(M, y - 10, jv)617 c.setFont("Helvetica", 8.5)618 c.setFillColor(INK2)619 c.drawString(M + c.stringWidth(jv, "Helvetica-Bold", 17) + 8, y - 10,620 "/ mois — juste valeur estimée par le modèle Lou-Ka")621 meta = []622 if fv.get("fv_low") and fv.get("fv_high"):623 meta.append(f"fourchette {_fmt_money(round(fv['fv_low']))} – "624 f"{_fmt_money(round(fv['fv_high']))}")625 if fv.get("confidence"):626 meta.append(f"confiance {fv['confidence']}")627 if fv.get("comps"):628 meta.append(f"{fv['comps']} comparables")629 if fv.get("segment_n"):630 meta.append(f"segment de {fv['segment_n']} annonces")631 c.setFont("Helvetica", 8)632 c.setFillColor(INK3)633 c.drawString(M, y - 24, " · ".join(meta)[:115])634 if l.get("price") and fv.get("verdict") in _VERDICTS:635 dev = fv.get("deviation") or 0636 pct = f"{'+' if dev > 0 else '−'}{abs(round(dev * 100))}{NBSP}%"637 lab, fg, bg, stk = _VERDICTS[fv["verdict"]]638 s.pilule(M, y - 48, f"{pct} vs juste valeur · {lab}", fg, bg, stk)639 y -= 58640 if hist:641 ch_h = 40642 lo, hi = hist[0]["x0"], hist[-1]["x1"]643 larg = PAGE_W - 2 * M644 base = y - ch_h - 6645 if hi > lo and fv.get("fv_low") and fv.get("fv_high"):646 bx0 = M + larg * max(0.0, (fv["fv_low"] - lo) / (hi - lo))647 bx1 = M + larg * min(1.0, (fv["fv_high"] - lo) / (hi - lo))648 c.setFillColor(LIME_SOFT)649 c.rect(bx0, base, max(2, bx1 - bx0), ch_h, stroke=0, fill=1)650 max_n = max((h["n"] for h in hist), default=1) or 1651 bw = larg / len(hist)652 c.setFillColor(GREEN)653 for i, h in enumerate(hist):654 bh = ch_h * h["n"] / max_n655 if bh > 0:656 c.rect(M + i * bw + 1, base, bw - 2, max(0.6, bh),657 stroke=0, fill=1)658 if hi > lo and l.get("price"):659 px = M + larg * (min(max(l["price"], lo), hi) - lo) / (hi - lo)660 c.setStrokeColor(LIME)661 c.setLineWidth(2)662 c.line(px, base - 3, px, base + ch_h + 3)663 c.setFont("Courier-Bold", 6.5)664 c.setFillColor(LIME)665 c.drawString(min(max(px - 28, M), PAGE_W - M - 92),666 base + ch_h + 6,667 f"CE LOYER · {_fmt_money(l['price'])}")668 c.setFont("Helvetica", 6.5)669 c.setFillColor(INK3)670 c.drawString(M, base - 9, _fmt_money(lo))671 c.drawRightString(PAGE_W - M, base - 9,672 _fmt_money(hi) + " — distribution des loyers du "673 "segment de référence")674 y = base - 20675 ph = [p for p in price_history if p.get("price")]676 if len(ph) >= 2 and ph[0]["price"] != ph[-1]["price"]:677 c.setFont("Helvetica", 8)678 c.setFillColor(INK2)679 chn = " → ".join(_fmt_money(p["price"]) for p in reversed(ph[:4]))680 c.drawString(M, y - 2, f"Historique de prix de l'annonce : {chn}")681 y -= 16682683 # --- Coût réel mensuel (loyer + frais, chaque poste étiqueté honnêtement)684 if cout and cout.get("loyer") is not None:685 lignes_cr = cout.get("lignes") or []686 y = place(y, 58 + len(lignes_cr) * 12 + 46)687 y = s.titre_section(y, "Coût réel mensuel")688 stat_cr = {"included": ("INCLUS", GREEN), "observed": ("OBSERVÉ", INK),689 "estimated": ("ESTIMÉ", LIME), "unknown": ("INCONNU", INK3)}690 for li in lignes_cr:691 lab, col = stat_cr.get(li.get("statut"), stat_cr["unknown"])692 c.setFont("Helvetica", 8.5)693 c.setFillColor(INK2)694 c.drawString(M, y, (li.get("poste") or "")[:46])695 c.setFont("Courier-Bold", 6.5)696 c.setFillColor(col)697 c.drawString(M + 230, y, lab)698 m_ = li.get("montant")699 if m_ is not None and m_ > 0:700 mtx = _fmt_money(m_)701 elif m_ == 0 and li.get("statut") == "included":702 mtx = f"0{NBSP}$"703 else:704 mtx = "—"705 c.setFont("Helvetica-Bold", 8.5)706 c.setFillColor(INK)707 c.drawRightString(PAGE_W - M, y, mtx)708 y -= 12709 if cout.get("total_estime") is not None:710 c.setStrokeColor(INK)711 c.setLineWidth(1.2)712 c.line(M, y + 8, PAGE_W - M, y + 8)713 c.setFont("Helvetica-Bold", 10)714 c.setFillColor(INK)715 c.drawString(M, y - 4, "Total estimé")716 tot = f"≈{NBSP}{_fmt_money(cout['total_estime'])} / mois"717 if cout.get("annuel_estime") is not None:718 tot += f" · ≈{NBSP}{_fmt_money(cout['annuel_estime'])} / an"719 c.drawRightString(PAGE_W - M, y - 4, tot)720 y -= 18721 if cout.get("postes_inconnus"):722 y = s.paragraphe(M, y - 2, "Postes non chiffrables avec les données "723 "publiées : "724 + ", ".join(cout["postes_inconnus"]).lower()725 + " — le total réel peut être plus élevé.",726 PAGE_W - 2 * M, taille=7.5,727 couleur=HexColor("#8a5a12"), interligne=9.5,728 max_lignes=3)729 pi2_d = cout.get("pi2")730 if pi2_d and pi2_d.get("valeur") is not None:731 v = f"{pi2_d['valeur']:.2f}".replace(".", ",")732 suite = f"{v}{NBSP}$/pi²"733 if pi2_d.get("percentile_secteur") is not None:734 suite += (f" — moins cher que {100 - pi2_d['percentile_secteur']}"735 f"{NBSP}% des {pi2_d.get('n_secteur')} comparables du "736 "secteur (~2 km)")737 elif pi2_d.get("percentile_ville") is not None:738 suite += (f" — moins cher que {100 - pi2_d['percentile_ville']}"739 f"{NBSP}% des {pi2_d.get('n_ville')} comparables "740 f"({pi2_d.get('portee_ville', '')})")741 c.setFont("Helvetica", 8)742 c.setFillColor(INK2)743 c.drawString(M, y - 2, suite[:120])744 y -= 12745 y -= 8746747 # --- Historique Lou-Ka (observations réelles des synchronisations)748 if histo:749 tl = (histo.get("timeline") or [])[:8]750 matches = ((recyc or {}).get("matches") or [])[:2]751 y = place(y, 46 + len(tl) * 11 + len(matches) * 22 + 18)752 y = s.titre_section(y, "Historique Lou-Ka")753 entete_h = (f"Suivie depuis {_fmt_ts(histo.get('premiere_observation'), jour=True)}"754 f" · {histo.get('jours_en_ligne', 0)} jour"755 f"{'s' if (histo.get('jours_en_ligne') or 0) > 1 else ''} en ligne"756 f" · {histo.get('modifications', 0)} modification"757 f"{'s' if (histo.get('modifications') or 0) > 1 else ''} observée"758 f"{'s' if (histo.get('modifications') or 0) > 1 else ''}")759 pi_, pa_ = histo.get("prix_initial"), histo.get("prix_actuel")760 if pi_ is not None and pa_ is not None and pi_ != pa_:761 var_ = histo.get("variation")762 entete_h += f" · {_fmt_money(pi_)} → {_fmt_money(pa_)}"763 if var_ is not None:764 entete_h += (f" ({'+' if var_ > 0 else '−'}"765 f"{abs(round(var_ * 100))}{NBSP}%)")766 c.setFont("Helvetica-Bold", 8.5)767 c.setFillColor(INK)768 c.drawString(M, y - 2, entete_h[:120])769 y -= 16770 ev_labels = {"description": "Description modifiée",771 "superficie": "Superficie modifiée",772 "dispo": "Disponibilité modifiée",773 "inclusions": "Inclusions modifiées",774 "photos": "Photos modifiées",775 "disparition": "Annonce retirée",776 "reapparition": "Annonce republiée"}777 if tl:778 for it in tl:779 c.setFont("Courier-Bold", 7)780 c.setFillColor(INK3)781 c.drawString(M, y, _fmt_ts(it.get("ts"), jour=True).upper())782 c.setFont("Helvetica", 8)783 c.setFillColor(INK2)784 if it.get("type") == "prix":785 if it.get("prix_avant") is not None:786 sens = ("baissé" if it["prix_avant"] > (it.get("prix") or 0)787 else "monté")788 txt_ev = (f"Prix {sens} de {_fmt_money(it['prix_avant'])} "789 f"à {_fmt_money(it.get('prix'))}")790 else:791 txt_ev = f"Premier prix observé : {_fmt_money(it.get('prix'))}"792 else:793 txt_ev = ev_labels.get(it.get("type"), it.get("type") or "")794 c.drawString(M + 78, y, txt_ev[:95])795 y -= 11796 else:797 c.setFont("Helvetica", 8)798 c.setFillColor(INK2)799 c.drawString(M, y, "Aucune modification observée depuis la première "800 "synchronisation de cette annonce.")801 y -= 11802 for m_ in matches:803 suite = f"Vie antérieure probable ({m_.get('confiance')}{NBSP}% de confiance)"804 if m_.get("prix") is not None:805 suite += f" — affiché {_fmt_money(m_['prix'])}"806 if m_.get("derniere_observation"):807 suite += f" jusqu'en {_fmt_ts(m_['derniere_observation'])}"808 c.setFont("Helvetica-Bold", 8)809 c.setFillColor(HexColor("#8a5a12"))810 c.drawString(M, y - 2, suite[:115])811 y -= 10812 c.setFont("Helvetica", 7)813 c.setFillColor(INK3)814 c.drawString(M, y - 2, ("signaux : " + " · ".join(m_.get("signaux") or []))[:125])815 y -= 12816 y -= 8817818 # --- Passeport de l'immeuble (ce que Lou-Ka observe du bâtiment)819 if imm and (imm.get("annonces_total") or 0) >= 2:820 y = place(y, 128)821 y = s.titre_section(y, "Passeport de l'immeuble")822 tw = (PAGE_W - 2 * M - 30) / 4823 rot = imm.get("rotation") or {}824 pres = imm.get("pression_loyers")825 tuiles_im = [826 (str(imm["annonces_total"]),827 f"annonces obs. ({imm.get('annonces_actives', 0)} actives)"),828 (f"≥{NBSP}{imm.get('unites_estimees', 0)}", "unités estimées"),829 (_fmt_money(imm.get("loyer_median")), "loyer médian (actives)"),830 (f"{imm['pi2_median']:.2f}".replace(".", ",") + f"{NBSP}$"831 if imm.get("pi2_median") is not None else "—", "médiane $/pi²"),832 ]833 for i, (val, lab) in enumerate(tuiles_im):834 s.tuile(M + i * (tw + 10), y - 44, tw, 38, val, lab)835 y -= 58836 par_cc = imm.get("loyer_median_par_cc") or {}837 if par_cc:838 parts = [f"{cc}{NBSP}ch. {_fmt_money(v)}"839 for cc, v in sorted(par_cc.items())]840 c.setFont("Helvetica", 8)841 c.setFillColor(INK2)842 c.drawString(M, y, ("Loyer médian par nombre de chambres : "843 + " · ".join(parts))[:118])844 y -= 13845 c.setFont("Helvetica-Bold", 8)846 c.setFillColor(INK)847 c.drawString(M, y, "Rotation des logements :")848 c.setFont("Helvetica", 8)849 c.setFillColor(INK2)850 if rot.get("statut") == "calculated":851 c.drawString(M + 118, y,852 (f"{rot.get('classe', '')} — {rot.get('annonces_12m')} "853 f"annonces sur 12 mois pour ≥{NBSP}"854 f"{rot.get('unites_estimees')} unités")[:100])855 else:856 c.drawString(M + 118, y, "données insuffisantes")857 y -= 12858 c.setFont("Helvetica-Bold", 8)859 c.setFillColor(INK)860 c.drawString(M, y, "Pression sur les loyers :")861 c.setFont("Helvetica", 8)862 c.setFillColor(INK2)863 if pres:864 v12 = pres.get("variation_12m") or 0865 c.drawString(M + 118, y,866 (f"{'+' if v12 > 0 else '−'}{abs(round(v12 * 100))}"867 f"{NBSP}% sur 12 mois — médiane des prix d'entrée "868 f"{_fmt_money(pres.get('mediane_12_24m'))} → "869 f"{_fmt_money(pres.get('mediane_12m'))} "870 f"({pres.get('n_12_24m')} vs {pres.get('n_12m')} annonces)")[:110])871 else:872 c.drawString(M + 118, y, "échantillon insuffisant")873 y -= 12874 c.setFont("Helvetica", 6.5)875 c.setFillColor(INK3)876 c.drawString(M, y - 2, (f"Immeuble suivi par Lou-Ka depuis "877 f"{_fmt_ts(imm.get('premiere_observation'))} — "878 "indicateurs calculés uniquement sur les annonces "879 "observées (pas un recensement du bâtiment).")[:135])880 y -= 16881882 # --- Qui gère ce logement? (fiche Google associée + avis synchronisés)883 g_ = (gest or {}).get("google_maps")884 if gest and g_ and g_.get("statut") != "non_associe":885 avis_g = gest.get("avis") or {}886 dist_g = avis_g.get("distribution") or {}887 tot_g = sum(dist_g.values()) if dist_g else 0888 y = place(y, 108 + (5 * 11 if tot_g else 0))889 y = s.titre_section(y, "Qui gère ce logement?")890 c.setFont("Helvetica-Bold", 10.5)891 c.setFillColor(INK)892 c.drawString(M, y - 2, (gest.get("nom") or "")[:60])893 n_act = gest.get("annonces_actives") or 0894 c.setFont("Helvetica", 8)895 c.setFillColor(INK2)896 c.drawString(M + c.stringWidth((gest.get("nom") or "")[:60],897 "Helvetica-Bold", 10.5) + 10, y - 2,898 f"{n_act} annonce{'s' if n_act > 1 else ''} active"899 f"{'s' if n_act > 1 else ''} sur Lou-Ka")900 y -= 16901 if g_.get("note") is not None:902 note_t = f"{g_['note']:.1f}".replace(".", ",")903 s.pilule(M, y - 10, f"Note Google {note_t} / 5", LIME, INK)904 c.setFont("Helvetica", 8)905 c.setFillColor(INK2)906 c.drawString(M + 110, y - 5,907 (f"{g_.get('nombre_avis', 0)}{NBSP}avis Google — fiche "908 f"« {g_.get('nom', '')} »")[:90])909 y -= 22910 if tot_g:911 bw_g = 150.0912 for n_ in (5, 4, 3, 2, 1):913 cnt = dist_g.get(str(n_), 0)914 c.setFont("Courier-Bold", 7)915 c.setFillColor(INK2)916 c.drawString(M, y, f"{n_}*")917 c.setFillColor(SURFACE)918 c.setStrokeColor(INK)919 c.setLineWidth(0.8)920 c.rect(M + 22, y - 1, bw_g, 7, stroke=1, fill=1)921 if cnt:922 c.setFillColor(GREEN if n_ >= 4 else (LIME if n_ <= 2 else INK3))923 c.rect(M + 22, y - 1, bw_g * cnt / tot_g, 7, stroke=0, fill=1)924 c.setFont("Courier-Bold", 7)925 c.setFillColor(INK)926 c.drawString(M + 22 + bw_g + 6, y, str(cnt))927 y -= 11928 y -= 2929 stats_g = []930 if avis_g.get("moyenne_12m") is not None:931 stats_g.append(f"moyenne des 12 derniers mois : "932 f"{avis_g['moyenne_12m']:.1f}".replace(".", ",")933 + f" ({avis_g.get('n_12m')} avis)")934 if avis_g.get("tendance"):935 stats_g.append(avis_g["tendance"])936 if avis_g.get("plaintes_frequentes"):937 stats_g.append("plaintes récurrentes : "938 + ", ".join(avis_g["plaintes_frequentes"][:4]))939 if stats_g:940 y = s.paragraphe(M, y, " · ".join(stats_g), PAGE_W - 2 * M,941 taille=8, couleur=INK2, interligne=10,942 max_lignes=2)943 y -= 2944 conf_g = round((g_.get("confiance_association") or 0) * 100)945 y = s.paragraphe(M, y - 2, f"Fiche Google Maps associée automatiquement "946 f"(confiance {conf_g}{NBSP}%). Statistiques sur "947 f"les {avis_g.get('n', 0)} avis synchronisés dans "948 "la base Lou-Ka — échantillon des plus récents, "949 "pas une lecture humaine.",950 PAGE_W - 2 * M, taille=6.5, couleur=INK3,951 interligne=8.5, max_lignes=3)952 y -= 6953954 # --- Registre des loyers (déclarations citoyennes à proximité)955 if rdl_d and rdl_d.get("n"):956 comp = rdl_d.get("items") or []957 y = place(y, 128 + min(len(comp), 8) * 12)958 y = s.titre_section(y, "Registre des loyers — déclarations citoyennes")959 tw = (PAGE_W - 2 * M - 20) / 3960 med_rec = rdl_d.get("median_recent")961 tuiles = [(str(rdl_d["n"]), f"loyers déclarés à <{rdl_d['radius_m']} m"),962 (_fmt_money(rdl_d.get("median")), "médiane du secteur"),963 (_fmt_money(med_rec) if med_rec else "—",964 f"médiane depuis 2023 ({rdl_d.get('n_recent', 0)} décl.)")]965 for i, (val, lab) in enumerate(tuiles):966 s.tuile(M + i * (tw + 10), y - 44, tw, 38, val, lab)967 y -= 56968 rooms = rdl_d.get("by_rooms") or {}969 if rooms:970 def _rk(k: str) -> float:971 try:972 return float(k)973 except ValueError:974 return 99.0975 parts = [f"{k}{NBSP}ch. {_fmt_money(v['median'])} ({v['n']})"976 for k, v in sorted(rooms.items(), key=lambda kv: _rk(kv[0]))]977 c.setFont("Helvetica", 8)978 c.setFillColor(INK2)979 c.drawString(M, y, ("Médianes par taille : " + " · ".join(parts))[:118])980 y -= 14981 if comp:982 c.setFont("Courier-Bold", 7)983 c.setFillColor(INK3)984 for lab, xoff in (("ADRESSE", 0), ("CH.", 280), ("DÉBUT DE BAIL", 320),985 ("DIST.", 420), ("LOYER", 480)):986 c.drawString(M + xoff, y, lab)987 y -= 4988 c.setStrokeColor(INK)989 c.setLineWidth(1)990 c.line(M, y, PAGE_W - M, y)991 y -= 11992 for it in comp[:8]:993 c.setFont("Helvetica", 8)994 c.setFillColor(INK2)995 c.drawString(M, y, (it.get("address") or "")[:52])996 c.drawString(M + 280, y, str(it["rooms"]) if it.get("rooms") is not None else "—")997 c.drawString(M + 320, y, _fmt_mois(it.get("date")))998 c.drawString(M + 420, y, _fmt_dist(it["dist_m"]))999 c.setFont("Helvetica-Bold", 8)1000 c.setFillColor(INK)1001 c.drawString(M + 480, y, _fmt_money(it.get("price")))1002 y -= 121003 c.setFont("Helvetica", 6.5)1004 c.setFillColor(INK3)1005 c.drawString(M, y - 2, "Loyers déclarés volontairement par des locataires "1006 "au Registre des loyers (registre-des-loyers.ca) — "1007 "données citoyennes non vérifiées.")1008 y -= 1610091010 # --- Historique au TAL (décisions SOQUIJ à l'adresse)1011 if tal_d and tal_d.get("status") in ("ok", "pending"):1012 decs = (tal_d.get("decisions") or [])[:6]1013 y = place(y, 70 + len(decs) * 24)1014 y = s.titre_section(y, "Historique au Tribunal administratif du logement")1015 if tal_d["status"] == "pending":1016 c.setFont("Helvetica", 8.5)1017 c.setFillColor(INK2)1018 c.drawString(M, y - 4, "Adresse en file de vérification auprès des "1019 "décisions publiées du TAL (résultat sur la "1020 "fiche en ligne sous peu).")1021 y -= 181022 elif not decs:1023 s.pilule(M, y - 12, "Aucune décision trouvée", GREEN_DEEP,1024 LIME_SOFT, GREEN)1025 c.setFont("Helvetica", 8.5)1026 c.setFillColor(INK2)1027 c.drawString(M + 130, y - 7, "Aucune décision publiée du TAL n'a été "1028 "repérée à cette adresse.")1029 y -= 261030 else:1031 n = tal_d.get("n") or len(decs)1032 cl = tal_d.get("contre_locataire") or 01033 c.setFont("Helvetica-Bold", 9)1034 c.setFillColor(INK)1035 c.drawString(M, y - 4,1036 f"{n} décision{'s' if n > 1 else ''} publiée"1037 f"{'s' if n > 1 else ''} à cette adresse — "1038 f"{cl} à l'initiative du propriétaire.")1039 y -= 201040 for dec in decs:1041 qui = {"locateur": "demande du propriétaire",1042 "locataire": "demande du locataire"}.get(1043 dec.get("demandeur") or "", "demandeur inconnu")1044 c.setFont("Helvetica-Bold", 8)1045 c.setFillColor(INK)1046 c.drawString(M, y, _fmt_mois(dec.get("date")))1047 c.setFont("Helvetica", 8)1048 c.setFillColor(INK2)1049 suite = qui1050 if dec.get("verdict"):1051 suite += f" · demande {dec['verdict']}"1052 if dec.get("tags"):1053 suite += " · " + ", ".join(dec["tags"][:3])1054 c.drawString(M + 78, y, suite[:88])1055 c.setFont("Courier-Bold", 7)1056 c.setFillColor(GREEN)1057 c.drawRightString(PAGE_W - M, y, dec.get("citation") or "SOQUIJ")1058 y -= 121059 y -= 61060 c.setFont("Helvetica", 6.5)1061 c.setFillColor(INK3)1062 c.drawString(M, y - 2, "Décisions publiques diffusées par SOQUIJ, repérées "1063 "par correspondance d'adresse — une décision peut "1064 "concerner un autre logement du même immeuble.")1065 y -= 1610661067 # --- Risque d'inondation (BDZI)1068 if inon:1069 zones = (inon.get("zones") or [])[:3]1070 y = place(y, 56 + len(zones) * 12)1071 y = s.titre_section(y, "Risque d'inondation")1072 statut = inon.get("statut")1073 sev = {"eleve": "récurrence élevée", "modere": "récurrence modérée",1074 "present": "zone cartographiée"}.get(inon.get("severite") or "", "")1075 if statut == "en_zone":1076 s.pilule(M, y - 12, f"En zone inondable ({sev})",1077 HexColor("#a12622"), HexColor("#fde8e8"), HexColor("#a12622"))1078 elif statut == "a_proximite":1079 d0 = zones[0]["distance_m"] if zones else "?"1080 s.pilule(M, y - 12, f"Zone inondable à ~{d0} m",1081 HexColor("#8a5a12"), AMBER_SOFT, AMBER)1082 elif statut == "hors_zone":1083 s.pilule(M, y - 12, "Hors des zones inondables cartographiées",1084 GREEN_DEEP, LIME_SOFT, GREEN)1085 else:1086 s.pilule(M, y - 12, "Secteur non couvert par la cartographie BDZI",1087 INK2, SURFACE, INK)1088 y -= 261089 for z in zones:1090 c.setFont("Helvetica", 8)1091 c.setFillColor(INK2)1092 c.drawString(M, y, f"{z['type']} — à {z['distance_m']} m"1093 + (f" (rapport {z['date_rapport']})"1094 if z.get("date_rapport") else ""))1095 y -= 121096 y -= 810971098 # --- Qualité de l'air (RSQAQ)1099 if air_d and air_d.get("station"):1100 mes = air_d.get("mesures") or {}1101 y = place(y, 44 + len(mes) * 11)1102 y = s.titre_section(y, "Qualité de l'air")1103 c.setFont("Helvetica", 8.5)1104 c.setFillColor(INK2)1105 c.drawString(M, y - 2,1106 f"Station {air_d['station']} ({air_d['ville']}), à "1107 + f"{air_d['distance_km']}".replace(".", ",") + f"{NBSP}km "1108 "du logement — moyennes annuelles :")1109 y -= 161110 for pol, m_ in list(mes.items())[:5]:1111 c.setFont("Helvetica-Bold", 8)1112 c.setFillColor(INK)1113 c.drawString(M, y, pol)1114 c.setFont("Helvetica", 8)1115 c.setFillColor(INK2)1116 val = f"{m_['moyenne']:.1f}".replace(".", ",") if m_.get("moyenne") is not None else "—"1117 txt = f"{val}{NBSP}{m_.get('unite', '')} ({m_.get('annee', '')})"1118 if m_.get("ref"):1119 txt += f" · référence {m_.get('ref_nom', '')} : {m_['ref']}"1120 c.drawString(M + 56, y, txt[:95])1121 y -= 111122 y -= 811231124 # --- Coût d'électricité (Hydro-Québec)1125 if hyd and hyd.get("disponible"):1126 y = place(y, 52)1127 y = s.titre_section(y, "Coût d'électricité (Hydro-Québec)")1128 c.setFont("Helvetica-Bold", 15)1129 c.setFillColor(INK)1130 mens = f"≈{NBSP}{_fmt_money(round(hyd['cout_mensuel']))} / mois"1131 c.drawString(M, y - 8, mens)1132 c.setFont("Helvetica", 8.5)1133 c.setFillColor(INK2)1134 suite = f"{_fmt_money(round(hyd['cout_annuel']))} / an"1135 if hyd.get("kwh_annuel"):1136 suite += f" · {round(hyd['kwh_annuel']):,}".replace(",", NBSP) + f"{NBSP}kWh/an"1137 suite += " — estimation officielle Hydro-Québec pour cette adresse."1138 c.drawString(M + c.stringWidth(mens, "Helvetica-Bold", 15) + 10, y - 8, suite)1139 y -= 2611401141 # --- Commerces et transport1142 if com and (com.get("commerces") or com.get("transit")):1143 entrees = ([(t["commerce"], t["nom"], t["dist_m"])1144 for t in (com.get("transit") or [])[:4]]1145 + [(i["commerce"], i["nom"], i["dist_m"])1146 for i in (com.get("commerces") or [])[:10]])1147 lignes = (len(entrees) + 1) // 21148 y = place(y, 36 + lignes * 13)1149 y = s.titre_section(y, "Commerces et transport")1150 col_w = (PAGE_W - 2 * M) / 21151 for i, (cat, nom, dist) in enumerate(entrees):1152 px = M if i % 2 == 0 else M + col_w + 101153 py = y - (i // 2) * 131154 c.setFont("Helvetica", 8)1155 c.setFillColor(INK2)1156 nomc = nom if len(nom) <= 22 else nom[:21] + "…"1157 c.drawString(px, py, f"{cat} — {nomc}")1158 c.setFont("Courier-Bold", 7.5)1159 c.setFillColor(INK)1160 c.drawRightString(px + col_w - 14, py, _fmt_dist(dist))1161 y -= lignes * 13 + 1211621163 # --- Essence à proximité1164 if gaz_d and gaz_d.get("stations"):1165 sts = gaz_d["stations"][:3]1166 y = place(y, 40 + len(sts) * 11)1167 y = s.titre_section(y, "Essence à proximité")1168 if gaz_d.get("mediane_regulier"):1169 c.setFont("Helvetica", 8.5)1170 c.setFillColor(INK2)1171 c.drawString(M, y - 2, "Prix médian de l'essence régulière à <5 km : "1172 + f"{gaz_d['mediane_regulier']}".replace(".", ",")1173 + f"{NBSP}¢/L")1174 y -= 141175 for st in sts:1176 c.setFont("Helvetica", 8)1177 c.setFillColor(INK2)1178 reg_p = (f"{st['regulier']}".replace(".", ",") + f"{NBSP}¢/L"1179 if st.get("regulier") else "—")1180 c.drawString(M, y, f"{st['nom']} — {_fmt_dist(st['dist_m'])} : {reg_p}"1181 + (" · la moins chère" if st.get("moins_chere") else ""))1182 y -= 111183 y -= 811841185 # --- KA Scores (immeuble et environnement)1186 if kasc and kasc.get("glob") is not None:1187 from . import kascores as ks_mod1188 y = place(y, 92)1189 y = s.titre_section(y, "KA Scores")1190 paires = [("Global", kasc.get("glob")), ("À pied", kasc.get("walk")),1191 ("Transport", kasc.get("transit")), ("Vélo", kasc.get("bike")),1192 ("Calme", kasc.get("calme")), ("Services", kasc.get("services"))]1193 tw = (PAGE_W - 2 * M - 5 * 8) / 61194 for i, (lab, v) in enumerate(paires):1195 val = "—" if v is None else str(round(v))1196 sub = ks_mod.label(v) or ""1197 s.tuile(M + i * (tw + 8), y - 46, tw, 42, val,1198 f"{lab} · {sub}" if sub else lab)1199 y -= 6212001201 # --- Vie quotidienne en hiver (quotidien à pied, même à −20 °C)1202 if hiv:1203 det_h = hiv.get("detail") or []1204 y = place(y, 52 + len(det_h) * 11 + 14)1205 y = s.titre_section(y, "Vie quotidienne en hiver")1206 c.setFont("Helvetica-Bold", 17)1207 c.setFillColor(INK)1208 sc_t = str(hiv.get("score", "—"))1209 c.drawString(M, y - 8, sc_t)1210 s.pilule(M + c.stringWidth(sc_t, "Helvetica-Bold", 17) + 10, y - 12,1211 (hiv.get("classe") or "").upper())1212 c.setFont("Helvetica", 8)1213 c.setFillColor(INK3)1214 c.drawString(M + c.stringWidth(sc_t, "Helvetica-Bold", 17) + 105, y - 7,1215 "quotidien à pied, même à −20 °C")1216 y -= 261217 for cr_ in det_h:1218 c.setFont("Helvetica-Bold", 8)1219 c.setFillColor(INK)1220 c.drawString(M, y, (cr_.get("critere") or "")[:24])1221 c.setFont("Helvetica", 8)1222 c.setFillColor(INK2)1223 if cr_.get("distance_m") is not None:1224 val_h = f"≈{NBSP}{cr_.get('minutes')}{NBSP}min à pied"1225 if cr_.get("nom"):1226 val_h += f" ({cr_['nom']})"1227 else:1228 val_h = cr_.get("note") or "—"1229 c.drawString(M + 90, y, val_h[:80])1230 c.setFont("Courier-Bold", 7.5)1231 c.setFillColor(INK)1232 c.drawRightString(PAGE_W - M, y, str(cr_.get("score", "—")))1233 y -= 111234 c.setFont("Helvetica", 6.5)1235 c.setFillColor(INK3)1236 c.drawString(M, y - 2, (hiv.get("methode") or "")[:135])1237 y -= 1612381239 # --- Le quartier1240 if quartier:1241 y = place(y, 270)1242 y = s.titre_section(y, "Le quartier")1243 demo = quartier.get("demographie") or {}1244 tuiles = [("Revenu médian", _fmt_money(demo.get("revenu_median"))),1245 ("Ménages locataires", f"{round(demo['pct_locataires'])}{NBSP}%" if demo.get("pct_locataires") is not None else "—"),1246 ("Loyer moyen secteur", _fmt_money(demo.get("loyer_moyen"))),1247 ("Âge médian", f"{round(demo['age_median'])} ans" if demo.get("age_median") is not None else "—"),1248 ("Français à la maison", f"{round(demo['pct_francais'])}{NBSP}%" if demo.get("pct_francais") is not None else "—"),1249 ("Diplôme universitaire", f"{round(demo['pct_univ'])}{NBSP}%" if demo.get("pct_univ") is not None else "—")]1250 tw = (PAGE_W - 2 * M - 20) / 31251 for i, (lab, val) in enumerate(tuiles):1252 s.tuile(M + (i % 3) * (tw + 10), y - 34 - (i // 3) * 44,1253 tw, 38, val, lab)1254 y -= 34 + 44 + 1612551256 prox = quartier.get("proximite") or {}1257 for k, lab in PROX_LABELS:1258 if k not in prox:1259 continue1260 v = max(0.0, min(1.0, prox[k]))1261 c.setFont("Helvetica", 8)1262 c.setFillColor(INK2)1263 c.drawString(M, y, lab)1264 bx0, bw_ = M + 130, PAGE_W - 2 * M - 1601265 c.setFillColor(SURFACE)1266 c.setStrokeColor(INK)1267 c.setLineWidth(0.8)1268 c.roundRect(bx0, y - 1, bw_, 7, 3.5, stroke=1, fill=1)1269 c.setFillColor(GREEN)1270 c.roundRect(bx0, y - 1, bw_ * v, 7, 3.5, stroke=0, fill=1)1271 c.setFont("Courier-Bold", 7.5)1272 c.setFillColor(INK)1273 c.drawRightString(PAGE_W - M, y, str(round(v * 100)))1274 y -= 141275 y -= 41276 badges_q = []1277 ch = quartier.get("chaleur")1278 if ch:1279 if ch["classe"] <= 3:1280 badges_q.append(("Îlot de fraîcheur", GREEN_DEEP, LIME_SOFT, GREEN))1281 elif ch["classe"] >= 7:1282 badges_q.append((f"Îlot de chaleur (+{ch['ecart']:.1f} °C)".replace(".", ","),1283 HexColor("#8a5a12"), AMBER_SOFT, AMBER))1284 cr = quartier.get("crime")1285 if cr and cr.get("type") == "igc" and cr.get("indice_canada"):1286 dlt = round(100 * (cr["indice"] - cr["indice_canada"]) / cr["indice_canada"])1287 badges_q.append((f"Criminalité {abs(dlt)}{NBSP}% "1288 f"{'sous' if dlt <= 0 else 'au-dessus de'} la moyenne canadienne",1289 INK2, SURFACE, INK))1290 elif cr and cr.get("type") == "points":1291 badges_q.append((f"{cr['douze_mois']} actes criminels à <500 m (12 mois)",1292 INK2, SURFACE, INK))1293 x = M1294 for txt, fg, bg, stk in badges_q:1295 x = s.pilule(x, y - 8, txt, fg, bg, stk)1296 y -= 3012971298 # --- À proximité (commodités du cache POI)1299 if poi:1300 lignes = (min(len(poi), 12) + 1) // 21301 y = place(y, 36 + lignes * 13)1302 y = s.titre_section(y, "À proximité")1303 col_w = (PAGE_W - 2 * M) / 21304 for i, p in enumerate(poi[:12]):1305 px = M if i % 2 == 0 else M + col_w + 101306 py = y - (i // 2) * 131307 c.setFont("Helvetica", 8)1308 c.setFillColor(INK2)1309 lab = POI_LABELS.get(p["cat"], p["cat"])1310 nom_poi = p["name"][:19] + "…" if len(p["name"]) > 20 else p["name"]1311 c.drawString(px, py, f"{lab} — {nom_poi}")1312 c.setFont("Courier-Bold", 7.5)1313 c.setFillColor(INK)1314 c.drawRightString(px + col_w - 14, py,1315 f"{_fmt_dist(p['dist_m'])} · {_marche(p['dist_m'])}")1316 y -= lignes * 13 + 1413171318 # --- Références : QR + gestionnaire + source1319 y = place(y, 120)1320 y = s.titre_section(y, "Références")1321 qr = qrcode.make(f"https://www.lou-ka.com/logement/{uid}", box_size=4, border=1)1322 qb = io.BytesIO()1323 qr.save(qb, format="PNG")1324 c.drawImage(ImageReader(io.BytesIO(qb.getvalue())), M, y - 74, 70, 70)1325 c.setFont("Helvetica-Bold", 9)1326 c.setFillColor(INK)1327 c.drawString(M + 82, y - 14, f"Gestionnaire : {src_name}")1328 c.setFont("Helvetica", 8)1329 c.setFillColor(INK2)1330 c.drawString(M + 82, y - 28, "Annonce originale :")1331 c.setFillColor(GREEN)1332 c.drawString(M + 82, y - 40, (l.get("url") or "")[:90])1333 c.setFillColor(INK2)1334 c.drawString(M + 82, y - 56, "Fiche à jour en ligne (scannez le code) :")1335 c.setFillColor(GREEN)1336 c.drawString(M + 82, y - 68, f"www.lou-ka.com/logement/{uid}")1337 y -= 861338 c.setFont("Helvetica", 6.5)1339 c.setFillColor(INK3)1340 c.drawString(M, y, "Sources : Statistique Canada (2021), INSPQ (CC-BY 4.0), "1341 "Ville de Montréal (CC-BY 4.0), OpenStreetMap, BDZI, RSQAQ, "1342 "Hydro-Québec, registre-des-loyers.ca, SOQUIJ, gazquebec.ca.")13431344 s.pied(_PIED_FICHE, page[0])1345 c.save()1346 return buf.getvalue()134713481349def s_titre_droite(c, y, x, texte):1350 c.setFont("Helvetica-Bold", 12.5)1351 c.setFillColor(INK)1352 c.drawString(x, y, texte)1353 c.setStrokeColor(LIME)1354 c.setLineWidth(3)1355 c.line(x, y - 4, x + c.stringWidth(texte, "Helvetica-Bold", 12.5), y - 4)1356 return y - 18135713581359# ---------------------------------------------------------------------------1360# Rapport global du marché1361# ---------------------------------------------------------------------------13621363_REGIONS = [1364 ("Québec métro", {"Québec", "Lévis", "Saint-Augustin-de-Desmaures", "L'Ancienne-Lorette", "Pont-Rouge", "Shannon"}),1365 ("Outaouais", {"Gatineau", "Chelsea", "Thurso", "Perkins", "Maniwaki", "Val-des-Monts"}),1366 ("Estrie / Montérégie-Est", {"Sherbrooke", "Magog", "Orford", "East Angus", "Waterville", "Granby", "Waterloo", "Bromont", "Cowansville", "Richmond"}),1367 ("Mauricie / Centre-du-Québec", {"Trois-Rivières", "Bécancour", "Shawinigan", "Drummondville", "Victoriaville", "Notre-Dame-du-Bon-Conseil", "Saint-Léonard-d'Aston", "Louiseville", "Nicolet", "Wickham", "Saint-Narcisse", "Saint-Nicéphore"}),1368 ("Lanaudière / Laurentides", {"Joliette", "Saint-Jérôme", "Berthierville", "Saint-Ambroise-de-Kildare", "Saint-Gabriel-de-Brandon", "Lachute", "Brownsburg-Chatham", "Saint-Charles-Borromée", "Mirabel", "Sainte-Agathe-des-Monts", "Sainte-Thérèse", "Blainville", "Charlemagne", "Notre-Dame-des-Prairies"}),1369 ("Bas-Saint-Laurent / Gaspésie", {"Rimouski", "Rivière-du-Loup", "Matane", "Saint-Ulric", "Amqui", "Le Bic", "New Richmond", "Carleton-sur-Mer", "Gaspé"}),1370 ("Saguenay–Lac-Saint-Jean", {"Saguenay", "Alma", "Chicoutimi", "Jonquière", "Chambord", "La Malbaie"}),1371 ("Abitibi-Témiscamingue", {"Rouyn-Noranda", "Val-d'Or", "Amos", "Malartic"}),1372 ("Côte-Nord", {"Sept-Îles", "Port-Cartier", "Baie-Comeau", "Forestville"}),1373 ("Chaudière-Appalaches", {"Saint-Georges", "Sainte-Marie", "Thetford Mines", "Montmagny", "Vallée-Jonction", "Scott", "Saint-Isidore", "La Guadeloupe", "Saint-Raphaël"}),1374]137513761377def _region_de(city: str) -> str:1378 for nom, villes in _REGIONS:1379 if city in villes:1380 return nom1381 return "Grand Montréal & environs"138213831384def rapport_pdf() -> bytes:1385 """Rapport global du marché locatif Lou-Ka (multi-pages).13861387 Tous les chiffres viennent de marketstats.compute() — la même source1388 que la page Statistiques du site.1389 """1390 from . import marketstats1391 st = marketstats.compute()1392 reg_file = json.loads((db.DB_PATH.parent / "sources.json").read_text("utf-8"))["sources"]1393 noms = {s["id"]: s["name"] for s in reg_file}13941395 t = st["totals"]1396 total, moy, med, gps = t["total"], t["avg"] or 0, t["median"] or 0, t["gps_pct"]1397 n_sources = t["sources"]13981399 buf = io.BytesIO()1400 c = rl_canvas.Canvas(buf, pagesize=letter)1401 c.setTitle("Lou-Ka — Rapport du marché locatif")1402 s = _Style(c)14031404 # ---- page 1 : couverture + grands chiffres + régions1405 s.fond()1406 s.logo(M, PAGE_H - 130, 42)1407 c.setFont("Helvetica-Bold", 24)1408 c.setFillColor(INK)1409 c.drawString(M, PAGE_H - 185, "Rapport du marché locatif")1410 c.setFont("Courier-Bold", 9)1411 c.setFillColor(INK3)1412 c.drawString(M, PAGE_H - 205,1413 time.strftime("PROVINCE DE QUÉBEC · GÉNÉRÉ LE %Y-%m-%d · WWW.LOU-KA.COM"))14141415 grands = [(f"{total:,}".replace(",", NBSP), "annonces actives"),1416 (str(n_sources), "gestionnaires connectés"),1417 (_fmt_money(moy), "loyer moyen"),1418 (_fmt_money(med), "loyer médian"),1419 (f"{gps}{NBSP}%", "annonces géolocalisées")]1420 tw = (PAGE_W - 2 * M - 4 * 10) / 51421 for i, (val, lab) in enumerate(grands):1422 tx = M + i * (tw + 10)1423 ty = PAGE_H - 2851424 c.setFillColor(INK)1425 c.roundRect(tx + 3, ty - 3, tw, 58, 6, stroke=0, fill=1) # ombre décalée1426 c.setFillColor(SURFACE)1427 c.setStrokeColor(INK)1428 c.setLineWidth(1.5)1429 c.roundRect(tx, ty, tw, 58, 6, stroke=1, fill=1)1430 c.setFont("Helvetica-Bold", 15)1431 c.setFillColor(INK)1432 c.drawCentredString(tx + tw / 2, ty + 32, val)1433 c.setFont("Courier", 6.3)1434 c.setFillColor(INK3)1435 c.drawCentredString(tx + tw / 2, ty + 14, lab.upper())14361437 y = s.titre_section(PAGE_H - 330, "Couverture par région")1438 c.setFont("Courier-Bold", 7)1439 c.setFillColor(INK3)1440 for lab, xoff in (("RÉGION", 0), ("ANNONCES", 280), ("SOURCES", 360),1441 ("LOYER MOYEN", 430)):1442 c.drawString(M + xoff, y, lab)1443 y -= 41444 c.setStrokeColor(INK)1445 c.setLineWidth(1)1446 c.line(M, y, PAGE_W - M, y)1447 y -= 141448 regions = st["by_region"]1449 max_n = max((r["count"] for r in regions), default=1)1450 for r in regions:1451 c.setFont("Helvetica-Bold", 8.5)1452 c.setFillColor(INK)1453 c.drawString(M, y, r["key"])1454 c.setFillColor(LIME)1455 c.setStrokeColor(INK)1456 c.setLineWidth(0.7)1457 bw = 90 * r["count"] / max_n1458 c.roundRect(M + 180, y - 1, max(3, bw), 8, 3, stroke=1, fill=1)1459 c.setFont("Helvetica", 8.5)1460 c.setFillColor(INK2)1461 c.drawRightString(M + 330, y, f"{r['count']:,}".replace(",", NBSP))1462 c.drawRightString(M + 400, y, str(r["sources"]))1463 c.drawRightString(M + 500, y, _fmt_money(r["avg_price"]) if r["avg_price"] else "—")1464 y -= 151465 s.pied("Rapport généré automatiquement à partir des annonces publiques "1466 "agrégées par Lou-Ka. Loyers : bornes 300–10 000 $.", 1)1467 c.showPage()14681469 # ---- page 2 : histogramme des loyers + par type1470 s.fond()1471 y = s.entete("Rapport du marché · loyers")1472 y = s.titre_section(y, "Distribution des loyers")1473 hist = st["histogram"]1474 max_c = max((h["count"] for h in hist), default=1) or 11475 ch_h, ch_y = 150, y - 1701476 bw = (PAGE_W - 2 * M) / len(hist)1477 for i, h in enumerate(hist):1478 bh = ch_h * h["count"] / max_c1479 bx = M + i * bw1480 borne = h["hi"] is None or h["lo"] == 01481 c.setFillColor(INK3 if borne else GREEN)1482 c.setStrokeColor(INK)1483 c.setLineWidth(0.6)1484 c.rect(bx + 2, ch_y, bw - 4, max(1, bh), stroke=1, fill=1)1485 if h["count"] and h["count"] > max_c * 0.06:1486 c.setFont("Courier-Bold", 6)1487 c.setFillColor(INK)1488 c.drawCentredString(bx + bw / 2, ch_y + bh + 3, str(h["count"]))1489 c.setFont("Helvetica", 5.6)1490 c.setFillColor(INK3)1491 lab = f"<{h['hi']}" if h["lo"] == 0 else (f"{h['lo']}+" if h["hi"] is None1492 else str(h["lo"]))1493 c.drawCentredString(bx + bw / 2, ch_y - 9, lab)1494 y = ch_y - 3014951496 y = s.titre_section(y, "Par taille de logement")1497 c.setFont("Courier-Bold", 7)1498 c.setFillColor(INK3)1499 for lab, xoff in (("TAILLE", 0), ("ANNONCES", 160), ("LOYER MOYEN", 260),1500 ("LOYER MIN", 360)):1501 c.drawString(M + xoff, y, lab)1502 y -= 41503 c.line(M, y, PAGE_W - M, y)1504 y -= 131505 for r in st["by_type"][:9]:1506 c.setFont("Helvetica-Bold", 8.5)1507 c.setFillColor(INK)1508 c.drawString(M, y, r["key"])1509 c.setFont("Helvetica", 8.5)1510 c.setFillColor(INK2)1511 c.drawRightString(M + 220, y, str(r["count"]))1512 c.drawRightString(M + 330, y, _fmt_money(r["avg_price"]) if r["avg_price"] else "—")1513 c.drawRightString(M + 430, y, _fmt_money(r["min_price"]) if r["min_price"] else "—")1514 y -= 131515 s.pied("Lou-Ka — agrégateur indépendant. Chaque annonce renvoie à la "1516 "source originale du gestionnaire.", 2)1517 c.showPage()15181519 # ---- page 3 : offre, inclusions, prix au pi², baisses de prix1520 s.fond()1521 y = s.entete("Rapport du marché · offre")1522 o = st["offre"]1523 y = s.titre_section(y, "Inclusions et caractéristiques du parc")1524 carac = [("Chauffage inclus", o["chauffage_pct"]),1525 ("Électricité incluse", o["electricite_pct"]),1526 ("Eau chaude incluse", o["eau_chaude_pct"]),1527 ("Internet inclus", o["internet_pct"]),1528 ("Climatisation", o["clim_pct"]),1529 ("Stationnement", o["stationnement_pct"]),1530 ("Balcon", o["balcon_pct"]),1531 ("Meublé", o["furnished_pct"])]1532 for lab, v in carac:1533 if v is None:1534 continue1535 c.setFont("Helvetica", 8.5)1536 c.setFillColor(INK2)1537 c.drawString(M, y, lab)1538 bx0, bw_ = M + 150, PAGE_W - 2 * M - 2001539 c.setFillColor(SURFACE)1540 c.setStrokeColor(INK)1541 c.setLineWidth(0.8)1542 c.roundRect(bx0, y - 1, bw_, 8, 4, stroke=1, fill=1)1543 c.setFillColor(GREEN)1544 c.roundRect(bx0, y - 1, bw_ * min(1, v / 100), 8, 4, stroke=0, fill=1)1545 c.setFont("Courier-Bold", 8)1546 c.setFillColor(INK)1547 c.drawRightString(PAGE_W - M, y, f"{v}{NBSP}%")1548 y -= 151549 y -= 61550 c.setFont("Helvetica", 8)1551 c.setFillColor(INK3)1552 c.drawString(M, y, f"Disponibles maintenant : {o['dispo_now']:,} · à date future : "1553 f"{o['dispo_date']:,} · superficie moyenne : "1554 f"{o['superficie_moyenne'] or '—'} pi² "1555 f"({o['superficie_connue']:,} annonces la publient)"1556 .replace(",", NBSP))1557 y -= 2415581559 if o["prix_pi2"]:1560 y = s.titre_section(y, "Prix au pied carré (loyer / superficie)")1561 for r in o["prix_pi2"][:6]:1562 c.setFont("Helvetica-Bold", 8.5)1563 c.setFillColor(INK)1564 c.drawString(M, y, r["key"])1565 c.setFont("Helvetica", 8.5)1566 c.setFillColor(INK2)1567 c.drawString(M + 70, y, f"{r['val']:.2f}".replace(".", ",") +1568 f"{NBSP}$/pi² · {r['count']} annonces")1569 y -= 131570 y -= 1015711572 if st["baisses"]:1573 y = s.titre_section(y, "Baisses de prix récentes (30 jours)")1574 for b in st["baisses"][:8]:1575 c.setFont("Helvetica", 8.5)1576 c.setFillColor(INK2)1577 c.drawString(M, y, f"{(b['title'] or b['uid'])[:46]} — {b['city'] or ''}")1578 c.setFont("Courier-Bold", 8)1579 c.setFillColor(GREEN)1580 c.drawRightString(PAGE_W - M, y,1581 f"{_fmt_money(b['avant'])} → {_fmt_money(b['apres'])} "1582 f"({b['pct']}{NBSP}%)".replace(".", ","))1583 y -= 131584 s.pied("Caractéristiques dérivées des annonces publiées ; les inclusions "1585 "non mentionnées par une source ne sont pas comptées.", 3)1586 c.showPage()15871588 # ---- page 4 : top villes + top gestionnaires1589 s.fond()1590 y = s.entete("Rapport du marché · détail")1591 y = s.titre_section(y, "Top 20 des villes")1592 col_w = (PAGE_W - 2 * M) / 21593 for i, r in enumerate(st["by_city"][:20]):1594 vx = M if i < 10 else M + col_w1595 vy = y - (i % 10) * 131596 c.setFont("Helvetica", 8.5)1597 c.setFillColor(INK2)1598 c.drawString(vx, vy, f"{i + 1:>2}. {r['key']}")1599 c.setFont("Courier-Bold", 8)1600 c.setFillColor(INK)1601 c.drawRightString(vx + col_w - 24, vy, f"{r['count']:,}".replace(",", NBSP))1602 y -= 10 * 13 + 1616031604 y = s.titre_section(y, "Top 20 des gestionnaires")1605 for i, r in enumerate(st["by_source"][:20]):1606 vx = M if i < 10 else M + col_w1607 vy = y - (i % 10) * 131608 c.setFont("Helvetica", 8.5)1609 c.setFillColor(INK2)1610 c.drawString(vx, vy, f"{i + 1:>2}. {noms.get(r['key'], r['key'])[:34]}")1611 c.setFont("Courier-Bold", 8)1612 c.setFillColor(INK)1613 c.drawRightString(vx + col_w - 24, vy, f"{r['count']:,}".replace(",", NBSP))1614 y -= 10 * 13 + 2016151616 c.setFont("Helvetica", 7.5)1617 c.setFillColor(INK3)1618 c.drawString(M, y, "Sources de données de quartier : Statistique Canada (Recensement 2021, "1619 "licence ouverte), INSPQ (CC-BY 4.0), Ville de Montréal (CC-BY 4.0), OpenStreetMap.")1620 s.pied("© Lou-Ka — www.lou-ka.com · rapport non contractuel, généré automatiquement.", 4)1621 c.save()1622 return buf.getvalue()1623