s-ttp commited on
Commit
7dffd90
·
verified ·
1 Parent(s): 8cf30a3

Light print version of the PDF report (theme=print): white paper, navy ink, deepened state colours, brand logo colours kept

Browse files
app.py CHANGED
@@ -235,13 +235,15 @@ def api_result(run_id: str):
235
 
236
 
237
  @app.get("/api/report/{run_id}")
238
- def api_report(run_id: str):
 
239
  run = _runs.get(run_id)
240
  if not run or not run.get("result"):
241
  raise HTTPException(404, "No report for this run.")
242
  from src.pdf_report import build_pdf
 
243
  try:
244
- pdf = build_pdf(run["result"])
245
  except Exception: # PDF layout must never lose the report — fall back to markdown
246
  import traceback
247
  traceback.print_exc()
@@ -250,7 +252,7 @@ def api_report(run_id: str):
250
  "Content-Disposition": f'attachment; filename="vitals-report-{run_id}.md"'})
251
  from fastapi.responses import Response
252
  return Response(pdf, media_type="application/pdf", headers={
253
- "Content-Disposition": f'attachment; filename="vitals-report-{run_id}.pdf"'})
254
 
255
 
256
  @app.get("/api/audit/{run_id}")
 
235
 
236
 
237
  @app.get("/api/report/{run_id}")
238
+ def api_report(run_id: str, theme: str = "dark"):
239
+ """theme=dark (default, matches the app) or theme=print (white paper, navy ink)."""
240
  run = _runs.get(run_id)
241
  if not run or not run.get("result"):
242
  raise HTTPException(404, "No report for this run.")
243
  from src.pdf_report import build_pdf
244
+ theme = "print" if str(theme).lower() in ("print", "light") else "dark"
245
  try:
246
+ pdf = build_pdf(run["result"], theme=theme)
247
  except Exception: # PDF layout must never lose the report — fall back to markdown
248
  import traceback
249
  traceback.print_exc()
 
252
  "Content-Disposition": f'attachment; filename="vitals-report-{run_id}.md"'})
253
  from fastapi.responses import Response
254
  return Response(pdf, media_type="application/pdf", headers={
255
+ "Content-Disposition": f'attachment; filename="vitals-report-{run_id}{"-print" if theme == "print" else ""}.pdf"'})
256
 
257
 
258
  @app.get("/api/audit/{run_id}")
data/europanel.json CHANGED
The diff for this file is too large to render. See raw diff
 
src/pdf_report.py CHANGED
@@ -18,7 +18,22 @@ from reportlab.platypus import Flowable
18
  from reportlab.platypus import Paragraph as _RLParagraph
19
  from reportlab.platypus import SimpleDocTemplate, Spacer, Table, TableStyle
20
 
21
- # ── EmergentSignals tokens (rules are the site's white-at-9%/16% flattened onto the navy) ──
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
22
  BG = colors.HexColor("#08111c")
23
  TEXT = colors.HexColor("#f3f7fb")
24
  TEXT2 = colors.HexColor("#a8b4c3")
@@ -80,16 +95,35 @@ def _sty(name, **kw):
80
  return ParagraphStyle(name, **base) # type: ignore[arg-type]
81
 
82
 
83
- S_TITLE = _sty("t", fontName=SERIF, fontSize=30, leading=32, textColor=TEXT)
84
- S_TAG = _sty("tag", fontName=MONO, fontSize=6.8, leading=10, textColor=MUTED)
85
- S_LABEL = _sty("lab", fontName=MONO, fontSize=6.5, leading=9, textColor=MUTED)
86
- S_H2 = _sty("h2", fontName=MONO, fontSize=7, leading=10, textColor=TEXT, spaceBefore=12, spaceAfter=5)
87
- S_SUB = _sty("sub", fontName=MONO, fontSize=6.8, leading=10, textColor=TEXT, spaceBefore=8, spaceAfter=3)
88
- S_BODY = _sty("b")
89
- S_VERDICT = _sty("v", fontName=SERIF, fontSize=14, leading=18, textColor=TEXT)
90
- S_LEAD = _sty("lead", fontName=SANS, fontSize=12.5, leading=17, textColor=TEXT)
91
- S_DIM = _sty("d", fontSize=7.4, leading=10.5, textColor=MUTED)
92
- S_CELL = _sty("c", fontSize=7.8, leading=10.8)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
93
 
94
 
95
  _UNI = {"✕": "×", "✗": "×", "⚠": "!", "✓": "+", "🟢": "", "🔁": "", "🔻": "", "⏸": "", "👁": ""}
@@ -219,7 +253,8 @@ def _wordmark(c, x, y, size=11.5):
219
  600 with the green-dot i."""
220
  mw, mh = 0.705 * size, 0.581 * size
221
  sx, sy = mw / 61.3, mh / 50.5
222
- for cx, cy, r, col in ((8.3, 42.2, 8.3, BAD), (27.75, 27.81, 9.9, WARN), (49.78, 11.51, 11.5, GOOD)):
 
223
  c.setFillColor(col); c.circle(x + cx * sx, y + (50.5 - cy) * sy, r * sx, stroke=0, fill=1)
224
  tx = x + mw + 0.22 * size
225
  c.setFillColor(TEXT)
@@ -229,7 +264,7 @@ def _wordmark(c, x, y, size=11.5):
229
  c.drawString(tx, y, dotless)
230
  iw = pdfmetrics.stringWidth(dotless, SANS_SEMI, size)
231
  if _FONTS_OK:
232
- c.setFillColor(GOOD); c.circle(tx + iw / 2 + 0.01 * size, y + 0.70 * size, 0.09 * size, stroke=0, fill=1)
233
  c.setFillColor(TEXT)
234
  tx += iw
235
  c.drawString(tx, y, "tals")
@@ -238,7 +273,8 @@ def _wordmark(c, x, y, size=11.5):
238
  def _page(c, doc):
239
  w, h = A4
240
  c.saveState()
241
- c.setFillColor(BG); c.rect(0, 0, w, h, stroke=0, fill=1)
 
242
  _wordmark(c, 16 * mm, h - 11.5 * mm)
243
  c.setFont(MONO, 6.4); c.setFillColor(TEXT)
244
  right = "YOUR PORTFOLIO'S AI HEALTH CHECK"
@@ -252,7 +288,20 @@ def _page(c, doc):
252
  c.restoreState()
253
 
254
 
255
- def build_pdf(res: dict) -> bytes:
 
 
 
 
 
 
 
 
 
 
 
 
 
256
  buf = io.BytesIO()
257
  doc = SimpleDocTemplate(buf, pagesize=A4, leftMargin=16 * mm, rightMargin=16 * mm,
258
  topMargin=24 * mm, bottomMargin=18 * mm, title="Vitals — Portfolio Verdict",
 
18
  from reportlab.platypus import Paragraph as _RLParagraph
19
  from reportlab.platypus import SimpleDocTemplate, Spacer, Table, TableStyle
20
 
21
+ # ── EmergentSignals tokens. Two themes share one layout: "dark" mirrors the site (rules are its
22
+ # white-at-9%/16% flattened onto the navy); "print" is the same system on white paper with
23
+ # navy ink and the state colours deepened for legibility in print. The logo keeps its exact
24
+ # brand colours in both. ──
25
+ _THEMES = {
26
+ "dark": {"BG": "#08111c", "TEXT": "#f3f7fb", "TEXT2": "#a8b4c3", "MUTED": "#748399",
27
+ "RULE": "#1e2630", "RULE_STRONG": "#303740",
28
+ "GOOD": "#20c997", "WARN": "#f2c14e", "BAD": "#e76f6f"},
29
+ "print": {"BG": None, "TEXT": "#08111c", "TEXT2": "#3b4757", "MUTED": "#6b778a",
30
+ "RULE": "#dde3ea", "RULE_STRONG": "#aeb8c5",
31
+ "GOOD": "#0f8a66", "WARN": "#9a6d08", "BAD": "#c0453f"},
32
+ }
33
+ BRAND_REJECTED = colors.HexColor("#e76f6f")
34
+ BRAND_CANDIDATE = colors.HexColor("#f2c14e")
35
+ BRAND_VALIDATED = colors.HexColor("#20c997")
36
+ _THEME = "dark"
37
  BG = colors.HexColor("#08111c")
38
  TEXT = colors.HexColor("#f3f7fb")
39
  TEXT2 = colors.HexColor("#a8b4c3")
 
95
  return ParagraphStyle(name, **base) # type: ignore[arg-type]
96
 
97
 
98
+ def _build_styles():
99
+ global S_TITLE, S_TAG, S_LABEL, S_H2, S_SUB, S_BODY, S_VERDICT, S_LEAD, S_DIM, S_CELL
100
+ S_TITLE = _sty("t", fontName=SERIF, fontSize=30, leading=32, textColor=TEXT)
101
+ S_TAG = _sty("tag", fontName=MONO, fontSize=6.8, leading=10, textColor=MUTED)
102
+ S_LABEL = _sty("lab", fontName=MONO, fontSize=6.5, leading=9, textColor=MUTED)
103
+ S_H2 = _sty("h2", fontName=MONO, fontSize=7, leading=10, textColor=TEXT, spaceBefore=12, spaceAfter=5)
104
+ S_SUB = _sty("sub", fontName=MONO, fontSize=6.8, leading=10, textColor=TEXT, spaceBefore=8, spaceAfter=3)
105
+ S_BODY = _sty("b")
106
+ S_VERDICT = _sty("v", fontName=SERIF, fontSize=14, leading=18, textColor=TEXT)
107
+ S_LEAD = _sty("lead", fontName=SANS, fontSize=12.5, leading=17, textColor=TEXT)
108
+ S_DIM = _sty("d", fontSize=7.4, leading=10.5, textColor=MUTED)
109
+ S_CELL = _sty("c", fontSize=7.8, leading=10.8)
110
+
111
+
112
+ def _apply_theme(name: str) -> None:
113
+ """Swap the palette (and the styles built from it) for 'dark' or 'print'."""
114
+ global _THEME, INK, BRASS, DIM, LINE, _ACTION_COLOR, _SEV_COLOR
115
+ name = name if name in _THEMES else "dark"
116
+ g = globals()
117
+ for k, v in _THEMES[name].items():
118
+ g[k] = colors.HexColor(v) if v else None
119
+ _THEME = name
120
+ INK, BRASS, DIM, LINE = TEXT2, TEXT, MUTED, RULE
121
+ _ACTION_COLOR = {"Buy More": GOOD, "Keep": TEXT2, "Trim": WARN, "Sell": BAD}
122
+ _SEV_COLOR = {"good": GOOD, "warn": WARN, "bad": BAD, "OK": GOOD, "WATCH": WARN, "ALERT": BAD}
123
+ _build_styles()
124
+
125
+
126
+ _build_styles()
127
 
128
 
129
  _UNI = {"✕": "×", "✗": "×", "⚠": "!", "✓": "+", "🟢": "", "🔁": "", "🔻": "", "⏸": "", "👁": ""}
 
253
  600 with the green-dot i."""
254
  mw, mh = 0.705 * size, 0.581 * size
255
  sx, sy = mw / 61.3, mh / 50.5
256
+ for cx, cy, r, col in ((8.3, 42.2, 8.3, BRAND_REJECTED), (27.75, 27.81, 9.9, BRAND_CANDIDATE),
257
+ (49.78, 11.51, 11.5, BRAND_VALIDATED)):
258
  c.setFillColor(col); c.circle(x + cx * sx, y + (50.5 - cy) * sy, r * sx, stroke=0, fill=1)
259
  tx = x + mw + 0.22 * size
260
  c.setFillColor(TEXT)
 
264
  c.drawString(tx, y, dotless)
265
  iw = pdfmetrics.stringWidth(dotless, SANS_SEMI, size)
266
  if _FONTS_OK:
267
+ c.setFillColor(BRAND_VALIDATED); c.circle(tx + iw / 2 + 0.01 * size, y + 0.70 * size, 0.09 * size, stroke=0, fill=1)
268
  c.setFillColor(TEXT)
269
  tx += iw
270
  c.drawString(tx, y, "tals")
 
273
  def _page(c, doc):
274
  w, h = A4
275
  c.saveState()
276
+ if BG is not None: # the print theme leaves the paper white — no ink flood
277
+ c.setFillColor(BG); c.rect(0, 0, w, h, stroke=0, fill=1)
278
  _wordmark(c, 16 * mm, h - 11.5 * mm)
279
  c.setFont(MONO, 6.4); c.setFillColor(TEXT)
280
  right = "YOUR PORTFOLIO'S AI HEALTH CHECK"
 
288
  c.restoreState()
289
 
290
 
291
+ _BUILD_LOCK = __import__("threading").Lock()
292
+
293
+
294
+ def build_pdf(res: dict, theme: str = "dark") -> bytes:
295
+ """theme: 'dark' (matches the app and emergentsignals.ai) or 'print' (white paper, navy ink)."""
296
+ with _BUILD_LOCK: # the palette is module state: one build at a time
297
+ _apply_theme(theme)
298
+ try:
299
+ return _build_pdf(res)
300
+ finally:
301
+ _apply_theme("dark")
302
+
303
+
304
+ def _build_pdf(res: dict) -> bytes:
305
  buf = io.BytesIO()
306
  doc = SimpleDocTemplate(buf, pagesize=A4, leftMargin=16 * mm, rightMargin=16 * mm,
307
  topMargin=24 * mm, bottomMargin=18 * mm, title="Vitals — Portfolio Verdict",
static/app.js CHANGED
@@ -525,6 +525,7 @@ function renderResults(R) {
525
  renderRisk(R);
526
  renderRejected(R);
527
  $("#download").href = "/api/report/" + currentRun;
 
528
  $("#audit").href = "/api/audit/" + currentRun;
529
  $("#meta").textContent = `Generated ${R.generated_at}` +
530
  (R.metrics.equal_weighted ? " · equal-weighted (no quantities given)" : "") +
 
525
  renderRisk(R);
526
  renderRejected(R);
527
  $("#download").href = "/api/report/" + currentRun;
528
+ $("#download-print").href = "/api/report/" + currentRun + "?theme=print";
529
  $("#audit").href = "/api/audit/" + currentRun;
530
  $("#meta").textContent = `Generated ${R.generated_at}` +
531
  (R.metrics.equal_weighted ? " · equal-weighted (no quantities given)" : "") +
static/index.html CHANGED
@@ -266,6 +266,7 @@
266
  <footer class="card footer">
267
  <div class="footer-actions">
268
  <a id="download" class="primary" href="#" download>Download the full report (PDF)</a>
 
269
  <a id="audit" class="ghost" href="#" download>Audit trail (JSON)</a>
270
  <button class="ghost" id="save-track">Save and track this portfolio</button>
271
  <button class="ghost" id="rerun">New analysis</button>
 
266
  <footer class="card footer">
267
  <div class="footer-actions">
268
  <a id="download" class="primary" href="#" download>Download the full report (PDF)</a>
269
+ <a id="download-print" class="ghost" href="#" download>Print version (light PDF)</a>
270
  <a id="audit" class="ghost" href="#" download>Audit trail (JSON)</a>
271
  <button class="ghost" id="save-track">Save and track this portfolio</button>
272
  <button class="ghost" id="rerun">New analysis</button>
tests/test_recommend.py CHANGED
@@ -355,3 +355,23 @@ def test_shortlist_covers_the_missing_sectors_first():
355
  O._ensure_single_names.needs = None
356
  tickers = [a["ticker"] for a in out]
357
  assert tickers[:3] == ["TSM", "NOC", "SHW"] and "EXC" in tickers
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
355
  O._ensure_single_names.needs = None
356
  tickers = [a["ticker"] for a in out]
357
  assert tickers[:3] == ["TSM", "NOC", "SHW"] and "EXC" in tickers
358
+
359
+
360
+ def test_pdf_print_theme_is_light_and_the_palette_resets():
361
+ from src import pdf_report as PR
362
+ res = {"generated_at": "2026-11-19", "health_score": 55, "verdict": "A test book.", "holdings": [],
363
+ "highlights": [{"severity": "good", "title": "t", "detail": "d", "lens": "risk"}],
364
+ "action_counts": {"Keep": 1}, "disclaimer": "Educational."}
365
+ dark = PR.build_pdf(res)
366
+ light = PR.build_pdf(res, theme="print")
367
+ assert dark[:4] == b"%PDF" and light[:4] == b"%PDF" and dark != light
368
+ assert PR._THEME == "dark" and PR.BG is not None # module palette restored after a print build
369
+ from fastapi.testclient import TestClient
370
+ import app as A
371
+ A._runs["themetest01"] = {"result": res}
372
+ try:
373
+ r = TestClient(A.app).get("/api/report/themetest01?theme=print")
374
+ assert r.status_code == 200 and r.headers["content-type"] == "application/pdf"
375
+ assert "-print.pdf" in r.headers["content-disposition"]
376
+ finally:
377
+ A._runs.pop("themetest01", None)