Files
Data_Visualisation_DMH/backend/scripts/generate_pdf_doc.py
T

296 lines
21 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import os
import sys
from pathlib import Path
from reportlab.lib.pagesizes import A4
from reportlab.lib import colors
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import (
SimpleDocTemplate, Paragraph, Spacer, Table, TableStyle, PageBreak, KeepTogether, HRFlowable
)
from reportlab.pdfgen import canvas
class NumberedCanvas(canvas.Canvas):
"""Two-pass canvas to dynamically compute and print 'Page X of Y'."""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self._saved_page_states = []
def showPage(self):
self._saved_page_states.append(dict(self.__dict__))
self._startPage()
def save(self):
num_pages = len(self._saved_page_states)
for state in self._saved_page_states:
self.__dict__.update(state)
self.draw_page_number(num_pages)
canvas.Canvas.showPage(self)
canvas.Canvas.save(self)
def draw_page_number(self, page_count):
self.saveState()
self.setFont("Helvetica", 8)
self.setFillColor(colors.HexColor("#64748B"))
# Header (on pages > 1)
if self._pageNumber > 1:
self.drawString(36, 810, "DMH Hospital Data Visualisation Platform — System Documentation")
self.setStrokeColor(colors.HexColor("#E2E8F0"))
self.setLineWidth(0.5)
self.line(36, 804, 559, 804)
# Footer
page_str = f"Page {self._pageNumber} of {page_count}"
self.drawRightString(559, 25, page_str)
self.drawString(36, 25, "Confidential — Deenanath Mangeshkar Hospital (DMH)")
self.setStrokeColor(colors.HexColor("#E2E8F0"))
self.setLineWidth(0.5)
self.line(36, 35, 559, 35)
self.restoreState()
def build_pdf(output_path: str):
doc = SimpleDocTemplate(
output_path,
pagesize=A4,
leftMargin=36,
rightMargin=36,
topMargin=46,
bottomMargin=46
)
styles = getSampleStyleSheet()
# Custom palette
c_primary = colors.HexColor("#1E3A8A") # Navy Blue
c_secondary = colors.HexColor("#0284C7") # Hospital Sky Blue
c_dark = colors.HexColor("#0F172A") # Slate Dark
c_text = colors.HexColor("#334155") # Body text
c_light = colors.HexColor("#F8FAFC") # Table BG
c_border = colors.HexColor("#CBD5E1") # Border
c_success = colors.HexColor("#16A34A") # Green
c_warning = colors.HexColor("#D97706") # Amber
# Typography styles
styles.add(ParagraphStyle('DocTitle', parent=styles['Heading1'], fontName='Helvetica-Bold', fontSize=22, leading=26, textColor=c_primary, spaceAfter=4))
styles.add(ParagraphStyle('DocSubtitle', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=11, leading=14, textColor=c_secondary, spaceAfter=12))
styles.add(ParagraphStyle('SectionHeading', parent=styles['Heading2'], fontName='Helvetica-Bold', fontSize=13, leading=16, textColor=c_primary, spaceBefore=12, spaceAfter=6, keepWithNext=True))
styles.add(ParagraphStyle('SubSectionHeading', parent=styles['Heading3'], fontName='Helvetica-Bold', fontSize=10.5, leading=13, textColor=c_dark, spaceBefore=8, spaceAfter=4, keepWithNext=True))
styles.add(ParagraphStyle('BodyCustom', parent=styles['Normal'], fontName='Helvetica', fontSize=8.5, leading=12, textColor=c_text, spaceAfter=5))
styles.add(ParagraphStyle('BodyBold', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=8.5, leading=12, textColor=c_dark, spaceAfter=5))
styles.add(ParagraphStyle('Callout', parent=styles['Normal'], fontName='Helvetica-Oblique', fontSize=8.5, leading=12, textColor=colors.HexColor("#1E293B"), spaceBefore=4, spaceAfter=6))
styles.add(ParagraphStyle('TableHeader', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=8, leading=10, textColor=colors.white, alignment=1))
styles.add(ParagraphStyle('TableCell', parent=styles['Normal'], fontName='Helvetica', fontSize=7.8, leading=10, textColor=c_dark))
styles.add(ParagraphStyle('TableCellBold', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=7.8, leading=10, textColor=c_dark))
styles.add(ParagraphStyle('BadgeSuccess', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=7.5, leading=9, textColor=c_success, alignment=1))
styles.add(ParagraphStyle('BadgePending', parent=styles['Normal'], fontName='Helvetica-Bold', fontSize=7.5, leading=9, textColor=c_warning, alignment=1))
story = []
# 1. Title Banner
story.append(Paragraph("DMH Role-Based Data Visualisation Platform", styles['DocTitle']))
story.append(Paragraph("System Architecture, Delivered Modules & Comprehensive Project Roadmap", styles['DocSubtitle']))
story.append(HRFlowable(width="100%", thickness=1.5, color=c_secondary, spaceBefore=0, spaceAfter=10))
# Meta Info Table
meta_data = [
[Paragraph("<b>Target Organisation:</b> Deenanath Mangeshkar Hospital (DMH), Pune", styles['TableCell']),
Paragraph("<b>Date:</b> 24 November 2026", styles['TableCell'])],
[Paragraph("<b>Initial Dataset:</b> admissionData-2025_v1.csv (86,099 rows, 19 fields)", styles['TableCell']),
Paragraph("<b>Status:</b> Phases 1–3 Complete (25/25 Tests Passing)", styles['TableCell'])],
[Paragraph("<b>Tech Stack:</b> FastAPI, SQLAlchemy 2.0 Core, React 18, Apache ECharts", styles['TableCell']),
Paragraph("<b>Lead:</b> AI Engineering Team", styles['TableCell'])]
]
meta_table = Table(meta_data, colWidths=[270, 253])
meta_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,-1), c_light),
('BOX', (0,0), (-1,-1), 0.5, c_border),
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
('TOPPADDING', (0,0), (-1,-1), 4),
('BOTTOMPADDING', (0,0), (-1,-1), 4),
]))
story.append(meta_table)
story.append(Spacer(1, 10))
# 2. Executive Summary
story.append(Paragraph("1. Executive Summary & Background", styles['SectionHeading']))
p1 = ("Healthcare organisations manage high-volume operational and clinical records. Historically, this data is either "
"circulated via raw spreadsheets (causing privacy risks, version confusion, and non-compliance) or locked behind one-off "
"manual reports built by developers (which are expensive and slow). "
"This platform provides a governed, self-service visualization hub where a <b>Super Admin</b> configures exact permissions, "
"and departmental users log in to see interactive charts limited strictly to their permitted data.")
story.append(Paragraph(p1, styles['BodyCustom']))
# 3. The One Rule That Matters Most
story.append(Paragraph("2. The One Rule That Matters Most (Zero Data Leakage)", styles['SectionHeading']))
rule_box_data = [[
Paragraph("<b>THE CRUCIAL SECURITY RULE:</b><br/>"
"The browser must never receive data the user is not allowed to see. All permission checks, column masking, "
"and aggregations happen on the backend. The frontend client sends a declarative JSON chart specification, "
"never SQL. The backend validates it against a strict whitelist, applies user/role row-level rules, runs an "
"aggregated query via SQLAlchemy Core with bound parameters, and returns only the mathematical summary result.",
styles['Callout'])
]]
rule_table = Table(rule_box_data, colWidths=[523])
rule_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,-1), colors.HexColor("#EFF6FF")),
('BOX', (0,0), (-1,-1), 1, c_secondary),
('TOPPADDING', (0,0), (-1,-1), 6),
('BOTTOMPADDING', (0,0), (-1,-1), 6),
('LEFTPADDING', (0,0), (-1,-1), 10),
('RIGHTPADDING', (0,0), (-1,-1), 10),
]))
story.append(rule_table)
story.append(Spacer(1, 8))
# 4. Tech Stack Table
story.append(Paragraph("3. Technology Stack & Architectural Decisions", styles['SectionHeading']))
tech_data = [
[Paragraph("Layer", styles['TableHeader']), Paragraph("Technology", styles['TableHeader']), Paragraph("Architectural Rationale & Implementation", styles['TableHeader'])],
[Paragraph("Backend API", styles['TableCellBold']), Paragraph("FastAPI (Python 3.11+)", styles['TableCell']), Paragraph("Async endpoints, Pydantic v2 data validation, OpenAPI autodoc", styles['TableCell'])],
[Paragraph("Data Engine", styles['TableCellBold']), Paragraph("SQLAlchemy 2.0 Core", styles['TableCell']), Paragraph("Dynamic typed table reflections, parameter binding, whitelisting (Zero f-string SQL)", styles['TableCell'])],
[Paragraph("Migrations", styles['TableCellBold']), Paragraph("Alembic", styles['TableCell']), Paragraph("System schema versioning; dynamic data tables (ds_*) excluded cleanly", styles['TableCell'])],
[Paragraph("Auth & Crypto", styles['TableCellBold']), Paragraph("Argon2-cffi + PyJWT", styles['TableCell']), Paragraph("GPU-resistant password hashing; 8-hour stateless signed JWT tokens", styles['TableCell'])],
[Paragraph("Database", styles['TableCellBold']), Paragraph("PostgreSQL 16 / SQLite", styles['TableCell']), Paragraph("Postgres for production; zero-dependency SQLite for fast isolated unit tests", styles['TableCell'])],
[Paragraph("Frontend UI", styles['TableCellBold']), Paragraph("React 18 + TypeScript + Vite", styles['TableCell']), Paragraph("Type-safe SPA with strict compilation checks (no unused locals/params)", styles['TableCell'])],
[Paragraph("Visualisations", styles['TableCellBold']), Paragraph("Apache ECharts (React)", styles['TableCell']), Paragraph("High-performance canvas/SVG charts with responsive resize and custom DMH palette", styles['TableCell'])],
[Paragraph("Deployment", styles['TableCellBold']), Paragraph("Docker Compose + Nginx", styles['TableCell']), Paragraph("Reverse proxy, asset compression, multi-container orchestration", styles['TableCell'])]
]
tech_table = Table(tech_data, colWidths=[80, 130, 313])
tech_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,0), c_primary),
('BOX', (0,0), (-1,-1), 0.5, c_border),
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, c_light]),
('TOPPADDING', (0,0), (-1,-1), 3.5),
('BOTTOMPADDING', (0,0), (-1,-1), 3.5),
]))
story.append(tech_table)
story.append(Spacer(1, 10))
# 5. What Has Been Developed (Phases 1-3)
story.append(Paragraph("4. Modules Currently Developed & Verified (Phases 1, 2 & 3)", styles['SectionHeading']))
story.append(Paragraph("A. Authentication & User Management (Phase 1)", styles['SubSectionHeading']))
story.append(Paragraph("• Implemented Argon2id password hashing and PyJWT token generation.<br/>"
"• Established 4-role RBAC hierarchy: Super Admin, Viewer, Department Manager, and Finance User.<br/>"
"• Built Super Admin user management CRUD (/api/v1/users) with full 403 Forbidden enforcement for non-admin requests.", styles['BodyCustom']))
story.append(Paragraph("B. Data Ingestion & Schema Registration (Phase 1)", styles['SubSectionHeading']))
story.append(Paragraph("• Ingested all <b>86,099 rows and 19 fields</b> from <code>admissionData-2025_v1.csv</code> into <code>ds_hospital_admissions_2025</code>.<br/>"
"• Robust parsing of <code>DD-MM-YYYY HH:MM</code> timestamps into real database <code>DATETIME</code> types.<br/>"
"• Automatic sensitive column tagging: direct patient identifiers (<code>mrdNumber</code>) and doctor names flagged as sensitive by default; <code>bedNumber</code> handled as text.", styles['BodyCustom']))
story.append(Paragraph("C. Access Control Matrix & Rule Intersection (Phase 2)", styles['SubSectionHeading']))
story.append(Paragraph("• Three-tiered access control: Dataset grants, Column masking, and Row-level filter rules.<br/>"
"• Mathematical AND-rule intersection: users inherit all applicable role and user-specific constraints.<br/>"
"• Super Admin <b>'Preview As' Simulation Tool</b>: Allows administrators to simulate restricted roles (Medicine only, TPA only) with instant live UI re-rendering.", styles['BodyCustom']))
story.append(Paragraph("D. Declarative Query & Aggregation Engine (Phase 3)", styles['SubSectionHeading']))
story.append(Paragraph("• Accepts client JSON <code>ChartSpec</code>, verifies whitelist, injects parameterized WHERE clauses.<br/>"
"• Rejects restricted dimensions/measures with HTTP 403. Executes aggregations (COUNT, SUM, AVG) via SQLAlchemy Core.", styles['BodyCustom']))
story.append(Paragraph("E. Interactive Apache ECharts Dashboard (Phase 3)", styles['SubSectionHeading']))
story.append(Paragraph("• <b>4 Executive KPIs:</b> Total Admissions, Average Patient Age, Active Clinical Specialities, Hospital Wings.<br/>"
"• <b>5 Core Charts:</b> Admissions by Medical Speciality (Bar), Hospital Building Breakdown (Donut), Monthly Volume Trend (Area), Admission Categories (Pie), and Patient Payer Mix & Demographics (Stacked Bar).<br/>"
"• <b>Dynamic Filter Bar:</b> Permission-scoped dropdowns for Building, Speciality, and Admission Type.", styles['BodyCustom']))
story.append(Spacer(1, 8))
# 6. Live Ingested Dataset Verification Table
story.append(Paragraph("5. Live Dataset Verification Metrics (86,099 Records)", styles['SectionHeading']))
verif_data = [
[Paragraph("Role / Persona", styles['TableHeader']), Paragraph("Enforced Access Boundaries", styles['TableHeader']), Paragraph("Verified Output Metric", styles['TableHeader']), Paragraph("Status", styles['TableHeader'])],
[Paragraph("Super Admin", styles['TableCellBold']), Paragraph("Unrestricted hospital-wide access", styles['TableCell']), Paragraph("<b>86,099</b> admissions across all 19 columns", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
[Paragraph("Top Specialities", styles['TableCellBold']), Paragraph("Hospital rankings (Unrestricted)", styles['TableCell']), Paragraph("Oncology: 18,536 | Medicine: 9,770 | Eye: 5,366", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
[Paragraph("Department Manager", styles['TableCellBold']), Paragraph("Row rule: Speciality = 'MEDICINE'", styles['TableCell']), Paragraph("<b>9,770</b> admissions (Non-Medicine rows excluded)", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
[Paragraph("Finance User", styles['TableCellBold']), Paragraph("Row rule: PatientCategory = 'TPA'", styles['TableCell']), Paragraph("<b>32,056</b> claims (Cash/GNL rows excluded)", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
[Paragraph("Restricted Viewer", styles['TableCellBold']), Paragraph("Column masking (mrdNumber, Doctor)", styles['TableCell']), Paragraph("HTTP 403 Forbidden on sensitive fields", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
[Paragraph("Automated Tests", styles['TableCellBold']), Paragraph("Pytest test suite (backend/tests)", styles['TableCell']), Paragraph("<b>25/25 unit tests passing</b> (7.27 seconds)", styles['TableCell']), Paragraph("PASSED", styles['BadgeSuccess'])],
]
verif_table = Table(verif_data, colWidths=[95, 145, 203, 80])
verif_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,0), c_primary),
('BOX', (0,0), (-1,-1), 0.5, c_border),
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, c_light]),
('TOPPADDING', (0,0), (-1,-1), 3),
('BOTTOMPADDING', (0,0), (-1,-1), 3),
]))
story.append(verif_table)
story.append(Spacer(1, 10))
# 7. What is Remaining (Roadmap)
story.append(Paragraph("6. Remaining Roadmap & Planned Enhancements", styles['SectionHeading']))
plan_data = [
[Paragraph("Phase", styles['TableHeader']), Paragraph("Module Title", styles['TableHeader']), Paragraph("Scope & Planned Functionality", styles['TableHeader']), Paragraph("Status", styles['TableHeader'])],
[Paragraph("Phase 3.5", styles['TableCellBold']),
Paragraph("Advanced Healthcare Analytics & Cross-Filtering", styles['TableCell']),
Paragraph("• <b>Average Length of Stay (ALOS):</b> Days calculation per department.<br/>"
"• <b>24x7 Day-vs-Hour Surge Heatmap:</b> Emergency surge hours visualization.<br/>"
"• <b>Geographic Breakdown:</b> In-state vs out-of-state and district spread.<br/>"
"• <b>Cross-Filtering:</b> Click-to-filter across all dashboard widgets.<br/>"
"• <b>Image Exports:</b> High-resolution PNG/SVG chart export via ECharts.", styles['TableCell']),
Paragraph("READY TO BUILD", styles['BadgePending'])],
[Paragraph("Phase 4", styles['TableCellBold']),
Paragraph("Governance, Compliance & Export Engine", styles['TableCell']),
Paragraph("• <b>Tamper-Evident Audit Logging:</b> Log user logins, queries, permission edits.<br/>"
"• <b>Admin Audit Viewer:</b> Searchable audit trail (/admin/audit-logs).<br/>"
"• <b>India DPDP Act Compliance:</b> Small-group suppression (k &lt; 5 patients).<br/>"
"• <b>Role-Gated Data Exports:</b> Watermarked Excel/CSV export gated by can_export.", styles['TableCell']),
Paragraph("SCHEDULED", styles['BadgePending'])],
[Paragraph("Phase 5", styles['TableCellBold']),
Paragraph("Live Enterprise Connectors & Deployment", styles['TableCell']),
Paragraph("• <b>External Database Connectors:</b> Direct PostgreSQL, MySQL, SQL Server.<br/>"
"• <b>Encrypted Credentials:</b> Symmetric Fernet encryption for connection strings.<br/>"
"• <b>Aggregation Caching:</b> Redis / In-memory caching for sub-50ms query responses.<br/>"
"• <b>Docker Compose Hardening:</b> Production Nginx reverse proxy & containers.", styles['TableCell']),
Paragraph("SCHEDULED", styles['BadgePending'])],
]
plan_table = Table(plan_data, colWidths=[65, 125, 253, 80])
plan_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,0), c_primary),
('BOX', (0,0), (-1,-1), 0.5, c_border),
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, c_light]),
('TOPPADDING', (0,0), (-1,-1), 4),
('BOTTOMPADDING', (0,0), (-1,-1), 4),
]))
story.append(plan_table)
story.append(Spacer(1, 10))
# 8. Demo Credentials & How to Run
story.append(Paragraph("7. Execution Guide & Demo Accounts", styles['SectionHeading']))
creds_data = [
[Paragraph("Role", styles['TableHeader']), Paragraph("Username", styles['TableHeader']), Paragraph("Password", styles['TableHeader']), Paragraph("Enforced Data Scope", styles['TableHeader'])],
[Paragraph("Super Admin", styles['TableCellBold']), Paragraph("admin", styles['TableCell']), Paragraph("Admin@123456", styles['TableCell']), Paragraph("Unrestricted hospital-wide access (86,099 rows)", styles['TableCell'])],
[Paragraph("Staff Viewer", styles['TableCellBold']), Paragraph("viewer", styles['TableCell']), Paragraph("Viewer@123456", styles['TableCell']), Paragraph("General view; sensitive doctor and MRN masked", styles['TableCell'])],
[Paragraph("Dept Manager", styles['TableCellBold']), Paragraph("dept_manager", styles['TableCell']), Paragraph("Manager@123456", styles['TableCell']), Paragraph("Medicine department admissions only (9,770 rows)", styles['TableCell'])],
[Paragraph("Finance Analyst", styles['TableCellBold']), Paragraph("finance_user", styles['TableCell']), Paragraph("Finance@123456", styles['TableCell']), Paragraph("TPA insurance claims only (32,056 rows)", styles['TableCell'])],
]
creds_table = Table(creds_data, colWidths=[90, 80, 95, 258])
creds_table.setStyle(TableStyle([
('BACKGROUND', (0,0), (-1,0), c_primary),
('BOX', (0,0), (-1,-1), 0.5, c_border),
('INNERGRID', (0,0), (-1,-1), 0.5, colors.HexColor("#E2E8F0")),
('ROWBACKGROUNDS', (0,1), (-1,-1), [colors.white, c_light]),
('TOPPADDING', (0,0), (-1,-1), 3),
('BOTTOMPADDING', (0,0), (-1,-1), 3),
]))
story.append(creds_table)
# Build PDF with custom numbered canvas
doc.build(story, canvasmaker=NumberedCanvas)
print(f"PDF successfully built at: {output_path}")
if __name__ == "__main__":
out_dir = Path(__file__).resolve().parent.parent.parent / "docs"
out_dir.mkdir(parents=True, exist_ok=True)
out_file = str(out_dir / "DMH_Role_Based_Data_Visualisation_Platform_Documentation.pdf")
build_pdf(out_file)