Spaces:
Sleeping
Sleeping
File size: 15,046 Bytes
fdfe81a | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 | """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"]
|