SPB Git

Repository Public

pdf.py 9.9 KB 202 lines python

1# -----------------------------------------------------------------------------2# Food-Ka v2 — pdf.py : PDF à l'identité Food-Ka v2 (fiche produit, état du marché)3# Auteur : Simon-Pierre Boucher — contact@spboucher.ai4#5# Identité (brand/README.md, tokens.css) : papier #F5F1E8, ardoise #1B2023,6# betterave #8A1F52, filets #E3DDCF ; mot-symbole horizontal en tête de page.7# Composition éditoriale : titres serif romains, chiffres alignés, filets plutôt8# que boîtes. Les polices de la marque ne sont pas embarquées : Times et9# Helvetica de base. Remplace kapdf.py et pdfgen.py de la v1.10# Mêmes chiffres que l'API (services.fiche, marche.resume, marche.indice).11# -----------------------------------------------------------------------------12from __future__ import annotations1314import io15import time1617from reportlab.lib import colors18from reportlab.lib.pagesizes import LETTER19from reportlab.lib.styles import ParagraphStyle20from reportlab.lib.units import mm21from reportlab.platypus import Paragraph, SimpleDocTemplate, Spacer, Table, TableStyle2223NOM = "Food-Ka"24CONTACT = "contact@spboucher.ai"25ENCRE = colors.HexColor("#1B2023")       # ardoise26GRIS = colors.HexColor("#636660")27FILET = colors.HexColor("#E3DDCF")28PAPIER = colors.HexColor("#F5F1E8")29BETTERAVE = colors.HexColor("#8A1F52")30LOGO = __import__("pathlib").Path(__file__).resolve().parent / "assets" / "logo-horizontal-clair.png"3132_T = ParagraphStyle("t", fontName="Times-Roman", fontSize=20, leading=24, textColor=ENCRE)33_H = ParagraphStyle("h", fontName="Times-Roman", fontSize=13, leading=17, textColor=ENCRE,34                    spaceBefore=10, spaceAfter=4)35_P = ParagraphStyle("p", fontName="Helvetica", fontSize=9.5, leading=13.5, textColor=ENCRE)36_S = ParagraphStyle("s", fontName="Helvetica", fontSize=8, leading=11, textColor=GRIS)373839def _argent(v) -> str:40    return "—" if v is None else f"{v:,.2f} $".replace(",", " ").replace(".", ",")414243def _e(t) -> str:44    return (str(t or "").replace("&", "&amp;").replace("<", "&lt;").replace(">", "&gt;"))454647def _date(ts) -> str:48    return time.strftime("%Y-%m-%d", time.localtime(ts)) if ts else "—"495051def _table(lignes: list[list], largeurs: list[float], entete: bool = True) -> Table:52    t = Table(lignes, colWidths=largeurs, repeatRows=1 if entete else 0)53    style = [54        ("FONTNAME", (0, 0), (-1, -1), "Helvetica"), ("FONTSIZE", (0, 0), (-1, -1), 8.5),55        ("TEXTCOLOR", (0, 0), (-1, -1), ENCRE), ("VALIGN", (0, 0), (-1, -1), "TOP"),56        ("LINEBELOW", (0, 0), (-1, -1), 0.4, FILET),57        ("TOPPADDING", (0, 0), (-1, -1), 3.5), ("BOTTOMPADDING", (0, 0), (-1, -1), 3.5),58        ("LEFTPADDING", (0, 0), (-1, -1), 0), ("RIGHTPADDING", (0, 0), (-1, -1), 6),59    ]60    if entete:61        style += [("TEXTCOLOR", (0, 0), (-1, 0), GRIS), ("LINEBELOW", (0, 0), (-1, 0), 0.8, ENCRE)]62    t.setStyle(TableStyle(style))63    return t646566def _pied(canvas, doc) -> None:67    canvas.saveState()68    larg, haut = LETTER69    canvas.setFillColor(PAPIER)                       # le papier de la marque70    canvas.rect(0, 0, larg, haut, stroke=0, fill=1)71    if LOGO.is_file():                                # mot-symbole, 9 mm de haut72        h = 9 * mm73        canvas.drawImage(str(LOGO), 18 * mm, haut - 16 * mm - h / 2, width=h * 1091 / 362,74                         height=h, mask=None)75    canvas.setFillColor(GRIS)76    canvas.setFont("Helvetica", 7.5)77    canvas.drawRightString(larg - 18 * mm, haut - 17 * mm, time.strftime("%Y-%m-%d"))78    canvas.setStrokeColor(BETTERAVE)                  # filet betterave sous l'en-tête79    canvas.setLineWidth(1.2)80    canvas.line(18 * mm, haut - 24 * mm, larg - 18 * mm, haut - 24 * mm)81    canvas.setFont("Helvetica", 7.5)82    canvas.setFillColor(GRIS)83    canvas.drawString(18 * mm, 12 * mm,84                      f"{NOM} — prix relevés sur les sites et circulaires des enseignes, à titre "85                      f"indicatif. {CONTACT}")86    canvas.drawRightString(LETTER[0] - 18 * mm, 12 * mm, f"{doc.page}")87    canvas.restoreState()888990def _doc(titre: str, flux: list) -> bytes:91    tampon = io.BytesIO()92    doc = SimpleDocTemplate(tampon, pagesize=LETTER, leftMargin=18 * mm, rightMargin=18 * mm,93                            topMargin=31 * mm, bottomMargin=20 * mm, title=titre, author=NOM)94    doc.build(flux, onFirstPage=_pied, onLaterPages=_pied)95    return tampon.getvalue()969798_MATCH = {"identique": "identique (même code)", "meme_produit": "même produit (nom)",99          "equivalent": "équivalent"}100101102def fiche_pdf(f: dict) -> bytes:103    L = LETTER[0] - 36 * mm104    flux = [Paragraph(_e(f["name"]), _T), Spacer(1, 3)]105    sous = " · ".join(x for x in [f.get("brand"), f.get("size"), f.get("store_name"),106                                  f.get("category")] if x)107    flux.append(Paragraph(_e(sous), _S))108    flux.append(Spacer(1, 8))109    pu = f.get("unit_price") or {}110    v = f.get("verdict") or {}111    h = f.get("history") or {}112    lignes = [113        ["Prix courant", _argent(f.get("price"))],114        ["Prix régulier annoncé", _argent(f.get("regular_price"))],115        ["Prix unitaire", pu.get("label") or "—"],116        ["Position du prix", ((v.get("label") or "—")117                              + (f" ({v['score_pct']:+.1f} %)".replace(".", ",") if v else ""))],118        ["Plus bas / médiane / plus haut (90 j)",119         f"{_argent(h.get('low_90d'))} / {_argent(h.get('median_90d'))} / {_argent(h.get('high_90d'))}"],120        ["Suivi depuis", _date(h.get("since"))],121        ["Dernier relevé", _date(f.get("last_seen"))],122    ]123    val = f.get("validity")124    if val:125        lignes.append(["Circulaire valide", f"{_date(val.get('from'))} au {_date(val.get('to'))}"])126    flux.append(_table(lignes, [L * 0.45, L * 0.55], entete=False))127    portee = (f.get("price_scope") or {}).get("note")128    if portee:129        flux.append(Spacer(1, 4))130        flux.append(Paragraph(_e(portee), _S))131    if f.get("offers"):132        flux.append(Paragraph("Le même produit ailleurs", _H))133        t = [["Enseigne", "Produit", "Format", "Prix", "Appariement"]]134        for o in f["offers"][:15]:135            t.append([Paragraph(_e(o["store_name"]), _P), Paragraph(_e(o["name"]), _P),136                      o.get("size") or "—", _argent(o["price"]), _MATCH.get(o["match"], o["match"])])137        flux.append(_table(t, [L * .18, L * .40, L * .12, L * .12, L * .18]))138    if f.get("equivalents"):139        flux.append(Paragraph("Produits équivalents (pas le même produit)", _H))140        t = [["Enseigne", "Produit", "Format", "Prix", "Prix unitaire"]]141        for o in f["equivalents"][:10]:142            t.append([Paragraph(_e(o["store_name"]), _P), Paragraph(_e(o["name"]), _P),143                      o.get("size") or "—", _argent(o["price"]),144                      (o.get("unit_price") or {}).get("label") or "—"])145        flux.append(_table(t, [L * .18, L * .40, L * .12, L * .12, L * .18]))146    pts = (h.get("points") or [])[-18:]147    if pts:148        flux.append(Paragraph("Changements de prix observés", _H))149        t = [["Date", "Prix"]] + [[_date(p["t"]), _argent(p["price"])] for p in pts]150        flux.append(_table(t, [L * .3, L * .7]))151    flux.append(Spacer(1, 8))152    flux.append(Paragraph(_e(f.get("url") or ""), _S))153    return _doc(f["name"], flux)154155156def marche_pdf(resume: dict, indice: dict, mouv: dict) -> bytes:157    L = LETTER[0] - 36 * mm158    flux = [Paragraph("État du marché de l'épicerie au Québec", _T), Spacer(1, 3),159            Paragraph(f"{NOM} — données du {_date(resume.get('updated'))}", _S), Spacer(1, 8)]160    d = resume["deals"]161    flux.append(_table([162        ["Produits publics", f"{resume['total']:,}".replace(",", " ")],163        ["Enseignes", str(resume["stores"])],164        ["Prix médian", _argent(resume["median_price"])],165        ["Soldes vérifiés contre l'historique", str(d["verifiee"])],166        ["Soldes annoncés mais non réels (prix régulier gonflé)", str(d["gonflee"])],167        ["Produits appariés entre enseignes", str(resume["matching"]["linked_products"])],168    ], [L * .6, L * .4], entete=False))169    s = indice.get("summary")170    if s:171        flux.append(Paragraph("Indice du panier d'épicerie", _H))172        flux.append(Paragraph(_e(173            f"Indice {s['index']:.2f} (base 100 le {s['since']}), soit "174            f"{s['change_total_pct']:+.2f} % en {s['weeks']} semaines. "175            + indice["method"]["type"] + ". " + indice["method"]["champ"] + "."), _P))176        t = [["Semaine du", "Indice", "Variation", "Produits comparés"]]177        for p in indice["series"][-16:]:178            t.append([p["week"], f"{p['index']:.2f}",179                      "—" if p["change_pct"] is None else f"{p['change_pct']:+.2f} %", str(p["n"])])180        flux.append(_table(t, [L * .25] * 4))181        t = [["Rayon", "Indice", "Depuis la base", "4 semaines"]]182        for c in indice["by_category"]:183            r = c["summary"]184            if r:185                t.append([c["category"], f"{r['index']:.2f}", f"{r['change_total_pct']:+.2f} %",186                          "—" if r["change_4w_pct"] is None else f"{r['change_4w_pct']:+.2f} %"])187        flux.append(Spacer(1, 6))188        flux.append(_table(t, [L * .4, L * .2, L * .2, L * .2]))189    flux.append(Paragraph(f"Plus fortes baisses en {mouv['days']} jours", _H))190    t = [["Produit", "Enseigne", "Avant", "Maintenant", "Variation"]]191    for m in mouv["top_down"][:12]:192        t.append([Paragraph(_e(m["name"]), _P), Paragraph(_e(m["store_name"]), _P),193                  _argent(m["price_before"]), _argent(m["price"]), f"{m['change_pct']:+.1f} %"])194    flux.append(_table(t, [L * .42, L * .2, L * .13, L * .13, L * .12]))195    flux.append(Paragraph(f"Plus fortes hausses en {mouv['days']} jours", _H))196    t = [["Produit", "Enseigne", "Avant", "Maintenant", "Variation"]]197    for m in mouv["top_up"][:12]:198        t.append([Paragraph(_e(m["name"]), _P), Paragraph(_e(m["store_name"]), _P),199                  _argent(m["price_before"]), _argent(m["price"]), f"{m['change_pct']:+.1f} %"])200    flux.append(_table(t, [L * .42, L * .2, L * .13, L * .13, L * .12]))201    return _doc("État du marché de l'épicerie au Québec", flux)202
Files main
Menu

Theme