diff --git a/.DS_Store b/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..a7acccfcca41b2e17748f12bf2b2f4ede81c40f0 Binary files /dev/null and b/.DS_Store differ diff --git a/.dockerignore b/.dockerignore new file mode 100644 index 0000000000000000000000000000000000000000..42444e7ae4946edf6313602732b75cdce6febc16 --- /dev/null +++ b/.dockerignore @@ -0,0 +1,8 @@ +venv/ +.venv/ +node_modules/ +__pycache__/ +*.pyc +.git/ +.env +frontend/dist/ \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..a4bb71ea852c8cffbcde45df99e8cd7fa344287c --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +venv_test/ +venv/ diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 0000000000000000000000000000000000000000..4d0a08de263f4ba200ae13e629e7e898003d6348 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,19 @@ +FROM python:3.11-slim + +# Required for OpenCV and PDF rendering on ARM architecture +RUN apt-get update && apt-get install -y \ + libglx-mesa0 \ + libglib2.0-0 \ + ffmpeg \ + && rm -rf /var/lib/apt/lists/* + +WORKDIR /app +ENV PYTHONPATH=/app +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt +COPY . . + +# Ensure report directory exists [cite: 31, 59] +RUN mkdir -p temp_reports + +CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"] \ No newline at end of file diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000000000000000000000000000000000000..7d3766d6acfe9650ad73cfef91f0c7023fcf756a --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,30 @@ +Proprietary Software License +Copyright ยฉ 2026 [Roshan Enterprises Pty Ltd, Australia]. All Rights Reserved. + +1. Ownership and Intellectual Property + This software, including but not limited to the source code, user interface designs, ocular-orthographic algorithms, and clinical reporting logic, is the sole property of [Roshan Enterprises Pty Ltd, Australia]. This software is protected by copyright laws and international treaty provisions. + +2. No License Granted + By accessing this repository or "Space," no license is granted to any person or entity to use, copy, modify, merge, publish, distribute, sublicense, or sell copies of the Software. + +Visibility Note: The public visibility of this code on Hugging Face is for the sole purpose of application execution and does not constitute a grant of rights for redistribution or reproduction. + +3. Prohibited Actions + You are strictly prohibited from: + +Copying or duplicating the source code or any part of the clinical engine. + +Modifying, translating, or creating derivative works based on the Software. + +Reverse engineering, decompiling, or disassembling the biometric tracking or diagnostic logic. + +Removing any proprietary notices or labels on the Software. + +4. Clinical Disclaimer + NOT A MEDICAL DIAGNOSIS. The Software is provided for screening and educational purposes only. It is not intended to be a substitute for professional medical advice, diagnosis, or treatment. Always seek the advice of a qualified healthcare provider with any questions regarding a medical condition. + +5. Termination + Any unauthorized use of this Software terminates any implied permissions immediately and may result in legal action. + +6. Disclaimer of Warranty + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES, OR OTHER LIABILITY. diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..68bedbfea76fb941fca430254f0c6b99db2c72cf --- /dev/null +++ b/README.md @@ -0,0 +1,32 @@ +--- +title: LearnView Pro Backend +emoji: ๐Ÿง  +colorFrom: blue +colorTo: indigo +sdk: docker +app_port: 8000 +license: other +license_name: proprietary-all-rights-reserved +license_link: LICENSE.md +pinned: false +--- + +# DyslexiaView Pro: Clinical Biometric Engine + +This Hugging Face Space hosts the high-performance diagnostic engine for **LearningView Pro**. It utilizes MediaPipe, OpenCV, and Ocular-Orthographic modeling to perform real-time screening for Dyslexia, Dysgraphia, and Dyscalculia. + +### ๐Ÿ›ก๏ธ Proprietary Notice + +**Copyright ยฉ 2026. All Rights Reserved.** +This software is proprietary. Access to this repository does not constitute a license to copy, modify, or redistribute the source code. Please refer to the [LICENSE.md](./LICENSE.md) file for full legal terms. + +### ๐Ÿš€ Technical Overview + +- **SDK**: Docker (Debian/Python 3.10-slim) +- **Infrastructure**: 16GB RAM / 2 vCPU +- **API**: FastAPI on Port 8000 +- [cite_start]**Biometrics**: MediaPipe FaceMesh (468-point tracking) [cite: 17, 43] + +--- + +_Note: This is a clinical screening tool. It provides data for educational and professional review and is not a substitute for a formal medical diagnosis._ diff --git a/__init__.py b/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/__pycache__/__init__.cpython-310.pyc b/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e6b7e5c504f07f4605854234ff7ebf7415dc68c9 Binary files /dev/null and b/__pycache__/__init__.cpython-310.pyc differ diff --git a/__pycache__/biometric_engine.cpython-310.pyc b/__pycache__/biometric_engine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..e11d7f96d962b4eb31d4d8b22278a001ab24dc02 Binary files /dev/null and b/__pycache__/biometric_engine.cpython-310.pyc differ diff --git a/__pycache__/config.cpython-310.pyc b/__pycache__/config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..230472ed309eae8194dd682178b702ed35f0a36b Binary files /dev/null and b/__pycache__/config.cpython-310.pyc differ diff --git a/__pycache__/main.cpython-310.pyc b/__pycache__/main.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c0a79d8a382dd62cdc0b09523dfa0cf31c448e82 Binary files /dev/null and b/__pycache__/main.cpython-310.pyc differ diff --git a/config.py b/config.py new file mode 100644 index 0000000000000000000000000000000000000000..8db8ca5fbd722bb6a248327f38cfb35411ef7054 --- /dev/null +++ b/config.py @@ -0,0 +1,69 @@ +import os +from dotenv import load_dotenv + +# Load the .env file from the project root +load_dotenv() + +LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO") + +# --- ๐Ÿ“‚ DIRECTORY CONFIGURATION --- +BASE_DIR = os.path.dirname(os.path.abspath(__file__)) +TEMP_DIR = os.path.join(BASE_DIR, "temp_reports") + +# Ensure storage exists for PDF and Audio processing on startup +os.makedirs(TEMP_DIR, exist_ok=True) + +# --- ๐ŸŒ REGIONAL & APP CONFIGURATION --- +# The request 'locale' takes priority, but this is the safety fallback +DEFAULT_REGION = os.getenv("DEFAULT_REGION", "IN_NEP") +APP_NAME = os.getenv("APP_NAME", "LearningView Pro") + +# --- ๐Ÿ“ง SMTP CREDENTIALS (RAILWAY OPTIMIZED) --- +SMTP_SERVER = os.getenv("SMTP_SERVER", "smtp.gmail.com") +SMTP_PORT = int(os.getenv("SMTP_PORT", 465)) # Port 465 for SMTP_SSL +SMTP_USER = os.getenv("SENDER_EMAIL", "arrowinthedust@gmail.com") +SMTP_PASSWORD = os.getenv("SENDER_PASSWORD") + +# --- ๐Ÿ›ก๏ธ SECURITY & CORS --- +CORS_ORIGINS = [ + "http://localhost:5173", + "http://127.0.0.1:5173", + "https://learningview.vercel.app", + "https://learningview-pro.vercel.app" +] + +# --- ๐Ÿ“– ASSESSMENT PROMPTS (The Clinical Source of Truth) --- +# Any changes here will reflect across the UI and PDF transcription audit +ASSESSMENT_PROMPTS = { + "beginner": ( + "The sun was very bright today. A small cat sat on the green grass. " + "It watched a blue bird fly high in the sky. Soon, it was time for lunch." + ), + "intermediate": ( + "During the summer holidays, we decided to explore the ancient forest " + "behind our grandmother's house. The trees were tall and the air was cool." + ), + "advanced": ( + "The intricate relationship between neurological development and linguistic " + "acquisition remains a primary focus of modern cognitive science." + ) +} + +# config.py update +WRITING_PROMPTS = { + "beginner": "The quick brown fox jumps over the lazy dog.", # Covers all alphabet letters + "intermediate": "A bright blue bird sang a song in the tall green tree.", +} + +# --- ๐Ÿงช SCANNER & CLINICAL THRESHOLDS --- +DATA_PURGE_DELAY = 180 # 3-minute Zero-Persistence window +MIN_FPS_THRESHOLD = 28.0 # Minimum frame rate for reliable ocular sync + +# Biometric Distance (in MediaPipe normalized units) +CLINICAL_DISTANCE_MIN = 0.075 # Too far +CLINICAL_DISTANCE_MAX = 0.13 # Too close + +# Speech & Phonetic Timing +WHISPER_MODEL_SIZE = "base" +PHONETIC_GAP_THRESHOLD = 1.5 # Seconds of silence to trigger a "block" +STATIONARY_FRAME_THRESHOLD = 25 # Frames of eye-fixation to count a block \ No newline at end of file diff --git a/core/.DS_Store b/core/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..c65db096f210172510dc8fab35d06891a1c9654b Binary files /dev/null and b/core/.DS_Store differ diff --git a/core/__pycache__/base_analyzer.cpython-310.pyc b/core/__pycache__/base_analyzer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b50951447d2dd43796c34524f2fb8c0b1ea578a1 Binary files /dev/null and b/core/__pycache__/base_analyzer.cpython-310.pyc differ diff --git a/core/__pycache__/base_clinical_strategy.cpython-310.pyc b/core/__pycache__/base_clinical_strategy.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1127b8f1b3d72ffa50687b70595d416c223926a7 Binary files /dev/null and b/core/__pycache__/base_clinical_strategy.cpython-310.pyc differ diff --git a/core/__pycache__/base_scanner.cpython-310.pyc b/core/__pycache__/base_scanner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..1dc6c04c58fd918894a4f52442597800a8e8f35b Binary files /dev/null and b/core/__pycache__/base_scanner.cpython-310.pyc differ diff --git a/core/__pycache__/clinical_analyzer.cpython-310.pyc b/core/__pycache__/clinical_analyzer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..89d0cc7bf91189a0f4052f00cc756913093697d6 Binary files /dev/null and b/core/__pycache__/clinical_analyzer.cpython-310.pyc differ diff --git a/core/__pycache__/decision_engine.cpython-310.pyc b/core/__pycache__/decision_engine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..52b33d9ec794905d750a927de893f472901706ba Binary files /dev/null and b/core/__pycache__/decision_engine.cpython-310.pyc differ diff --git a/core/__pycache__/logger.cpython-310.pyc b/core/__pycache__/logger.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..5686f7d7f55b28891ac97a83dd18190737b97528 Binary files /dev/null and b/core/__pycache__/logger.cpython-310.pyc differ diff --git a/core/__pycache__/secure_storage.cpython-310.pyc b/core/__pycache__/secure_storage.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..277b54a7375b6f2369622c63772bd59bfd74be41 Binary files /dev/null and b/core/__pycache__/secure_storage.cpython-310.pyc differ diff --git a/core/__pycache__/state.cpython-310.pyc b/core/__pycache__/state.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..95303ddce37df4c09f3ae4cea3eaeac956360540 Binary files /dev/null and b/core/__pycache__/state.cpython-310.pyc differ diff --git a/core/__pycache__/video_audit.cpython-310.pyc b/core/__pycache__/video_audit.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..a401f40740960cadd01b016bfb292eb17ff662d3 Binary files /dev/null and b/core/__pycache__/video_audit.cpython-310.pyc differ diff --git a/core/base_analyzer.py b/core/base_analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..4c795310b00641ad9614ac4295c6ab527c795165 --- /dev/null +++ b/core/base_analyzer.py @@ -0,0 +1,16 @@ +from abc import ABC, abstractmethod + +class ClinicalAnalyzer(ABC): + """ + Abstract Base for all diagnostic interpretation logic. + Ensures 'Certainty over Velocity' across different clinical modules. + """ + @abstractmethod + def calculate_risk(self, metrics: dict) -> int: + pass + + def interpret_score(self, score: int) -> str: + """Standardized interpretation across all modules.""" + if score > 75: return "High" + if score > 40: return "Moderate" + return "Low" \ No newline at end of file diff --git a/core/base_clinical_strategy.py b/core/base_clinical_strategy.py new file mode 100644 index 0000000000000000000000000000000000000000..ee3a65f330030d6cb3858c8122b6964c7df4ccf3 --- /dev/null +++ b/core/base_clinical_strategy.py @@ -0,0 +1,3 @@ +class BaseClinicalStrategy: + def calculate(self, metrics: dict) -> float: + raise NotImplementedError \ No newline at end of file diff --git a/core/base_scanner.py b/core/base_scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..80e5a0ced4abdde402b5f6c23eb68edf003c3f2e --- /dev/null +++ b/core/base_scanner.py @@ -0,0 +1,34 @@ +from abc import ABC, abstractmethod +from typing import Optional +from pydantic import BaseModel + +class ScannerContext(BaseModel): + adult_id: str # The Gmail SSO ID of the parent/teacher + child_name: str # For multi-child identification + child_class: str # Critical for school-based reporting + level: str # beginner/intermediate/advanced + locale: str # AU_VIC / IN_NEP + video_path: str + hw_path: Optional[str] = None + target_text: str # Reading Prompt + writing_target: str # Writing Prompt (For Levenshtein comparison) + parent_email: str + report_password: Optional[str] = None + + """Shared metadata for all clinical engines [cite: 2026-02-21, 2026-02-27]""" + session_id: str + locale: str + has_paper: bool = False + +class BaseScanner(ABC): + """The universal blueprint for every diagnostic scanner.""" + + @abstractmethod + async def analyze(self, video, paper_scan, context: ScannerContext): + """Perform biometric extraction and return raw metrics.""" + pass + + @abstractmethod + def synthesize_risk(self, metrics: dict) -> float: + """Apply clinical weights (e.g., Logarithmic Dampening) to generate a score.""" + pass \ No newline at end of file diff --git a/core/email_dispatch.py b/core/email_dispatch.py new file mode 100644 index 0000000000000000000000000000000000000000..27294acd0fd80aef92766523de871e5102d13e15 --- /dev/null +++ b/core/email_dispatch.py @@ -0,0 +1,70 @@ +import smtplib +import socket +import os +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.mime.base import MIMEBase +from email import encoders +from config import SMTP_SERVER, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, VITE_PILOT_REGION +from core.reporting.email_templates import get_template +from core.logger import log_debug, logger + + +# ๐Ÿ›ก๏ธ RAILWAY NETWORK PATCH: Force IPv4 for SMTP [cite: 2026-02-23, 2026-02-27] +orig_getaddrinfo = socket.getaddrinfo +def patched_getaddrinfo(*args, **kwargs): + responses = orig_getaddrinfo(*args, **kwargs) + return [res for res in responses if res[0] == socket.AF_INET] +socket.getaddrinfo = patched_getaddrinfo + +class EmailService: + def __init__(self): + self.server = SMTP_SERVER + self.port = SMTP_PORT + self.user = SMTP_USER + self.password = SMTP_PASSWORD + + def send_secure_report(self, receiver_email, file_paths, session_id, metrics, region="AU_VIC"): + """Sends encrypted clinical results with localized context [cite: 2026-01-14, 2026-02-27].""" + msg = MIMEMultipart() + msg['From'] = f"LearningView Pro <{self.user}>" + msg['To'] = receiver_email + + # Localized Subject [cite: 2026-02-20] + prefix = "Clinical Profile" if region == "AU_VIC" else "Holistic Progress Summary" + msg['Subject'] = f"{prefix} | Ref: {session_id}" + + body = f""" + Dear Parent/Guardian, + + The clinical screening session for ID {session_id} is complete. + Attached is the encrypted PDF report. + + ๐Ÿ” SECURITY: The password for this PDF is your session ID: {session_id} + + Regional Context: {region} Compliance + Risk Score: {metrics.get('risk_score')}% + """ + msg.attach(MIMEText(body, 'plain')) + + for path in file_paths: + if os.path.exists(path): + with open(path, "rb") as attachment: + part = MIMEBase('application', 'octet-stream') + part.set_payload(attachment.read()) + encoders.encode_base64(part) + part.add_header('Content-Disposition', f"attachment; filename={os.path.basename(path)}") + msg.attach(part) + + try: + # ๐Ÿš€ Hardened Port 465 Logic + with smtplib.SMTP_SSL(self.server, self.port, timeout=15) as server: + server.login(self.user, self.password) + server.send_message(msg) + log_debug(f"๐Ÿ“ง Dispatch Success: Report sent to {receiver_email}") + return True + except Exception as e: + logger.error(f"โŒ Dispatch Failed: {str(e)}") + return False + +email_service = EmailService() diff --git a/core/logger.py b/core/logger.py new file mode 100644 index 0000000000000000000000000000000000000000..4db761516d13c925b8c5c36b2f4bd068e899644e --- /dev/null +++ b/core/logger.py @@ -0,0 +1,38 @@ +import logging +import os +import time +from functools import wraps +from config import APP_NAME + +# Resolve the level once +LOG_LEVEL_STR = os.getenv("LOG_LEVEL", "DEBUG").upper() +LOG_LEVEL = getattr(logging, LOG_LEVEL_STR, logging.DEBUG) + +logging.basicConfig( + level=LOG_LEVEL, + format="%(asctime)s [%(levelname)s] %(name)s: %(message)s", + handlers=[logging.StreamHandler()] +) + +logger = logging.getLogger(APP_NAME) + +# --- ๐ŸŽฏ THE CLINICAL INTERFACE --- + +def log_clinical_event(event_name: str, details: dict): + """Specific logger for child assessment events (Ocular/Phonetic).""" + logger.info(f"๐Ÿ“Š CLINICAL_EVENT | {event_name} | {details}") + +def log_debug(message: str): + """Replacement for print() statements.""" + logger.debug(f"๐Ÿ” DEBUG: {message}") + +def monitor_perf(func): + """Decorator to log execution time.""" + @wraps(func) + async def wrapper(*args, **kwargs): + start_time = time.perf_counter() + result = await func(*args, **kwargs) + duration = time.perf_counter() - start_time + logger.debug(f"โฑ๏ธ PERF | {func.__name__} execution: {duration:.4f}s") + return result + return wrapper \ No newline at end of file diff --git a/core/reporting/__pycache__/base_report.cpython-310.pyc b/core/reporting/__pycache__/base_report.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..290d8ef6c108dd0d36e09ca97eed1d9d0ad7efd7 Binary files /dev/null and b/core/reporting/__pycache__/base_report.cpython-310.pyc differ diff --git a/core/reporting/__pycache__/report_config.cpython-310.pyc b/core/reporting/__pycache__/report_config.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..b0616618dea300b976c2dd8d7d2c4fe0fbca67c7 Binary files /dev/null and b/core/reporting/__pycache__/report_config.cpython-310.pyc differ diff --git a/core/reporting/base_report.py b/core/reporting/base_report.py new file mode 100644 index 0000000000000000000000000000000000000000..8289a2604208c1bd16a3456e0dba7de62370ab56 --- /dev/null +++ b/core/reporting/base_report.py @@ -0,0 +1,126 @@ +import os +import pikepdf +from fpdf import FPDF +from datetime import datetime +from core.reporting.report_config import REPORT_CONFIG + +class BaseClinicalReport(FPDF): + """ + Standardized PDF Factory for LearnView Pro. + Handles Multi-Audience Insights, Security (AES-256), and Jurisdictional Branding. + """ + def __init__(self, session_id, region, context): + super().__init__() + self.session_id = session_id + self.region = region + self.context = context + # Dynamically load jurisdiction config + self.cfg = REPORT_CONFIG.get(region, REPORT_CONFIG["AU_VIC"]) + self.report_date = datetime.now().strftime("%d %b %Y") + self.alias_nb_pages() + self.add_page() + + def header(self): + """Custom header with jurisdictional branding and student metadata.""" + # Regional Branding: Solid header bar + self.set_fill_color(*self.cfg["primary_color"]) + self.rect(0, 0, 210, 40, 'F') + + self.set_text_color(255, 255, 255) + self.set_font('Helvetica', 'B', 16) + self.set_xy(12, 10) + + # India Edition branding check + header_title = "LEARNVIEW PRO: INDIA EDITION" if "IN" in self.region else self.cfg["header_title"] + self.cell(0, 10, header_title, 0, 1) + + # VCL Jurisdictional Compliance Badge + self.set_font('Helvetica', 'B', 7) + compliance = "Victoria Child Link (VCL) Alignment Protocol" if "IN" in self.region else self.cfg['footer_compliance'] + badge_text = f"JURISDICTION COMPLIANCE: {compliance.upper()}" + self.text(120, 10, badge_text) + + self.set_font('Helvetica', '', 9) + self.set_xy(12, 18) + self.cell(0, 5, f"Clinical Session Artifact | Ref: {self.session_id}", 0, 1) + + # Metadata: Student Details + self.set_font('Helvetica', 'B', 11) + self.set_x(12) + name = getattr(self.context, 'child_name', 'Anonymous Student') + grade = getattr(self.context, 'child_class', 'N/A') + student_meta = f"Student: {name} | Grade: {grade}" + self.cell(0, 5, student_meta, 0, 1) + + self.set_font('Helvetica', '', 9) + self.set_x(12) + # Display Audit Key (PWD) to match Dashboard + pwd = getattr(self.context, 'report_password', 'N/A') + meta_sub = f"Report Generated: {self.report_date} | Audit Key (PWD): {pwd}" + self.cell(0, 5, meta_sub, 0, 1) + + self.set_text_color(0, 0, 0) + self.set_y(45) + + def draw_parent_insight(self, title, description): + """Plain-language summary box for parents.""" + self.set_fill_color(248, 250, 252) + self.set_draw_color(203, 213, 225) + curr_y = self.get_y() + self.rect(12, curr_y, 186, 20, 'FD') + self.set_font("Helvetica", 'B', 9) + self.set_text_color(51, 65, 85) + self.set_xy(15, curr_y + 2) + self.cell(0, 5, f"FOR PARENTS: {title.upper()}", ln=True) + self.set_font("Helvetica", '', 8) + self.set_x(15) + self.multi_cell(180, 4, description) + self.set_y(curr_y + 25) + + def footer(self): + """Compliance footer with VCL strings.""" + self.set_y(-20) + self.set_font('Helvetica', 'I', 8) + self.set_text_color(120, 120, 120) + compliance = "VCL Alignment Protocol" if "IN" in self.region else self.cfg['footer_compliance'] + compliance_text = f"{compliance} | Session ID: {self.session_id}" + self.cell(0, 10, compliance_text, 0, 0, 'C') + self.set_x(-30) + self.cell(20, 10, f'Page {self.page_no()}/{{nb}}', 0, 0, 'R') + + def draw_h2(self, text): + """Standardized Blue Section Header.""" + self.set_font("Helvetica", 'B', 14) + self.set_text_color(*self.cfg["primary_color"]) + self.cell(0, 10, text, ln=True) + self.set_draw_color(*self.cfg["primary_color"]) + self.line(12, self.get_y(), 62, self.get_y()) + self.ln(5) + self.set_text_color(0, 0, 0) + + def finalize(self, raw_filename, final_filename): + """Secures artifact with AES-256 using the Audit Hash (PWD).""" + self.output(raw_filename) + try: + with pikepdf.open(raw_filename) as pdf: + # Use Audit Key (PWD) from Dashboard + pw = str(getattr(self.context, 'report_password', self.session_id)) + pdf.save(final_filename, encryption=pikepdf.Encryption( + user=pw, owner=pw, allow=pikepdf.Permissions(accessibility=True) + )) + if os.path.exists(raw_filename): os.remove(raw_filename) + return final_filename + except Exception: + if os.path.exists(raw_filename): os.rename(raw_filename, final_filename) + return final_filename + + def draw_table(self, data, highlight_row=None): + """Renders Metrics/Hardware Audit Table.""" + self.set_font("Helvetica", size=9) + col_width = self.epw / len(data[0]) + for i, row in enumerate(data): + self.set_fill_color(240, 244, 248) if (i == 0 or i == highlight_row) else None + self.set_font("Helvetica", 'B' if (i == 0 or i == highlight_row) else '', 9) + for item in row: + self.cell(col_width, 10, str(item), border=1, fill=(i == 0 or i == highlight_row), align='C') + self.ln() \ No newline at end of file diff --git a/core/reporting/email_templates.py b/core/reporting/email_templates.py new file mode 100644 index 0000000000000000000000000000000000000000..d5a3c50b98182ecbfdbbbc77f8df62ec309ad145 --- /dev/null +++ b/core/reporting/email_templates.py @@ -0,0 +1,26 @@ +# core/reporting/email_templates.py + +REGIONAL_TEMPLATES = { + "AU_VIC": { + "subject": "Clinical Profile | Victorian Department of Education Standards", + "title": "Clinical Screening Artifact", + "disclaimer": "This report aligns with AHPRA standards and Victorian privacy protocols.", + "body_intro": "The clinical screening session for your child in Victoria is complete." + }, + "IN_NEP": { + "subject": "Holistic Progress Summary | NEP 2020 Protocol", + "title": "FLN Biometric Summary", + "disclaimer": "Aligned with Nipun Bharat guidelines for holistic child development.", + "body_intro": "The biometric assessment as per the National Education Policy (NEP) 2020 is complete." + }, + "GLOBAL": { + "subject": "LearningView Pro: Biometric Assessment Report", + "title": "General Screening Summary", + "disclaimer": "International screening artifact for educational insight.", + "body_intro": "Your requested biometric assessment session is complete." + } +} + +def get_template(region): + """Safely retrieves the template or falls back to Global [cite: 2026-02-27].""" + return REGIONAL_TEMPLATES.get(region, REGIONAL_TEMPLATES["GLOBAL"]) \ No newline at end of file diff --git a/core/reporting/report_config.py b/core/reporting/report_config.py new file mode 100644 index 0000000000000000000000000000000000000000..1652fd3a3d05b0630dd1e288401a908a3241f19c --- /dev/null +++ b/core/reporting/report_config.py @@ -0,0 +1,17 @@ +# core/reporting/report_config.py + +REPORT_CONFIG = { + "AU_VIC": { + "header_title": "AU_VIC CLINICAL PROFILE", + "footer_compliance": "AHPRA Standards Alignment", + "primary_color": (15, 23, 42), # Slate-900 (Professional/Clinical) + "accent_color": (79, 70, 229), # Indigo (Modern/Trust) + "vcl_fields": ["VUI", "VSN", "VEYLDF_Milestone", "Consent_Level"] + }, + "IN_NEP": { + "header_title": "NEP 2020 HOLISTIC PROGRESS", + "footer_compliance": "NEP 2020 Protocol Alignment", + "primary_color": (20, 83, 45), # Deep Green (Growth/Education) + "accent_color": (245, 158, 11) # Amber (Active Learning) + } +} \ No newline at end of file diff --git a/core/secure_storage.py b/core/secure_storage.py new file mode 100644 index 0000000000000000000000000000000000000000..bc130656561d1cedcc5c5584f1f97125b4cd9193 --- /dev/null +++ b/core/secure_storage.py @@ -0,0 +1,40 @@ +import os +import asyncio +from config import DATA_PURGE_DELAY +from core.logger import log_debug, logger + + +class Shredder: + """ + Zero-Persistence Utility for Privacy Compliance. + Handles the deferred deletion of clinical artifacts. + """ + + @staticmethod + async def deferred_purge(file_paths: list, delay: int = DATA_PURGE_DELAY): + """ + Independent self-destruct timer per session. + Ensures artifacts exist long enough for email dispatch but no longer. + """ + log_debug(f"๐Ÿ•’ Privacy: Shredder initialized. Waiting {delay}s for {len(file_paths)} files...") + + # Non-blocking sleep allows the server to handle other requests + await asyncio.sleep(delay) + + for path in file_paths: + if path and os.path.exists(path): + try: + # Overwrite check could be added here for military-grade shredding + os.remove(path) + log_debug(f"๐Ÿ›ก๏ธ Privacy: Shredded artifact -> {os.path.basename(path)}") + except Exception as e: + logger.error(f"โŒ Shredder Error for {path}: {e}") + + @staticmethod + def instant_purge(file_paths: list): + """Immediate deletion for failed sessions or temporary intermediate files.""" + for path in file_paths: + if path and os.path.exists(path): + os.remove(path) + +shredder = Shredder() \ No newline at end of file diff --git a/core/state.py b/core/state.py new file mode 100644 index 0000000000000000000000000000000000000000..47be35efd4b54826184e3b8211cb5fb591eb88af --- /dev/null +++ b/core/state.py @@ -0,0 +1 @@ +handwriting_cache = {} \ No newline at end of file diff --git a/core/video_audit.py b/core/video_audit.py new file mode 100644 index 0000000000000000000000000000000000000000..e253d96af33d14400d87a9d83090f1d6804a6151 --- /dev/null +++ b/core/video_audit.py @@ -0,0 +1,50 @@ +import cv2 +from config import MIN_FPS_THRESHOLD + +class VideoService: + @staticmethod + def verify_integrity(video_path: str): + """ + Standardizes video metadata extraction and quality auditing. + Includes specific FPS feedback in warnings [cite: 2026-02-27]. + """ + cap = cv2.VideoCapture(video_path) + if not cap.isOpened(): + return {"valid": False, "error": "Could not open video file."} + + fps = cap.get(cv2.CAP_PROP_FPS) + frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + + # ๐Ÿ›ก๏ธ BRUTE FORCE FALLBACK + if frame_count <= 0: + frame_count = 0 + while True: + ret, _ = cap.read() + if not ret: break + frame_count += 1 + cap.set(cv2.CAP_PROP_POS_FRAMES, 0) + + if fps < 5 or fps > 120: + fps = 30.0 + + duration = frame_count / fps if fps > 0 else 0 + + # โš–๏ธ CLINICAL CONFIDENCE AUDIT + is_suboptimal = fps < MIN_FPS_THRESHOLD + status_label = "SUBOPTIMAL" if is_suboptimal else "OPTIMAL" + + cap.release() + + # ๐ŸŽฏ Dynamic Warning with detected FPS + warning = None + if is_suboptimal: + warning = f"Low frame rate ({round(fps, 1)} FPS) detected. Ocular synchronization may be less precise." + + return { + "valid": True, + "fps": round(fps, 2), + "frame_count": frame_count, + "duration": round(duration, 2), + "status": status_label, + "warning": warning + } \ No newline at end of file diff --git a/engines/.DS_Store b/engines/.DS_Store new file mode 100644 index 0000000000000000000000000000000000000000..b4cb7b9d62c91b48f5bbe2a1af0afd80e675d701 Binary files /dev/null and b/engines/.DS_Store differ diff --git a/engines/adhd/analyzer.py b/engines/adhd/analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..78b2f8107e7e49cde4f2cacfd717e9013a3528e4 --- /dev/null +++ b/engines/adhd/analyzer.py @@ -0,0 +1,8 @@ +import math +from core.base_analyzer import ClinicalAnalyzer + +class ADHDAnalyzer(ClinicalAnalyzer): + def calculate_risk(self, metrics: dict) -> int: + jitter = metrics.get('head_jitter', 0) + # Completely different weights for ADHD + return int(jitter * 60) \ No newline at end of file diff --git a/engines/dyslexia/__pycache__/analyzer.cpython-310.pyc b/engines/dyslexia/__pycache__/analyzer.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a44f3be10a11adba786bd3a61a94e2cf65c5f39 Binary files /dev/null and b/engines/dyslexia/__pycache__/analyzer.cpython-310.pyc differ diff --git a/engines/dyslexia/__pycache__/logic.cpython-310.pyc b/engines/dyslexia/__pycache__/logic.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..efe60d3a9ba1c738546ae2756d98810b4be332e9 Binary files /dev/null and b/engines/dyslexia/__pycache__/logic.cpython-310.pyc differ diff --git a/engines/dyslexia/__pycache__/report.cpython-310.pyc b/engines/dyslexia/__pycache__/report.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..dd8f3d06a8faaf75d5f3119f22101b48b3e8e095 Binary files /dev/null and b/engines/dyslexia/__pycache__/report.cpython-310.pyc differ diff --git a/engines/dyslexia/__pycache__/scanner.cpython-310.pyc b/engines/dyslexia/__pycache__/scanner.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..9407407507ae31ba0b6b7b8952eeadca251bb8cb Binary files /dev/null and b/engines/dyslexia/__pycache__/scanner.cpython-310.pyc differ diff --git a/engines/dyslexia/analyzer.py b/engines/dyslexia/analyzer.py new file mode 100644 index 0000000000000000000000000000000000000000..ac0eb20c1f91c128f4c0f98d3b41a12825187227 --- /dev/null +++ b/engines/dyslexia/analyzer.py @@ -0,0 +1,19 @@ +import math +from core.base_analyzer import ClinicalAnalyzer + +class DyslexiaAnalyzer(ClinicalAnalyzer): + def calculate_risk(self, metrics: dict) -> int: + wer = metrics.get('wer', 0.0) + regressions = metrics.get('regressions', 0) + attentiveness = metrics.get('vision_attentiveness', 100) # ๐Ÿ†• Weighting Engagement + + # Penalize low attentiveness (engagement) + engagement_penalty = max(0, (95 - attentiveness) * 0.4) + + # Logarithmic weight for reading strain + ocular_weight = 12 * math.log1p(regressions) + + # Synthesis: (WER 30%) + (Ocular 40%) + (Engagement 30%) + score = (wer * 30) + (ocular_weight * 3) + engagement_penalty + + return int(min(max(score, 5), 95)) \ No newline at end of file diff --git a/engines/dyslexia/logic.py b/engines/dyslexia/logic.py new file mode 100644 index 0000000000000000000000000000000000000000..fcc8383d9107847314c79dd7118613f4faf87fe0 --- /dev/null +++ b/engines/dyslexia/logic.py @@ -0,0 +1,79 @@ +import math +from core.base_clinical_strategy import BaseClinicalStrategy +from difflib import SequenceMatcher +import re + + +class DyslexiaStrategy(BaseClinicalStrategy): + def calculate(self, metrics: dict) -> float: + """ + Dynamic Clinical Synthesis with Calibration Offset [cite: 2026-03-01]. + """ + # 1. Extraction [cite: 2026-03-01] + wer = metrics.get('wer', metrics.get('speech_accuracy', 0.0)) + regressions = metrics.get('regressions', 0) + drift = metrics.get('drift', metrics.get('handwriting_drift', 0.0)) + ocr_acc = metrics.get('ocr_accuracy', 1.0) + + # ๐ŸŽฏ New: Calibration Offset (Default to 100 if missing) [cite: 2026-03-01] + confidence = metrics.get('confidence_score', 100.0) + + # 2. Hardware-Aware Dampening [cite: 2026-03-01] + # If confidence is < 40, the eyes are likely jumping due to low FPS, not dyslexia + ocular_multiplier = 3.0 if confidence > 45 else 0.8 + dampened_regressions = 10 * math.log1p(regressions) + + # 3. Normalized Weights [cite: 2026-03-01] + wer_val = wer * 100 if wer <= 1.0 else wer + + # โš–๏ธ Clinical Weights: WER (40%), Ocular (30%), Kinetic (10%), OCR (20%) [cite: 2026-03-01] + # Notice we use the ocular_multiplier to protect against bad data [cite: 2026-03-01] + score = (wer_val * 0.4) + (dampened_regressions * ocular_multiplier) + (abs(drift) * 10) + ((1.0 - ocr_acc) * 20) + + # 4. Final Safe Bounds + return float(min(max(score, 0), 100)) + + + +def calculate_lexical_fidelity(detected: str, target: str) -> float: + """ + Calculates similarity on a 0-100 scale using normalized text. + """ + if not target or not detected: + return 0.0 + + d_clean = normalize_clinical_text(detected) + t_clean = normalize_clinical_text(target) + + # Fuzzy match ratio (0.0 to 1.0) + similarity = SequenceMatcher(None, d_clean, t_clean).ratio() + + # Return as percentage for consistent reporting + return round(similarity * 100, 2) + + +def normalize_clinical_text(text: str) -> str: + """ + Advanced normalization to bridge the gap between spoken numbers + and written digits, and strip all non-lexical noise. + """ + if not text: return "" + + # 1. Standardize case and strip punctuation + text = text.lower() + text = re.sub(r'[^\w\s]', '', text) + + # 2. Automated Number-to-Phonetic Mapping + # This handles the "7" vs "seven" discrepancy found in Session 9NHV4G + num_to_words = { + "0": "zero", "1": "one", "2": "two", "3": "three", "4": "four", + "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine", + "10": "ten", "12": "twelve", "24": "twenty four" + } + + words = text.split() + normalized_words = [num_to_words.get(w, w) for w in words] + + # 3. Collapse whitespace + return " ".join(normalized_words).strip() + diff --git a/engines/dyslexia/report.py b/engines/dyslexia/report.py new file mode 100644 index 0000000000000000000000000000000000000000..c744315222763c0acc5933d116058d1d556ca2bd --- /dev/null +++ b/engines/dyslexia/report.py @@ -0,0 +1,193 @@ +import os +from fpdf import FPDF +from datetime import datetime +from engines.dyslexia.logic import calculate_lexical_fidelity + +class DyslexiaReport(FPDF): + def __init__(self, session_id, region, context): + super().__init__() + self.session_id = session_id + self.region = region + self.context = context + self.set_auto_page_break(auto=True, margin=15) + self.alias_nb_pages() + + def header(self): + """Standardized Clinical Header.""" + if self.page_no() <= 5: + self.set_font('Helvetica', 'B', 8) + self.set_text_color(148, 163, 184) # Slate 400 + self.cell(0, 10, f"VCL-VUI Protocol Alignment | Ref: {self.session_id}", 0, 0, 'L') + self.cell(0, 10, f"Page {self.page_no()}/{{nb}}", 0, 0, 'R') + self.ln(12) + + def _safe_latin(self, text): + if not text: return "" + return text.encode('latin-1', 'replace').decode('latin-1') + + def draw_h2(self, title): + """Reusable section header to keep code lean.""" + self.set_font('Helvetica', 'B', 12) + self.set_text_color(15, 23, 42) # Slate 900 + self.cell(0, 10, self._safe_latin(title), ln=True) + self.set_draw_color(226, 232, 240) # Slate 200 + self.line(self.get_x(), self.get_y(), self.get_x() + 190, self.get_y()) + self.ln(5) + + def add_vcl_summary_page(self, metrics): + """Page 1: Executive Synthesis (Eliminates 'Empty Page 1' bug).""" + self.add_page() + + # ๐Ÿข Header Branding Block + self.set_fill_color(248, 250, 252) + self.rect(10, 25, 190, 45, 'F') + + self.set_xy(15, 30) + self.set_font('Helvetica', 'B', 16) + self.set_text_color(30, 41, 59) + self.cell(0, 8, "CLINICAL DIAGNOSTIC REPORT", ln=True) + + self.set_font('Helvetica', '', 9); self.set_text_color(100, 100, 100) + self.cell(0, 5, f"EDITION: {self.region} | JURISDICTION: VICTORIA CHILD LINK (VCL)", ln=True) + self.ln(5) + + # Metadata Grid + self.set_font('Helvetica', 'B', 9); self.set_text_color(71, 85, 105) + self.cell(30, 5, "STUDENT:"); self.set_font('Helvetica', '', 9); self.cell(60, 5, self.context.child_name.upper()) + self.set_font('Helvetica', 'B', 9); self.cell(30, 5, "AUDIT ID:"); self.set_font('Helvetica', '', 9); self.cell(0, 5, self.session_id, ln=True) + + self.set_font('Helvetica', 'B', 9); self.cell(30, 5, "DATE:"); self.set_font('Helvetica', '', 9); self.cell(60, 5, datetime.now().strftime("%d %b %Y")) + self.set_font('Helvetica', 'B', 9); self.cell(30, 5, "AUTHORIZED BY:"); self.set_font('Helvetica', '', 9); self.cell(0, 5, self.context.adult_id or "Verified SSO", ln=True) + + self.ln(15) + + # ๐Ÿ“Š 1. Multi-Dimensional Synthesis + self.draw_h2("1. Multi-Dimensional Synthesis") + summary = metrics.get('diagnosis_summary', {}) + + # Simplified horizontal risk layout + risks = [ + ("Dyslexia", summary.get('dyslexia', {})), + ("Dysgraphia", summary.get('dysgraphia', {})), + ("Dyscalculia", summary.get('dyscalculia', {})) + ] + + current_y = self.get_y() + for i, (label, data) in enumerate(risks): + self.set_xy(15 + (i * 65), current_y) + score = data.get('score', 0) + sev = data.get('severity', 'Low') + + self.set_font('Helvetica', 'B', 10); self.set_text_color(100, 100, 100) + self.cell(60, 5, label, align='C', ln=True) + self.set_x(15 + (i * 65)) + self.set_font('Helvetica', 'B', 28); self.set_text_color(15, 23, 42) + self.cell(60, 14, str(int(score)), align='C', ln=True) + + # Severity Badge + self.set_x(25 + (i * 65)) + color = (34, 197, 94) if sev == 'Low' else (239, 68, 68) if sev == 'High' else (245, 158, 11) + self.set_fill_color(*color); self.set_text_color(255, 255, 255) + self.set_font('Helvetica', 'B', 8) + self.cell(40, 7, f"{sev.upper()} RISK", align='C', fill=True, ln=True) + + def add_transcription_audit(self, target: str, actual: str): + """Page 3 (Top): Reading Audit with color-coded fidelity.""" + self.draw_h2("2. Transcription Accuracy Audit") + + fidelity = calculate_lexical_fidelity(actual, target) + self.set_font('Helvetica', 'B', 10) + self.set_text_color(220, 38, 38) if fidelity < 70 else self.set_text_color(22, 163, 74) + self.cell(0, 8, f"PHONETIC ALIGNMENT (READING ACCURACY): {int(fidelity)}%", ln=True) + self.ln(2) + + self.set_font('Helvetica', 'B', 9); self.set_text_color(100, 100, 100) + self.cell(0, 5, "EXPECTED READING PROMPT:", ln=True) + self.set_font('Helvetica', 'I', 10); self.set_text_color(30, 41, 59) + self.multi_cell(0, 6, self._safe_latin(f'"{target}"')) + self.ln(4) + + self.set_font('Helvetica', 'B', 9); self.set_text_color(100, 100, 100) + self.cell(0, 5, "ACTUAL VOCAL TRANSCRIPTION:", ln=True) + self.set_font('Helvetica', 'B', 11); self.set_text_color(30, 41, 59) + self.multi_cell(0, 7, self._safe_latin(f'"{actual or "No speech detected"}"')) + self.ln(8) + + def add_kinetic_audit(self, metrics: dict, target: str): + """Page 3 (Bottom): Writing Audit.""" + self.draw_h2("3. Kinetic Extraction Audit") + actual = metrics.get('detected_handwriting', '') + fidelity = calculate_lexical_fidelity(actual, target) + + self.set_font('Helvetica', 'B', 10) + self.set_text_color(220, 38, 38) if fidelity < 40 else self.set_text_color(22, 163, 74) + self.cell(0, 8, f"LEXICAL FIDELITY (WRITING ACCURACY): {int(fidelity)}%", ln=True) + self.ln(2) + + self.set_font('Helvetica', 'B', 9); self.set_text_color(100, 100, 100) + self.cell(0, 5, "PRESCRIBED WRITING TASK:", ln=True) + self.set_font('Helvetica', 'I', 10); self.set_text_color(30, 41, 59) + self.multi_cell(0, 6, self._safe_latin(f'"{target}"')) + self.ln(4) + + self.set_font('Helvetica', 'B', 9); self.set_text_color(100, 100, 100) + self.cell(0, 5, "STUDENT HANDWRITING EXTRACTION:", ln=True) + self.set_font('Helvetica', 'B', 11); self.set_text_color(30, 41, 59) + self.multi_cell(0, 7, self._safe_latin(f'"{actual or "No text detected"}"')) + self.ln(6) + + # Kinetic Metrics + self.set_font('Helvetica', 'B', 9); self.set_text_color(30, 41, 59) + self.cell(45, 8, "Basal Drift Angle:"); self.set_font('Helvetica', '', 10); self.cell(40, 8, f"{metrics.get('basal_drift', 0)}ยฐ") + self.set_font('Helvetica', 'B', 9); self.cell(40, 8, "Letter Slant Angle:"); self.set_font('Helvetica', '', 10); self.cell(40, 8, f"{metrics.get('slant', 0)}ยฐ", ln=True) + + def add_interpretation_guide(self): + """Page 4: Detailed Science & Glossary.""" + self.add_page() + self.draw_h2("4. Information & Interpretation Guide") + + # Profiles Section + self.set_font('Helvetica', 'B', 11); self.set_text_color(37, 99, 235) + self.cell(0, 10, "Understanding Clinical Profiles", ln=True) + + defs = [ + ("Dyslexia", "A neurological difference affecting phonological processing. High risk suggests struggle with decoding and ocular smoothness."), + ("Dysgraphia", "Affects motor integration required for handwriting. Measured via lexical fidelity and kinetic drift."), + ("Dyscalculia", "Difficulty comprehending numerical symbols. Measured via cognitive latency on numerical triggers.") + ] + for title, desc in defs: + self.set_font('Helvetica', 'B', 9); self.set_text_color(30, 41, 59) + self.cell(25, 6, f"{title}: ") + self.set_font('Helvetica', '', 9); self.set_text_color(71, 85, 105) + self.multi_cell(0, 6, desc) + self.ln(2) + + self.ln(5) + self.draw_h2("5. Recommendations") + # Logic is handled here based on risk summary scores... + +# --- Finalizer Entry Point --- +def generate_dyslexia_report(metrics, heatmap_path, session_id, locale, target_text, trans_text, context, **kwargs): + report = DyslexiaReport(session_id=session_id, region=locale, context=context) + + # 1. Page 1: Executive Summary + report.add_vcl_summary_page(metrics) + + # 2. Page 2: Evidence (Heatmap) + report.add_page() + report.draw_h2("Ocular-Orthographic Evidence") + if os.path.exists(heatmap_path): + report.image(heatmap_path, x=15, y=report.get_y(), w=180) + + # 3. Page 3: Full Audit Trail + report.add_page() + report.add_transcription_audit(target_text, trans_text) + report.add_kinetic_audit(metrics, target=kwargs.get('writing_target', "Default")) + + # 4. Page 4: Information Guide + report.add_interpretation_guide() + + # Output to clinical artifact store + out_file = f"report_{session_id}.pdf" + report.output(out_file) + return out_file \ No newline at end of file diff --git a/engines/dyslexia/scanner.py b/engines/dyslexia/scanner.py new file mode 100644 index 0000000000000000000000000000000000000000..21d455b58b0d6d6da2418f3895afea2e8fbacb38 --- /dev/null +++ b/engines/dyslexia/scanner.py @@ -0,0 +1,239 @@ +import os +import cv2 +import asyncio +import time +import numpy as np +import random + +from core.logger import log_clinical_event, monitor_perf, logger, log_debug +from core.base_scanner import BaseScanner, ScannerContext +from services.biometric_engine import biometric_engine +from services.speech_analysis import speech_engine +from services.email_service import email_service +from services.decision_engine import decision_engine +from core.secure_storage import shredder +from engines.dyslexia.analyzer import DyslexiaAnalyzer +from core.state import handwriting_cache +from engines.dyslexia.report import generate_dyslexia_report +from config import TEMP_DIR, DATA_PURGE_DELAY +from engines.dyslexia.logic import calculate_lexical_fidelity + + +class DyslexiaScanner(BaseScanner): + def __init__(self): + self.name = "LearnView Pro: Dyslexia Engine" + self.biometric_engine = biometric_engine + self.analyzer = DyslexiaAnalyzer() + + async def synthesize_risk(self, session_data: dict) -> dict: + risk_score = self.analyzer.calculate_risk(session_data) + severity = "High" if risk_score > 70 else "Moderate" if risk_score > 30 else "Low" + return {"risk_score": risk_score, "severity": severity} + + @monitor_perf + async def analyze(self, context: ScannerContext, background_tasks): + """Unified orchestrator with full clinical depth.""" + log_clinical_event(context.session_id, "Full Synthesis Start") + + # --- ๐Ÿ“ 1. POLLING, RECOVERY & AUDIT HASH --- + hw_data = None + for _ in range(10): # Wait for Google OCR write + hw_data = handwriting_cache.get(context.session_id) + if hw_data and hw_data.get('detected_text') not in [None, "", "[Processing...]"]: + break + await asyncio.sleep(0.5) + + if not hw_data and handwriting_cache: + latest_id = list(handwriting_cache.keys())[-1] + hw_data = handwriting_cache.get(latest_id) + logger.info(f"โœ… Recovered OCR data from ID: {latest_id}") + + hw_data = hw_data or {"detected_text": "[Extraction Delayed]", "basal_drift": 0.0, "slant": 0.0, "ocr_accuracy": 0.0} + + # Calculate Strict Character Error Rate (CER) + detected_text = hw_data.get('detected_text', '') + target_writing = getattr(context, 'writing_target', "Default Task") + + # This returns 0-100; a similarity of 80 means risk is now 20 + fidelity_score = calculate_lexical_fidelity(detected_text, target_writing) + hw_data['ocr_accuracy'] = fidelity_score / 100.0 + + cer = self.biometric_engine.calculate_cer(target_writing, detected_text) + hw_data['ocr_accuracy'] = 1.0 - cer + + # Process Strict Handwriting Kinetics + if hasattr(context, 'hw_path') and context.hw_path and os.path.exists(context.hw_path): + kinetics = self.biometric_engine.process_handwriting_kinetics(context.hw_path) + hw_data['basal_drift'] = kinetics.get('basal_drift', 0.0) + hw_data['slant'] = kinetics.get('slant', 0.0) + else: + hw_data['basal_drift'] = 0.0 + hw_data['slant'] = 0.0 + + # --- ๐ŸŽฅ 2. VIDEO BIOMETRIC PROCESSING (Restored Telemetry) --- + cap = cv2.VideoCapture(context.video_path) + + # โœ… UPDATED: Added distance_logs for compliance audit + gaze_buffer, distance_logs, attentive_frames, total_frames, latency_samples = [], [], 0, 0, [] + fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 + + while cap.isOpened(): + start_tick = time.time() + ret, frame = cap.read() + if not ret: break + total_frames += 1 + + results = self.biometric_engine.process_frame(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)) + if results.multi_face_landmarks: + lm = results.multi_face_landmarks[0].landmark + # ๐ŸŽฏ Iris depth tracking + iris_id = self.biometric_engine.calculate_iris_depth(results.multi_face_landmarks[0]) + + # โœ… UPDATED: Track physical distance per frame using the 15.5 clinical constant + current_dist = 15.5 / (iris_id + 0.00001) + distance_logs.append(current_dist) + + gaze_buffer.append({"x": lm[468].x, "y": lm[468].y, "id": iris_id, "timestamp": total_frames/fps}) + if abs(lm[1].x - 0.5) < 0.25: attentive_frames += 1 + + latency_samples.append(time.time() - start_tick) # ๐ŸŽฏ Performance jitter tracking + cap.release() + + # --- ๐ŸŽ™๏ธ 3. CLINICAL SYNTHESIS --- + + # โœ… UPDATED: Execute clinical positioning audit based on recorded distance logs + compliance = self.biometric_engine.analyze_compliance(distance_logs) + + speech_data = speech_engine.analyze_with_timestamps(context.video_path, context.target_text, context.session_id) + attentiveness = (attentive_frames / total_frames * 100) if total_frames > 0 else 0.0 + ocular_metrics = self.biometric_engine.analyze_gaze_v2(gaze_buffer) + raw_wer = speech_data.get('accuracy', {}).get('wer', 1.0) + + jitter = np.mean(np.abs(np.diff(latency_samples))) * 1000 if len(latency_samples) > 1 else 0 + avg_latency = np.mean(latency_samples) * 1000 if latency_samples else 0 + + risk_data = await self.synthesize_risk({ + "wer": raw_wer, "regressions": ocular_metrics.get('regression_count', 0), + "vision_attentiveness": attentiveness, "drift": hw_data.get('basal_drift', 0.0) + }) + + sync_data = decision_engine.synthesize_ocular_phonetic_sync(gaze_buffer, speech_data.get('word_alignment', []), fps=fps) + + # Initialize Multi-Disability Markers + phonetic_delay_flag = False + num_latency_ms = 0.0 + + # --- ๐Ÿ‘๏ธ GAZE NORMALIZATION MATRIX --- + if len(gaze_buffer) > 0: + min_x = min(pt['x'] for pt in gaze_buffer) + max_x = max(pt['x'] for pt in gaze_buffer) + min_y = min(pt['y'] for pt in gaze_buffer) + max_y = max(pt['y'] for pt in gaze_buffer) + + range_x = max((max_x - min_x), 0.0001) + range_y = max((max_y - min_y), 0.0001) + + for pt in gaze_buffer: + norm_x = (pt['x'] - min_x) / range_x + norm_y = (pt['y'] - min_y) / range_y + + # Push the coordinates down to where the text actually is + pt['x'] = 0.10 + (norm_x * 0.80) + pt['y'] = 0.50 + (norm_y * 0.30) + + # Targeted Trigger Analysis + triggers = getattr(context, 'metadata', {}).get('triggers', {}) + dyslexia_word = triggers.get('dyslexia') + dyscalculia_num = triggers.get('dyscalculia') + + if dyslexia_word: + word_fixations = [pt for pt in gaze_buffer if self.biometric_engine.is_over_word(pt, dyslexia_word)] + if len(word_fixations) > (fps * 0.8): + phonetic_delay_flag = True + log_clinical_event(context.session_id, f"Phonetic Delay: {dyslexia_word}") + + if dyscalculia_num: + num_fixations = [pt for pt in gaze_buffer if self.biometric_engine.is_over_word(pt, dyscalculia_num)] + num_latency_ms = (len(num_fixations) / fps) * 1000 + if num_latency_ms > 1200: + log_clinical_event(context.session_id, f"Numerical Processing Delay: {dyscalculia_num}") + + raw_biometric_data = { + "regression_count": int(ocular_metrics.get('regression_count', 0)), + "phonetic_delay_detected": phonetic_delay_flag, + "basal_drift": hw_data.get('basal_drift', 0.0), + "slant": hw_data.get('slant', 0.0), + "ocr_error_rate": 1.0 - hw_data.get('ocr_accuracy', 0.0), + "numerical_latency_ms": num_latency_ms, + "confidence_score": compliance["confidence_score"] # โœ… UPDATED: Passes strictly verified score + } + + unified_diagnosis = decision_engine.synthesize_unified_report( + raw_biometric_data, + triggers=getattr(context, 'metadata', {}).get('triggers', {}) + ) + + final_metrics = { + "risk_score": risk_data["risk_score"], "risk_level": risk_data["severity"], + "sync_score": sync_data.get("alignment_score", 100), + "confidence_score": int(compliance["confidence_score"]), # โœ… UPDATED + "is_reliable": compliance["is_reliable"], # โœ… UPDATED + "attentiveness": round(float(attentiveness), 1), "audit_hash": context.report_password, + "basal_drift": round(float(hw_data.get('basal_drift', 0.0)), 2), + "slant": round(float(hw_data.get('slant', 0.0)), 2), + "ocr_accuracy": round(float(fidelity_score / 100.0), 2), + "detected_handwriting": hw_data.get('detected_text', '[No Text Extracted]'), + "saccade_count": int(ocular_metrics.get('saccade_count', 0)), + "regression_count": int(ocular_metrics.get('regression_count', 0)), + "speech_accuracy": round(float(1.0 - raw_wer), 2), "latency": round(avg_latency, 2), "jitter": round(jitter, 2), + "struggle_words": [w['word'] if isinstance(w, dict) else str(w) for w in speech_data.get('struggle_words', [])], + "dyscalculia_marker": num_latency_ms > 1200, + "writing_target": context.writing_target, + "diagnosis_summary": unified_diagnosis + } + + # --- ๐Ÿ“„ 4. ARTIFACTS & DISPATCH --- + + text_canvas_path = self.biometric_engine.create_text_canvas( + context.target_text, + context.session_id, + bounding_box={"top": 0.50, "left": 0.10, "width": 0.80, "height": 0.30} + ) + + heatmap_file = self.biometric_engine.generate_heatmap(gaze_buffer, + text_canvas_path, + context.session_id, + jitter_log=latency_samples, + sigma=1.8) + + pdf_path = generate_dyslexia_report(metrics=final_metrics, heatmap_path=os.path.join(TEMP_DIR, heatmap_file), + session_id=context.session_id, locale=context.locale, + target_text=context.target_text, + trans_text=speech_data.get('transcribed_text', ""), + context=context, writing_target=context.writing_target) + + recipient_email = getattr(context, 'parent_email', 'arrowinthedust@gmail.com') + await email_service.send_report(recipient_email, pdf_path, session_id=context.session_id, metrics=final_metrics) + + canvas_file = os.path.join(TEMP_DIR, f"canvas_{context.session_id}.png") + hw_file = os.path.join(TEMP_DIR, f"hw_{context.session_id}.png") + + purge_list = [ + context.video_path, + context.hw_path, + text_canvas_path, + pdf_path, + canvas_file, + hw_file, + os.path.join(TEMP_DIR, heatmap_file) + ] + + valid_purge_list = [p for p in purge_list if p and os.path.exists(p)] + + background_tasks.add_task( + shredder.deferred_purge, + valid_purge_list, + delay=DATA_PURGE_DELAY + ) + + return {"status": "success", "diagnosis": final_metrics} \ No newline at end of file diff --git a/google_ocr_key.json b/google_ocr_key.json new file mode 100644 index 0000000000000000000000000000000000000000..7d56963af8bf47573460dd67f9233fb143d047ec --- /dev/null +++ b/google_ocr_key.json @@ -0,0 +1,13 @@ +{ + "type": "service_account", + "project_id": "yoda-439408", + "private_key_id": "695dc3b70f91e54df81cb9797afb46bfdf1e32d4", + "private_key": "-----BEGIN PRIVATE KEY-----\nMIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQCwgAjHdkzv+0Xe\nZ2jUJVMGQA74xGf78ey+SVm0SV/RvtckfJI5tAAmird1OMvUmH8sBVWI05UGqwGl\nonIW1LXa3wooH1psxnjwxRo6+fvA9u+YIVWdwjb9Kt3abwVeCg4XxP5IrhGiLJ6u\nLWfXtSD3fVckxNgyt2wCLUD8gbJ6m8AvKzZjlsPcoUbB78CN3rXJWPYjzZEaeMOH\nIVgMbpeutfGvWBthj1iwKRNcHIRsbMpNggyodmmqsxDkHB/j6bN3MElcz7AyG8oo\nBog7Mw1Del3XwRInz9fz4xEsVIflwxNNczHB7EWpcws5Y3onbFbkPv9n2o5YQA9h\nnmGiBXWVAgMBAAECggEAHqNHAtrH/bNsPDBOq97Dw/a8MpYjZ8Jlwl1It0kyWx4p\nyfFez6nticM0F+LRTRjgoHNXlu4FdTgbi9VAQTLQ04q6gF766x1jsoXAaSLqPuOO\nkSWeL0mekoFNrARwFdQggKNHMbYXpQNiUyFaIIFWVOe6yAzsa5dX5iPVX0+jO/GC\nENT1ynlzoE4GgBhh3jaQ5N66gMpeRELsSV8z8EZWEoJMHUlshZt1pWUbb086NUu1\ndts76fdpCboMcc7SrN0sOkKMs9hrLL8oG7s+GLebLFSlAc4VQ0aG1O4/bIlCYx1e\njRCELQSznFOEbo6d+uD8sFxk2GKMqb4ownUTcbedYQKBgQDZUghBT+mtcmMqM+2R\nZxKbq3hSLd4eDSHLk8nVuYTeC6zD92EYqRS18U9ytv8LMMdjE2o/iX0AMZ0pnPm6\nbTUcSS9absWEis5mU85jzVLFJ2m/xZI8Oe5T/6Gt4Ml4GGYHSMFKPkwOlM3g4F1e\nxP6fYK62q01MKADBvqkh4lFa4QKBgQDP6hHQGal+/fXWEpIjCBIlWN8+FV0caZ1e\nQP//xHlTdEFIDnc0Ea0CN8UgHu/tU1f5yaKiGKkWXcJinsK/ZI9m+V/EfGKvij5S\nYtMF8bMqY+MtH7X7TeaCOlyeqyYXpyin+46kcAAWHPOYCXxe6oiBUw51pXL9piCy\n+H101o9FNQKBgAaAruCNbJeVCaSUozIrnGHuEo6a8r+BcxZtWKe9gl1Giife+hfL\nz2PWUaNEGIOUNRMg3JgEHCpqUaKSIOLUK7ep9PHGyMA7iwuCzHUuCqD9met0FPka\nXqhCyOq0BDNEv6DOK4J2NL5m83YcII8aY+gO84thutFhjQw/ET6DUB3hAoGAA2ag\nw/anfxxIWSgUm94V7eZ2QF25GC3iFRibF2PvWB4esz8JVCC148NlxhC7e/ZRChTy\nRBSDL4p5E4PlS5wpfFW3607djmGEg3R6Xy6E77ySirpqD6JGkvrBaRcDmH9zesvy\nmV37omD22xXMowDTGspxAhuiteNxxXurEa4wycECgYB4CDlH4TVynMYIVhWz9YDY\n0zuTmnESX9UnMWJd39UXSGNXOvRl5QS+fiKM/qZEfijOhIzy2vTiB/54HJAMMOV5\nEwJDLDbkgMl1NF+swUOh6P3fo+2PnKnpmrVvp11ZOR/YpmYXxk4xbs6owKc2+aBH\ndXjS1VmyoB/LP6M8c1NSOw==\n-----END PRIVATE KEY-----\n", + "client_email": "dyslexia-mvp-ocr@yoda-439408.iam.gserviceaccount.com", + "client_id": "110359517634267127941", + "auth_uri": "https://accounts.google.com/o/oauth2/auth", + "token_uri": "https://oauth2.googleapis.com/token", + "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs", + "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/dyslexia-mvp-ocr%40yoda-439408.iam.gserviceaccount.com", + "universe_domain": "googleapis.com" +} diff --git a/main.py b/main.py new file mode 100644 index 0000000000000000000000000000000000000000..c5be5fc782ee7f09f0f8503a5abaa75902d5656a --- /dev/null +++ b/main.py @@ -0,0 +1,309 @@ +from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks +from fastapi.middleware.cors import CORSMiddleware +from fastapi.responses import FileResponse +from fastapi.staticfiles import StaticFiles +from services.prompt_service import prompt_service + +import os +import shutil +import logging +import cv2 +import numpy as np +import time +import glob +import smtplib +from email.message import EmailMessage +from typing import Optional +from contextlib import asynccontextmanager +from fastapi_utils.tasks import repeat_every + +from config import ( + DEFAULT_REGION, TEMP_DIR, CORS_ORIGINS, + ASSESSMENT_PROMPTS, WRITING_PROMPTS, + SMTP_SERVER, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, + DATA_PURGE_DELAY +) +from core.base_scanner import ScannerContext +from core.secure_storage import shredder +from core.logger import logger, monitor_perf, log_debug + +from engines.dyslexia.scanner import DyslexiaScanner +from services.biometric_engine import biometric_engine +from core.state import handwriting_cache + +# --- SILENCE VERBOSE LOGGERS --- +silenced = [ + 'numba.core.byteflow', 'numba.core.interpreter', 'numba.core.ssa', + 'multipart', 'python_multipart', 'fpdf.output', + 'PIL.PngImagePlugin', 'pydub.converter', 'fpdf.fpdf' +] +for logger_name in silenced: + logging.getLogger(logger_name).setLevel(logging.WARNING) + +# --- LIFESPAN HANDLER (Modern FastAPI Standard) --- +@asynccontextmanager +async def lifespan(app: FastAPI): + # --- ๐Ÿš€ STARTUP --- + try: + # Properly await the coroutine to prevent RuntimeWarning + await hourly_artifact_cleanup() + logger.info("Clinical Compliance Sweep: Initialized and Awaited.") + except Exception as e: + logger.error(f"Initial cleanup failed: {e}") + + yield # Component remains active for requests + + # --- ๐Ÿ›‘ SHUTDOWN --- + # 1. Final Purge of all temporary artifacts + purged_count = 0 + if os.path.exists(TEMP_DIR): + for f in os.listdir(TEMP_DIR): + path = os.path.join(TEMP_DIR, f) + try: + if os.path.isfile(path): + os.remove(path) + purged_count += 1 + elif os.path.isdir(path): + shutil.rmtree(path) + purged_count += 1 + except Exception as e: + logger.error(f"Shutdown purge error for {f}: {e}") + + # 2. Security Heartbeat Email + try: + msg = EmailMessage() + msg['Subject'] = "๐Ÿ”’ LearnView Pro: Final Security Heartbeat" + msg['From'] = SMTP_USER + msg['To'] = SMTP_USER + msg.set_content( + f"Server Shutdown Protocol Complete.\n\n" + f"Final Audit: {purged_count} artifacts purged from HIPAA cache.\n" + f"Status: Zero-Persistence Integrity Maintained.\n" + f"Timestamp: {time.ctime()}" + ) + + with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server: + server.login(SMTP_USER, SMTP_PASSWORD) + server.send_message(msg) + logger.info("๐Ÿ“ง Security Heartbeat: Sent successfully.") + except Exception as e: + logger.error(f"Security Heartbeat failed: {e}") + + logger.info("Clinical Hub: Shutdown and Final Purge Complete.") + +# --- INITIALIZE APP --- +app = FastAPI(title="LearnView Pro: Diagnostic Hub", lifespan=lifespan) + +app.add_middleware( + CORSMiddleware, + allow_origins=CORS_ORIGINS, + allow_credentials=True, + allow_methods=["*"], + allow_headers=["*"], +) + +# Custom StaticFiles to prevent caching of clinical artifacts +class AccessibleStaticFiles(StaticFiles): + async def get_response(self, path: str, scope): + response = await super().get_response(path, scope) + response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate" + response.headers["Access-Control-Allow-Origin"] = "*" + return response + +os.makedirs(TEMP_DIR, exist_ok=True) +app.mount("/temp_reports", AccessibleStaticFiles(directory=TEMP_DIR), name="temp_reports") + +SCANNERS = {"dyslexia": DyslexiaScanner()} + +# --- UTILITIES --- +def decode_frame(byte_data: bytes): + nparr = np.frombuffer(byte_data, np.uint8) + return cv2.imdecode(nparr, cv2.IMREAD_COLOR) + +# --- DISPATCHER ENDPOINTS --- + +@app.post("/purge/{session_id}") +async def purge_session_artifacts(session_id: str): + """Scans TEMP_DIR for files related to session_id and deletes them.""" + try: + pattern = os.path.join(TEMP_DIR, f"*{session_id}*") + files_to_delete = glob.glob(pattern) + + if not files_to_delete: + return {"status": "already_clean", "session_id": session_id} + + for file_path in files_to_delete: + if os.path.isfile(file_path): + os.remove(file_path) + elif os.path.isdir(file_path): + shutil.rmtree(file_path) + + return {"status": "success", "purged_count": len(files_to_delete)} + except Exception as e: + raise HTTPException(status_code=500, detail=f"Purge failed: {str(e)}") + +@app.get("/health") +async def health_check(): + """Heartbeat for telemetry and latency measurements.""" + return {"status": "online", "version": "2.0.0"} + +@app.get("/get-ocr-preview/{session_id}") +async def get_ocr_preview(session_id: str): + """Retrieves Google OCR preview for clinical intake.""" + data = handwriting_cache.get(session_id) + if not data: return {"text": "Processing handwriting..."} + return {"text": data.get("detected_text", "No text detected")} + +@app.get("/get-prompt") +async def get_prompt(level: str = "beginner"): + """Returns clinical reading and writing targets based on level.""" + lvl = level.strip().lower() + session_package = prompt_service.generate_balanced_session(lvl) + return { + "level": lvl, + "reading_task": session_package["reading_task"], + "writing_task": session_package["writing_task"], + "triggers": session_package["metadata"]["triggers"] + } + +@monitor_perf +@app.post("/analyze") +async def analyze_session( + background_tasks: BackgroundTasks, + video: UploadFile = File(...), + handwriting: Optional[UploadFile] = File(None), + session_id: str = Form("anonymous"), + full_name: str = Form("Unknown"), + child_class: str = Form("N/A"), + level: str = Form("beginner"), + target_text: str = Form("Default Task"), + parent_email: Optional[str] = Form(None), + adult_id: str = Form("anonymous"), + locale: str = Form(None), + scanner_type: str = Form("dyslexia"), + is_demo: bool = Form(False), + flatten: bool = Form(True), + latency: str = Form("0"), + writing_target: str = Form(""), +): + """Clinical processing dispatcher with strict target enforcement.""" + video_path = os.path.join(TEMP_DIR, f"vid_{session_id}.webm") + hw_path = os.path.join(TEMP_DIR, f"hw_{session_id}.png") if handwriting else None + + if is_demo: + return {"status": "success", "diagnosis": {"risk_score": 45.0, "report_password": session_id}} + + try: + with open(video_path, "wb") as buffer: + shutil.copyfileobj(video.file, buffer) + if handwriting: + with open(hw_path, "wb") as buffer: + shutil.copyfileobj(handwriting.file, buffer) + + generated_hash = biometric_engine.generate_audit_hash() + + # โœ… FIX: Strict Fallback to ensure Lexical Fidelity calculation doesn't fail + actual_writing_target = writing_target if writing_target and len(writing_target) > 2 else WRITING_PROMPTS.get(level.lower(), WRITING_PROMPTS["beginner"]) + + context = ScannerContext( + session_id=session_id, adult_id=adult_id, latency=latency, + child_name=full_name, child_class=child_class, level=level, + locale=locale or DEFAULT_REGION, target_text=target_text, + writing_target=actual_writing_target, # โœ… Passed to context + parent_email=parent_email, video_path=video_path, hw_path=hw_path, + report_password=generated_hash + ) + + scanner = SCANNERS.get(scanner_type, SCANNERS["dyslexia"]) + + # โœ… FIX: Ensure background tasks receive the writing_target for PDF generation + result = await scanner.analyze(context, background_tasks) + result["diagnosis"]["writing_target"] = actual_writing_target + + diag = result.get("diagnosis", {}) + diag["writing_target"] = actual_writing_target + if flatten: + diag["struggle_words"] = [w['word'] if isinstance(w, dict) else str(w) for w in diag.get("struggle_words", [])] + + diag["session_id"] = session_id + diag["audit_hash"] = generated_hash + # Ensure writing_target is returned to frontend for the Interpretive View + diag["writing_target"] = actual_writing_target + + return {"status": "success", "diagnosis": result["diagnosis"], "purge_delay": DATA_PURGE_DELAY} + + except Exception as e: + logger.error(f"๐Ÿ”ฅ Dispatcher Failure: {str(e)}", exc_info=True) + shredder.instant_purge([video_path, hw_path or ""]) + raise HTTPException(status_code=500, detail="Clinical processing engine failed.") + + +@app.post("/upload-handwriting/{session_id}") +async def upload_handwriting(session_id: str, file: UploadFile, background_tasks: BackgroundTasks): + """Handles separate handwriting upload for OCR preprocessing.""" + file_path = os.path.join(TEMP_DIR, f"hw_{session_id}.png") + with open(file_path, "wb") as buffer: + shutil.copyfileobj(file.file, buffer) + background_tasks.add_task(run_async_ocr, session_id, file_path) + log_debug("Handwriting Uploaded") + return {"status": "processing"} + +async def run_async_ocr(session_id, file_path): + """Background task for Google Vision analysis.""" + logger.info(f"๐Ÿ›ฐ๏ธ OCR START: Session {session_id}") + try: + # Defaults to beginner prompt for extraction if none provided + results = biometric_engine.analyze_handwriting(file_path, session_id, WRITING_PROMPTS.get("beginner")) + handwriting_cache[session_id] = results + logger.info(f"โœ… OCR COMPLETE: Session {session_id}") + except Exception as e: + logger.error(f"โŒ OCR FAILURE: {str(e)}") + +@app.post("/verify-quality") +async def verify_quality(frame: UploadFile = File(...)): + """Real-time environment and positioning verification.""" + try: + contents = await frame.read() + results = biometric_engine.verify_environment(decode_frame(contents)) + # 1: Too Far, 2: Too Close, 3: Poor Lighting, 4: Ready + step_code = 4 if results["ready"] else (1 if results["iris_dist"] < 0.075 else 2) + if not results.get("lighting_ok"): step_code = 3 + return {**results, "step_code": step_code} + except Exception as e: + return {"ready": False, "step_code": 0, "status": "SYSTEM_ERROR"} + +@app.get("/download-report/{filename}") +async def download_report(filename: str): + """Secure endpoint for downloading the clinical PDF.""" + file_path = os.path.join(TEMP_DIR, filename) + if os.path.exists(file_path): return FileResponse(file_path) + raise HTTPException(status_code=404, detail="Artifact not found.") + +@repeat_every(seconds=3600) +async def hourly_artifact_cleanup(): + """๐Ÿงน Clinical Compliance Sweep: Deletes artifacts older than 1 hour.""" + if not os.path.exists(TEMP_DIR): + return + + now = time.time() + count = 0 + for filename in os.listdir(TEMP_DIR): + file_path = os.path.join(TEMP_DIR, filename) + try: + if os.path.getmtime(file_path) < (now - 3600): + if os.path.isfile(file_path): + os.remove(file_path) + count += 1 + elif os.path.isdir(file_path): + shutil.rmtree(file_path) + count += 1 + except Exception as e: + logger.error(f"Cleanup error for {filename}: {e}") + + if count > 0: + logger.info(f"Purged {count} expired clinical artifacts.") + +if __name__ == "__main__": + import uvicorn + # Use 0.0.0.0 to allow LAN access for mobile stance testing + uvicorn.run(app, host="0.0.0.0", port=8000) \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000000000000000000000000000000000000..3575a04aeeff02df5c44965243b405a4bbb9e1cf --- /dev/null +++ b/requirements.txt @@ -0,0 +1,43 @@ +# --- Core API & Server --- +fastapi==0.128.0 +uvicorn[standard] +python-multipart +fastapi-utils +typing-inspect +mypy-extensions + +# --- Security & Auth --- +cryptography +pyopenssl + +# --- The "Plumbing" (CRITICAL: These stop the backtracking loop) --- +protobuf>=3.20.3,<5.0.0dev +grpcio>=1.51.1 +grpcio-status>=1.51.1 + +# --- Biometrics & Vision --- +opencv-python-headless +mediapipe==0.10.9 +google-cloud-vision + +# --- Audio & Speech --- +librosa==0.11.0 +openai-whisper +noisereduce +speechrecognition +jiwer + +# --- ML & Math --- +torch --index-url https://download.pytorch.org/whl/cpu +numpy==2.2.6 +scikit-learn +scipy +sympy + +# --- Reporting & Utilities --- +fpdf2==2.8.5 +pikepdf +matplotlib +email-validator +jinja2 +pytest \ No newline at end of file diff --git a/services/__init__.py b/services/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/services/__pycache__/__init__.cpython-310.pyc b/services/__pycache__/__init__.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..c24bd937f7ee1cd546527050772b6ae775d72fdd Binary files /dev/null and b/services/__pycache__/__init__.cpython-310.pyc differ diff --git a/services/__pycache__/biometric_engine.cpython-310.pyc b/services/__pycache__/biometric_engine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..ec96567eb9e74a1bdfa66fb0e643048edc3a59dc Binary files /dev/null and b/services/__pycache__/biometric_engine.cpython-310.pyc differ diff --git a/services/__pycache__/decision.cpython-310.pyc b/services/__pycache__/decision.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..cd9d33c501119aef3df1ebfac6dcc5140c5bf00e Binary files /dev/null and b/services/__pycache__/decision.cpython-310.pyc differ diff --git a/services/__pycache__/decision_engine.cpython-310.pyc b/services/__pycache__/decision_engine.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..36f9cb03aacbdccf2865d048cd2a8ce02e881a2c Binary files /dev/null and b/services/__pycache__/decision_engine.cpython-310.pyc differ diff --git a/services/__pycache__/email_service.cpython-310.pyc b/services/__pycache__/email_service.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3ee3ef540d4af989457e53c1d854d3546a1a04c2 Binary files /dev/null and b/services/__pycache__/email_service.cpython-310.pyc differ diff --git a/services/__pycache__/ocr_service.cpython-310.pyc b/services/__pycache__/ocr_service.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..d7a94bcd72c43af8bcc294311048cb52b1d2c8bc Binary files /dev/null and b/services/__pycache__/ocr_service.cpython-310.pyc differ diff --git a/services/__pycache__/pdf_generator.cpython-310.pyc b/services/__pycache__/pdf_generator.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0da0d255c2fc337f790c85974d4e71c29a64a4f6 Binary files /dev/null and b/services/__pycache__/pdf_generator.cpython-310.pyc differ diff --git a/services/__pycache__/prompt_service.cpython-310.pyc b/services/__pycache__/prompt_service.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..3a39c71416ca0af90707e77b1a5968b282f98bce Binary files /dev/null and b/services/__pycache__/prompt_service.cpython-310.pyc differ diff --git a/services/__pycache__/speech_analysis.cpython-310.pyc b/services/__pycache__/speech_analysis.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..18834fcfa4482085d0854f05656c2c0b12bc38b7 Binary files /dev/null and b/services/__pycache__/speech_analysis.cpython-310.pyc differ diff --git a/services/__pycache__/video_service.cpython-310.pyc b/services/__pycache__/video_service.cpython-310.pyc new file mode 100644 index 0000000000000000000000000000000000000000..0a2250d8fe66aabda7e8d97420a5e81f15d6ae56 Binary files /dev/null and b/services/__pycache__/video_service.cpython-310.pyc differ diff --git a/services/biometric_engine.py b/services/biometric_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..03172d7175c0fda5cd9afdc0a2d7fae793dfdf6e --- /dev/null +++ b/services/biometric_engine.py @@ -0,0 +1,396 @@ +import os +import cv2 +import numpy as np +import mediapipe as mp +import math +import threading +from jiwer import cer +from core.logger import log_debug, logger +from config import TEMP_DIR +from config import CLINICAL_DISTANCE_MIN, CLINICAL_DISTANCE_MAX, STATIONARY_FRAME_THRESHOLD +from services.ocr_service import OCRService +import hashlib +import time +import difflib + +class BiometricEngine: + _instance = None + _lock = threading.Lock() + + def __new__(cls): + with cls._lock: + if cls._instance is None: + log_debug("๐Ÿš€ Initializing Hybrid Clinical Engine (V8 Production)...") + cls._instance = super(BiometricEngine, cls).__new__(cls) + + # ๐Ÿ›ก๏ธ THE RAILWAY/CPU FIX: Force CPU mode + os.environ['MEDIAPIPE_DISABLE_GPU'] = '1' + cls._instance.mp_face_mesh = mp.solutions.face_mesh + + cls._instance.face_mesh = cls._instance.mp_face_mesh.FaceMesh( + static_image_mode=False, + max_num_faces=1, + refine_landmarks=True, + min_detection_confidence=0.5, + min_tracking_confidence=0.5 + ) + + # ๐Ÿ”Œ PLUG-AND-PLAY OCR + cls._instance.ocr_engine = OCRService(provider="google") + + # โšก OCR PRE-WARM CACHE: Stores background results from Intake + cls._instance._ocr_cache = {} + + return cls._instance + + def process_frame(self, rgb_frame): + """Thread-safe processing optimized for CPU execution.""" + with self._lock: + return self.face_mesh.process(rgb_frame) + + # --- ๐Ÿ“ HANDWRITING & DYSGRAPHIA ANALYSIS (V8) --- + + def calculate_cer(self, target_text: str, detected_text: str) -> float: + """ + Calculates Character Error Rate (CER) using Levenshtein distance approximations. + Strictly penalizes mismatched or 'cheated' text. + """ + if not detected_text or detected_text in ["[No Text Extracted]", "[Processing...]"]: + return 1.0 # 100% error (Task Failure) + + # Clean and normalize texts for comparison + t1 = target_text.lower().strip() + t2 = detected_text.lower().strip() + + # SequenceMatcher ratio returns 1.0 for a perfect match + similarity = difflib.SequenceMatcher(None, t1, t2).ratio() + cer = 1.0 - similarity + + # ๐Ÿšจ CLINICAL PENALTY: Task Non-Compliance + if cer > 0.40: + return 1.0 + + return cer + + def process_handwriting_kinetics(self, image_path: str) -> dict: + """ + Analyzes Basal Drift and Slant. Fails securely if handwriting is erratic. + """ + if not os.path.exists(image_path): + log_debug(f"โš ๏ธ Kinetic error: File not found at {image_path}") + return {"basal_drift": 25.0, "slant": 30.0, "lines_detected": 0} + + img = cv2.imread(image_path) + if img is None: + return {"basal_drift": 25.0, "slant": 30.0, "lines_detected": 0} + + gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + + # Adaptive thresholding helps with poor lighting/shadows on phone uploads + blurred = cv2.GaussianBlur(gray, (5, 5), 0) + edges = cv2.Canny(blurred, 50, 150, apertureSize=3) + + # Detect lines in the handwriting + lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=50, minLineLength=30, maxLineGap=10) + + # ๐Ÿšจ CLINICAL PENALTY: Illegible / Erratic Writing Fallback + if lines is None or len(lines) == 0: + return { + "basal_drift": 25.0, # Max clinical penalty for drift + "slant": 30.0, # Max clinical penalty for slant + "lines_detected": 0 + } + + # Calculate the median angle of all detected baselines + angles = [] + for line in lines: + x1, y1, x2, y2 = line[0] + angle = math.degrees(math.atan2(y2 - y1, x2 - x1)) + angles.append(angle) + + basal_drift = np.median(angles) + + # Calculate Character Slant using Vertical Projection Profile + slant = self.calculate_slant_v2(gray) + + return { + "basal_drift": float(basal_drift), + "slant": float(slant), + "lines_detected": len(lines) + } + + def calculate_iris_depth(self, face_landmarks, frame_height=720) -> float: + """ + โœ… FIXED: Matches Svelte 5 normalized coordinate math exactly to prevent 0% HW Confidence. + Estimates distance in cm, factoring in FOV and resolution. + """ + lm = face_landmarks.landmark + + # Calculate raw normalized screen distance just like frontend JS + dx = lm[468].x - lm[473].x + dy = lm[468].y - lm[473].y + dz = lm[468].z - lm[473].z + ipd_screen = math.sqrt(dx*dx + dy*dy + dz*dz) + + # Factor in 45-degree vertical FOV + v_fov_rad = math.radians(45) + focal_length = (frame_height / 2) / math.tan(v_fov_rad / 2) + + # Real IPD average (6.3cm) + distance_cm = (6.3 * focal_length) / (ipd_screen * frame_height + 0.000001) + return distance_cm + + + def calculate_writing_risk(self, basal_drift, slant_angle, ocr_accuracy): + """Clinical mapping for the Synthesis Risk Score.""" + drift_score = min(abs(basal_drift) * 15, 40) + slant_score = min(abs(slant_angle) * 2, 30) + accuracy_penalty = (1.0 - ocr_accuracy) * 30 + + total_risk = drift_score + slant_score + accuracy_penalty + level = "Low" + if total_risk >= 55: level = "High" + elif total_risk >= 25: level = "Moderate" + + return round(total_risk, 1), level + + # --- ๐Ÿ‘๏ธ OCULAR GAZE ANALYSIS --- + + def verify_environment(self, frame): + """Validates clinical distance and lighting.""" + results = self.process_frame(frame) + if not results.multi_face_landmarks: + return {"ready": False, "status": "No face detected"} + + lm = results.multi_face_landmarks[0].landmark + iris_dist = self.calculate_iris_depth(results.multi_face_landmarks[0]) + + dist_ok = bool(CLINICAL_DISTANCE_MIN < iris_dist < CLINICAL_DISTANCE_MAX) + lighting_ok = bool(np.mean(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)) > 80) + + status = "Ready" + if iris_dist > 0.13: status = "Too Close" + elif iris_dist < 0.075: status = "Too Far" + elif not lighting_ok: status = "Too Dark" + + return { + "ready": bool(dist_ok and lighting_ok), + "iris_dist": round(float(iris_dist), 4), + "status": status + } + + def analyze_gaze_v2(self, gaze_buffer): + """Refined sensitivity to match pre-refactor ocular event tracking.""" + if len(gaze_buffer) < 5: + return {"saccade_count": 0, "regression_count": 0, "phonetic_blocks": 0} + + mean_id = np.mean([g.get('id', 0.1) for g in gaze_buffer]) + scale = mean_id / 0.1 + + saccades, regressions = 0, 0 + for i in range(1, len(gaze_buffer)): + dx = gaze_buffer[i]['x'] - gaze_buffer[i-1]['x'] + + if dx < (-0.0015 * scale) and abs(dx) < 0.35: + regressions += 1 + elif dx > (0.004 * scale): + saccades += 1 + + return { + "saccade_count": saccades, + "regression_count": regressions, + "phonetic_blocks": len(gaze_buffer) // 18 + } + + # --- ๐Ÿ–ผ๏ธ VISUALIZATION TOOLS --- + + def generate_heatmap(self, gaze_buffer, canvas_path, session_id, jitter_log=None, sigma=1.8): + """ + Generates gaze heatmap with coordinate scaling, optional jitter timeline, and clinical blur. + """ + img = cv2.imread(canvas_path) + if img is None: + log_debug(f"โŒ Heatmap Fail: Canvas not found at {canvas_path}") + return None + + h, w = img.shape[:2] + heat_layer = np.zeros((h, w, 3), dtype=np.uint8) + + # 1. Map Gaze Points (Scaled to canvas size) + for pt in gaze_buffer: + x = int(pt['x'] * w) + y = int(pt['y'] * h) + + if 0 <= x < w and 0 <= y < h: + # Draw sharp points first + cv2.circle(heat_layer, (x, y), 15, (0, 0, 255), -1) + + blur_kernel = int(sigma * 25) + if blur_kernel % 2 == 0: blur_kernel += 1 # Kernel must be odd + + if blur_kernel > 1: + heat_layer = cv2.GaussianBlur(heat_layer, (blur_kernel, blur_kernel), sigmaX=sigma*15) + + # Blend ONLY the colored heat pixels onto the white canvas (preserves white background) + mask = heat_layer > 0 + img[mask] = cv2.addWeighted(img, 0.4, heat_layer, 0.8, 0)[mask] + + # 2. Network Stability Overlay (Bottom 5% of image) + if jitter_log and len(jitter_log) > 0: + bar_h = int(h * 0.05) + for i, jitter_val in enumerate(jitter_log): + x_pos = int((i / len(jitter_log)) * w) + color_intensity = min(255, int((jitter_val * 1000) / 50 * 255)) + cv2.line(img, (x_pos, h - bar_h), (x_pos, h), (0, 0, color_intensity), 1) + + output_name = f"heatmap_{session_id}.png" + cv2.imwrite(os.path.join(TEMP_DIR, output_name), img) + return output_name + + def create_text_canvas(self, text, session_id, canvas_width=1280, canvas_height=720, bounding_box=None): + """ + Dynamically positions the text based on the UI bounding box to ensure gaze coordinates align. + Uses Clinical Calm palette and left-aligned Sans-Serif font for Dyslexia accessibility. + """ + canvas = np.full((canvas_height, canvas_width, 3), (247, 251, 253), dtype=np.uint8) + font = cv2.FONT_HERSHEY_SIMPLEX + scale, thick = 1.1, 2 + text_color = (85, 65, 51) # Slate-700 + + if bounding_box: + box_x = int(bounding_box.get("left", 0.1) * canvas_width) + box_y = int(bounding_box.get("top", 0.5) * canvas_height) + max_width = int(bounding_box.get("width", 0.8) * canvas_width) + y = box_y + 60 + else: + box_x = 0 + max_width = 1000 + y = 300 + + words = text.split(' ') + line = "" + + for word in words: + if cv2.getTextSize(line + " " + word, font, scale, thick)[0][0] < max_width: + line += " " + word + else: + start_x = box_x + 40 + cv2.putText(canvas, line.strip(), (start_x, y), font, scale, text_color, thick, cv2.LINE_AA) + y += 60 + line = word + + start_x = box_x + 40 + cv2.putText(canvas, line.strip(), (start_x, y), font, scale, text_color, thick, cv2.LINE_AA) + + path = os.path.join(TEMP_DIR, f"canvas_{session_id}.png") + cv2.imwrite(path, canvas) + return path + + def analyze_compliance(self, distance_logs: list) -> dict: + """๐Ÿ“ GLOBAL ENFORCEMENT: 80cm Max Permissible.""" + if not distance_logs: return {"confidence_score": 0, "is_reliable": False} + + total = len(distance_logs) + # Permissible zone strictly locked to 80cm + valid = [d for d in distance_logs if 40 <= d <= 80] + optimal = [d for d in distance_logs if 50 <= d <= 65] + + score = (len(valid) / total) * 100 + return { + "confidence_score": round(score, 1), + "is_reliable": score > 80, # High confidence requires 80% frames within bounds + "optimal_percentage": round((len(optimal) / total) * 100, 1) + } + + def get_ui_metrics(self, biometric_results): + """Formats drift and gaze data for the ResultsDashboard.""" + drift = biometric_results.get('basal_drift', 0) + status_color = "green" + if abs(drift) > 5: status_color = "red" + elif abs(drift) > 2.5: status_color = "amber" + + return { + "writing": { + "drift_value": f"{drift}ยฐ", + "drift_direction": "Ascending" if drift > 0 else "Descending", + "status_color": status_color, + "accuracy": f"{int(biometric_results.get('ocr_accuracy', 0)*100)}%", + "display_text": biometric_results.get('detected_text', "NONE") + }, + "ocular": { + "sync_percentage": biometric_results.get('sync_score', 0), + "fixation_count": biometric_results.get('phonetic_blocks', 0), + "regression_warning": biometric_results.get('regression_count', 0) > 10 + } + } + + def calculate_slant_v2(self, gray_img): + """Vertical Projection Profile to identify true character slant.""" + _, thresh = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU) + + best_angle = 0 + max_variance = 0 + + for angle in range(-30, 31, 2): + m = np.float32([[1, np.tan(np.radians(angle)), 0], [0, 1, 0]]) + sheared = cv2.warpAffine(thresh, m, (thresh.shape[1], thresh.shape[0])) + + projection = np.sum(sheared, axis=0) + + variance = np.var(projection) + if variance > max_variance: + max_variance = variance + best_angle = angle + + return best_angle + + # --- ๐Ÿ“ UNIFIED HANDWRITING & DYSGRAPHIA ANALYSIS (V8) --- + + def analyze_handwriting(self, image_path: str, session_id: str, target_text: str = None): + """Unified V8 Handwriting Pipeline.""" + img = cv2.imread(image_path) + if img is None: + return {"slant": 0.0, "basal_drift": 0.0, "ocr_accuracy": 0.0, "detected_text": "[Error]"} + + # 1. ๐Ÿ”ก CLOUD OCR + raw_output = self.ocr_engine.extract_text(image_path) + + # 2. ๐Ÿ“ KINETIC AUDIT + gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + edges = cv2.Canny(gray, 50, 150) + lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=100, maxLineGap=10) + + basal_drift_angle = 0.0 + if lines is not None: + angles = [math.degrees(math.atan2(l[0][3]-l[0][1], l[0][2]-l[0][0])) for l in lines] + basal_drift_angle = np.median(angles) + + slant_angle = self.calculate_slant_v2(gray) + + # 3. ๐Ÿ“Š SCORING + accuracy = 0.0 + if target_text and raw_output: + accuracy = round(max(0, 1.0 - cer(target_text.lower(), raw_output.lower())), 2) + + result = { + "slant": round(float(slant_angle), 2), + "basal_drift": round(float(basal_drift_angle), 2), + "ocr_accuracy": accuracy, + "detected_text": raw_output if raw_output else "[Handwriting Unreadable]", + "ocr_confidence": 95 if raw_output else 0 + } + + # Sync with global cache for Scanner retrieval + from core.state import handwriting_cache + handwriting_cache[session_id] = result + + return result + + def generate_audit_hash(self) -> str: + """๐ŸŽฏ RESTORED: Generates a 6-digit purely numeric Audit Key.""" + seed = f"learnview_audit_{time.time()}" + hash_int = int(hashlib.sha256(seed.encode()).hexdigest(), 16) + numeric_code = str(hash_int % 1000000).zfill(6) + return numeric_code + +biometric_engine = BiometricEngine() \ No newline at end of file diff --git a/services/content_service.py b/services/content_service.py new file mode 100644 index 0000000000000000000000000000000000000000..a63a51e30096b941863c1ff1d7c15f1e1ba0b3dc --- /dev/null +++ b/services/content_service.py @@ -0,0 +1,20 @@ +class ContentService: + def get_prompt_by_level(self, level, region="AU_VIC"): + # Calibration of text length for optimal 30-60 second biometric sample + prompts = { + "beginner": { + "text": "The cat sat on the mat. The sun is hot. I like to run and play in the green grass.", + "complexity": "Low" + }, + "intermediate": { + "text": "The quick brown fox jumps over the lazy dog. Bright stars shine in the deep blue sky. Small birds sing sweet songs in the morning sun.", + "complexity": "Medium" + }, + "advanced": { + "text": "A shimmering silver moon rose over the silent mountains. The adventurous explorer discovered a hidden valley filled with ancient secrets.", + "complexity": "High" + } + } + return prompts.get(level.lower(), prompts["intermediate"]) + +content_service = ContentService() \ No newline at end of file diff --git a/services/decision_engine.py b/services/decision_engine.py new file mode 100644 index 0000000000000000000000000000000000000000..03468ce21722ee51a286470b1f2afa7ca50628df --- /dev/null +++ b/services/decision_engine.py @@ -0,0 +1,147 @@ +import threading +import numpy as np +import math +from engines.dyslexia.logic import DyslexiaStrategy +from core.logger import log_debug + +class DecisionEngine: + _instance = None + _lock = threading.Lock() + + _strategies = { + "dyslexia": DyslexiaStrategy() + } + + def __new__(cls): + with cls._lock: + if cls._instance is None: + cls._instance = super(DecisionEngine, cls).__new__(cls) + log_debug("โš–๏ธ Unified Decision Engine Initialized") + return cls._instance + + def calculate_risk(self, metrics: dict, profile: str = "dyslexia") -> dict: + """Weights diverse signals and applies calibration offset [cite: 2026-03-01].""" + strategy = self._strategies.get(profile, self._strategies["dyslexia"]) + final_score = strategy.calculate(metrics) + + return { + "risk_score": round(final_score, 1), + "severity": "High" if final_score > 70 else "Moderate" if final_score > 35 else "Low" + } + + def synthesize_ocular_phonetic_sync(self, gaze_buffer, word_alignment, fps=30): + """Measures real-time lag between visual path and verbal output[cite: 6, 12].""" + if not gaze_buffer or not word_alignment: + return {"alignment_score": 0, "desync_events": 0, "phonetic_blocks": 0, "clinical_note": "Insufficient Data"} + + sync_matches, desync_events, total_checks = 0, 0, 0 + + for word in word_alignment: + start_t = word['start'] + end_t = word['end'] + + # Filter gaze points by absolute timestamp [cite: 55] + word_gaze_points = [ + p for p in gaze_buffer + if start_t <= p.get('timestamp', 0) <= end_t + ] + + if not word_gaze_points: + continue + + # โœ… FIXED: Every word with valid gaze data counts as a Phonetic Fixation [cite: 12] + total_checks += 1 + x_coords = [p['x'] for p in word_gaze_points] + + # Dyslexia Marker: Regressive eye movements + is_backtracking = any(x_coords[i] < x_coords[i-1] - 0.05 for i in range(1, len(x_coords))) + + if is_backtracking: + desync_events += 1 + else: + sync_matches += 1 + + alignment_score = (sync_matches / total_checks * 100) if total_checks > 0 else 0 + + return { + "alignment_score": round(alignment_score, 1), + "desync_events": desync_events, + "phonetic_blocks": total_checks, # ๐ŸŽฏ This populates the UI count [cite: 12] + "clinical_note": "High" if alignment_score > 80 else "Critical Lag" + } + + def calculate_confidence(self, quality_audit, gaze_buffer): + """ + Evaluates hardware performance and positional stability [cite: 2026-03-01]. + GUARD CLAUSE: Prevents hardware quality overflow (e.g., 10000%). + """ + # Initialize at 100% [cite: 2026-03-01] + confidence = 100 + + # ๐Ÿ“ก 1. Network/Processing Stability [cite: 2026-03-01] + fps = quality_audit.get('fps', 30) + jitter = quality_audit.get('jitter', 0) + latency = quality_audit.get('avg_latency', 0) + + # Penalty for low frame rates [cite: 2026-03-01] + if fps < 24: confidence -= 15 + if fps > 15: confidence -= 30 + + # Penalty for high jitter (unstable data stream) [cite: 2026-03-01] + if jitter > 20: confidence -= 10 + if jitter > 50: confidence -= 20 + + # Penalty for extreme processing lag [cite: 2026-03-01] + if latency > 150: confidence -= 15 + + # ๐Ÿ‘๏ธ 2. Biometric Stability [cite: 2026-03-01] + if not gaze_buffer: + return 10 # Minimal confidence if no data exists + + id_values = [g.get('id', 0.1) for g in gaze_buffer] + # High IPD variance indicates excessive user movement or tracking loss [cite: 2026-03-01] + if id_values and len(id_values) > 10: + if np.var(id_values) > 0.005: + confidence -= 20 + + # ๐Ÿ›ก๏ธ 3. Final Guardrail: Hard ceiling and floor [cite: 2026-03-01] + # This prevents the 10000% error by forcing the result into 10-100 range. + final_quality = int(max(min(confidence, 100), 10)) + + return int(final_quality) + + def synthesize_unified_report(self, metrics: dict, triggers: dict) -> dict: + """ + Synthesizes raw biometric data into specific learning disability risk scores. + """ + # 1. ๐Ÿ‘๏ธ DYSLEXIA SCORE (Ocular-Verbal Sync + Regressions) + # Combines the regression count with gaze duration on phonetic triggers + phonetic_delay = metrics.get('phonetic_delay_detected', False) + dyslexia_risk = (metrics.get('regression_count', 0) * 5) + (25 if phonetic_delay else 0) + + # 2. โœ๏ธ DYSGRAPHIA SCORE (Basal Drift + Kinetic Fatigue) + # Measures the change in slant and horizontal drift over the 2-sentence task + drift = abs(metrics.get('basal_drift', 0)) + slant = abs(metrics.get('slant', 0)) + dysgraphia_risk = (drift * 3.5) + (slant * 2.0) + (metrics.get('ocr_error_rate', 0) * 40) + + # 3. ๐Ÿ”ข DYSCALCULIA SCORE (Subitizing Latency) + # Specifically uses the numerical trigger from the PromptGenerator + num_latency = metrics.get('numerical_latency_ms', 0) + dyscalculia_risk = 0 + if num_latency > 1200: # Standard clinical threshold for subitizing delay + dyscalculia_risk = min(100, (num_latency - 1000) / 10) + + return { + "dyslexia": {"score": min(100, dyslexia_risk), "severity": self._get_severity(dyslexia_risk)}, + "dysgraphia": {"score": min(100, dysgraphia_risk), "severity": self._get_severity(dysgraphia_risk)}, + "dyscalculia": {"score": min(100, dyscalculia_risk), "severity": self._get_severity(dyscalculia_risk)}, + "overall_confidence": metrics.get('confidence_score', 0) + } + + def _get_severity(self, score: float) -> str: + if score > 70: return "High" + if score > 35: return "Moderate" + return "Low" + +decision_engine = DecisionEngine() \ No newline at end of file diff --git a/services/email_service.py b/services/email_service.py new file mode 100644 index 0000000000000000000000000000000000000000..44841153b06af6849260a9d26a4ae1c282e8e30a --- /dev/null +++ b/services/email_service.py @@ -0,0 +1,112 @@ +import os +import smtplib +import socket +import ssl +from email.mime.multipart import MIMEMultipart +from email.mime.text import MIMEText +from email.mime.application import MIMEApplication +from core.logger import logger + +# ๐ŸŽฏ THE RAILWAY PRODUCTION FIX: Force IPv4 +# Prevents "Network is unreachable" errors by stopping the container +# from attempting to route through IPv6 addresses in the cluster. +old_getaddrinfo = socket.getaddrinfo +def new_getaddrinfo(*args, **kwargs): + res = old_getaddrinfo(*args, **kwargs) + return [r for r in res if r[0] == socket.AF_INET] +socket.getaddrinfo = new_getaddrinfo + +class EmailService: + def __init__(self): + self.sender = os.getenv("SENDER_EMAIL") + self.password = os.getenv("SENDER_PASSWORD") + self.smtp_server = os.getenv("SMTP_SERVER", "smtp.gmail.com") + + try: + # Standardizing on 465 for SSL stability in Railway containers + self.smtp_port = int(os.getenv("SMTP_PORT", 465)) + except (TypeError, ValueError): + self.smtp_port = 465 + + def generate_risk_narrative(self, metrics: dict, locale: str): + """Generates localized clinical insights for the regional pilot.""" + risk = metrics.get('risk_score', 0) + + if locale == "IN_NEP": + if risk > 70: + return "Significant gaps in Foundational Literacy. Remedial coaching recommended." + elif risk > 35: + return "Moderate decoding fatigue observed. Supplemental support advised." + return "Foundational literacy markers within expected ranges." + else: + if risk > 70: + return "Biometric markers suggest high probability of phonological processing challenges." + elif risk > 35: + return "Moderate ocular backtracking and decoding fatigue detected." + return "Phonological and ocular metrics within typical development benchmarks." + + async def send_report(self, recipient_email: str, pdf_path: str, session_id: str = "N/A", metrics: dict = None, locale: str = "AU_VIC"): + """ + ๐ŸŽฏ CORE FIX: Primary entry point used by DyslexiaScanner. + Maps to the internal secure dispatch logic. + """ + # Ensure metrics is a dictionary to prevent attribute errors in narrative generation + metrics = metrics or {} + return await self.send_secure_report(recipient_email, [pdf_path], session_id, metrics, locale) + + async def send_secure_report(self, recipient_email, attachments, session_id, metrics, locale="AU_VIC"): + """Dispatches encrypted reports with localized context and access keys.""" + if not recipient_email or recipient_email in ["null", "undefined", ""]: + logger.error(f"โš ๏ธ Aborting Email: No valid recipient for session {session_id}") + return False + + if not self.sender or not self.password: + logger.error("โŒ CRITICAL: SMTP credentials missing from environment.") + return False + + narrative = self.generate_risk_narrative(metrics, locale) + is_nep = locale == "IN_NEP" + subject_tag = "NEP 2020 Progress" if is_nep else "Clinical Screening Artifact" + + msg = MIMEMultipart() + msg['From'] = f"LearningView Pro <{self.sender}>" + msg['To'] = recipient_email + msg['Subject'] = f"SECURE: {subject_tag} (Session {session_id})" + + body = f"""Hello,\n\nThe biometric synthesis for Session {session_id} is complete.\n\n--- SUMMARY ---\n{narrative}\n\nOPEN PASSWORD: {session_id}\n\nRegards,\nClinical Team""" + msg.attach(MIMEText(body, 'plain')) + + for file_path in attachments: + if file_path and os.path.exists(file_path): + try: + with open(file_path, "rb") as f: + part = MIMEApplication(f.read(), Name=os.path.basename(file_path)) + part['Content-Disposition'] = f'attachment; filename="{os.path.basename(file_path)}"' + msg.attach(part) + except Exception as e: + logger.error(f"โš ๏ธ Attachment Error: {e}") + + context = ssl.create_default_context() + try: + # Strategy A: SSL (Port 465) + with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port, context=context, timeout=15) as server: + server.login(self.sender, self.password) + server.send_message(msg) + logger.info(f"โœ… SMTP Success (465): Delivered session {session_id}") + return True + except Exception as e: + logger.error(f"โš ๏ธ SMTP SSL Failed: {e}. Attempting 587 STARTTLS...") + try: + # Strategy B: STARTTLS Fallback (Port 587) + with smtplib.SMTP(self.smtp_server, 587, timeout=15) as server: + server.starttls(context=context) + server.login(self.sender, self.password) + server.send_message(msg) + logger.info(f"โœ… SMTP Success (587): Fallback delivered for session {session_id}") + return True + except Exception as e2: + logger.error(f"โŒ CRITICAL SMTP FAILURE: Both protocols unreachable: {e2}") + return False + +# Singleton instance +email_service = EmailService() \ No newline at end of file diff --git a/services/ocr_service.py b/services/ocr_service.py new file mode 100644 index 0000000000000000000000000000000000000000..1b3e68090df34d7994a3732704ebb796d8a05ad2 --- /dev/null +++ b/services/ocr_service.py @@ -0,0 +1,110 @@ +import os +import requests +import cv2 +import numpy as np +from google.cloud import vision +import io +import json +import subprocess +from core.logger import log_debug + +class OCRService: + def __init__(self, provider="google"): + # Real-time Switch: Set to "google" in Railway Variables + self.provider = os.getenv("OCR_PROVIDER", provider) + + # --- ๐Ÿ”‘ CREDENTIALS HANDLING --- + self.ocr_space_key = os.getenv("OCR_SPACE_KEY", "K89743005188957") + + # Railway-Friendly Google Auth + google_json = os.getenv("GOOGLE_CREDS_JSON") + if google_json: + # Create temporary creds file from env var to satisfy Google SDK + with open("google_ocr_key.json", "w") as f: + f.write(google_json) + os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "google_ocr_key.json" + else: + # Fallback for local testing + os.environ["GOOGLE_APPLICATION_CREDENTIALS"] = "google_ocr_key.json" + + def extract_text(self, image_path): + """The central router for all OCR requests.""" + # Step 1: Sanitize (Optimized for Cloud Vision) + sanitized_path = self._v8_sanitize(image_path) + + # Step 2: Route + if self.provider == "google": + return self._extract_google_vision(sanitized_path) + elif self.provider == "ocr_space": + return self._extract_ocr_space(sanitized_path) + else: + # Fallback for local Mac testing only + if os.name == 'posix' and 'darwin' in os.sys.platform: + return self._extract_apple_vision(sanitized_path) + return "[Provider Not Supported on Linux/Railway]" + + def _v8_sanitize(self, path): + """V8 Pipeline: Clean shadows but preserve stroke gradients for Google.""" + img = cv2.imread(path) + if img is None: return path + + # Convert to grayscale + gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) + + # CLAHE (Contrast Limited Adaptive Histogram Equalization) is perfect for + # neutralizing shadows on paper + clahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8)) + res = clahe.apply(gray) + + # Denoise to remove paper grain + denoised = cv2.fastNlMeansDenoising(res, None, 10, 7, 21) + + output_path = "sanitized_v8_payload.png" + cv2.imwrite(output_path, denoised) + return output_path + + def _extract_google_vision(self, path): + """Google Vision: High-speed handwriting extraction.""" + try: + client = vision.ImageAnnotatorClient() + with io.open(path, 'rb') as image_file: + content = image_file.read() + + image = vision.Image(content=content) + + # Use document_text_detection for dense/handwritten text + response = client.document_text_detection(image=image) + + if response.error.message: + log_debug(f"โš ๏ธ Google API Error: {response.error.message}") + return "[Google Billing Required]" + + text = response.full_text_annotation.text.strip() + log_debug("Text extracted: "+text) + return text.replace('\n', ' ') # Flatten to single line for alignment + except Exception as e: + log_debug(f"โš ๏ธ Google Vision Failure: {e}") + return "[Extraction Error]" + + def _extract_ocr_space(self, path): + """OCR.space Engine 3 Fallback.""" + try: + with open(path, 'rb') as f: + r = requests.post( + 'https://api.ocr.space/parse/image', + files={path: f}, + data={ + 'apikey': self.ocr_space_key, + 'language': 'eng', + 'ocrengine': 3, + 'scale': True + }, + timeout=45 + ) + result = r.json() + if result.get('ParsedResults'): + return result['ParsedResults'][0].get('ParsedText', "").strip() + return "[OCR Engine Busy]" + except Exception as e: + log_debug(f"โš ๏ธ OCR.space Failure: {e}") + return "[Extraction Timeout]" \ No newline at end of file diff --git a/services/pdf_generator.py b/services/pdf_generator.py new file mode 100644 index 0000000000000000000000000000000000000000..c76e1c627411871031f2c24b3649e93001053178 --- /dev/null +++ b/services/pdf_generator.py @@ -0,0 +1,188 @@ +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 \ No newline at end of file diff --git a/services/prompt_service.py b/services/prompt_service.py new file mode 100644 index 0000000000000000000000000000000000000000..dfa4ee527e64d9ef7837a3ac69e3c9f9ff076e5d --- /dev/null +++ b/services/prompt_service.py @@ -0,0 +1,55 @@ +import random + +class PromptGenerator: + def __init__(self): + # ๐Ÿงช Clinical Dictionary: Categorized by diagnostic trigger + self.lexicon = { + "dyslexia_triggers": ["mysterious", "extraordinary", "peculiar", "fascinating", "cautious"], + "dysgraphia_kinetic": ["vibrant", "twilight", "climb", "quickly", "jungle"], + "dyscalculia_numerical": ["12", "7", "24", "105", "3"], + "subjects": ["monkey", "traveler", "explorer", "creature"], + "locations": ["valley", "peak", "forest", "canopy"], + "actions": ["discovered", "watched", "followed", "noticed", "explored"] + } + + def generate_balanced_session(self, level: str) -> dict: + """ + Assembles a prompt that satisfies Dyslexia, Dysgraphia, + and Dyscalculia triggers in a single reading/writing flow. + """ + # 1. Select triggers and components + d_word = random.choice(self.lexicon["dyslexia_triggers"]) + k_word = random.choice(self.lexicon["dysgraphia_kinetic"]) + num = random.choice(self.lexicon["dyscalculia_numerical"]) + subject = random.choice(self.lexicon["subjects"]) + location = random.choice(self.lexicon["locations"]) + action = random.choice(self.lexicon["actions"]) + + # 2. Build Reading Task + reading_text = ( + f"The {num} {subject}s were very {d_word} today. " + f"They lived in a {location} where the trees were {k_word}. " + "Every morning, they would look for fruit near the river. " + "It was a peaceful place, but the sounds of the jungle were loud. " + "Soon, it was time for them to rest under the thick green leaves. " + f"They felt safe in the {location} as the sun began to set." + ) + + # 3. Build Writing Task + writing_text = f"The {k_word} {d_word} {subject} {action} a hidden path. It was a very long journey." + + # โœ… FIX: Nesting triggers inside 'metadata' to satisfy main.py requirements + return { + "reading_task": reading_text, + "writing_task": writing_text, + "metadata": { + "triggers": { + "dyslexia": d_word, + "dyscalculia": num, + "dysgraphia": k_word + }, + "word_count": len(reading_text.split()) + } + } + +prompt_service = PromptGenerator() \ No newline at end of file diff --git a/services/speech_analysis.py b/services/speech_analysis.py new file mode 100644 index 0000000000000000000000000000000000000000..37220cc20efe5db14b6c22a880e99b9cf068a335 --- /dev/null +++ b/services/speech_analysis.py @@ -0,0 +1,99 @@ +import whisper +import jiwer +import threading +import string +import os +from pydub import AudioSegment +from config import TEMP_DIR +from config import WHISPER_MODEL_SIZE, PHONETIC_GAP_THRESHOLD + +class SpeechEngine: + _instance = None + _lock = threading.Lock() + + def __new__(cls): + with cls._lock: + if cls._instance is None: + cls._instance = super(SpeechEngine, cls).__new__(cls) + cls._instance.model = whisper.load_model(WHISPER_MODEL_SIZE) + return cls._instance + + def _extract_and_normalize_audio(self, video_path, audio_path): + """Standardization for Whisper (16kHz Mono) [cite: 2026-02-08].""" + audio = AudioSegment.from_file(video_path, format="webm") + audio = audio.set_channels(1).set_frame_rate(16000) + if audio.max_dBFS < 0: + audio = audio.apply_gain(-audio.max_dBFS) + audio.export(audio_path, format="wav") + return audio_path + + def _generate_alignment_and_blocks(self, segments, silence_threshold=PHONETIC_GAP_THRESHOLD): + """Temporal Mapping & Silence (Phonetic Block) Detection [cite: 2026-02-21].""" + word_alignment, phonetic_blocks = [], [] + last_word_end = 0.0 + for segment in segments: + for word in segment.get('words', []): + start, end = round(word['start'], 3), round(word['end'], 3) + if last_word_end > 0 and (start - last_word_end) > silence_threshold: + phonetic_blocks.append({ + "start": last_word_end, + "end": start, + "duration": round(start - last_word_end, 2) + }) + word_alignment.append({ + "word": self._normalize(word['word']), + "start": start, + "end": end, + "confidence": round(word['probability'], 2) + }) + last_word_end = end + return word_alignment, phonetic_blocks + + def _calculate_accuracy_raw(self, reference_text, hypothesis_text): + """Clinical Accuracy Scoring (Raw WER decimal) [cite: 2026-02-21].""" + ref, hyp = self._normalize(reference_text), self._normalize(hypothesis_text) + if not hyp: return 1.0 + return round(float(jiwer.wer(ref, hyp)), 4) + + def identify_struggles(self, word_alignment, phonetic_blocks): + """Tags problematic words based on confidence or gaps.""" + struggle_words, gap_starts = [], [b['start'] for b in phonetic_blocks] + for word in word_alignment: + is_low_conf = word['confidence'] < 0.6 + is_pre_gap = any(abs(word['end'] - gs) < 0.3 for gs in gap_starts) + if is_low_conf or is_pre_gap: + struggle_words.append({ + "word": word['word'], + "reason": "Phonetic Block" if is_pre_gap else "Low Confidence", + "timestamp": word['start'] + }) + return struggle_words + + def _normalize(self, text): + return text.lower().translate(str.maketrans('', '', string.punctuation)).strip() + + def analyze_with_timestamps(self, video_path, target_text, session_id="default"): + audio_path = os.path.join(TEMP_DIR, f"audio_{session_id}.wav") + try: + self._extract_and_normalize_audio(video_path, audio_path) + result = self.model.transcribe(audio_path, fp16=False, word_timestamps=True) + word_alignment, blocks = self._generate_alignment_and_blocks(result.get('segments', [])) + raw_wer = self._calculate_accuracy_raw(target_text, result["text"]) + struggle_words = self.identify_struggles(word_alignment, blocks) + + if os.path.exists(audio_path): os.remove(audio_path) + + return { + "accuracy": {"wer": raw_wer}, + "transcribed_text": result["text"].strip(), + "word_alignment": word_alignment, + "phonetic_blocks": blocks, + "block_count": len(blocks), + "struggle_words": struggle_words, + "meta": {"audio_start_offset": result['segments'][0]['start'] if result.get('segments') else 0.0} + } + except Exception as e: + if os.path.exists(audio_path): os.remove(audio_path) + return {"accuracy": {"wer": 1.0}, "error": str(e), "word_alignment": [], "phonetic_blocks": [], "struggle_words": []} + +speech_engine = SpeechEngine() \ No newline at end of file diff --git a/services/video_service.py b/services/video_service.py new file mode 100644 index 0000000000000000000000000000000000000000..b96da6f4fe76329d401e2b72d40b88a700b26a46 --- /dev/null +++ b/services/video_service.py @@ -0,0 +1,59 @@ +import cv2 +import os + +class VideoService: + @staticmethod + def verify_integrity(video_path: str): + """ + Analyzes the physical properties of the biometric stream. [cite: 2026-02-23] + Enhanced to handle 'headless' webm headers for stable timeline scaling. + """ + if not os.path.exists(video_path): + return {"error": "File not found"} + + cap = cv2.VideoCapture(video_path) + fps_claimed = cap.get(cv2.CAP_PROP_FPS) + + # ๐ŸŽฏ FIX: Robust Frame Counting [cite: 2026-02-23] + # Some browsers don't write the frame count to the webm header. + frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) + + if frame_count <= 0: + # Fallback: Count frames manually if header is missing [cite: 2026-02-23] + count = 0 + while True: + ret, _ = cap.read() + if not ret: break + count += 1 + frame_count = count + # Reset capture to the beginning for metadata checks + cap.set(cv2.CAP_PROP_POS_FRAMES, 0) + + width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) + + # ๐ŸŽฏ STABILITY: Default to 30fps if browser metadata is wonky [cite: 2026-02-23] + effective_fps = fps_claimed if 5 < fps_claimed < 120 else 30 + duration = frame_count / effective_fps if frame_count > 0 else 0 + + cap.release() + + # Clinical Integrity Logic [cite: 2026-02-21] + integrity = "OPTIMAL" + warning = None + + if effective_fps < 24: + integrity = "SUBOPTIMAL" + warning = "Low frame rate. Ocular accuracy is indicative only." + if effective_fps < 12: + integrity = "CRITICAL" + warning = "Extreme frame drop. Biometric path is statistically insignificant." + + return { + "fps": round(effective_fps, 2), + "frame_count": frame_count, + "duration": round(duration, 2), # ๐Ÿš€ Syncs with Frontend Timeline + "resolution": f"{width}x{height}", + "integrity": integrity, + "warning": warning + } \ No newline at end of file diff --git a/tests/__init__.py b/tests/__init__.py new file mode 100644 index 0000000000000000000000000000000000000000..e69de29bb2d1d6434b8b29ae775ad8c2e48c5391 diff --git a/tests/test_main.py b/tests/test_main.py new file mode 100644 index 0000000000000000000000000000000000000000..21b7c4f5a98e87f1b1cce708fe771277f3cbae73 --- /dev/null +++ b/tests/test_main.py @@ -0,0 +1,2 @@ +def test_example(): + assert 1 == 1