import os import pikepdf import string from fpdf import FPDF # --- ROBUST CONFIG IMPORT --- try: from config import TEMP_DIR, VITE_PILOT_REGION except ImportError: TEMP_DIR = "temp_reports" VITE_PILOT_REGION = "AU_VIC" class ClinicalReport(FPDF): def __init__(self, access_key, region): super().__init__() self.access_key = access_key self.region = region def header(self): # 🛡️ Branded Header: Slate-900 Background self.set_fill_color(15, 23, 42) self.rect(0, 0, 210, 45, 'F') self.set_text_color(255, 255, 255) self.set_font('Helvetica', 'B', 20) self.set_xy(12, 12) # Dynamic Regional Title [cite: 2026-02-20, 2026-02-22] title = 'AU_VIC CLINICAL PROFILE' if self.region == "AU_VIC" else 'NEP 2020 HOLISTIC PROGRESS' self.cell(0, 10, title, 0, 1, 'L') self.set_font('Helvetica', '', 9) self.set_text_color(148, 163, 184) subtitle = "Clinical Screening Artifact" if self.region == "AU_VIC" else "FLN Biometric Summary" self.cell(0, 5, f"{subtitle} | LearningView Pro", 0, 1, 'L') self.ln(10) def footer(self): self.set_y(-25) self.set_font('Helvetica', 'I', 7) self.set_text_color(100, 116, 139) disclaimer = ( "Disclaimer: This AI-generated report is a screening tool for educational insight and NOT a clinical diagnosis. " "LearningView Pro (Roshan Enterprises Pty Ltd) does not provide medical advice." ) self.multi_cell(0, 4, disclaimer, 0, 'C') self.ln(2) self.set_font('Helvetica', 'B', 8) compliance = "AHPRA Standards Alignment" if self.region == "AU_VIC" else "NEP 2020 Protocol Alignment" footer_text = f'{compliance} | ID: {self.access_key} | Page {self.page_no()}' self.cell(0, 5, footer_text, 0, 0, 'C') def get_clinical_insight(metrics): """Translates raw scores into parent-friendly insights [cite: 2026-02-21].""" insights = [] score = metrics.get('alignment_score', 0) if score < 60: insights.append("Processing Sync: Notable delay between sight and sound, suggesting labored decoding.") elif score < 85: insights.append("Processing Sync: Coordination is present but requires significant mental effort.") else: insights.append("Processing Sync: Strong visual and phonetic harmony.") blocks = metrics.get('phonetic_blocks', 0) timeline = metrics.get('phonetic_timeline', []) longest_gap = max([b['duration'] for b in timeline]) if timeline else 0.0 if blocks > 0: insights.append(f"Fluency Gaps: {blocks} significant pauses detected, indicating phonetic decoding hurdles.") if longest_gap > 2.0: insights.append(f"Peak Latency: A {longest_gap}s decoding pause was identified during retrieval.") return insights def get_dynamic_recommendations(data, region): recommendations = [] if data.get('regressions', 0) > 12: if region == "AU_VIC": recommendations.append(("Ocular-Motor Anchoring (Tier 2)", "Frequent regressions suggest 'losing their place'. Action: Use a tracking ruler or colored line-guide.")) else: recommendations.append(("Visual Tracking & Finger Pointing", "Implement 'Finger-Point Reading' to synchronize visual path with phonetic output.")) if data.get('phonetic_blocks', 0) > 3: if region == "AU_VIC": recommendations.append(("Phonological Blending", "Utilize Elkonin Boxes to help the child physically segment words before blending.")) else: recommendations.append(("Oral Phonemic Drills", "Use Akshara-blending games to build speed in sound-letter association.")) if len(recommendations) < 2: recommendations.append(("Fluency Maintenance", "Continue with 'Paired Reading' (reading aloud together) to increase confidence.")) return recommendations[:3] def generate_secure_pdf(data, heatmap_path, session_id, locale=None): region = locale if locale else VITE_PILOT_REGION pdf = ClinicalReport(session_id, region) pdf.set_auto_page_break(auto=True, margin=30) timeline = data.get('phonetic_timeline', []) longest_gap = max([b['duration'] for b in timeline]) if timeline else 0.0 # --- PAGE 1: CLINICAL SYNTHESIS --- pdf.add_page() pdf.set_y(50) pdf.set_fill_color(254, 242, 242); pdf.set_text_color(153, 27, 27); pdf.set_font('Helvetica', 'B', 9) notice = "NOTICE: This document is a screening summary for educational specialists. NOT a formal clinical diagnosis." pdf.multi_cell(0, 8, notice, 1, 'C', True) pdf.ln(5); pdf.set_font('Helvetica', 'B', 14); pdf.set_text_color(30, 41, 59) pdf.cell(0, 10, "1. Diagnostic Probability Summary", 0, 1) risk = data.get('risk_score', 0) pdf.set_fill_color(248, 250, 252); pdf.rect(10, 85, 190, 35, 'F') pdf.set_xy(15, 92); pdf.set_font('Helvetica', 'B', 12); pdf.cell(70, 10, "CUMULATIVE RISK:", 0, 0) if risk > 70: pdf.set_text_color(225, 29, 72) elif risk > 35: pdf.set_text_color(217, 119, 6) else: pdf.set_text_color(79, 70, 229) pdf.set_font('Helvetica', 'B', 20); pdf.cell(30, 10, f"{risk}%", 0, 1) pdf.set_xy(15, 105); pdf.set_font('Helvetica', 'B', 9); pdf.set_text_color(100, 116, 139) pdf.cell(50, 5, f"PHONETIC BLOCKS: {data.get('phonetic_blocks', 0)}", 0, 0) pdf.cell(60, 5, f"PEAK DECODING LATENCY: {longest_gap}s", 0, 1) # 🚀 FIX: Transcription Transparency Audit (No redundant lines) [cite: 2026-02-21, 2026-02-23] pdf.set_xy(10, 125); pdf.set_font('Helvetica', 'B', 11); pdf.set_text_color(30, 41, 59) pdf.cell(0, 10, "Transcription Accuracy Audit:", 0, 1) pdf.set_x(10) pdf.set_font('Helvetica', 'I', 9); pdf.set_text_color(71, 85, 105) pdf.multi_cell(190, 5, f"Target Text: '{data.get('target_text', 'N/A')}'") pdf.ln(1) pdf.set_x(10) pdf.set_text_color(79, 70, 229) pdf.multi_cell(190, 5, f"Actual Audio: '{data.get('transcribed_text', 'N/A')}'") # 🚀 Word-Level Struggle Insights [cite: 2026-02-21] pdf.ln(5) pdf.set_x(10) pdf.set_font('Helvetica', 'B', 11); pdf.set_text_color(30, 41, 59) pdf.cell(0, 10, "Word-Level Struggle Insights:", 0, 1, 'L') struggles = data.get('struggle_words', []) if struggles: pdf.set_font('Helvetica', 'B', 9); pdf.set_fill_color(241, 245, 249) pdf.cell(40, 8, " Word", 1, 0, 'L', True); pdf.cell(40, 8, " Reason", 1, 0, 'L', True); pdf.cell(40, 8, " Timestamp", 1, 1, 'L', True) pdf.set_font('Helvetica', '', 9) for s in struggles[:8]: pdf.cell(40, 7, f" {s['word']}", 1, 0); pdf.cell(40, 7, f" {s['reason']}", 1, 0); pdf.cell(40, 7, f" {s['timestamp']}s", 1, 1) else: pdf.set_font('Helvetica', 'I', 9); pdf.cell(0, 10, "No specific phoneme omissions identified.", 0, 1) # --- PAGE 2: HEATMAP --- pdf.add_page() pdf.set_y(50); pdf.set_font('Helvetica', 'B', 14); pdf.set_text_color(30, 41, 59) pdf.cell(0, 10, "2. Ocular Audit & Visual Path", 0, 1) if heatmap_path and os.path.exists(heatmap_path): pdf.image(heatmap_path, x=15, w=180) pdf.set_font('Helvetica', 'I', 8); pdf.cell(0, 8, "*Heatmap overlays eye fixation path onto student samples.", 0, 1, 'C') # --- PAGE 3: RECOMMENDATIONS --- pdf.add_page() pdf.set_y(50); pdf.set_font('Helvetica', 'B', 14); pdf.set_text_color(30, 41, 59) pathway_title = "3. Specialist Intervention Pathway (Tier 2)" if region == "AU_VIC" else "3. Nipun Bharat Intervention Pathway" pdf.cell(0, 10, pathway_title, 0, 1) for category, text in get_dynamic_recommendations(data, region): pdf.set_font('Helvetica', 'B', 11); pdf.set_text_color(79, 70, 229) pdf.cell(0, 8, f"{category}:", 0, 1) pdf.set_font('Helvetica', '', 10); pdf.set_text_color(51, 65, 85) pdf.multi_cell(0, 6, text); pdf.ln(3) # --- 🛡️ SECURE SAVE [cite: 2026-02-22] --- raw_path = os.path.join(TEMP_DIR, f"raw_{session_id}.pdf") final_path = os.path.join(TEMP_DIR, f"report_{session_id}.pdf") pdf.output(raw_path) with pikepdf.open(raw_path) as secure_pdf: secure_pdf.save(final_path, encryption=pikepdf.Encryption( user=str(session_id), owner=str(session_id), allow=pikepdf.Permissions(print_lowres=True) )) if os.path.exists(raw_path): os.remove(raw_path) return final_path