add PDF export (FR10)
pdf_export.py builds a PDF report (summary stats, AGP chart, hypo/hyper event summaries) via fpdf2 + matplotlib rather than plotly's kaleido, to avoid bundling a Chromium build into the image just for this. The Export page lets the user pick which sections to include and a date range, then download the result to send to the hospital team. This completes all ten functional requirements in docs/requirements-reporting.md. Co-Authored-By: Claude Sonnet 5 <[email protected]>
This commit is contained in:
@@ -0,0 +1,52 @@
|
|||||||
|
import requests
|
||||||
|
import streamlit as st
|
||||||
|
|
||||||
|
from auth import require_auth
|
||||||
|
from nightscout_client import NightscoutConfigError
|
||||||
|
from pdf_export import AVAILABLE_SECTIONS, SECTION_EVENTS, build_report_pdf
|
||||||
|
from reporting import HIGH, LOW, VERY_HIGH, VERY_LOW, detect_events, summarize_events
|
||||||
|
from ui_common import load_range_data, select_period_days
|
||||||
|
|
||||||
|
st.set_page_config(page_title="Glucose dashboard — Export", page_icon="📊", layout="wide")
|
||||||
|
require_auth()
|
||||||
|
|
||||||
|
st.title("Export")
|
||||||
|
st.caption("Stel een PDF-rapport samen om naar het diabetesteam te sturen (FR10).")
|
||||||
|
|
||||||
|
start, end, days = select_period_days(default_label="90 dagen")
|
||||||
|
sections = st.multiselect("Onderdelen", AVAILABLE_SECTIONS, default=AVAILABLE_SECTIONS)
|
||||||
|
|
||||||
|
try:
|
||||||
|
glucose, _treatments = load_range_data(start, end)
|
||||||
|
except NightscoutConfigError as exc:
|
||||||
|
st.error(str(exc))
|
||||||
|
st.stop()
|
||||||
|
except (requests.RequestException, ValueError) as exc:
|
||||||
|
st.error(f"Kon geen data ophalen van Nightscout: {exc}")
|
||||||
|
st.stop()
|
||||||
|
|
||||||
|
if glucose.empty:
|
||||||
|
st.info("Geen glucosemetingen gevonden in deze periode.")
|
||||||
|
st.stop()
|
||||||
|
|
||||||
|
events_summary = {}
|
||||||
|
if SECTION_EVENTS in sections:
|
||||||
|
levels = {
|
||||||
|
f"Hypo Level 1 (<{LOW})": (LOW, "below"),
|
||||||
|
f"Hypo Level 2 (<{VERY_LOW})": (VERY_LOW, "below"),
|
||||||
|
f"Hyper Level 1 (>{HIGH})": (HIGH, "above"),
|
||||||
|
f"Hyper Level 2 (>{VERY_HIGH})": (VERY_HIGH, "above"),
|
||||||
|
}
|
||||||
|
for label, (threshold, direction) in levels.items():
|
||||||
|
events = detect_events(glucose, threshold, direction)
|
||||||
|
events_summary[label] = summarize_events(events, days)
|
||||||
|
|
||||||
|
pdf_bytes = build_report_pdf(sections, glucose, events_summary, start, end)
|
||||||
|
|
||||||
|
st.download_button(
|
||||||
|
"Download PDF",
|
||||||
|
data=pdf_bytes,
|
||||||
|
file_name=f"glucoserapport_{start.strftime('%Y%m%d')}_{end.strftime('%Y%m%d')}.pdf",
|
||||||
|
mime="application/pdf",
|
||||||
|
)
|
||||||
|
st.caption(f"Periode: {start.strftime('%d-%m-%Y')} t/m {end.strftime('%d-%m-%Y')}")
|
||||||
+134
@@ -0,0 +1,134 @@
|
|||||||
|
"""
|
||||||
|
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 (
|
||||||
|
agp_percentile_bands,
|
||||||
|
gmi_percent,
|
||||||
|
percent_cv,
|
||||||
|
sensor_active_percent,
|
||||||
|
tir_breakdown_5band,
|
||||||
|
)
|
||||||
|
|
||||||
|
SECTION_SUMMARY = "Samenvatting"
|
||||||
|
SECTION_AGP = "AGP profiel"
|
||||||
|
SECTION_EVENTS = "Hypo-/hyperevents"
|
||||||
|
|
||||||
|
AVAILABLE_SECTIONS = [SECTION_SUMMARY, SECTION_AGP, SECTION_EVENTS]
|
||||||
|
|
||||||
|
_LINE_KWARGS = {"new_x": XPos.LMARGIN, "new_y": YPos.NEXT}
|
||||||
|
|
||||||
|
|
||||||
|
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")
|
||||||
|
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 _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)
|
||||||
|
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(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_events_section(pdf: FPDF, 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(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_EVENTS in sections and events_summary:
|
||||||
|
_add_events_section(pdf, events_summary)
|
||||||
|
|
||||||
|
return bytes(pdf.output())
|
||||||
@@ -3,5 +3,7 @@ pandas>=2.2,<3.0
|
|||||||
requests>=2.32,<3.0
|
requests>=2.32,<3.0
|
||||||
plotly>=5.24,<6.0
|
plotly>=5.24,<6.0
|
||||||
python-dotenv>=1.0,<2.0
|
python-dotenv>=1.0,<2.0
|
||||||
|
matplotlib>=3.9,<4.0
|
||||||
|
fpdf2>=2.7,<3.0
|
||||||
pytest>=8.0,<9.0
|
pytest>=8.0,<9.0
|
||||||
ruff>=0.6,<1.0
|
ruff>=0.6,<1.0
|
||||||
|
|||||||
@@ -0,0 +1,41 @@
|
|||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import pandas as pd
|
||||||
|
|
||||||
|
from pdf_export import SECTION_AGP, SECTION_EVENTS, SECTION_SUMMARY, build_report_pdf
|
||||||
|
|
||||||
|
|
||||||
|
def _sample_glucose():
|
||||||
|
timestamps = pd.date_range("2026-01-01", periods=48, freq="30min")
|
||||||
|
return pd.DataFrame({"timestamp": timestamps, "mmol": [6.0 + (i % 5) for i in range(48)]})
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_produces_valid_pdf_bytes():
|
||||||
|
glucose = _sample_glucose()
|
||||||
|
events_summary = {
|
||||||
|
"Hypo Level 1": {"count": 2, "avg_duration_minutes": 20.0, "events_per_week": 1.0},
|
||||||
|
}
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_SUMMARY, SECTION_AGP, SECTION_EVENTS],
|
||||||
|
glucose,
|
||||||
|
events_summary,
|
||||||
|
date(2026, 1, 1),
|
||||||
|
date(2026, 1, 2),
|
||||||
|
)
|
||||||
|
assert isinstance(pdf_bytes, bytes)
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
assert len(pdf_bytes) > 500
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_handles_empty_glucose():
|
||||||
|
empty = pd.DataFrame(columns=["timestamp", "mmol"])
|
||||||
|
pdf_bytes = build_report_pdf(
|
||||||
|
[SECTION_SUMMARY, SECTION_AGP], empty, {}, date(2026, 1, 1), date(2026, 1, 2)
|
||||||
|
)
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
|
|
||||||
|
|
||||||
|
def test_build_report_pdf_handles_no_sections_selected():
|
||||||
|
glucose = _sample_glucose()
|
||||||
|
pdf_bytes = build_report_pdf([], glucose, {}, date(2026, 1, 1), date(2026, 1, 2))
|
||||||
|
assert pdf_bytes.startswith(b"%PDF")
|
||||||
Reference in New Issue
Block a user