Spaces:
Sleeping
Sleeping
Download services/export_pdf.py from DerXanity/farient-deckcheck: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/spaces/DerXanity/farient-deckcheck/resolve/main/services/export_pdf.py
- Command line
-
hf download hf://spaces/DerXanity/farient-deckcheck/services/export_pdf.py
-
curl -L -o export_pdf.py https://huggingface.co/spaces/DerXanity/farient-deckcheck/resolve/main/services/export_pdf.py
15 kB
| """PDF export for the Farient brand-review API. | |
| Generates a polished, paginated PDF report from the strict-PRD audit | |
| envelope (``AuditExportJson``). | |
| Engine choice: **ReportLab Platypus** — pure-Python, no system dependencies | |
| (no Pango/Cairo required, unlike WeasyPrint). The ``fn-2-3zh`` spec planned | |
| for WeasyPrint, but the local dev environment is missing libpango/libcairo | |
| and the install fails on macOS without Homebrew Pango. ReportLab gives us a | |
| deterministic, dependency-light path that still produces a professional | |
| report. Brand color #1F2D5F (Farient navy) is used for headings and the | |
| severity-pill backgrounds. | |
| Public API: ``render_audit_pdf(audit_export) -> bytes``. | |
| """ | |
| from __future__ import annotations | |
| import io | |
| import time | |
| from typing import Any | |
| from reportlab.lib import colors | |
| from reportlab.lib.enums import TA_LEFT | |
| from reportlab.lib.pagesizes import LETTER | |
| from reportlab.lib.styles import ParagraphStyle, getSampleStyleSheet | |
| from reportlab.lib.units import inch | |
| from reportlab.platypus import ( | |
| BaseDocTemplate, | |
| Frame, | |
| KeepTogether, | |
| PageBreak, | |
| PageTemplate, | |
| Paragraph, | |
| Spacer, | |
| Table, | |
| TableStyle, | |
| ) | |
| from schemas.api import AuditExportJson, Finding, SlideEnvelope | |
| # --------------------------------------------------------------------------- | |
| # Brand palette | |
| # --------------------------------------------------------------------------- | |
| # Farient brand navy | |
| BRAND_NAVY = colors.HexColor("#1F2D5F") | |
| BRAND_NAVY_LIGHT = colors.HexColor("#E5E8F0") | |
| # Severity pill colors | |
| SEVERITY_BG = { | |
| "high": colors.HexColor("#FEE2E2"), | |
| "medium": colors.HexColor("#FEF3C7"), | |
| "low": colors.HexColor("#DCFCE7"), | |
| } | |
| SEVERITY_FG = { | |
| "high": colors.HexColor("#991B1B"), | |
| "medium": colors.HexColor("#92400E"), | |
| "low": colors.HexColor("#166534"), | |
| } | |
| # Evidence box (monospace block) | |
| EVIDENCE_BG = colors.HexColor("#F3F4F6") | |
| EVIDENCE_BORDER = colors.HexColor("#D1D5DB") | |
| # Suggested-fix highlight | |
| FIX_BG = colors.HexColor("#EFF6FF") | |
| FIX_BORDER = colors.HexColor("#93C5FD") | |
| # --------------------------------------------------------------------------- | |
| # Styles | |
| # --------------------------------------------------------------------------- | |
| def _build_styles() -> dict[str, ParagraphStyle]: | |
| base = getSampleStyleSheet() | |
| styles: dict[str, ParagraphStyle] = {} | |
| styles["title"] = ParagraphStyle( | |
| "FarientTitle", | |
| parent=base["Title"], | |
| fontName="Helvetica-Bold", | |
| fontSize=22, | |
| leading=26, | |
| textColor=BRAND_NAVY, | |
| spaceAfter=10, | |
| alignment=TA_LEFT, | |
| ) | |
| styles["subtitle"] = ParagraphStyle( | |
| "FarientSubtitle", | |
| parent=base["Normal"], | |
| fontName="Helvetica", | |
| fontSize=10, | |
| leading=14, | |
| textColor=colors.HexColor("#475569"), | |
| spaceAfter=8, | |
| ) | |
| styles["h2"] = ParagraphStyle( | |
| "FarientH2", | |
| parent=base["Heading2"], | |
| fontName="Helvetica-Bold", | |
| fontSize=15, | |
| leading=18, | |
| textColor=BRAND_NAVY, | |
| spaceBefore=14, | |
| spaceAfter=6, | |
| ) | |
| styles["h3"] = ParagraphStyle( | |
| "FarientH3", | |
| parent=base["Heading3"], | |
| fontName="Helvetica-Bold", | |
| fontSize=12, | |
| leading=15, | |
| textColor=BRAND_NAVY, | |
| spaceBefore=10, | |
| spaceAfter=4, | |
| ) | |
| styles["body"] = ParagraphStyle( | |
| "FarientBody", | |
| parent=base["BodyText"], | |
| fontName="Helvetica", | |
| fontSize=10, | |
| leading=14, | |
| spaceAfter=4, | |
| ) | |
| styles["meta"] = ParagraphStyle( | |
| "FarientMeta", | |
| parent=base["BodyText"], | |
| fontName="Helvetica", | |
| fontSize=9, | |
| leading=12, | |
| textColor=colors.HexColor("#475569"), | |
| spaceAfter=2, | |
| ) | |
| styles["evidence"] = ParagraphStyle( | |
| "FarientEvidence", | |
| parent=base["Code"], | |
| fontName="Courier", | |
| fontSize=9, | |
| leading=12, | |
| textColor=colors.HexColor("#1F2937"), | |
| ) | |
| styles["fix"] = ParagraphStyle( | |
| "FarientFix", | |
| parent=base["BodyText"], | |
| fontName="Helvetica", | |
| fontSize=10, | |
| leading=14, | |
| textColor=colors.HexColor("#1E3A8A"), | |
| ) | |
| styles["finding_title"] = ParagraphStyle( | |
| "FarientFindingTitle", | |
| parent=base["Heading4"], | |
| fontName="Helvetica-Bold", | |
| fontSize=11, | |
| leading=14, | |
| textColor=BRAND_NAVY, | |
| spaceBefore=6, | |
| spaceAfter=4, | |
| ) | |
| return styles | |
| # --------------------------------------------------------------------------- | |
| # Building blocks | |
| # --------------------------------------------------------------------------- | |
| def _xml_escape(text: str) -> str: | |
| """Escape ReportLab Paragraph mini-language reserved chars.""" | |
| return ( | |
| text.replace("&", "&") | |
| .replace("<", "<") | |
| .replace(">", ">") | |
| ) | |
| def _severity_pill(severity: str) -> Table: | |
| """Render a small colored severity pill as a 1x1 table.""" | |
| sev = severity.lower() | |
| bg = SEVERITY_BG.get(sev, colors.lightgrey) | |
| fg = SEVERITY_FG.get(sev, colors.black) | |
| label = sev.upper() | |
| pill = Table([[label]], colWidths=[0.7 * inch]) | |
| pill.setStyle( | |
| TableStyle( | |
| [ | |
| ("BACKGROUND", (0, 0), (-1, -1), bg), | |
| ("TEXTCOLOR", (0, 0), (-1, -1), fg), | |
| ("FONTNAME", (0, 0), (-1, -1), "Helvetica-Bold"), | |
| ("FONTSIZE", (0, 0), (-1, -1), 8), | |
| ("ALIGN", (0, 0), (-1, -1), "CENTER"), | |
| ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), | |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 3), | |
| ("TOPPADDING", (0, 0), (-1, -1), 3), | |
| ("LEFTPADDING", (0, 0), (-1, -1), 4), | |
| ("RIGHTPADDING", (0, 0), (-1, -1), 4), | |
| ] | |
| ) | |
| ) | |
| return pill | |
| def _evidence_block(text: str, styles: dict[str, ParagraphStyle]) -> Table: | |
| """Render evidence in a bordered, light-grey monospace block.""" | |
| safe = _xml_escape(text or "(no evidence)") | |
| para = Paragraph(safe, styles["evidence"]) | |
| box = Table([[para]], colWidths=[6.5 * inch]) | |
| box.setStyle( | |
| TableStyle( | |
| [ | |
| ("BACKGROUND", (0, 0), (-1, -1), EVIDENCE_BG), | |
| ("BOX", (0, 0), (-1, -1), 0.5, EVIDENCE_BORDER), | |
| ("LEFTPADDING", (0, 0), (-1, -1), 6), | |
| ("RIGHTPADDING", (0, 0), (-1, -1), 6), | |
| ("TOPPADDING", (0, 0), (-1, -1), 5), | |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 5), | |
| ] | |
| ) | |
| ) | |
| return box | |
| def _fix_block(text: str, styles: dict[str, ParagraphStyle]) -> Table: | |
| """Render the suggested-fix in a highlighted box.""" | |
| safe = _xml_escape(text or "(no suggestion)") | |
| para = Paragraph(f"<b>Suggested fix:</b> {safe}", styles["fix"]) | |
| box = Table([[para]], colWidths=[6.5 * inch]) | |
| box.setStyle( | |
| TableStyle( | |
| [ | |
| ("BACKGROUND", (0, 0), (-1, -1), FIX_BG), | |
| ("LINEBEFORE", (0, 0), (0, -1), 2.5, FIX_BORDER), | |
| ("LEFTPADDING", (0, 0), (-1, -1), 8), | |
| ("RIGHTPADDING", (0, 0), (-1, -1), 6), | |
| ("TOPPADDING", (0, 0), (-1, -1), 6), | |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 6), | |
| ] | |
| ) | |
| ) | |
| return box | |
| def _finding_card( | |
| f: Finding, styles: dict[str, ParagraphStyle] | |
| ) -> KeepTogether: | |
| """Render one finding as a self-contained, page-break-resistant card.""" | |
| title = Paragraph(_xml_escape(f.title), styles["finding_title"]) | |
| pill = _severity_pill(f.severity) | |
| header = Table( | |
| [[title, pill]], colWidths=[5.8 * inch, 0.7 * inch] | |
| ) | |
| header.setStyle( | |
| TableStyle( | |
| [ | |
| ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), | |
| ("LEFTPADDING", (0, 0), (-1, -1), 0), | |
| ("RIGHTPADDING", (0, 0), (-1, -1), 0), | |
| ("TOPPADDING", (0, 0), (-1, -1), 0), | |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 0), | |
| ] | |
| ) | |
| ) | |
| meta = Paragraph( | |
| f"<b>Category:</b> {_xml_escape(f.category)} · " | |
| f"<b>Confidence:</b> {f.confidence:.2f} · " | |
| f"<b>Guideline:</b> {_xml_escape(f.guideline_reference)}", | |
| styles["meta"], | |
| ) | |
| description = Paragraph(_xml_escape(f.description), styles["body"]) | |
| evidence_label = Paragraph("<b>Evidence:</b>", styles["meta"]) | |
| evidence = _evidence_block(f.evidence, styles) | |
| fix = _fix_block(f.suggested_fix, styles) | |
| flow: list[Any] = [ | |
| header, | |
| Spacer(1, 2), | |
| meta, | |
| Spacer(1, 4), | |
| description, | |
| Spacer(1, 4), | |
| evidence_label, | |
| evidence, | |
| Spacer(1, 4), | |
| fix, | |
| Spacer(1, 8), | |
| ] | |
| return KeepTogether(flow) | |
| # --------------------------------------------------------------------------- | |
| # Page decoration (header / footer) | |
| # --------------------------------------------------------------------------- | |
| def _make_on_page(file_name: str, generated_at: str): | |
| """Return a ``onPage`` callback that draws the header/footer.""" | |
| def _on_page(canvas, doc): # noqa: ANN001 — ReportLab signature | |
| canvas.saveState() | |
| # Header | |
| canvas.setFillColor(BRAND_NAVY) | |
| canvas.setFont("Helvetica-Bold", 8) | |
| canvas.drawString( | |
| 0.75 * inch, | |
| 10.5 * inch, | |
| "FARIENT BRAND COMPLIANCE AUDIT", | |
| ) | |
| canvas.setFillColor(colors.HexColor("#94A3B8")) | |
| canvas.setFont("Helvetica", 8) | |
| # Truncate the filename if it's too long to keep the header tidy. | |
| display_name = file_name if len(file_name) <= 60 else file_name[:57] + "..." | |
| canvas.drawRightString( | |
| 7.75 * inch, | |
| 10.5 * inch, | |
| display_name, | |
| ) | |
| # Header rule | |
| canvas.setStrokeColor(BRAND_NAVY) | |
| canvas.setLineWidth(0.75) | |
| canvas.line(0.75 * inch, 10.4 * inch, 7.75 * inch, 10.4 * inch) | |
| # Footer | |
| canvas.setFillColor(colors.HexColor("#94A3B8")) | |
| canvas.setFont("Helvetica", 8) | |
| canvas.drawString( | |
| 0.75 * inch, 0.5 * inch, f"Generated {generated_at}" | |
| ) | |
| canvas.drawRightString( | |
| 7.75 * inch, 0.5 * inch, f"Page {doc.page}" | |
| ) | |
| canvas.restoreState() | |
| return _on_page | |
| # --------------------------------------------------------------------------- | |
| # Public renderer | |
| # --------------------------------------------------------------------------- | |
| def _summary_table(audit: AuditExportJson, must_flag_count: int) -> Table: | |
| """Top-of-document summary stats table.""" | |
| data = [ | |
| ["Slides", "Total findings", "High", "Medium", "Low", "Must-flag"], | |
| [ | |
| str(audit.slide_count), | |
| str( | |
| audit.summary.high | |
| + audit.summary.medium | |
| + audit.summary.low | |
| ), | |
| str(audit.summary.high), | |
| str(audit.summary.medium), | |
| str(audit.summary.low), | |
| str(must_flag_count), | |
| ], | |
| ] | |
| table = Table( | |
| data, | |
| colWidths=[ | |
| 0.95 * inch, | |
| 1.3 * inch, | |
| 0.85 * inch, | |
| 1.0 * inch, | |
| 0.85 * inch, | |
| 1.05 * inch, | |
| ], | |
| ) | |
| table.setStyle( | |
| TableStyle( | |
| [ | |
| ("BACKGROUND", (0, 0), (-1, 0), BRAND_NAVY), | |
| ("TEXTCOLOR", (0, 0), (-1, 0), colors.white), | |
| ("FONTNAME", (0, 0), (-1, 0), "Helvetica-Bold"), | |
| ("FONTSIZE", (0, 0), (-1, 0), 9), | |
| ("ALIGN", (0, 0), (-1, -1), "CENTER"), | |
| ("VALIGN", (0, 0), (-1, -1), "MIDDLE"), | |
| ("FONTNAME", (0, 1), (-1, 1), "Helvetica"), | |
| ("FONTSIZE", (0, 1), (-1, 1), 11), | |
| ("BACKGROUND", (0, 1), (-1, 1), BRAND_NAVY_LIGHT), | |
| ("BOTTOMPADDING", (0, 0), (-1, -1), 6), | |
| ("TOPPADDING", (0, 0), (-1, -1), 6), | |
| ("BOX", (0, 0), (-1, -1), 0.5, BRAND_NAVY), | |
| ] | |
| ) | |
| ) | |
| return table | |
| def _slide_section( | |
| slide: SlideEnvelope, styles: dict[str, ParagraphStyle] | |
| ) -> list[Any]: | |
| """Build the flow elements for one slide (only when it has findings).""" | |
| flow: list[Any] = [ | |
| Paragraph( | |
| f"Slide {slide.slide_number} " | |
| f"<font color='#94A3B8'>" | |
| f"({len(slide.findings)} finding" | |
| f"{'' if len(slide.findings) == 1 else 's'})" | |
| f"</font>", | |
| styles["h3"], | |
| ), | |
| Spacer(1, 4), | |
| ] | |
| for f in slide.findings: | |
| flow.append(_finding_card(f, styles)) | |
| return flow | |
| def _count_must_flag(audit: AuditExportJson) -> int: | |
| """Heuristic must-flag count: confidence >= 0.99 and severity high.""" | |
| n = 0 | |
| for slide in audit.slides: | |
| for f in slide.findings: | |
| if f.severity == "high" and f.confidence >= 0.99: | |
| n += 1 | |
| return n | |
| def render_audit_pdf(audit: AuditExportJson) -> bytes: | |
| """Render the audit as a PDF and return raw bytes.""" | |
| styles = _build_styles() | |
| generated_at = time.strftime("%Y-%m-%d %H:%M UTC", time.gmtime()) | |
| must_flag = _count_must_flag(audit) | |
| buf = io.BytesIO() | |
| page_w, page_h = LETTER | |
| margin = 0.75 * inch | |
| frame = Frame( | |
| margin, | |
| margin, | |
| page_w - 2 * margin, | |
| page_h - 2 * margin, | |
| id="content", | |
| leftPadding=0, | |
| rightPadding=0, | |
| topPadding=0, | |
| bottomPadding=0, | |
| ) | |
| on_page = _make_on_page(audit.file_name, generated_at) | |
| template = PageTemplate(id="default", frames=[frame], onPage=on_page) | |
| doc = BaseDocTemplate( | |
| buf, | |
| pagesize=LETTER, | |
| leftMargin=margin, | |
| rightMargin=margin, | |
| topMargin=margin, | |
| bottomMargin=margin, | |
| title=f"Brand Audit — {audit.file_name}", | |
| author="Farient Brand Review", | |
| ) | |
| doc.addPageTemplates([template]) | |
| story: list[Any] = [] | |
| story.append( | |
| Paragraph( | |
| f"Brand Compliance Audit", | |
| styles["title"], | |
| ) | |
| ) | |
| story.append( | |
| Paragraph( | |
| f"<b>Deck:</b> {_xml_escape(audit.file_name)}<br/>" | |
| f"<b>Job ID:</b> {_xml_escape(audit.job_id)}<br/>" | |
| f"<b>Generated:</b> {generated_at}", | |
| styles["subtitle"], | |
| ) | |
| ) | |
| story.append(Spacer(1, 6)) | |
| story.append(_summary_table(audit, must_flag)) | |
| story.append(Spacer(1, 14)) | |
| # Slide-by-slide | |
| story.append(Paragraph("Findings by slide", styles["h2"])) | |
| slides_with_findings = [s for s in audit.slides if s.findings] | |
| if not slides_with_findings: | |
| story.append( | |
| Paragraph( | |
| "<i>No findings recorded across the deck.</i>", | |
| styles["body"], | |
| ) | |
| ) | |
| else: | |
| for slide in slides_with_findings: | |
| story.extend(_slide_section(slide, styles)) | |
| doc.build(story) | |
| return buf.getvalue() | |
| __all__ = ["render_audit_pdf"] | |