SPB Git

Repository Public

pdffiche.py 42.9 KB 1,054 lines python

1# =============================================================================2#                  SP BOUCHER | SOFTWARE & RESEARCH3#             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4# =============================================================================5#6# PROJECT METADATA7# -----------------------------------------------------------------------------8# Project          : Immo·Ka9# File             : immoka/pdffiche.py10# Module           : immoka11# Repository       : https://git.spboucher.ai/immo-ka12# Created          : 2026-08-2413# Last Modified    : 2026-08-2414#15# =============================================================================16# AUTHOR & PROFESSIONAL AFFILIATION17# =============================================================================18#19# Author           : Simon-Pierre Boucher20# Position         : Professor of Finance21# Institution      : Université du Québec en Outaouais (UQO)22# Department       : Département des sciences administratives23# Organization     : SP Boucher24#25# Website          : https://spboucher.ai26# Git              : https://git.spboucher.ai27#28# =============================================================================29# OFFICIAL CONTACT DIRECTORY30# =============================================================================31#32# General          : info@spboucher.ai33# Professional     : contact@spboucher.ai34# Direct           : simon@spboucher.ai35# Research         : research@spboucher.ai36# Development      : dev@spboucher.ai37# Support          : support@spboucher.ai38# Security/Admin   : admin@spboucher.ai39# Notifications    : notifications@spboucher.ai40#41# Preferred Contact: contact@spboucher.ai42#43# =============================================================================44# COPYRIGHT & INTELLECTUAL PROPERTY45# =============================================================================46#47# Copyright (c) 202648# Simon-Pierre Boucher49#50# All rights reserved where applicable.51#52# This file is governed by the applicable project license,53# copyright notices, institutional agreements and relevant law.54#55# Unless expressly authorized by the applicable license or56# rights holder, copying, redistribution, sublicensing,57# publication and commercial exploitation are not permitted.58#59# Existing third-party rights and notices remain unaffected.60#61# =============================================================================62# CONFIDENTIALITY & SECURITY63# =============================================================================64#65# Classification   : Public66# Distribution     : Public repository; use is governed by the project license67# Security Contact : admin@spboucher.ai68#69# Access to this source does not independently grant permission70# to redistribute or disclose confidential materials.71#72# Do not embed credentials, private keys, access tokens,73# certificates or confidential personal information.74#75# =============================================================================76# LICENSE & MAINTENANCE77# =============================================================================78#79# License          : None specified (no license file in this repository)80# Maintainer       : Simon-Pierre Boucher81# Technical Contact: dev@spboucher.ai82#83# =============================================================================84# END OF SP BOUCHER SOURCE HEADER85# =============================================================================8687# -----------------------------------------------------------------------------88# Immo-Ka — Agrégateur de propriétés à vendre (province de Québec)89# Auteur : Simon-Pierre Boucher — contact@spboucher.ai90# pdffiche.py : fiche PDF complète d'une propriété — reflète TOUS les blocs de91#   la fiche web : prix + verdict Vrai-Prix, photos, description, inclusions,92#   caractéristiques, pièces, analyse Vrai-Prix (jauge + rôle foncier),93#   historique de prix, inondation, qualité de l'air, coût d'électricité,94#   commerces/transport, essence, quartier, références + QR.95#   Style « éditorial sharp » (bordures encre, ombres décalées dures, tuiles96#   KPI, micro-étiquettes Courier) — palette Immo-Ka v2 : chaux #F6F3EC,97#   charbon #1B1D22, ardoise #2B4A63, rouge porte #D12C37. Pagination dynamique : saut_page()/place(),98#   aucune section coupée entre deux pages.99# -----------------------------------------------------------------------------100from __future__ import annotations101102import io103import json104import time105106import qrcode107import requests108from pathlib import Path109110from reportlab.lib.colors import HexColor111from reportlab.lib.pagesizes import letter112from reportlab.lib.utils import ImageReader113from reportlab.pdfgen import canvas as rl_canvas114115from . import db116117# --- palette Immo-Ka v2 (système de marque « Larmier ») -----------------------118PAPER = HexColor("#F6F3EC")         # chaux119SURFACE = HexColor("#ffffff")120INK = HexColor("#1B1D22")           # charbon121INK2 = HexColor("#4A4E57")122INK3 = HexColor("#8A8E96")123ACCENT = HexColor("#D12C37")        # rouge porte124ACCENT_SOFT = HexColor("#F7DCDE")125ACCENT_DEEP = HexColor("#B5252F")   # rouge profond126SLATE = HexColor("#2B4A63")         # ardoise (action principale)127LOGO_PATH = Path(__file__).resolve().parent / "assets" / "logo-immo-ka.png"128GREEN_FG = HexColor("#1c5c41")      # verdict « sous l'estimation » (site .vp-under)129GREEN_BG = HexColor("#e2f0e6")130RED_FG = HexColor("#8a2b2b")        # verdict « au-dessus » (site .vp-over)131RED_BG = HexColor("#f6e2e2")132AMBER_FG = HexColor("#8a5a12")133AMBER_BG = HexColor("#faf0dc")134135PAGE_W, PAGE_H = letter136M = 40          # marge137IMG_TIMEOUT = 6138UA = "ImmoKaBot/1.0 (+https://www.immo-ka.com; contact@spboucher.ai)"139140NBSP = " "     # espace fine insécable (mise en forme française)141142# clés de details jamais affichées (mêmes exclusions que la fiche web)143DETAIL_HIDDEN = {144    "pieces", "price_from", "cover_thumb", "photo_captions", "img_audited",145    "needs_image_review", "postal_code", "region", "transaction",146    "prix_pi2", "prix_m2", "listing_origin_url",147}148149PROX_LABELS = [150    ("prox_epicerie", "Épiceries"), ("prox_transport", "Transport en commun"),151    ("prox_parc", "Parcs"), ("prox_ecole_prim", "Écoles primaires"),152    ("prox_sante", "Soins de santé"), ("prox_pharmacie", "Pharmacies"),153]154155_MOIS = ["janvier", "février", "mars", "avril", "mai", "juin", "juillet",156         "août", "septembre", "octobre", "novembre", "décembre"]157158_PIED_FICHE = ("Données de l'annonce publiée par l'agence — Immo-Ka est un "159               "agrégateur indépendant. Enrichissements fournis à titre "160               "indicatif, sans valeur légale.")161162163def _fmt_money(v) -> str:164    return f"{v:,.0f}".replace(",", f"{NBSP}") + f"{NBSP}$" if v is not None else "—"165166167def _fmt_dist(m_: float) -> str:168    return (f"{round(m_ / 10) * 10}{NBSP}m" if m_ < 1000169            else f"{m_ / 1000:.1f}".replace(".", ",") + f"{NBSP}km")170171172def _fmt_mois(d) -> str:173    """« 2017-11-04 » ou epoch → « novembre 2017 » (sinon valeur telle quelle)."""174    if d is None:175        return "—"176    try:177        if isinstance(d, (int, float)):178            st = time.localtime(d)179            return f"{_MOIS[st.tm_mon - 1]} {st.tm_year}"180        an, mois = str(d)[:7].split("-")181        return f"{_MOIS[int(mois) - 1]} {an}"182    except Exception:183        return str(d)184185186def _fmt_jour(ts: float) -> str:187    """epoch → « 4 novembre 2024 » (« 1er » pour le premier du mois)."""188    st = time.localtime(ts)189    j = "1er" if st.tm_mday == 1 else str(st.tm_mday)190    return f"{j} {_MOIS[st.tm_mon - 1]} {st.tm_year}"191192193def _fetch_image(url: str) -> ImageReader | None:194    try:195        r = requests.get(url, timeout=IMG_TIMEOUT, headers={"User-Agent": UA})196        r.raise_for_status()197        raw = r.content198        try:199            # les photos source dépassent parfois 5 Mo chacune : sans200            # redimensionnement le PDF grimpe à plusieurs dizaines de Mo201            from PIL import Image202            im = Image.open(io.BytesIO(raw))203            im.thumbnail((1000, 1000))204            buf = io.BytesIO()205            im.convert("RGB").save(buf, "JPEG", quality=78)206            buf.seek(0)207            return ImageReader(buf)208        except Exception:209            return ImageReader(io.BytesIO(raw))210    except Exception:211        return None212213214class _Style:215    """Petits composants du style « éditorial sharp » sur un canvas."""216217    def __init__(self, c: rl_canvas.Canvas):218        self.c = c219220    def fond(self):221        self.c.setFillColor(PAPER)222        self.c.rect(0, 0, PAGE_W, PAGE_H, stroke=0, fill=1)223224    def logo(self, x: float, y: float, taille: float = 22):225        """Logo Immo-Ka : la maison à la porte rouge + « Immo-Ka » (image de226        marque) ; à défaut du fichier, le logotype en texte."""227        c = self.c228        try:229            from reportlab.lib.utils import ImageReader230            img = ImageReader(str(LOGO_PATH))231            iw, ih = img.getSize()232            h = taille * 1.5233            w = h * iw / ih234            c.drawImage(img, x, y - h * 0.30, width=w, height=h, mask="auto")235            return x + w236        except Exception:237            c.setFont("Times-Bold", taille)238            c.setFillColor(INK)239            c.drawString(x, y, "Immo")240            w = c.stringWidth("Immo", "Times-Bold", taille)241            c.setFillColor(INK3)242            c.drawString(x + w, y, "-")243            w += c.stringWidth("-", "Times-Bold", taille)244            c.setFillColor(ACCENT)245            c.drawString(x + w, y, "Ka")246            return x + w + c.stringWidth("Ka", "Times-Bold", taille)247248    def entete(self, titre: str):249        c = self.c250        self.logo(M, PAGE_H - M - 16)251        c.setFont("Courier-Bold", 8)252        c.setFillColor(INK3)253        c.drawRightString(PAGE_W - M, PAGE_H - M - 6, titre.upper())254        c.drawRightString(PAGE_W - M, PAGE_H - M - 16,255                          time.strftime("GÉNÉRÉ LE %Y-%m-%d · WWW.IMMO-KA.COM"))256        c.setStrokeColor(INK)257        c.setLineWidth(2)258        c.line(M, PAGE_H - M - 26, PAGE_W - M, PAGE_H - M - 26)259        return PAGE_H - M - 40   # y de départ du contenu260261    def pied(self, texte: str, page: int | None = None):262        c = self.c263        c.setStrokeColor(INK)264        c.setLineWidth(1)265        c.line(M, M + 16, PAGE_W - M, M + 16)266        c.setFont("Helvetica", 6.5)267        c.setFillColor(INK3)268        c.drawString(M, M + 6, texte[:150])269        if page:270            c.setFont("Courier-Bold", 7)271            c.drawRightString(PAGE_W - M, M + 6, f"P.{page}")272273    def pilule(self, x: float, y: float, texte: str, fg=ACCENT, bg=INK,274               stroke=None, taille: float = 8) -> float:275        """Chip arrondie ; retourne le x suivant."""276        c = self.c277        w = c.stringWidth(texte, "Helvetica-Bold", taille) + 14278        c.setFillColor(bg)279        if stroke:280            c.setStrokeColor(stroke)281            c.setLineWidth(1.2)282        c.roundRect(x, y, w, taille + 9, (taille + 9) / 2,283                    stroke=1 if stroke else 0, fill=1)284        c.setFillColor(fg)285        c.setFont("Helvetica-Bold", taille)286        c.drawString(x + 7, y + 5, texte)287        return x + w + 6288289    def titre_section(self, y: float, texte: str) -> float:290        c = self.c291        # carré accent à ombre dure (signature de la passe éditoriale du site)292        c.setFillColor(INK)293        c.rect(M + 2, y - 1.5, 9, 9, stroke=0, fill=1)294        c.setFillColor(ACCENT)295        c.setStrokeColor(INK)296        c.setLineWidth(1)297        c.rect(M, y + 0.5, 9, 9, stroke=1, fill=1)298        c.setFont("Helvetica-Bold", 12.5)299        c.setFillColor(INK)300        c.drawString(M + 16, y, texte)301        c.setStrokeColor(ACCENT)302        c.setLineWidth(3)303        w = c.stringWidth(texte, "Helvetica-Bold", 12.5)304        c.line(M + 16, y - 4, M + 16 + w, y - 4)305        return y - 18306307    def paragraphe(self, x: float, y: float, texte: str, largeur: float,308                   taille: float = 8.5, couleur=INK2, interligne: float = 11.5,309                   max_lignes: int = 100) -> float:310        """Texte multi-lignes avec découpe aux mots ; retourne le y suivant."""311        c = self.c312        c.setFont("Helvetica", taille)313        c.setFillColor(couleur)314        mots = texte.split()315        ligne = ""316        n = 0317        for mot in mots:318            essai = (ligne + " " + mot).strip()319            if c.stringWidth(essai, "Helvetica", taille) <= largeur:320                ligne = essai321            else:322                c.drawString(x, y, ligne)323                y -= interligne324                n += 1325                ligne = mot326                if n >= max_lignes - 1:327                    ligne += " …"328                    break329        if ligne:330            c.drawString(x, y, ligne)331            y -= interligne332        return y333334    def nb_lignes(self, texte: str, largeur: float, taille: float = 8.5,335                  max_lignes: int = 100) -> int:336        """Nombre de lignes qu'occupera `paragraphe` (pour réserver la place)."""337        c = self.c338        mots = texte.split()339        ligne = ""340        n = 1341        for mot in mots:342            essai = (ligne + " " + mot).strip()343            if c.stringWidth(essai, "Helvetica", taille) <= largeur:344                ligne = essai345            else:346                n += 1347                ligne = mot348                if n >= max_lignes:349                    break350        return min(n, max_lignes)351352    def tuile(self, x: float, y: float, w: float, h: float,353              val: str, lab: str):354        """Tuile KPI blanche à ombre décalée (x, y = coin inférieur gauche)."""355        c = self.c356        c.setFillColor(INK)357        c.roundRect(x + 2.5, y - 2.5, w, h, 5, stroke=0, fill=1)358        c.setFillColor(SURFACE)359        c.setStrokeColor(INK)360        c.setLineWidth(1.2)361        c.roundRect(x, y, w, h, 5, stroke=1, fill=1)362        c.setFont("Helvetica-Bold", 12)363        c.setFillColor(INK)364        c.drawString(x + 8, y + h - 20, str(val))365        c.setFont("Courier", 6.2)366        c.setFillColor(INK3)367        c.drawString(x + 8, y + 7, lab.upper()[: max(4, int(w / 4.2))])368369370def _titre_droite(c, y, x, texte):371    c.setFillColor(INK)372    c.rect(x + 2, y - 1.5, 9, 9, stroke=0, fill=1)373    c.setFillColor(ACCENT)374    c.setStrokeColor(INK)375    c.setLineWidth(1)376    c.rect(x, y + 0.5, 9, 9, stroke=1, fill=1)377    c.setFont("Helvetica-Bold", 12.5)378    c.setFillColor(INK)379    c.drawString(x + 16, y, texte)380    c.setStrokeColor(ACCENT)381    c.setLineWidth(3)382    c.line(x + 16, y - 4, x + 16 + c.stringWidth(texte, "Helvetica-Bold", 12.5), y - 4)383    return y - 18384385386def _verdict_vraiprix(price, vp):387    """Pastille verdict — la règle unique de l'application (immoka/public.py) :388    sous l'estimation (≤ −8 %), au prix du marché, au-dessus (≥ +8 %) ; rien si389    l'écart est aberrant ou si l'estimation sort de sa propre fourchette."""390    from . import public391    if not vp:392        return None393    dev, verdict = public.verdict(price, vp.get("value"), vp.get("low"), vp.get("high"))394    if verdict is None:395        return None396    pct = abs(round(dev))397    if verdict == "sur":398        return (f"▲{NBSP}{pct}{NBSP}% au-dessus de l'estimation",399                RED_FG, RED_BG, ACCENT_DEEP)400    if verdict == "sous":401        return (f"▼{NBSP}{pct}{NBSP}% sous l'estimation",402                GREEN_FG, GREEN_BG, GREEN_FG)403    return (f"≈{NBSP}Au prix du marché", INK2, SURFACE, INK)404405406def fiche_pdf(uid: str) -> bytes | None:407    """PDF de la fiche de la propriété `uid` — reflète tous les blocs de la408    fiche web ; None si introuvable."""409    con = db.connect()410    row = con.execute("SELECT * FROM listings WHERE uid=?", (uid,)).fetchone()411    if row is None:412        con.close()413        return None414    l = dict(row)415    l["features"] = json.loads(l.get("features") or "[]")416    l["images"] = json.loads(l.get("images") or "[]")417    l["details"] = json.loads(l.get("details") or "{}")418    try:419        l["vraiprix"] = json.loads(l["vraiprix"]) or None if l.get("vraiprix") else None420    except (ValueError, TypeError):421        l["vraiprix"] = None422    price_history = [dict(r) for r in con.execute(423        "SELECT ts, price FROM price_log WHERE uid=? ORDER BY ts DESC LIMIT 10",424        (uid,)).fetchall()]425    quartier = None426    lat, lng = l.get("lat"), l.get("lng")427    geo = lat is not None and lng is not None428    if geo:429        from . import quartier as qmod430        dauid = l.get("dauid")431        try:432            quartier = qmod.fiche_quartier(433                lat, lng, l.get("city") or "",434                dauid if dauid and dauid != "hors-zone" else None)435        except Exception:436            quartier = None437    try:438        reg = json.loads(439            (db.DB_PATH.parent / "sources.json").read_text("utf-8"))["sources"]440        src_name = next((s["name"] for s in reg if s["id"] == l["source"]),441                        l["source"])442    except Exception:443        src_name = l["source"]444    con.close()445446    # --- enrichissements (mêmes modules que les blocs de la fiche web) -------447    def _safe(fn, *a, **k):448        try:449            return fn(*a, **k)450        except Exception:451            return None452453    from . import air as air_mod454    from . import commerces as com_mod455    from . import gaz as gaz_mod456    from . import hydro as hydro_mod457    from . import inondation as inon_mod458    inon = _safe(inon_mod.lookup, lat, lng) if geo else None459    air_d = _safe(air_mod.lookup, lat, lng) if geo else None460    gaz_d = _safe(gaz_mod.nearby, lat, lng) if geo else None461    com = _safe(com_mod.nearby, lat, lng) if geo else None462    hyd = _safe(hydro_mod.estimate, adresse=l.get("address") or "",463                uid=uid, lat=lat, lng=lng, solve=False)464465    d = l["details"]466    vp = l.get("vraiprix")467    # ville et adresse normalisées, comme sur le site (immoka/villes.py)468    from . import villes469    raw_city = l.get("city") or ""470    l["city"] = villes.label(raw_city) or raw_city471    l["address"] = villes.clean_address(l.get("address"), raw_city)472    location = (d.get("transaction") == "location")473474    buf = io.BytesIO()475    c = rl_canvas.Canvas(buf, pagesize=letter)476    c.setTitle(f"Immo-Ka — {l.get('address') or l.get('title') or uid}")477    s = _Style(c)478    s.fond()479    y = s.entete("Fiche propriété")480    page = [1]481482    def saut_page() -> float:483        s.pied(_PIED_FICHE, page[0])484        c.showPage()485        page[0] += 1486        s.fond()487        return s.entete("Fiche propriété · suite")488489    def place(y_: float, besoin: float) -> float:490        """Saute de page si `besoin` points ne tiennent plus sous y_."""491        return saut_page() if (y_ - besoin) < M + 34 else y_492493    # --- héro : prix + pastille verdict Vrai-Prix -----------------------------494    prix_txt = (_fmt_money(l["price"]) + (f"{NBSP}/ mois" if location else "")) \495        if l.get("price") else (l.get("price_label") or "Prix sur demande")496    c.setFont("Helvetica-Bold", 30)497    c.setFillColor(INK)498    c.drawString(M, y - 24, prix_txt)499    bx = M + c.stringWidth(prix_txt, "Helvetica-Bold", 30) + 14500    verd = _verdict_vraiprix(l.get("price"), vp)501    if verd:502        txt, fg, bg, stk = verd503        bx = s.pilule(bx, y - 22, txt, fg, bg, stk)504    if l.get("property_type"):505        s.pilule(bx, y - 22, l["property_type"], ACCENT, INK)506    y -= 44507508    # --- titre + adresse -------------------------------------------------------509    titre = l.get("address") or l.get("title") or ""510    c.setFont("Helvetica-Bold", 13)511    c.setFillColor(INK)512    c.drawString(M, y, titre[:80])513    y -= 14514    loc = " · ".join(x for x in (l.get("sector"), l.get("city"), l.get("region"))515                     if x)516    c.setFont("Helvetica", 9)517    c.setFillColor(INK2)518    c.drawString(M, y, loc[:110])519    y -= 20520521    # --- chips clés (mêmes specs que le héro du site) --------------------------522    chips = []523    if l.get("bedrooms") is not None:524        chips.append(f"{l['bedrooms']}{NBSP}ch.")525    if l.get("bathrooms") is not None:526        chips.append(f"{l['bathrooms']}{NBSP}sdb")527    if l.get("powder_rooms"):528        chips.append(f"{l['powder_rooms']}{NBSP}s. d'eau")529    if l.get("area_sqft"):530        chips.append(f"{round(l['area_sqft']):,}".replace(",", NBSP) + f"{NBSP}pi²")531    if l.get("lot_sqft"):532        chips.append(f"Terrain {round(l['lot_sqft']):,}".replace(",", NBSP)533                     + f"{NBSP}pi²")534    if l.get("year_built"):535        chips.append(f"Construit en {l['year_built']}")536    if l.get("price") and l.get("area_sqft") and l["area_sqft"] > 200:537        chips.append(f"{round(l['price'] / l['area_sqft'])}{NBSP}$/pi²")538    if l.get("mls"):539        chips.append(f"MLS {l['mls']}")540    if l.get("first_seen"):541        dom = max(0, int((time.time() - l["first_seen"]) // 86400))542        chips.append(f"{dom}{NBSP}j sur Immo-Ka")543    x = M544    for chip in chips[:8]:545        x = s.pilule(x, y - 6, chip)546    y -= 30547548    # --- photos : 1 grande + 3 vignettes ---------------------------------------549    imgs = [im for im in (_fetch_image(u) for u in l["images"][:4]) if im]550    if imgs:551        big_h = 170552        big_w = big_h * 16 / 10.5553        c.setStrokeColor(INK)554        c.setLineWidth(1.5)555        try:556            c.drawImage(imgs[0], M, y - big_h, big_w, big_h,557                        preserveAspectRatio=True, anchor="c", mask="auto")558        except Exception:559            pass560        c.rect(M, y - big_h, big_w, big_h, stroke=1, fill=0)561        tx = M + big_w + 10562        th = (big_h - 16) / 3563        for i, im in enumerate(imgs[1:4]):564            ty = y - (i + 1) * th - i * 8565            try:566                c.drawImage(im, tx, ty, PAGE_W - M - tx, th,567                            preserveAspectRatio=True, anchor="c", mask="auto")568                c.rect(tx, ty, PAGE_W - M - tx, th, stroke=1, fill=0)569            except Exception:570                pass571        y -= big_h + 18572573    # --- baisse/hausse de prix (bandeau, comme le site) -------------------------574    ph = [p for p in price_history if p.get("price")]575    if len(ph) >= 2 and ph[0]["price"] != ph[1]["price"]:576        y = place(y, 34)577        de, a = ph[1]["price"], ph[0]["price"]578        bas = a < de579        c.setFillColor(GREEN_BG if bas else RED_BG)580        c.setStrokeColor(GREEN_FG if bas else RED_FG)581        c.setLineWidth(1.2)582        c.roundRect(M, y - 20, PAGE_W - 2 * M, 24, 5, stroke=1, fill=1)583        c.setFont("Helvetica-Bold", 9)584        c.setFillColor(GREEN_FG if bas else RED_FG)585        c.drawString(M + 10, y - 12,586                     f"{'▼' if bas else '▲'} Prix passé de {_fmt_money(de)} à "587                     f"{_fmt_money(a)} le {_fmt_jour(ph[0]['ts'])}")588        y -= 34589590    # --- description | inclusions (2 colonnes, comme le site) -------------------591    col_g = PAGE_W * 0.56 - M592    feats = [str(f) for f in (l.get("features") or []) if f]593    desc = (l.get("description") or "").strip()594    if desc or feats:595        besoin = 30 + max(596            s.nb_lignes(desc, col_g, max_lignes=26) * 11.5 if desc else 0,597            min(len(feats), 18) * 12)598        y = place(y, min(besoin, 340))599        y_desc = y600        if desc:601            y_desc = s.titre_section(y, "Description")602            y_desc = s.paragraphe(M, y_desc, desc, col_g, max_lignes=26)603        y_incl = y604        if feats:605            xr = M + col_g + 24606            y_incl = _titre_droite(c, y, xr, "Inclusions et caractéristiques")607            c.setFont("Helvetica", 8.5)608            for f in feats[:18]:609                c.setFillColor(ACCENT_DEEP)610                c.drawString(xr, y_incl, "✓")611                c.setFillColor(INK2)612                c.drawString(xr + 12, y_incl, f[:42])613                y_incl -= 12614            if len(feats) > 18:615                c.setFillColor(INK3)616                c.drawString(xr + 12, y_incl, f"+ {len(feats) - 18} autres…")617                y_incl -= 12618        y = min(y_desc, y_incl) - 16619620    # --- caractéristiques (details, mêmes exclusions que le site) ---------------621    dets = [(str(k), str(v)) for k, v in d.items()622            if k not in DETAIL_HIDDEN and v not in (None, "", [], {})623            and str(v).strip("-— ") != "" and not isinstance(v, (dict, list))]624    if dets:625        col_w = PAGE_W - 2 * M626        besoin = 40 + sum(627            s.nb_lignes(v, col_w - 190, taille=8, max_lignes=4) * 11 + 3628            for _, v in dets)629        y = place(y, min(besoin, 420))630        y = s.titre_section(y, "Caractéristiques")631        c.setFont("Courier-Bold", 7)632        c.setFillColor(INK3)633        c.drawString(M, y, "DÉTAIL")634        c.drawString(M + 180, y, "VALEUR")635        y -= 4636        c.setStrokeColor(INK)637        c.setLineWidth(1.5)638        c.line(M, y, PAGE_W - M, y)639        y -= 12640        for i, (k, v) in enumerate(dets):641            nl = s.nb_lignes(v, col_w - 190, taille=8, max_lignes=4)642            y = place(y, nl * 11 + 6)643            if i % 2 == 0:   # zébrage éditorial644                c.setFillColor(SURFACE)645                c.rect(M - 3, y - (nl - 1) * 11 - 3, col_w + 6, nl * 11 + 2,646                       stroke=0, fill=1)647            c.setFont("Helvetica-Bold", 8)648            c.setFillColor(INK)649            c.drawString(M, y, k[:38])650            y = s.paragraphe(M + 180, y, v, col_w - 190, taille=8,651                             interligne=11, max_lignes=4)652            y -= 3653        y -= 10654655    # --- pièces (details.pieces) -------------------------------------------------656    pieces = d.get("pieces") or []657    if isinstance(pieces, list) and pieces:658        rows = pieces[:24]659        y = place(y, 46 + len(rows) * 12)660        y = s.titre_section(y, "Pièces")661        c.setFont("Courier-Bold", 7)662        c.setFillColor(INK3)663        for lab, xoff in (("PIÈCE", 0), ("NIVEAU", 190), ("DIMENSIONS", 330),664                          ("REVÊTEMENT", 430)):665            c.drawString(M + xoff, y, lab)666        y -= 4667        c.setStrokeColor(INK)668        c.setLineWidth(1.5)669        c.line(M, y, PAGE_W - M, y)670        y -= 11671        for i, p in enumerate(rows):672            if i % 2 == 0:673                c.setFillColor(SURFACE)674                c.rect(M - 3, y - 3, PAGE_W - 2 * M + 6, 12, stroke=0, fill=1)675            c.setFont("Helvetica-Bold", 8)676            c.setFillColor(INK)677            c.drawString(M, y, str(p.get("nom") or "—")[:36])678            c.setFont("Helvetica", 8)679            c.setFillColor(INK2)680            c.drawString(M + 190, y, str(p.get("niveau") or "—")[:24])681            c.drawString(M + 330, y, str(p.get("dimensions") or "—")[:18])682            c.drawString(M + 430, y, str(p.get("revetement") or "—")[:22])683            y -= 12684        y -= 10685686    # --- analyse Vrai-Prix (valeur, jauge, rôle foncier) -------------------------687    if vp and vp.get("value") is not None:688        role = [(lab, vp.get(k)) for k, lab in689                (("valeur_role", "Évaluation au rôle"),690                 ("valeur_terrain", "Valeur du terrain"),691                 ("valeur_batiment", "Valeur du bâtiment"))692                if vp.get(k)]693        besoin = 96 + (56 if vp.get("low") is not None else 0) \694            + (62 if role else 0) + 18695        y = place(y, besoin)696        y = s.titre_section(y, "Analyse Vrai-Prix")697        val_txt = _fmt_money(round(vp["value"]))698        c.setFont("Helvetica-Bold", 17)699        c.setFillColor(INK)700        c.drawString(M, y - 10, val_txt)701        c.setFont("Helvetica", 8.5)702        c.setFillColor(INK2)703        c.drawString(M + c.stringWidth(val_txt, "Helvetica-Bold", 17) + 8,704                     y - 10, "— valeur marchande estimée par le modèle Vrai-Prix")705        meta = []706        if vp.get("confidence"):707            meta.append(f"confiance {vp['confidence']}"708                        + (f" ({vp['confidence_pct']}{NBSP}%)"709                           if vp.get("confidence_pct") else ""))710        if vp.get("annee_construction_role"):711            meta.append(f"construction {vp['annee_construction_role']} (rôle)")712        if vp.get("superficie_terrain_role_m2"):713            meta.append(714                f"terrain {round(vp['superficie_terrain_role_m2']):,}".replace(",", NBSP)715                + f"{NBSP}m² (rôle)")716        if meta:717            c.setFont("Helvetica", 8)718            c.setFillColor(INK3)719            c.drawString(M, y - 24, " · ".join(meta)[:115])720        verd = _verdict_vraiprix(l.get("price"), vp)721        if verd:722            txt, fg, bg, stk = verd723            s.pilule(M, y - 48, txt, fg, bg, stk)724        y -= 58725        lo, hi = vp.get("low"), vp.get("high")726        if lo is not None and hi is not None and hi > lo:727            larg = PAGE_W - 2 * M728            base = y - 22729            span = hi - lo730            c.setFillColor(ACCENT_SOFT)731            c.setStrokeColor(INK)732            c.setLineWidth(1)733            c.roundRect(M, base, larg, 12, 6, stroke=1, fill=1)734735            def _pos(v):736                return M + larg * max(0.02, min(0.98, (v - lo) / span))737738            px = _pos(vp["value"])739            c.setStrokeColor(ACCENT_DEEP)740            c.setLineWidth(2.5)741            c.line(px, base - 3, px, base + 15)742            c.setFont("Courier-Bold", 6.5)743            c.setFillColor(ACCENT_DEEP)744            c.drawString(min(max(px - 30, M), PAGE_W - M - 100), base + 18,745                         f"ESTIMATION · {_fmt_money(round(vp['value']))}")746            if l.get("price") and lo * 0.7 <= l["price"] <= hi * 1.3:747                ax = _pos(l["price"])748                c.setStrokeColor(INK)749                c.setLineWidth(2)750                c.line(ax, base - 3, ax, base + 15)751                c.setFont("Courier-Bold", 6.5)752                c.setFillColor(INK)753                c.drawString(min(max(ax - 30, M), PAGE_W - M - 116), base - 12,754                             f"PRIX DEMANDÉ · {_fmt_money(l['price'])}")755            c.setFont("Helvetica", 6.5)756            c.setFillColor(INK3)757            c.drawString(M, base - 24, _fmt_money(round(lo)))758            c.drawRightString(PAGE_W - M, base - 24,759                              _fmt_money(round(hi)) + " — fourchette d'estimation")760            y = base - 36761        if role:762            tw = (PAGE_W - 2 * M - (len(role) - 1) * 10) / len(role)763            for i, (lab, v) in enumerate(role):764                s.tuile(M + i * (tw + 10), y - 44, tw, 38,765                        _fmt_money(round(v)), lab)766            y -= 56767        c.setFont("Helvetica", 6.5)768        c.setFillColor(INK3)769        c.drawString(M, y - 2, "Estimation automatisée Vrai-Prix (vrai-prix.ca) "770                               "croisée au rôle d'évaluation foncière — ne "771                               "remplace pas une évaluation professionnelle.")772        y -= 16773774    # --- historique de prix -------------------------------------------------------775    if len(ph) >= 2:776        rows = ph[:8]777        y = place(y, 46 + len(rows) * 12)778        y = s.titre_section(y, "Historique du prix demandé")779        c.setFont("Courier-Bold", 7)780        c.setFillColor(INK3)781        for lab, xoff in (("DATE", 0), ("PRIX AFFICHÉ", 190), ("VARIATION", 330)):782            c.drawString(M + xoff, y, lab)783        y -= 4784        c.setStrokeColor(INK)785        c.setLineWidth(1.5)786        c.line(M, y, PAGE_W - M, y)787        y -= 11788        for i, p in enumerate(rows):789            prec = rows[i + 1]["price"] if i + 1 < len(rows) else None790            c.setFont("Helvetica", 8)791            c.setFillColor(INK2)792            c.drawString(M, y, _fmt_jour(p["ts"]))793            c.setFont("Helvetica-Bold", 8)794            c.setFillColor(INK)795            c.drawString(M + 190, y, _fmt_money(p["price"]))796            if prec and p.get("price"):797                delta = p["price"] - prec798                c.setFont("Courier-Bold", 7.5)799                c.setFillColor(GREEN_FG if delta < 0800                               else (RED_FG if delta > 0 else INK3))801                sig = "▼" if delta < 0 else ("▲" if delta > 0 else "=")802                c.drawString(M + 330, y,803                             f"{sig} {_fmt_money(abs(delta))}" if delta else "=")804            y -= 12805        y -= 10806807    # --- risque d'inondation (BDZI) ------------------------------------------------808    if inon:809        zones = (inon.get("zones") or [])[:3]810        y = place(y, 56 + len(zones) * 12)811        y = s.titre_section(y, "Risque d'inondation")812        statut = inon.get("statut")813        sev = {"eleve": "récurrence élevée", "modere": "récurrence modérée",814               "present": "zone cartographiée"}.get(inon.get("severite") or "", "")815        if statut == "en_zone":816            s.pilule(M, y - 12, f"En zone inondable ({sev})" if sev817                     else "En zone inondable", RED_FG, RED_BG, RED_FG)818        elif statut == "a_proximite":819            d0 = zones[0]["distance_m"] if zones else "?"820            s.pilule(M, y - 12, f"Zone inondable à ~{d0} m",821                     AMBER_FG, AMBER_BG, AMBER_FG)822        elif statut == "hors_zone":823            s.pilule(M, y - 12, "Hors des zones inondables cartographiées",824                     GREEN_FG, GREEN_BG, GREEN_FG)825        else:826            s.pilule(M, y - 12, "Secteur non couvert par la cartographie BDZI",827                     INK2, SURFACE, INK)828        y -= 26829        for z in zones:830            c.setFont("Helvetica", 8)831            c.setFillColor(INK2)832            c.drawString(M, y, f"{z.get('type') or 'Zone'} — à {z.get('distance_m')} m"833                               + (f" (rapport {z['date_rapport']})"834                                  if z.get("date_rapport") else ""))835            y -= 12836        y -= 8837838    # --- qualité de l'air (RSQAQ) ---------------------------------------------------839    if air_d and air_d.get("station"):840        mes = air_d.get("mesures") or {}841        y = place(y, 44 + len(mes) * 11)842        y = s.titre_section(y, "Qualité de l'air")843        c.setFont("Helvetica", 8.5)844        c.setFillColor(INK2)845        c.drawString(M, y - 2,846                     f"Station {air_d['station']} ({air_d['ville']}), à "847                     + f"{air_d['distance_km']}".replace(".", ",") + f"{NBSP}km "848                     "de la propriété — moyennes annuelles :")849        y -= 16850        for pol, m_ in list(mes.items())[:5]:851            c.setFont("Helvetica-Bold", 8)852            c.setFillColor(INK)853            c.drawString(M, y, pol)854            c.setFont("Helvetica", 8)855            c.setFillColor(INK2)856            val = (f"{m_['moyenne']:.1f}".replace(".", ",")857                   if m_.get("moyenne") is not None else "—")858            txt = f"{val}{NBSP}{m_.get('unite', '')} ({m_.get('annee', '')})"859            if m_.get("ref"):860                txt += f" · référence {m_.get('ref_nom', '')} : {m_['ref']}"861            c.drawString(M + 56, y, txt[:95])862            y -= 11863        y -= 8864865    # --- coût d'électricité (Hydro-Québec) -------------------------------------------866    if hyd and hyd.get("disponible"):867        y = place(y, 52)868        y = s.titre_section(y, "Coût d'électricité (Hydro-Québec)")869        c.setFont("Helvetica-Bold", 15)870        c.setFillColor(INK)871        mens = f"≈{NBSP}{_fmt_money(round(hyd['cout_mensuel']))} / mois"872        c.drawString(M, y - 8, mens)873        c.setFont("Helvetica", 8.5)874        c.setFillColor(INK2)875        suite = f"{_fmt_money(round(hyd['cout_annuel']))} / an"876        if hyd.get("kwh_annuel"):877            suite += (f" · {round(hyd['kwh_annuel']):,}".replace(",", NBSP)878                      + f"{NBSP}kWh/an")879        suite += " — estimation officielle Hydro-Québec pour cette adresse."880        c.drawString(M + c.stringWidth(mens, "Helvetica-Bold", 15) + 10, y - 8, suite)881        y -= 26882883    # --- commerces et transport --------------------------------------------------------884    if com and (com.get("commerces") or com.get("transit")):885        entrees = ([(t["commerce"], t["nom"], t["dist_m"])886                    for t in (com.get("transit") or [])[:4]]887                   + [(i["commerce"], i["nom"], i["dist_m"])888                      for i in (com.get("commerces") or [])[:12]])889        lignes = (len(entrees) + 1) // 2890        y = place(y, 36 + lignes * 13)891        y = s.titre_section(y, "Commerces et transport")892        col_w = (PAGE_W - 2 * M) / 2893        for i, (cat, nom, dist) in enumerate(entrees):894            px = M if i % 2 == 0 else M + col_w + 10895            py = y - (i // 2) * 13896            c.setFont("Helvetica", 8)897            c.setFillColor(INK2)898            nomc = nom if len(nom) <= 22 else nom[:21] + "…"899            c.drawString(px, py, f"{cat} — {nomc}")900            c.setFont("Courier-Bold", 7.5)901            c.setFillColor(INK)902            c.drawRightString(px + col_w - 14, py, _fmt_dist(dist))903        y -= lignes * 13 + 12904905    # --- essence à proximité --------------------------------------------------------------906    if gaz_d and gaz_d.get("stations"):907        sts = gaz_d["stations"][:3]908        y = place(y, 40 + len(sts) * 11)909        y = s.titre_section(y, "Essence à proximité")910        if gaz_d.get("mediane_regulier"):911            c.setFont("Helvetica", 8.5)912            c.setFillColor(INK2)913            c.drawString(M, y - 2, "Prix médian de l'essence régulière à <5 km : "914                         + f"{gaz_d['mediane_regulier']}".replace(".", ",")915                         + f"{NBSP}¢/L")916            y -= 14917        for st in sts:918            c.setFont("Helvetica", 8)919            c.setFillColor(INK2)920            reg_p = (f"{st['regulier']}".replace(".", ",") + f"{NBSP}¢/L"921                     if st.get("regulier") else "—")922            c.drawString(M, y, f"{st['nom']} — {_fmt_dist(st['dist_m'])} : {reg_p}"923                               + (" · la moins chère" if st.get("moins_chere") else ""))924            y -= 11925        y -= 8926927    # --- le quartier -------------------------------------------------------------------------928    if quartier and (quartier.get("demographie") or quartier.get("proximite")929                     or quartier.get("chaleur") or quartier.get("crime")):930        demo = quartier.get("demographie") or {}931        prox = quartier.get("proximite") or {}932        prox_aff = [(k, lab) for k, lab in PROX_LABELS933                    if isinstance(prox.get(k), (int, float))]934        besoin = 44 + (94 if demo else 0) + len(prox_aff) * 14 + 44935        y = place(y, besoin)936        y = s.titre_section(y, "Le quartier")937        c.setFont("Helvetica", 7.5)938        c.setFillColor(INK3)939        c.drawString(M, y, "Secteur immédiat de la propriété (aire de diffusion "940                           "du recensement 2021, ± 500 habitants).")941        y -= 14942        if demo:943            tuiles = [("Revenu médian", _fmt_money(demo.get("revenu_median"))),944                      ("Ménages locataires",945                       f"{round(demo['pct_locataires'])}{NBSP}%"946                       if demo.get("pct_locataires") is not None else "—"),947                      ("Loyer moyen secteur", _fmt_money(demo.get("loyer_moyen"))),948                      ("Âge médian",949                       f"{round(demo['age_median'])} ans"950                       if demo.get("age_median") is not None else "—"),951                      ("Français à la maison",952                       f"{round(demo['pct_francais'])}{NBSP}%"953                       if demo.get("pct_francais") is not None else "—"),954                      ("Diplôme universitaire",955                       f"{round(demo['pct_univ'])}{NBSP}%"956                       if demo.get("pct_univ") is not None else "—")]957            tw = (PAGE_W - 2 * M - 20) / 3958            for i, (lab, val) in enumerate(tuiles):959                s.tuile(M + (i % 3) * (tw + 10), y - 34 - (i // 3) * 44,960                        tw, 38, val, lab)961            y -= 34 + 44 + 16962        for k, lab in prox_aff:963            v = max(0.0, min(1.0, prox[k]))964            c.setFont("Helvetica", 8)965            c.setFillColor(INK2)966            c.drawString(M, y, lab)967            bx0, bw_ = M + 130, PAGE_W - 2 * M - 160968            c.setFillColor(SURFACE)969            c.setStrokeColor(INK)970            c.setLineWidth(0.8)971            c.roundRect(bx0, y - 1, bw_, 7, 3.5, stroke=1, fill=1)972            c.setFillColor(ACCENT)973            c.roundRect(bx0, y - 1, max(3, bw_ * v), 7, 3.5, stroke=0, fill=1)974            c.setFont("Courier-Bold", 7.5)975            c.setFillColor(INK)976            c.drawRightString(PAGE_W - M, y, str(round(v * 100)))977            y -= 14978        if prox_aff:979            c.setFont("Helvetica", 6.5)980            c.setFillColor(INK3)981            c.drawString(M, y, "Accessibilité 0–100 — mesures de proximité de "982                               "Statistique Canada.")983            y -= 12984        badges_q = []985        ch = quartier.get("chaleur")986        if ch:987            if ch.get("classe", 5) <= 3:988                badges_q.append(("Îlot de fraîcheur", GREEN_FG, GREEN_BG, GREEN_FG))989            elif ch.get("classe", 5) >= 7:990                ec = (f" (+{ch['ecart']:.1f} °C)".replace(".", ",")991                      if ch.get("ecart") is not None else "")992                badges_q.append((f"Îlot de chaleur{ec}",993                                 AMBER_FG, AMBER_BG, AMBER_FG))994        cr = quartier.get("crime")995        if cr and cr.get("type") == "igc" and cr.get("indice_canada"):996            dlt = round(100 * (cr["indice"] - cr["indice_canada"])997                        / cr["indice_canada"])998            badges_q.append((f"Criminalité {abs(dlt)}{NBSP}% "999                             f"{'sous' if dlt <= 0 else 'au-dessus de'} "1000                             "la moyenne canadienne", INK2, SURFACE, INK))1001        elif cr and cr.get("type") == "points":1002            badges_q.append((f"{cr['douze_mois']} actes criminels à <500 m "1003                             "(12 mois)", INK2, SURFACE, INK))1004        if badges_q:1005            x = M1006            for txt, fg, bg, stk in badges_q:1007                x = s.pilule(x, y - 8, txt, fg, bg, stk)1008            y -= 261009        y -= 610101011    # --- références : QR + courtier + source ------------------------------------------------1012    y = place(y, 140)1013    y = s.titre_section(y, "Références")1014    qr = qrcode.make(f"https://www.immo-ka.com/propriete/{uid}",1015                     box_size=4, border=1)1016    qb = io.BytesIO()1017    qr.save(qb, format="PNG")1018    c.drawImage(ImageReader(io.BytesIO(qb.getvalue())), M, y - 74, 70, 70)1019    yy = y - 141020    c.setFont("Helvetica-Bold", 9)1021    c.setFillColor(INK)1022    courtier = l.get("broker_name") or d.get("Courtier inscripteur")1023    if courtier:1024        ligne = f"Courtier : {courtier}"1025        if l.get("broker_phone"):1026            ligne += f" · {l['broker_phone']}"1027        c.drawString(M + 82, yy, ligne[:95])1028        yy -= 131029    c.drawString(M + 82, yy, f"Agence : {src_name}")1030    yy -= 141031    c.setFont("Helvetica", 8)1032    c.setFillColor(INK2)1033    c.drawString(M + 82, yy, "Annonce originale :")1034    yy -= 111035    c.setFillColor(ACCENT_DEEP)1036    c.drawString(M + 82, yy,1037                 (l.get("url") or d.get("listing_origin_url") or "")[:90])1038    yy -= 141039    c.setFillColor(INK2)1040    c.drawString(M + 82, yy, "Fiche à jour en ligne (scannez le code) :")1041    yy -= 111042    c.setFillColor(ACCENT_DEEP)1043    c.drawString(M + 82, yy, f"www.immo-ka.com/propriete/{uid}")1044    y -= 901045    s.paragraphe(M, y, "Sources : annonce de l'agence, Vrai-Prix (vrai-prix.ca), "1046                       "rôle d'évaluation foncière, Statistique Canada (2021), "1047                       "INSPQ (CC-BY 4.0), Ville de Montréal (CC-BY 4.0), BDZI, "1048                       "RSQAQ, Hydro-Québec, gazquebec.ca, OpenStreetMap.",1049                 PAGE_W - 2 * M, taille=6.5, couleur=INK3, interligne=9)10501051    s.pied(_PIED_FICHE, page[0])1052    c.save()1053    return buf.getvalue()1054
Files main
Menu

Theme