SPB Git

Repository Public

fichepdf.py 9.5 KB 237 lines python

1# -----------------------------------------------------------------------------2# Auto-Ka v2 — véhicules d'occasion à vendre au Québec3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4# fichepdf.py : fiche PDF d'une annonce (fpdf2), à une identité NEUTRE et5# provisoire (encre, filets, chiffres alignés) en attendant la marque de la v2.6# Entrée : le dictionnaire de web.fiche(uid). Aucune donnée inventée : une7# rubrique sans donnée n'est pas imprimée.8# -----------------------------------------------------------------------------9from __future__ import annotations1011import io12import time13from datetime import datetime14from zoneinfo import ZoneInfo1516from fpdf import FPDF1718ENCRE = (27, 29, 34)19GRIS = (107, 111, 118)20FILET = (217, 214, 207)21ACCENT = (31, 58, 95)22SITE = "Auto-Ka"23DOMAINE = "www.auto-ka.com"24CONTACT = "contact@spboucher.ai"2526_REMPL = {"’": "'", "‘": "'", "“": '"', "”": '"', "–": "-",27          "—": "-", "…": "...", " ": " ", " ": " ", "−": "-",28          "•": "-", "œ": "oe", "Œ": "OE", " ": " "}293031def _t(s) -> str:32    """Texte imprimable par les polices de base (latin-1)."""33    s = "" if s is None else str(s)34    for a, b in _REMPL.items():35        s = s.replace(a, b)36    return s.encode("latin-1", "replace").decode("latin-1")373839def _prix(p) -> str:40    return "Prix sur demande" if p is None else f"{int(round(p)):,}".replace(",", " ") + " $"414243def _km(k) -> str:44    return "" if k is None else f"{int(round(k)):,}".replace(",", " ") + " km"454647class _PDF(FPDF):48    def footer(self):49        self.set_y(-14)50        self.set_draw_color(*FILET)51        self.set_line_width(0.2)52        self.line(18, self.get_y() - 1.5, 192, self.get_y() - 1.5)53        self.set_font("helvetica", "", 7.5)54        self.set_text_color(*GRIS)55        self.cell(130, 5, _t(f"{SITE} - {DOMAINE} - {CONTACT}"))56        self.cell(0, 5, f"p. {self.page_no()}/{{nb}}", align="R")575859def _photo(url: str | None):60    if not url:61        return None62    try:63        import requests64        from PIL import Image65        r = requests.get(url.replace(" ", "%20"), timeout=6, headers={66            "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "67                          "(KHTML, like Gecko) Chrome/126 Safari/537.36"})68        if r.status_code != 200 or len(r.content) > 12_000_000:69            return None70        im = Image.open(io.BytesIO(r.content))71        im.load()72        im = im.convert("RGB")73        if im.width > 1400:74            im = im.resize((1400, round(im.height * 1400 / im.width)))75        return im76    except Exception:  # noqa: BLE00177        return None787980def _titre(p: _PDF, texte: str) -> None:81    if p.get_y() > 255:82        p.add_page()83    p.ln(3)84    p.set_draw_color(*FILET)85    p.set_line_width(0.2)86    p.line(18, p.get_y(), 192, p.get_y())87    p.ln(3)88    p.set_font("times", "", 13)89    p.set_text_color(*ENCRE)90    p.cell(0, 7, _t(texte), new_x="LMARGIN", new_y="NEXT")91    p.ln(1)929394def _paires(p: _PDF, paires: list[tuple[str, str]]) -> None:95    paires = [(k, v) for k, v in paires if v not in (None, "", 0)]96    for i in range(0, len(paires), 2):97        y = p.get_y()98        for j, (k, v) in enumerate(paires[i:i + 2]):99            x = 18 + j * 88100            p.set_xy(x, y)101            p.set_font("helvetica", "", 8)102            p.set_text_color(*GRIS)103            p.cell(34, 5.5, _t(k))104            p.set_font("helvetica", "", 9.5)105            p.set_text_color(*ENCRE)106            p.cell(52, 5.5, _t(str(v))[:34])107        p.set_y(y + 6)108109110def construire(v: dict) -> bytes:111    p = _PDF(format="letter")112    p.set_margins(18, 16, 18)113    p.set_auto_page_break(True, margin=18)114    p.alias_nb_pages()115    p.add_page()116    # en-tête117    p.set_font("times", "", 15)118    p.set_text_color(*ENCRE)119    p.cell(100, 7, SITE)120    p.set_font("helvetica", "", 8)121    p.set_text_color(*GRIS)122    now = datetime.now(ZoneInfo("America/Toronto"))123    p.cell(0, 7, _t(f"Fiche du {now.strftime('%Y-%m-%d')}"), align="R",124           new_x="LMARGIN", new_y="NEXT")125    p.set_draw_color(*ENCRE)126    p.set_line_width(0.4)127    p.line(18, p.get_y() + 1, 192, p.get_y() + 1)128    p.ln(5)129    # photo130    im = _photo((v.get("images") or [None])[0])131    if im is not None:132        w = 174.0133        h = min(w * im.height / im.width, 98.0)134        w = h * im.width / im.height135        p.image(im, x=18 + (174 - w) / 2, y=p.get_y(), w=w, h=h)136        p.set_y(p.get_y() + h + 5)137    # titre, prix, verdict138    p.set_font("times", "", 20)139    p.set_text_color(*ENCRE)140    p.multi_cell(0, 9, _t(" ".join(x for x in (v.get("title"), v.get("trim")) if x)),141                 new_x="LMARGIN", new_y="NEXT")142    p.set_font("helvetica", "B", 16)143    p.cell(60, 9, _t(_prix(v.get("price"))))144    vd = v.get("price_verdict")145    if vd:146        p.set_font("helvetica", "", 9.5)147        p.set_text_color(*ACCENT)148        ecart = f"{vd['deviation_pct']:+.1f}".replace(".", ",")149        p.cell(0, 9, _t(f"{vd['label']} - prix de marché {_prix(vd['market_price'])} ({ecart} %, "150                        f"{vd['comparables']} comparables)"), align="R")151    p.ln(10)152    p.set_font("helvetica", "", 9.5)153    p.set_text_color(*GRIS)154    lieu = ", ".join(x for x in (v.get("dealer_name"), v.get("city"), v.get("region")) if x)155    if lieu:156        p.cell(0, 5.5, _t(lieu), new_x="LMARGIN", new_y="NEXT")157    if not v.get("active"):158        p.set_text_color(160, 50, 40)159        p.cell(0, 5.5, _t("Annonce retirée par son vendeur."), new_x="LMARGIN", new_y="NEXT")160    # caractéristiques161    _titre(p, "Caractéristiques")162    _paires(p, [163        ("Année", v.get("year")), ("Kilométrage", _km(v.get("mileage_km"))),164        ("Transmission", v.get("transmission")), ("Carburant", v.get("fuel")),165        ("Rouage", v.get("drivetrain")), ("Carrosserie", v.get("body_type")),166        ("Couleur extérieure", v.get("exterior_color")),167        ("Couleur intérieure", v.get("interior_color")),168        ("Moteur", v.get("engine")), ("Portes", v.get("doors")), ("Places", v.get("seats")),169        ("NIV", v.get("vin")), ("No d'inventaire", v.get("stock_number")),170        ("En ligne depuis", f"{v['days_listed']} jours" if v.get("days_listed") is not None else ""),171    ])172    if vd:173        _titre(p, "Prix face au marché")174        _paires(p, [175            ("Prix demandé", _prix(v.get("price"))), ("Prix de marché", _prix(vd["market_price"])),176            ("Intervalle", f"{_prix(vd['market_low'])} à {_prix(vd['market_high'])}"),177            ("Écart", f"{vd['deviation_pct']:+.1f} %".replace(".", ",")),178            ("Comparables", vd["comparables"]), ("Années comparées", f"± {vd['year_span']} an(s)"),179        ])180        p.set_font("helvetica", "", 7.5)181        p.set_text_color(*GRIS)182        p.multi_cell(0, 4, _t("Médiane des prix de véhicules comparables (même marque, même modèle, "183                              "même motorisation), ramenés au kilométrage et à l'année de ce véhicule."),184                     new_x="LMARGIN", new_y="NEXT")185    hist = v.get("price_history") or []186    if len(hist) > 1:187        _titre(p, "Historique du prix")188        _paires(p, [(time.strftime("%Y-%m-%d", time.localtime(h["ts"])), _prix(h["price"]))189                    for h in hist[-10:]])190    if v.get("description"):191        _titre(p, "Description")192        p.set_font("helvetica", "", 9)193        p.set_text_color(*ENCRE)194        p.multi_cell(0, 4.6, _t(v["description"][:2200]), new_x="LMARGIN", new_y="NEXT")195    if v.get("features"):196        _titre(p, "Équipement")197        p.set_font("helvetica", "", 8.5)198        p.set_text_color(*ENCRE)199        p.multi_cell(0, 4.4, _t(" · ".join(v["features"][:70]).replace("·", "-")),200                     new_x="LMARGIN", new_y="NEXT")201    rc = v.get("recalls") or {}202    if rc.get("checked"):203        _titre(p, "Rappels de sécurité (Transports Canada)")204        p.set_font("helvetica", "", 9)205        p.set_text_color(*ENCRE)206        if rc.get("count"):207            for r in rc["items"][:8]:208                p.multi_cell(0, 4.6, _t(f"{r.get('date', '')} - no {r.get('recall_number', '')} - "209                                        f"{r.get('component', '')}"), new_x="LMARGIN", new_y="NEXT")210            p.set_font("helvetica", "", 7.5)211            p.set_text_color(*GRIS)212            p.multi_cell(0, 4, _t("Rappels visant la marque, le modèle et l'année ; vérifiez avec le "213                                  "NIV auprès du constructeur si ce véhicule est touché et corrigé."),214                         new_x="LMARGIN", new_y="NEXT")215        else:216            p.multi_cell(0, 4.6, _t("Aucun rappel répertorié pour cette marque, ce modèle et cette année."),217                         new_x="LMARGIN", new_y="NEXT")218    d = v.get("dealer")219    if d or v.get("dealer_name"):220        _titre(p, "Vendeur")221        _paires(p, [("Nom", v.get("dealer_name")), ("Ville", v.get("city")),222                    ("Adresse", (d or {}).get("address")), ("Téléphone", (d or {}).get("phone")),223                    ("Source", v.get("source_name"))])224    if v.get("url"):225        p.ln(2)226        p.set_font("helvetica", "", 8)227        p.set_text_color(*ACCENT)228        p.multi_cell(0, 4.4, _t("Annonce d'origine : " + v["url"]), link=v["url"],229                     new_x="LMARGIN", new_y="NEXT")230    p.set_font("helvetica", "", 7.5)231    p.set_text_color(*GRIS)232    p.ln(2)233    p.multi_cell(0, 4, _t(f"{SITE} rassemble des annonces publiées ailleurs : il ne vend rien et n'est "234                          "partie à aucune transaction. Données lues à la source au moment indiqué."),235                 new_x="LMARGIN", new_y="NEXT")236    return bytes(p.output())237
Files main
Menu

Theme