285 lines
10 KiB
Python
285 lines
10 KiB
Python
"""
|
|
PDF-rapportgeneratie voor geselecteerde rapportageonderdelen (FR10).
|
|
|
|
Gebruikt fpdf2 (puur Python, geen systeemdependencies) voor de PDF-opbouw en
|
|
matplotlib voor een eenvoudige statische AGP-grafiek specifiek voor de PDF —
|
|
bewust niet dezelfde Plotly-figuren als op de pagina's zelf (die zouden
|
|
kaleido vereisen, met een ingebakken Chromium-build: een groter image en meer
|
|
Trivy-oppervlak, voor dit doel niet nodig).
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import io
|
|
|
|
import matplotlib
|
|
|
|
matplotlib.use("Agg")
|
|
import matplotlib.pyplot as plt
|
|
import pandas as pd
|
|
from fpdf import FPDF
|
|
from fpdf.enums import XPos, YPos
|
|
|
|
from reporting import (
|
|
HIGH,
|
|
LOW,
|
|
VERY_HIGH,
|
|
VERY_LOW,
|
|
agp_percentile_bands,
|
|
completeness_warning,
|
|
detect_events,
|
|
gmi_percent,
|
|
percent_cv,
|
|
sensor_active_percent,
|
|
tir_breakdown_5band,
|
|
)
|
|
|
|
SECTION_SUMMARY = "Samenvatting"
|
|
SECTION_AGP = "AGP profiel"
|
|
SECTION_DAGOVERZICHT = "Dagoverzicht"
|
|
SECTION_EVENTS = "Hypo-/hyperevents"
|
|
|
|
AVAILABLE_SECTIONS = [SECTION_SUMMARY, SECTION_AGP, SECTION_DAGOVERZICHT, SECTION_EVENTS]
|
|
|
|
_LINE_KWARGS = {"new_x": XPos.LMARGIN, "new_y": YPos.NEXT}
|
|
|
|
# Zelfde kleuren als het PALETTE["light"] in ui_common.py — bewust hier
|
|
# gedupliceerd (5 hex-waarden) in plaats van ui_common.py te importeren, want
|
|
# dat zou een streamlit-dependency in deze module trekken die verder bewust
|
|
# vrij van UI-framework-imports is (los te unit-testen, zie moduledocstring).
|
|
_MUTED = "#898781"
|
|
_TIR_BAND_ORDER = ["very_low", "low", "in_range", "high", "very_high"]
|
|
_TIR_BAND_LABELS = {
|
|
"very_low": "Zeer laag",
|
|
"low": "Laag",
|
|
"in_range": "In bereik",
|
|
"high": "Hoog",
|
|
"very_high": "Zeer hoog",
|
|
}
|
|
_TIR_COLORS = {
|
|
"very_low": "#8b1a1a",
|
|
"low": "#d03b3b",
|
|
"in_range": "#0ca30c",
|
|
"high": "#fab219",
|
|
"very_high": "#c76f0a",
|
|
}
|
|
_THRESHOLD_LINES = [VERY_LOW, LOW, HIGH, VERY_HIGH]
|
|
DAGOVERZICHT_MAX_DAYS = 14
|
|
|
|
|
|
def _add_threshold_lines(ax) -> None:
|
|
"""Teken de 4 klinische drempellijnen (3.0/3.9/10.0/13.9 mmol/L) op een matplotlib-as.
|
|
|
|
PDF-tegenhanger van ui_common.add_threshold_lines() voor de Plotly-versie
|
|
op de dashboardpagina's (gitea #15) — zelfde 4 waarden, zelfde grijstint.
|
|
"""
|
|
for value in _THRESHOLD_LINES:
|
|
ax.axhline(value, color=_MUTED, linewidth=0.7, linestyle=":")
|
|
|
|
|
|
def _agp_figure_png(glucose: pd.DataFrame) -> bytes:
|
|
bands = agp_percentile_bands(glucose)
|
|
fig, ax = plt.subplots(figsize=(7, 3))
|
|
hours = bands["minute_of_day"] / 60
|
|
ax.fill_between(hours, bands["p5"], bands["p95"], alpha=0.15, color="#2a78d6", label="5e-95e pct")
|
|
ax.fill_between(hours, bands["p25"], bands["p75"], alpha=0.3, color="#2a78d6", label="25e-75e pct")
|
|
ax.plot(hours, bands["p50"], color="#2a78d6", linewidth=2, label="Mediaan")
|
|
_add_threshold_lines(ax)
|
|
ax.set_xlabel("Uur van de dag")
|
|
ax.set_ylabel("mmol/L")
|
|
ax.set_xlim(0, 24)
|
|
ax.legend(loc="upper right", fontsize=8)
|
|
fig.tight_layout()
|
|
|
|
buf = io.BytesIO()
|
|
fig.savefig(buf, format="png", dpi=150)
|
|
plt.close(fig)
|
|
buf.seek(0)
|
|
return buf.getvalue()
|
|
|
|
|
|
def _tir_bar_figure_png(tir: dict) -> bytes:
|
|
"""Gestapelde staafgrafiek van de 5 TIR-banden — PDF-tegenhanger van
|
|
ui_common.build_tir_stacked_bar_figure() (gitea #14)."""
|
|
fig, ax = plt.subplots(figsize=(7, 1.1))
|
|
left = 0.0
|
|
for band in _TIR_BAND_ORDER:
|
|
value = tir[band]
|
|
ax.barh(0, value, left=left, color=_TIR_COLORS[band], label=_TIR_BAND_LABELS[band])
|
|
left += value
|
|
ax.set_xlim(0, 100)
|
|
ax.set_yticks([])
|
|
ax.set_xlabel("%")
|
|
ax.legend(loc="upper center", bbox_to_anchor=(0.5, -0.75), ncol=5, fontsize=7, frameon=False)
|
|
|
|
buf = io.BytesIO()
|
|
# bbox_inches="tight" i.p.v. fig.tight_layout(): de legend zit buiten de
|
|
# axes (bbox_to_anchor met negatieve y), waar tight_layout() niet voor
|
|
# kan compenseren — savefig's eigen bbox-berekening kan dat wel.
|
|
fig.savefig(buf, format="png", dpi=150, bbox_inches="tight")
|
|
plt.close(fig)
|
|
buf.seek(0)
|
|
return buf.getvalue()
|
|
|
|
|
|
def _daily_figure_png(day_df: pd.DataFrame, day_label: str) -> bytes:
|
|
"""Eén dag als kleine lijngrafiek — PDF-tegenhanger van de Dagoverzicht-pagina (gitea #16)."""
|
|
hours = day_df["timestamp"].dt.hour + day_df["timestamp"].dt.minute / 60
|
|
fig, ax = plt.subplots(figsize=(7, 1.4))
|
|
ax.plot(hours, day_df["mmol"], color="#2a78d6", linewidth=1.2)
|
|
_add_threshold_lines(ax)
|
|
ax.set_xlim(0, 24)
|
|
ax.set_xticks(range(0, 25, 4))
|
|
ax.set_ylabel("mmol/L", fontsize=8)
|
|
ax.set_title(day_label, fontsize=9, loc="left")
|
|
ax.tick_params(labelsize=7)
|
|
fig.tight_layout()
|
|
|
|
buf = io.BytesIO()
|
|
fig.savefig(buf, format="png", dpi=150)
|
|
plt.close(fig)
|
|
buf.seek(0)
|
|
return buf.getvalue()
|
|
|
|
|
|
def _event_hour_histogram_png(events: pd.DataFrame, color: str) -> bytes:
|
|
"""Aantal events per uur-van-de-dag — PDF-tegenhanger van render_event_level()'s
|
|
histogram op de Hypo/Hyper Events-pagina's (gitea #17, #18)."""
|
|
hour_counts = events["start"].dt.hour.value_counts().reindex(range(24), fill_value=0).sort_index()
|
|
fig, ax = plt.subplots(figsize=(7, 2))
|
|
ax.bar(hour_counts.index, hour_counts.to_numpy(), color=color)
|
|
ax.set_xlabel("Uur van de dag")
|
|
ax.set_ylabel("Aantal events")
|
|
ax.set_xlim(-0.5, 23.5)
|
|
ax.set_xticks(range(0, 24, 2))
|
|
fig.tight_layout()
|
|
|
|
buf = io.BytesIO()
|
|
fig.savefig(buf, format="png", dpi=150)
|
|
plt.close(fig)
|
|
buf.seek(0)
|
|
return buf.getvalue()
|
|
|
|
|
|
def _add_summary_section(pdf: FPDF, glucose: pd.DataFrame, start, end) -> None:
|
|
mean_mmol = glucose["mmol"].mean()
|
|
tir = tir_breakdown_5band(glucose)
|
|
active_pct = sensor_active_percent(glucose, start, end)
|
|
|
|
pdf.set_font("Helvetica", "B", 13)
|
|
pdf.cell(0, 8, "Samenvatting", **_LINE_KWARGS)
|
|
|
|
warning = completeness_warning(glucose, start, end)
|
|
if warning:
|
|
pdf.set_font("Helvetica", "BI", 10)
|
|
pdf.multi_cell(0, 5, warning)
|
|
pdf.ln(2)
|
|
|
|
pdf.set_font("Helvetica", "", 11)
|
|
pdf.cell(0, 6, f"Sensordekking: {active_pct:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Gemiddelde glucose: {mean_mmol:.1f} mmol/L", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Geschat HbA1c (GMI): {gmi_percent(mean_mmol):.1f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Variabiliteit (%CV): {percent_cv(glucose):.0f}%", **_LINE_KWARGS)
|
|
pdf.ln(2)
|
|
pdf.cell(0, 6, f"Zeer laag (<3.0 mmol/L): {tir['very_low']:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Laag (3.0-3.9 mmol/L): {tir['low']:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"In bereik (3.9-10.0 mmol/L): {tir['in_range']:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Hoog (10.0-13.9 mmol/L): {tir['high']:.0f}%", **_LINE_KWARGS)
|
|
pdf.cell(0, 6, f"Zeer hoog (>13.9 mmol/L): {tir['very_high']:.0f}%", **_LINE_KWARGS)
|
|
pdf.ln(2)
|
|
png_bytes = _tir_bar_figure_png(tir)
|
|
pdf.image(io.BytesIO(png_bytes), w=160)
|
|
pdf.ln(4)
|
|
|
|
|
|
def _add_agp_section(pdf: FPDF, glucose: pd.DataFrame) -> None:
|
|
pdf.set_font("Helvetica", "B", 13)
|
|
pdf.cell(0, 8, "AGP profiel", **_LINE_KWARGS)
|
|
png_bytes = _agp_figure_png(glucose)
|
|
pdf.image(io.BytesIO(png_bytes), w=180)
|
|
pdf.ln(4)
|
|
|
|
|
|
def _add_dagoverzicht_section(pdf: FPDF, glucose: pd.DataFrame) -> None:
|
|
"""Eén dagelijkse mini-grafiek per kalenderdag (gitea #16), max. de meest
|
|
recente DAGOVERZICHT_MAX_DAYS dagen — voor langere periodes zou de PDF
|
|
anders onwerkbaar lang worden."""
|
|
pdf.set_font("Helvetica", "B", 13)
|
|
pdf.cell(0, 8, "Dagoverzicht", **_LINE_KWARGS)
|
|
|
|
df = glucose.copy()
|
|
df["date"] = df["timestamp"].dt.date
|
|
dates = sorted(df["date"].unique())
|
|
if len(dates) > DAGOVERZICHT_MAX_DAYS:
|
|
dates = dates[-DAGOVERZICHT_MAX_DAYS:]
|
|
pdf.set_font("Helvetica", "I", 9)
|
|
pdf.cell(0, 5, f"Beperkt tot de meest recente {DAGOVERZICHT_MAX_DAYS} dagen.", **_LINE_KWARGS)
|
|
|
|
for day in dates:
|
|
day_df = df[df["date"] == day]
|
|
png_bytes = _daily_figure_png(day_df, day.strftime("%A %d-%m-%Y"))
|
|
pdf.image(io.BytesIO(png_bytes), w=180)
|
|
pdf.ln(4)
|
|
|
|
|
|
def _add_events_section(pdf: FPDF, glucose: pd.DataFrame, events_summary: dict[str, dict]) -> None:
|
|
pdf.set_font("Helvetica", "B", 13)
|
|
pdf.cell(0, 8, "Hypo-/hyperevents", **_LINE_KWARGS)
|
|
pdf.set_font("Helvetica", "", 11)
|
|
for label, summary in events_summary.items():
|
|
pdf.cell(
|
|
0,
|
|
6,
|
|
f"{label}: {summary['count']} events, gemiddeld {summary['avg_duration_minutes']:.0f} min, "
|
|
f"{summary['events_per_week']:.1f}/week",
|
|
**_LINE_KWARGS,
|
|
)
|
|
pdf.ln(2)
|
|
|
|
# Alleen Level 1 krijgt een grafiek in het PDF-rapport (gitea #17, #18) —
|
|
# geen tabel met losse events, de samenvattende cijfers staan al hierboven.
|
|
if not glucose.empty:
|
|
hypo_events = detect_events(glucose, LOW, "below")
|
|
if not hypo_events.empty:
|
|
pdf.image(io.BytesIO(_event_hour_histogram_png(hypo_events, _TIR_COLORS["low"])), w=180)
|
|
hyper_events = detect_events(glucose, HIGH, "above")
|
|
if not hyper_events.empty:
|
|
pdf.image(io.BytesIO(_event_hour_histogram_png(hyper_events, _TIR_COLORS["high"])), w=180)
|
|
|
|
pdf.ln(4)
|
|
|
|
|
|
def build_report_pdf(
|
|
sections: list[str],
|
|
glucose: pd.DataFrame,
|
|
events_summary: dict[str, dict],
|
|
start,
|
|
end,
|
|
) -> bytes:
|
|
"""Bouw een PDF met de geselecteerde onderdelen.
|
|
|
|
`events_summary` bevat vooraf berekende hypo/hyper-samenvattingen (label ->
|
|
resultaat van reporting.summarize_events), zodat deze module geen
|
|
event-detectie hoeft te herhalen.
|
|
"""
|
|
pdf = FPDF()
|
|
pdf.add_page()
|
|
pdf.set_font("Helvetica", "B", 16)
|
|
pdf.cell(0, 10, "Glucoserapport", **_LINE_KWARGS)
|
|
pdf.set_font("Helvetica", "", 11)
|
|
pdf.cell(0, 8, f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}", **_LINE_KWARGS)
|
|
pdf.ln(4)
|
|
|
|
if not glucose.empty:
|
|
if SECTION_SUMMARY in sections:
|
|
_add_summary_section(pdf, glucose, start, end)
|
|
if SECTION_AGP in sections:
|
|
_add_agp_section(pdf, glucose)
|
|
if SECTION_DAGOVERZICHT in sections:
|
|
_add_dagoverzicht_section(pdf, glucose)
|
|
|
|
if SECTION_EVENTS in sections and events_summary:
|
|
_add_events_section(pdf, glucose, events_summary)
|
|
|
|
return bytes(pdf.output())
|