ArrowDust commited on
Commit
408b7e6
·
0 Parent(s):

LearnView Pro: Clean Production Build

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .DS_Store +0 -0
  2. .dockerignore +8 -0
  3. .gitignore +2 -0
  4. Dockerfile +19 -0
  5. LICENSE.md +30 -0
  6. README.md +32 -0
  7. __init__.py +0 -0
  8. __pycache__/__init__.cpython-310.pyc +0 -0
  9. __pycache__/biometric_engine.cpython-310.pyc +0 -0
  10. __pycache__/config.cpython-310.pyc +0 -0
  11. __pycache__/main.cpython-310.pyc +0 -0
  12. config.py +69 -0
  13. core/.DS_Store +0 -0
  14. core/__pycache__/base_analyzer.cpython-310.pyc +0 -0
  15. core/__pycache__/base_clinical_strategy.cpython-310.pyc +0 -0
  16. core/__pycache__/base_scanner.cpython-310.pyc +0 -0
  17. core/__pycache__/clinical_analyzer.cpython-310.pyc +0 -0
  18. core/__pycache__/decision_engine.cpython-310.pyc +0 -0
  19. core/__pycache__/logger.cpython-310.pyc +0 -0
  20. core/__pycache__/secure_storage.cpython-310.pyc +0 -0
  21. core/__pycache__/state.cpython-310.pyc +0 -0
  22. core/__pycache__/video_audit.cpython-310.pyc +0 -0
  23. core/base_analyzer.py +16 -0
  24. core/base_clinical_strategy.py +3 -0
  25. core/base_scanner.py +34 -0
  26. core/email_dispatch.py +70 -0
  27. core/logger.py +38 -0
  28. core/reporting/__pycache__/base_report.cpython-310.pyc +0 -0
  29. core/reporting/__pycache__/report_config.cpython-310.pyc +0 -0
  30. core/reporting/base_report.py +126 -0
  31. core/reporting/email_templates.py +26 -0
  32. core/reporting/report_config.py +17 -0
  33. core/secure_storage.py +40 -0
  34. core/state.py +1 -0
  35. core/video_audit.py +50 -0
  36. engines/.DS_Store +0 -0
  37. engines/adhd/analyzer.py +8 -0
  38. engines/dyslexia/__pycache__/analyzer.cpython-310.pyc +0 -0
  39. engines/dyslexia/__pycache__/logic.cpython-310.pyc +0 -0
  40. engines/dyslexia/__pycache__/report.cpython-310.pyc +0 -0
  41. engines/dyslexia/__pycache__/scanner.cpython-310.pyc +0 -0
  42. engines/dyslexia/analyzer.py +19 -0
  43. engines/dyslexia/logic.py +79 -0
  44. engines/dyslexia/report.py +193 -0
  45. engines/dyslexia/scanner.py +239 -0
  46. google_ocr_key.json +13 -0
  47. main.py +309 -0
  48. requirements.txt +43 -0
  49. services/__init__.py +0 -0
  50. services/__pycache__/__init__.cpython-310.pyc +0 -0
.DS_Store ADDED
Binary file (10.2 kB). View file
 
.dockerignore ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ venv/
2
+ .venv/
3
+ node_modules/
4
+ __pycache__/
5
+ *.pyc
6
+ .git/
7
+ .env
8
+ frontend/dist/
.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ venv_test/
2
+ venv/
Dockerfile ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ FROM python:3.11-slim
2
+
3
+ # Required for OpenCV and PDF rendering on ARM architecture
4
+ RUN apt-get update && apt-get install -y \
5
+ libglx-mesa0 \
6
+ libglib2.0-0 \
7
+ ffmpeg \
8
+ && rm -rf /var/lib/apt/lists/*
9
+
10
+ WORKDIR /app
11
+ ENV PYTHONPATH=/app
12
+ COPY requirements.txt .
13
+ RUN pip install --no-cache-dir -r requirements.txt
14
+ COPY . .
15
+
16
+ # Ensure report directory exists [cite: 31, 59]
17
+ RUN mkdir -p temp_reports
18
+
19
+ CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
LICENSE.md ADDED
@@ -0,0 +1,30 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Proprietary Software License
2
+ Copyright © 2026 [Roshan Enterprises Pty Ltd, Australia]. All Rights Reserved.
3
+
4
+ 1. Ownership and Intellectual Property
5
+ 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.
6
+
7
+ 2. No License Granted
8
+ 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.
9
+
10
+ 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.
11
+
12
+ 3. Prohibited Actions
13
+ You are strictly prohibited from:
14
+
15
+ Copying or duplicating the source code or any part of the clinical engine.
16
+
17
+ Modifying, translating, or creating derivative works based on the Software.
18
+
19
+ Reverse engineering, decompiling, or disassembling the biometric tracking or diagnostic logic.
20
+
21
+ Removing any proprietary notices or labels on the Software.
22
+
23
+ 4. Clinical Disclaimer
24
+ 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.
25
+
26
+ 5. Termination
27
+ Any unauthorized use of this Software terminates any implied permissions immediately and may result in legal action.
28
+
29
+ 6. Disclaimer of Warranty
30
+ 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.
README.md ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ title: LearnView Pro Backend
3
+ emoji: 🧠
4
+ colorFrom: blue
5
+ colorTo: indigo
6
+ sdk: docker
7
+ app_port: 8000
8
+ license: other
9
+ license_name: proprietary-all-rights-reserved
10
+ license_link: LICENSE.md
11
+ pinned: false
12
+ ---
13
+
14
+ # DyslexiaView Pro: Clinical Biometric Engine
15
+
16
+ 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.
17
+
18
+ ### 🛡️ Proprietary Notice
19
+
20
+ **Copyright © 2026. All Rights Reserved.**
21
+ 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.
22
+
23
+ ### 🚀 Technical Overview
24
+
25
+ - **SDK**: Docker (Debian/Python 3.10-slim)
26
+ - **Infrastructure**: 16GB RAM / 2 vCPU
27
+ - **API**: FastAPI on Port 8000
28
+ - [cite_start]**Biometrics**: MediaPipe FaceMesh (468-point tracking) [cite: 17, 43]
29
+
30
+ ---
31
+
32
+ _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._
__init__.py ADDED
File without changes
__pycache__/__init__.cpython-310.pyc ADDED
Binary file (148 Bytes). View file
 
__pycache__/biometric_engine.cpython-310.pyc ADDED
Binary file (3.76 kB). View file
 
__pycache__/config.cpython-310.pyc ADDED
Binary file (1.74 kB). View file
 
__pycache__/main.cpython-310.pyc ADDED
Binary file (8.35 kB). View file
 
config.py ADDED
@@ -0,0 +1,69 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from dotenv import load_dotenv
3
+
4
+ # Load the .env file from the project root
5
+ load_dotenv()
6
+
7
+ LOG_LEVEL = os.getenv("LOG_LEVEL", "INFO")
8
+
9
+ # --- 📂 DIRECTORY CONFIGURATION ---
10
+ BASE_DIR = os.path.dirname(os.path.abspath(__file__))
11
+ TEMP_DIR = os.path.join(BASE_DIR, "temp_reports")
12
+
13
+ # Ensure storage exists for PDF and Audio processing on startup
14
+ os.makedirs(TEMP_DIR, exist_ok=True)
15
+
16
+ # --- 🌍 REGIONAL & APP CONFIGURATION ---
17
+ # The request 'locale' takes priority, but this is the safety fallback
18
+ DEFAULT_REGION = os.getenv("DEFAULT_REGION", "IN_NEP")
19
+ APP_NAME = os.getenv("APP_NAME", "LearningView Pro")
20
+
21
+ # --- 📧 SMTP CREDENTIALS (RAILWAY OPTIMIZED) ---
22
+ SMTP_SERVER = os.getenv("SMTP_SERVER", "smtp.gmail.com")
23
+ SMTP_PORT = int(os.getenv("SMTP_PORT", 465)) # Port 465 for SMTP_SSL
24
+ SMTP_USER = os.getenv("SENDER_EMAIL", "arrowinthedust@gmail.com")
25
+ SMTP_PASSWORD = os.getenv("SENDER_PASSWORD")
26
+
27
+ # --- 🛡️ SECURITY & CORS ---
28
+ CORS_ORIGINS = [
29
+ "http://localhost:5173",
30
+ "http://127.0.0.1:5173",
31
+ "https://learningview.vercel.app",
32
+ "https://learningview-pro.vercel.app"
33
+ ]
34
+
35
+ # --- 📖 ASSESSMENT PROMPTS (The Clinical Source of Truth) ---
36
+ # Any changes here will reflect across the UI and PDF transcription audit
37
+ ASSESSMENT_PROMPTS = {
38
+ "beginner": (
39
+ "The sun was very bright today. A small cat sat on the green grass. "
40
+ "It watched a blue bird fly high in the sky. Soon, it was time for lunch."
41
+ ),
42
+ "intermediate": (
43
+ "During the summer holidays, we decided to explore the ancient forest "
44
+ "behind our grandmother's house. The trees were tall and the air was cool."
45
+ ),
46
+ "advanced": (
47
+ "The intricate relationship between neurological development and linguistic "
48
+ "acquisition remains a primary focus of modern cognitive science."
49
+ )
50
+ }
51
+
52
+ # config.py update
53
+ WRITING_PROMPTS = {
54
+ "beginner": "The quick brown fox jumps over the lazy dog.", # Covers all alphabet letters
55
+ "intermediate": "A bright blue bird sang a song in the tall green tree.",
56
+ }
57
+
58
+ # --- 🧪 SCANNER & CLINICAL THRESHOLDS ---
59
+ DATA_PURGE_DELAY = 180 # 3-minute Zero-Persistence window
60
+ MIN_FPS_THRESHOLD = 28.0 # Minimum frame rate for reliable ocular sync
61
+
62
+ # Biometric Distance (in MediaPipe normalized units)
63
+ CLINICAL_DISTANCE_MIN = 0.075 # Too far
64
+ CLINICAL_DISTANCE_MAX = 0.13 # Too close
65
+
66
+ # Speech & Phonetic Timing
67
+ WHISPER_MODEL_SIZE = "base"
68
+ PHONETIC_GAP_THRESHOLD = 1.5 # Seconds of silence to trigger a "block"
69
+ STATIONARY_FRAME_THRESHOLD = 25 # Frames of eye-fixation to count a block
core/.DS_Store ADDED
Binary file (6.15 kB). View file
 
core/__pycache__/base_analyzer.cpython-310.pyc ADDED
Binary file (1 kB). View file
 
core/__pycache__/base_clinical_strategy.cpython-310.pyc ADDED
Binary file (526 Bytes). View file
 
core/__pycache__/base_scanner.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
core/__pycache__/clinical_analyzer.cpython-310.pyc ADDED
Binary file (1.01 kB). View file
 
core/__pycache__/decision_engine.cpython-310.pyc ADDED
Binary file (1.53 kB). View file
 
core/__pycache__/logger.cpython-310.pyc ADDED
Binary file (1.52 kB). View file
 
core/__pycache__/secure_storage.cpython-310.pyc ADDED
Binary file (1.66 kB). View file
 
core/__pycache__/state.cpython-310.pyc ADDED
Binary file (170 Bytes). View file
 
core/__pycache__/video_audit.cpython-310.pyc ADDED
Binary file (1.42 kB). View file
 
core/base_analyzer.py ADDED
@@ -0,0 +1,16 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+
3
+ class ClinicalAnalyzer(ABC):
4
+ """
5
+ Abstract Base for all diagnostic interpretation logic.
6
+ Ensures 'Certainty over Velocity' across different clinical modules.
7
+ """
8
+ @abstractmethod
9
+ def calculate_risk(self, metrics: dict) -> int:
10
+ pass
11
+
12
+ def interpret_score(self, score: int) -> str:
13
+ """Standardized interpretation across all modules."""
14
+ if score > 75: return "High"
15
+ if score > 40: return "Moderate"
16
+ return "Low"
core/base_clinical_strategy.py ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ class BaseClinicalStrategy:
2
+ def calculate(self, metrics: dict) -> float:
3
+ raise NotImplementedError
core/base_scanner.py ADDED
@@ -0,0 +1,34 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from abc import ABC, abstractmethod
2
+ from typing import Optional
3
+ from pydantic import BaseModel
4
+
5
+ class ScannerContext(BaseModel):
6
+ adult_id: str # The Gmail SSO ID of the parent/teacher
7
+ child_name: str # For multi-child identification
8
+ child_class: str # Critical for school-based reporting
9
+ level: str # beginner/intermediate/advanced
10
+ locale: str # AU_VIC / IN_NEP
11
+ video_path: str
12
+ hw_path: Optional[str] = None
13
+ target_text: str # Reading Prompt
14
+ writing_target: str # Writing Prompt (For Levenshtein comparison)
15
+ parent_email: str
16
+ report_password: Optional[str] = None
17
+
18
+ """Shared metadata for all clinical engines [cite: 2026-02-21, 2026-02-27]"""
19
+ session_id: str
20
+ locale: str
21
+ has_paper: bool = False
22
+
23
+ class BaseScanner(ABC):
24
+ """The universal blueprint for every diagnostic scanner."""
25
+
26
+ @abstractmethod
27
+ async def analyze(self, video, paper_scan, context: ScannerContext):
28
+ """Perform biometric extraction and return raw metrics."""
29
+ pass
30
+
31
+ @abstractmethod
32
+ def synthesize_risk(self, metrics: dict) -> float:
33
+ """Apply clinical weights (e.g., Logarithmic Dampening) to generate a score."""
34
+ pass
core/email_dispatch.py ADDED
@@ -0,0 +1,70 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import smtplib
2
+ import socket
3
+ import os
4
+ from email.mime.multipart import MIMEMultipart
5
+ from email.mime.text import MIMEText
6
+ from email.mime.base import MIMEBase
7
+ from email import encoders
8
+ from config import SMTP_SERVER, SMTP_PORT, SMTP_USER, SMTP_PASSWORD, VITE_PILOT_REGION
9
+ from core.reporting.email_templates import get_template
10
+ from core.logger import log_debug, logger
11
+
12
+
13
+ # 🛡️ RAILWAY NETWORK PATCH: Force IPv4 for SMTP [cite: 2026-02-23, 2026-02-27]
14
+ orig_getaddrinfo = socket.getaddrinfo
15
+ def patched_getaddrinfo(*args, **kwargs):
16
+ responses = orig_getaddrinfo(*args, **kwargs)
17
+ return [res for res in responses if res[0] == socket.AF_INET]
18
+ socket.getaddrinfo = patched_getaddrinfo
19
+
20
+ class EmailService:
21
+ def __init__(self):
22
+ self.server = SMTP_SERVER
23
+ self.port = SMTP_PORT
24
+ self.user = SMTP_USER
25
+ self.password = SMTP_PASSWORD
26
+
27
+ def send_secure_report(self, receiver_email, file_paths, session_id, metrics, region="AU_VIC"):
28
+ """Sends encrypted clinical results with localized context [cite: 2026-01-14, 2026-02-27]."""
29
+ msg = MIMEMultipart()
30
+ msg['From'] = f"LearningView Pro <{self.user}>"
31
+ msg['To'] = receiver_email
32
+
33
+ # Localized Subject [cite: 2026-02-20]
34
+ prefix = "Clinical Profile" if region == "AU_VIC" else "Holistic Progress Summary"
35
+ msg['Subject'] = f"{prefix} | Ref: {session_id}"
36
+
37
+ body = f"""
38
+ Dear Parent/Guardian,
39
+
40
+ The clinical screening session for ID {session_id} is complete.
41
+ Attached is the encrypted PDF report.
42
+
43
+ 🔐 SECURITY: The password for this PDF is your session ID: {session_id}
44
+
45
+ Regional Context: {region} Compliance
46
+ Risk Score: {metrics.get('risk_score')}%
47
+ """
48
+ msg.attach(MIMEText(body, 'plain'))
49
+
50
+ for path in file_paths:
51
+ if os.path.exists(path):
52
+ with open(path, "rb") as attachment:
53
+ part = MIMEBase('application', 'octet-stream')
54
+ part.set_payload(attachment.read())
55
+ encoders.encode_base64(part)
56
+ part.add_header('Content-Disposition', f"attachment; filename={os.path.basename(path)}")
57
+ msg.attach(part)
58
+
59
+ try:
60
+ # 🚀 Hardened Port 465 Logic
61
+ with smtplib.SMTP_SSL(self.server, self.port, timeout=15) as server:
62
+ server.login(self.user, self.password)
63
+ server.send_message(msg)
64
+ log_debug(f"📧 Dispatch Success: Report sent to {receiver_email}")
65
+ return True
66
+ except Exception as e:
67
+ logger.error(f"❌ Dispatch Failed: {str(e)}")
68
+ return False
69
+
70
+ email_service = EmailService()
core/logger.py ADDED
@@ -0,0 +1,38 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import logging
2
+ import os
3
+ import time
4
+ from functools import wraps
5
+ from config import APP_NAME
6
+
7
+ # Resolve the level once
8
+ LOG_LEVEL_STR = os.getenv("LOG_LEVEL", "DEBUG").upper()
9
+ LOG_LEVEL = getattr(logging, LOG_LEVEL_STR, logging.DEBUG)
10
+
11
+ logging.basicConfig(
12
+ level=LOG_LEVEL,
13
+ format="%(asctime)s [%(levelname)s] %(name)s: %(message)s",
14
+ handlers=[logging.StreamHandler()]
15
+ )
16
+
17
+ logger = logging.getLogger(APP_NAME)
18
+
19
+ # --- 🎯 THE CLINICAL INTERFACE ---
20
+
21
+ def log_clinical_event(event_name: str, details: dict):
22
+ """Specific logger for child assessment events (Ocular/Phonetic)."""
23
+ logger.info(f"📊 CLINICAL_EVENT | {event_name} | {details}")
24
+
25
+ def log_debug(message: str):
26
+ """Replacement for print() statements."""
27
+ logger.debug(f"🔍 DEBUG: {message}")
28
+
29
+ def monitor_perf(func):
30
+ """Decorator to log execution time."""
31
+ @wraps(func)
32
+ async def wrapper(*args, **kwargs):
33
+ start_time = time.perf_counter()
34
+ result = await func(*args, **kwargs)
35
+ duration = time.perf_counter() - start_time
36
+ logger.debug(f"⏱️ PERF | {func.__name__} execution: {duration:.4f}s")
37
+ return result
38
+ return wrapper
core/reporting/__pycache__/base_report.cpython-310.pyc ADDED
Binary file (4.99 kB). View file
 
core/reporting/__pycache__/report_config.cpython-310.pyc ADDED
Binary file (576 Bytes). View file
 
core/reporting/base_report.py ADDED
@@ -0,0 +1,126 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import pikepdf
3
+ from fpdf import FPDF
4
+ from datetime import datetime
5
+ from core.reporting.report_config import REPORT_CONFIG
6
+
7
+ class BaseClinicalReport(FPDF):
8
+ """
9
+ Standardized PDF Factory for LearnView Pro.
10
+ Handles Multi-Audience Insights, Security (AES-256), and Jurisdictional Branding.
11
+ """
12
+ def __init__(self, session_id, region, context):
13
+ super().__init__()
14
+ self.session_id = session_id
15
+ self.region = region
16
+ self.context = context
17
+ # Dynamically load jurisdiction config
18
+ self.cfg = REPORT_CONFIG.get(region, REPORT_CONFIG["AU_VIC"])
19
+ self.report_date = datetime.now().strftime("%d %b %Y")
20
+ self.alias_nb_pages()
21
+ self.add_page()
22
+
23
+ def header(self):
24
+ """Custom header with jurisdictional branding and student metadata."""
25
+ # Regional Branding: Solid header bar
26
+ self.set_fill_color(*self.cfg["primary_color"])
27
+ self.rect(0, 0, 210, 40, 'F')
28
+
29
+ self.set_text_color(255, 255, 255)
30
+ self.set_font('Helvetica', 'B', 16)
31
+ self.set_xy(12, 10)
32
+
33
+ # India Edition branding check
34
+ header_title = "LEARNVIEW PRO: INDIA EDITION" if "IN" in self.region else self.cfg["header_title"]
35
+ self.cell(0, 10, header_title, 0, 1)
36
+
37
+ # VCL Jurisdictional Compliance Badge
38
+ self.set_font('Helvetica', 'B', 7)
39
+ compliance = "Victoria Child Link (VCL) Alignment Protocol" if "IN" in self.region else self.cfg['footer_compliance']
40
+ badge_text = f"JURISDICTION COMPLIANCE: {compliance.upper()}"
41
+ self.text(120, 10, badge_text)
42
+
43
+ self.set_font('Helvetica', '', 9)
44
+ self.set_xy(12, 18)
45
+ self.cell(0, 5, f"Clinical Session Artifact | Ref: {self.session_id}", 0, 1)
46
+
47
+ # Metadata: Student Details
48
+ self.set_font('Helvetica', 'B', 11)
49
+ self.set_x(12)
50
+ name = getattr(self.context, 'child_name', 'Anonymous Student')
51
+ grade = getattr(self.context, 'child_class', 'N/A')
52
+ student_meta = f"Student: {name} | Grade: {grade}"
53
+ self.cell(0, 5, student_meta, 0, 1)
54
+
55
+ self.set_font('Helvetica', '', 9)
56
+ self.set_x(12)
57
+ # Display Audit Key (PWD) to match Dashboard
58
+ pwd = getattr(self.context, 'report_password', 'N/A')
59
+ meta_sub = f"Report Generated: {self.report_date} | Audit Key (PWD): {pwd}"
60
+ self.cell(0, 5, meta_sub, 0, 1)
61
+
62
+ self.set_text_color(0, 0, 0)
63
+ self.set_y(45)
64
+
65
+ def draw_parent_insight(self, title, description):
66
+ """Plain-language summary box for parents."""
67
+ self.set_fill_color(248, 250, 252)
68
+ self.set_draw_color(203, 213, 225)
69
+ curr_y = self.get_y()
70
+ self.rect(12, curr_y, 186, 20, 'FD')
71
+ self.set_font("Helvetica", 'B', 9)
72
+ self.set_text_color(51, 65, 85)
73
+ self.set_xy(15, curr_y + 2)
74
+ self.cell(0, 5, f"FOR PARENTS: {title.upper()}", ln=True)
75
+ self.set_font("Helvetica", '', 8)
76
+ self.set_x(15)
77
+ self.multi_cell(180, 4, description)
78
+ self.set_y(curr_y + 25)
79
+
80
+ def footer(self):
81
+ """Compliance footer with VCL strings."""
82
+ self.set_y(-20)
83
+ self.set_font('Helvetica', 'I', 8)
84
+ self.set_text_color(120, 120, 120)
85
+ compliance = "VCL Alignment Protocol" if "IN" in self.region else self.cfg['footer_compliance']
86
+ compliance_text = f"{compliance} | Session ID: {self.session_id}"
87
+ self.cell(0, 10, compliance_text, 0, 0, 'C')
88
+ self.set_x(-30)
89
+ self.cell(20, 10, f'Page {self.page_no()}/{{nb}}', 0, 0, 'R')
90
+
91
+ def draw_h2(self, text):
92
+ """Standardized Blue Section Header."""
93
+ self.set_font("Helvetica", 'B', 14)
94
+ self.set_text_color(*self.cfg["primary_color"])
95
+ self.cell(0, 10, text, ln=True)
96
+ self.set_draw_color(*self.cfg["primary_color"])
97
+ self.line(12, self.get_y(), 62, self.get_y())
98
+ self.ln(5)
99
+ self.set_text_color(0, 0, 0)
100
+
101
+ def finalize(self, raw_filename, final_filename):
102
+ """Secures artifact with AES-256 using the Audit Hash (PWD)."""
103
+ self.output(raw_filename)
104
+ try:
105
+ with pikepdf.open(raw_filename) as pdf:
106
+ # Use Audit Key (PWD) from Dashboard
107
+ pw = str(getattr(self.context, 'report_password', self.session_id))
108
+ pdf.save(final_filename, encryption=pikepdf.Encryption(
109
+ user=pw, owner=pw, allow=pikepdf.Permissions(accessibility=True)
110
+ ))
111
+ if os.path.exists(raw_filename): os.remove(raw_filename)
112
+ return final_filename
113
+ except Exception:
114
+ if os.path.exists(raw_filename): os.rename(raw_filename, final_filename)
115
+ return final_filename
116
+
117
+ def draw_table(self, data, highlight_row=None):
118
+ """Renders Metrics/Hardware Audit Table."""
119
+ self.set_font("Helvetica", size=9)
120
+ col_width = self.epw / len(data[0])
121
+ for i, row in enumerate(data):
122
+ self.set_fill_color(240, 244, 248) if (i == 0 or i == highlight_row) else None
123
+ self.set_font("Helvetica", 'B' if (i == 0 or i == highlight_row) else '', 9)
124
+ for item in row:
125
+ self.cell(col_width, 10, str(item), border=1, fill=(i == 0 or i == highlight_row), align='C')
126
+ self.ln()
core/reporting/email_templates.py ADDED
@@ -0,0 +1,26 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/reporting/email_templates.py
2
+
3
+ REGIONAL_TEMPLATES = {
4
+ "AU_VIC": {
5
+ "subject": "Clinical Profile | Victorian Department of Education Standards",
6
+ "title": "Clinical Screening Artifact",
7
+ "disclaimer": "This report aligns with AHPRA standards and Victorian privacy protocols.",
8
+ "body_intro": "The clinical screening session for your child in Victoria is complete."
9
+ },
10
+ "IN_NEP": {
11
+ "subject": "Holistic Progress Summary | NEP 2020 Protocol",
12
+ "title": "FLN Biometric Summary",
13
+ "disclaimer": "Aligned with Nipun Bharat guidelines for holistic child development.",
14
+ "body_intro": "The biometric assessment as per the National Education Policy (NEP) 2020 is complete."
15
+ },
16
+ "GLOBAL": {
17
+ "subject": "LearningView Pro: Biometric Assessment Report",
18
+ "title": "General Screening Summary",
19
+ "disclaimer": "International screening artifact for educational insight.",
20
+ "body_intro": "Your requested biometric assessment session is complete."
21
+ }
22
+ }
23
+
24
+ def get_template(region):
25
+ """Safely retrieves the template or falls back to Global [cite: 2026-02-27]."""
26
+ return REGIONAL_TEMPLATES.get(region, REGIONAL_TEMPLATES["GLOBAL"])
core/reporting/report_config.py ADDED
@@ -0,0 +1,17 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # core/reporting/report_config.py
2
+
3
+ REPORT_CONFIG = {
4
+ "AU_VIC": {
5
+ "header_title": "AU_VIC CLINICAL PROFILE",
6
+ "footer_compliance": "AHPRA Standards Alignment",
7
+ "primary_color": (15, 23, 42), # Slate-900 (Professional/Clinical)
8
+ "accent_color": (79, 70, 229), # Indigo (Modern/Trust)
9
+ "vcl_fields": ["VUI", "VSN", "VEYLDF_Milestone", "Consent_Level"]
10
+ },
11
+ "IN_NEP": {
12
+ "header_title": "NEP 2020 HOLISTIC PROGRESS",
13
+ "footer_compliance": "NEP 2020 Protocol Alignment",
14
+ "primary_color": (20, 83, 45), # Deep Green (Growth/Education)
15
+ "accent_color": (245, 158, 11) # Amber (Active Learning)
16
+ }
17
+ }
core/secure_storage.py ADDED
@@ -0,0 +1,40 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import asyncio
3
+ from config import DATA_PURGE_DELAY
4
+ from core.logger import log_debug, logger
5
+
6
+
7
+ class Shredder:
8
+ """
9
+ Zero-Persistence Utility for Privacy Compliance.
10
+ Handles the deferred deletion of clinical artifacts.
11
+ """
12
+
13
+ @staticmethod
14
+ async def deferred_purge(file_paths: list, delay: int = DATA_PURGE_DELAY):
15
+ """
16
+ Independent self-destruct timer per session.
17
+ Ensures artifacts exist long enough for email dispatch but no longer.
18
+ """
19
+ log_debug(f"🕒 Privacy: Shredder initialized. Waiting {delay}s for {len(file_paths)} files...")
20
+
21
+ # Non-blocking sleep allows the server to handle other requests
22
+ await asyncio.sleep(delay)
23
+
24
+ for path in file_paths:
25
+ if path and os.path.exists(path):
26
+ try:
27
+ # Overwrite check could be added here for military-grade shredding
28
+ os.remove(path)
29
+ log_debug(f"🛡️ Privacy: Shredded artifact -> {os.path.basename(path)}")
30
+ except Exception as e:
31
+ logger.error(f"❌ Shredder Error for {path}: {e}")
32
+
33
+ @staticmethod
34
+ def instant_purge(file_paths: list):
35
+ """Immediate deletion for failed sessions or temporary intermediate files."""
36
+ for path in file_paths:
37
+ if path and os.path.exists(path):
38
+ os.remove(path)
39
+
40
+ shredder = Shredder()
core/state.py ADDED
@@ -0,0 +1 @@
 
 
1
+ handwriting_cache = {}
core/video_audit.py ADDED
@@ -0,0 +1,50 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import cv2
2
+ from config import MIN_FPS_THRESHOLD
3
+
4
+ class VideoService:
5
+ @staticmethod
6
+ def verify_integrity(video_path: str):
7
+ """
8
+ Standardizes video metadata extraction and quality auditing.
9
+ Includes specific FPS feedback in warnings [cite: 2026-02-27].
10
+ """
11
+ cap = cv2.VideoCapture(video_path)
12
+ if not cap.isOpened():
13
+ return {"valid": False, "error": "Could not open video file."}
14
+
15
+ fps = cap.get(cv2.CAP_PROP_FPS)
16
+ frame_count = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
17
+
18
+ # 🛡️ BRUTE FORCE FALLBACK
19
+ if frame_count <= 0:
20
+ frame_count = 0
21
+ while True:
22
+ ret, _ = cap.read()
23
+ if not ret: break
24
+ frame_count += 1
25
+ cap.set(cv2.CAP_PROP_POS_FRAMES, 0)
26
+
27
+ if fps < 5 or fps > 120:
28
+ fps = 30.0
29
+
30
+ duration = frame_count / fps if fps > 0 else 0
31
+
32
+ # ⚖️ CLINICAL CONFIDENCE AUDIT
33
+ is_suboptimal = fps < MIN_FPS_THRESHOLD
34
+ status_label = "SUBOPTIMAL" if is_suboptimal else "OPTIMAL"
35
+
36
+ cap.release()
37
+
38
+ # 🎯 Dynamic Warning with detected FPS
39
+ warning = None
40
+ if is_suboptimal:
41
+ warning = f"Low frame rate ({round(fps, 1)} FPS) detected. Ocular synchronization may be less precise."
42
+
43
+ return {
44
+ "valid": True,
45
+ "fps": round(fps, 2),
46
+ "frame_count": frame_count,
47
+ "duration": round(duration, 2),
48
+ "status": status_label,
49
+ "warning": warning
50
+ }
engines/.DS_Store ADDED
Binary file (6.15 kB). View file
 
engines/adhd/analyzer.py ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from core.base_analyzer import ClinicalAnalyzer
3
+
4
+ class ADHDAnalyzer(ClinicalAnalyzer):
5
+ def calculate_risk(self, metrics: dict) -> int:
6
+ jitter = metrics.get('head_jitter', 0)
7
+ # Completely different weights for ADHD
8
+ return int(jitter * 60)
engines/dyslexia/__pycache__/analyzer.cpython-310.pyc ADDED
Binary file (893 Bytes). View file
 
engines/dyslexia/__pycache__/logic.cpython-310.pyc ADDED
Binary file (2.37 kB). View file
 
engines/dyslexia/__pycache__/report.cpython-310.pyc ADDED
Binary file (7.51 kB). View file
 
engines/dyslexia/__pycache__/scanner.cpython-310.pyc ADDED
Binary file (7.67 kB). View file
 
engines/dyslexia/analyzer.py ADDED
@@ -0,0 +1,19 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from core.base_analyzer import ClinicalAnalyzer
3
+
4
+ class DyslexiaAnalyzer(ClinicalAnalyzer):
5
+ def calculate_risk(self, metrics: dict) -> int:
6
+ wer = metrics.get('wer', 0.0)
7
+ regressions = metrics.get('regressions', 0)
8
+ attentiveness = metrics.get('vision_attentiveness', 100) # 🆕 Weighting Engagement
9
+
10
+ # Penalize low attentiveness (engagement)
11
+ engagement_penalty = max(0, (95 - attentiveness) * 0.4)
12
+
13
+ # Logarithmic weight for reading strain
14
+ ocular_weight = 12 * math.log1p(regressions)
15
+
16
+ # Synthesis: (WER 30%) + (Ocular 40%) + (Engagement 30%)
17
+ score = (wer * 30) + (ocular_weight * 3) + engagement_penalty
18
+
19
+ return int(min(max(score, 5), 95))
engines/dyslexia/logic.py ADDED
@@ -0,0 +1,79 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import math
2
+ from core.base_clinical_strategy import BaseClinicalStrategy
3
+ from difflib import SequenceMatcher
4
+ import re
5
+
6
+
7
+ class DyslexiaStrategy(BaseClinicalStrategy):
8
+ def calculate(self, metrics: dict) -> float:
9
+ """
10
+ Dynamic Clinical Synthesis with Calibration Offset [cite: 2026-03-01].
11
+ """
12
+ # 1. Extraction [cite: 2026-03-01]
13
+ wer = metrics.get('wer', metrics.get('speech_accuracy', 0.0))
14
+ regressions = metrics.get('regressions', 0)
15
+ drift = metrics.get('drift', metrics.get('handwriting_drift', 0.0))
16
+ ocr_acc = metrics.get('ocr_accuracy', 1.0)
17
+
18
+ # 🎯 New: Calibration Offset (Default to 100 if missing) [cite: 2026-03-01]
19
+ confidence = metrics.get('confidence_score', 100.0)
20
+
21
+ # 2. Hardware-Aware Dampening [cite: 2026-03-01]
22
+ # If confidence is < 40, the eyes are likely jumping due to low FPS, not dyslexia
23
+ ocular_multiplier = 3.0 if confidence > 45 else 0.8
24
+ dampened_regressions = 10 * math.log1p(regressions)
25
+
26
+ # 3. Normalized Weights [cite: 2026-03-01]
27
+ wer_val = wer * 100 if wer <= 1.0 else wer
28
+
29
+ # ⚖️ Clinical Weights: WER (40%), Ocular (30%), Kinetic (10%), OCR (20%) [cite: 2026-03-01]
30
+ # Notice we use the ocular_multiplier to protect against bad data [cite: 2026-03-01]
31
+ score = (wer_val * 0.4) + (dampened_regressions * ocular_multiplier) + (abs(drift) * 10) + ((1.0 - ocr_acc) * 20)
32
+
33
+ # 4. Final Safe Bounds
34
+ return float(min(max(score, 0), 100))
35
+
36
+
37
+
38
+ def calculate_lexical_fidelity(detected: str, target: str) -> float:
39
+ """
40
+ Calculates similarity on a 0-100 scale using normalized text.
41
+ """
42
+ if not target or not detected:
43
+ return 0.0
44
+
45
+ d_clean = normalize_clinical_text(detected)
46
+ t_clean = normalize_clinical_text(target)
47
+
48
+ # Fuzzy match ratio (0.0 to 1.0)
49
+ similarity = SequenceMatcher(None, d_clean, t_clean).ratio()
50
+
51
+ # Return as percentage for consistent reporting
52
+ return round(similarity * 100, 2)
53
+
54
+
55
+ def normalize_clinical_text(text: str) -> str:
56
+ """
57
+ Advanced normalization to bridge the gap between spoken numbers
58
+ and written digits, and strip all non-lexical noise.
59
+ """
60
+ if not text: return ""
61
+
62
+ # 1. Standardize case and strip punctuation
63
+ text = text.lower()
64
+ text = re.sub(r'[^\w\s]', '', text)
65
+
66
+ # 2. Automated Number-to-Phonetic Mapping
67
+ # This handles the "7" vs "seven" discrepancy found in Session 9NHV4G
68
+ num_to_words = {
69
+ "0": "zero", "1": "one", "2": "two", "3": "three", "4": "four",
70
+ "5": "five", "6": "six", "7": "seven", "8": "eight", "9": "nine",
71
+ "10": "ten", "12": "twelve", "24": "twenty four"
72
+ }
73
+
74
+ words = text.split()
75
+ normalized_words = [num_to_words.get(w, w) for w in words]
76
+
77
+ # 3. Collapse whitespace
78
+ return " ".join(normalized_words).strip()
79
+
engines/dyslexia/report.py ADDED
@@ -0,0 +1,193 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ from fpdf import FPDF
3
+ from datetime import datetime
4
+ from engines.dyslexia.logic import calculate_lexical_fidelity
5
+
6
+ class DyslexiaReport(FPDF):
7
+ def __init__(self, session_id, region, context):
8
+ super().__init__()
9
+ self.session_id = session_id
10
+ self.region = region
11
+ self.context = context
12
+ self.set_auto_page_break(auto=True, margin=15)
13
+ self.alias_nb_pages()
14
+
15
+ def header(self):
16
+ """Standardized Clinical Header."""
17
+ if self.page_no() <= 5:
18
+ self.set_font('Helvetica', 'B', 8)
19
+ self.set_text_color(148, 163, 184) # Slate 400
20
+ self.cell(0, 10, f"VCL-VUI Protocol Alignment | Ref: {self.session_id}", 0, 0, 'L')
21
+ self.cell(0, 10, f"Page {self.page_no()}/{{nb}}", 0, 0, 'R')
22
+ self.ln(12)
23
+
24
+ def _safe_latin(self, text):
25
+ if not text: return ""
26
+ return text.encode('latin-1', 'replace').decode('latin-1')
27
+
28
+ def draw_h2(self, title):
29
+ """Reusable section header to keep code lean."""
30
+ self.set_font('Helvetica', 'B', 12)
31
+ self.set_text_color(15, 23, 42) # Slate 900
32
+ self.cell(0, 10, self._safe_latin(title), ln=True)
33
+ self.set_draw_color(226, 232, 240) # Slate 200
34
+ self.line(self.get_x(), self.get_y(), self.get_x() + 190, self.get_y())
35
+ self.ln(5)
36
+
37
+ def add_vcl_summary_page(self, metrics):
38
+ """Page 1: Executive Synthesis (Eliminates 'Empty Page 1' bug)."""
39
+ self.add_page()
40
+
41
+ # 🏢 Header Branding Block
42
+ self.set_fill_color(248, 250, 252)
43
+ self.rect(10, 25, 190, 45, 'F')
44
+
45
+ self.set_xy(15, 30)
46
+ self.set_font('Helvetica', 'B', 16)
47
+ self.set_text_color(30, 41, 59)
48
+ self.cell(0, 8, "CLINICAL DIAGNOSTIC REPORT", ln=True)
49
+
50
+ self.set_font('Helvetica', '', 9); self.set_text_color(100, 100, 100)
51
+ self.cell(0, 5, f"EDITION: {self.region} | JURISDICTION: VICTORIA CHILD LINK (VCL)", ln=True)
52
+ self.ln(5)
53
+
54
+ # Metadata Grid
55
+ self.set_font('Helvetica', 'B', 9); self.set_text_color(71, 85, 105)
56
+ self.cell(30, 5, "STUDENT:"); self.set_font('Helvetica', '', 9); self.cell(60, 5, self.context.child_name.upper())
57
+ 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)
58
+
59
+ 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"))
60
+ 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)
61
+
62
+ self.ln(15)
63
+
64
+ # 📊 1. Multi-Dimensional Synthesis
65
+ self.draw_h2("1. Multi-Dimensional Synthesis")
66
+ summary = metrics.get('diagnosis_summary', {})
67
+
68
+ # Simplified horizontal risk layout
69
+ risks = [
70
+ ("Dyslexia", summary.get('dyslexia', {})),
71
+ ("Dysgraphia", summary.get('dysgraphia', {})),
72
+ ("Dyscalculia", summary.get('dyscalculia', {}))
73
+ ]
74
+
75
+ current_y = self.get_y()
76
+ for i, (label, data) in enumerate(risks):
77
+ self.set_xy(15 + (i * 65), current_y)
78
+ score = data.get('score', 0)
79
+ sev = data.get('severity', 'Low')
80
+
81
+ self.set_font('Helvetica', 'B', 10); self.set_text_color(100, 100, 100)
82
+ self.cell(60, 5, label, align='C', ln=True)
83
+ self.set_x(15 + (i * 65))
84
+ self.set_font('Helvetica', 'B', 28); self.set_text_color(15, 23, 42)
85
+ self.cell(60, 14, str(int(score)), align='C', ln=True)
86
+
87
+ # Severity Badge
88
+ self.set_x(25 + (i * 65))
89
+ color = (34, 197, 94) if sev == 'Low' else (239, 68, 68) if sev == 'High' else (245, 158, 11)
90
+ self.set_fill_color(*color); self.set_text_color(255, 255, 255)
91
+ self.set_font('Helvetica', 'B', 8)
92
+ self.cell(40, 7, f"{sev.upper()} RISK", align='C', fill=True, ln=True)
93
+
94
+ def add_transcription_audit(self, target: str, actual: str):
95
+ """Page 3 (Top): Reading Audit with color-coded fidelity."""
96
+ self.draw_h2("2. Transcription Accuracy Audit")
97
+
98
+ fidelity = calculate_lexical_fidelity(actual, target)
99
+ self.set_font('Helvetica', 'B', 10)
100
+ self.set_text_color(220, 38, 38) if fidelity < 70 else self.set_text_color(22, 163, 74)
101
+ self.cell(0, 8, f"PHONETIC ALIGNMENT (READING ACCURACY): {int(fidelity)}%", ln=True)
102
+ self.ln(2)
103
+
104
+ self.set_font('Helvetica', 'B', 9); self.set_text_color(100, 100, 100)
105
+ self.cell(0, 5, "EXPECTED READING PROMPT:", ln=True)
106
+ self.set_font('Helvetica', 'I', 10); self.set_text_color(30, 41, 59)
107
+ self.multi_cell(0, 6, self._safe_latin(f'"{target}"'))
108
+ self.ln(4)
109
+
110
+ self.set_font('Helvetica', 'B', 9); self.set_text_color(100, 100, 100)
111
+ self.cell(0, 5, "ACTUAL VOCAL TRANSCRIPTION:", ln=True)
112
+ self.set_font('Helvetica', 'B', 11); self.set_text_color(30, 41, 59)
113
+ self.multi_cell(0, 7, self._safe_latin(f'"{actual or "No speech detected"}"'))
114
+ self.ln(8)
115
+
116
+ def add_kinetic_audit(self, metrics: dict, target: str):
117
+ """Page 3 (Bottom): Writing Audit."""
118
+ self.draw_h2("3. Kinetic Extraction Audit")
119
+ actual = metrics.get('detected_handwriting', '')
120
+ fidelity = calculate_lexical_fidelity(actual, target)
121
+
122
+ self.set_font('Helvetica', 'B', 10)
123
+ self.set_text_color(220, 38, 38) if fidelity < 40 else self.set_text_color(22, 163, 74)
124
+ self.cell(0, 8, f"LEXICAL FIDELITY (WRITING ACCURACY): {int(fidelity)}%", ln=True)
125
+ self.ln(2)
126
+
127
+ self.set_font('Helvetica', 'B', 9); self.set_text_color(100, 100, 100)
128
+ self.cell(0, 5, "PRESCRIBED WRITING TASK:", ln=True)
129
+ self.set_font('Helvetica', 'I', 10); self.set_text_color(30, 41, 59)
130
+ self.multi_cell(0, 6, self._safe_latin(f'"{target}"'))
131
+ self.ln(4)
132
+
133
+ self.set_font('Helvetica', 'B', 9); self.set_text_color(100, 100, 100)
134
+ self.cell(0, 5, "STUDENT HANDWRITING EXTRACTION:", ln=True)
135
+ self.set_font('Helvetica', 'B', 11); self.set_text_color(30, 41, 59)
136
+ self.multi_cell(0, 7, self._safe_latin(f'"{actual or "No text detected"}"'))
137
+ self.ln(6)
138
+
139
+ # Kinetic Metrics
140
+ self.set_font('Helvetica', 'B', 9); self.set_text_color(30, 41, 59)
141
+ self.cell(45, 8, "Basal Drift Angle:"); self.set_font('Helvetica', '', 10); self.cell(40, 8, f"{metrics.get('basal_drift', 0)}°")
142
+ 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)
143
+
144
+ def add_interpretation_guide(self):
145
+ """Page 4: Detailed Science & Glossary."""
146
+ self.add_page()
147
+ self.draw_h2("4. Information & Interpretation Guide")
148
+
149
+ # Profiles Section
150
+ self.set_font('Helvetica', 'B', 11); self.set_text_color(37, 99, 235)
151
+ self.cell(0, 10, "Understanding Clinical Profiles", ln=True)
152
+
153
+ defs = [
154
+ ("Dyslexia", "A neurological difference affecting phonological processing. High risk suggests struggle with decoding and ocular smoothness."),
155
+ ("Dysgraphia", "Affects motor integration required for handwriting. Measured via lexical fidelity and kinetic drift."),
156
+ ("Dyscalculia", "Difficulty comprehending numerical symbols. Measured via cognitive latency on numerical triggers.")
157
+ ]
158
+ for title, desc in defs:
159
+ self.set_font('Helvetica', 'B', 9); self.set_text_color(30, 41, 59)
160
+ self.cell(25, 6, f"{title}: ")
161
+ self.set_font('Helvetica', '', 9); self.set_text_color(71, 85, 105)
162
+ self.multi_cell(0, 6, desc)
163
+ self.ln(2)
164
+
165
+ self.ln(5)
166
+ self.draw_h2("5. Recommendations")
167
+ # Logic is handled here based on risk summary scores...
168
+
169
+ # --- Finalizer Entry Point ---
170
+ def generate_dyslexia_report(metrics, heatmap_path, session_id, locale, target_text, trans_text, context, **kwargs):
171
+ report = DyslexiaReport(session_id=session_id, region=locale, context=context)
172
+
173
+ # 1. Page 1: Executive Summary
174
+ report.add_vcl_summary_page(metrics)
175
+
176
+ # 2. Page 2: Evidence (Heatmap)
177
+ report.add_page()
178
+ report.draw_h2("Ocular-Orthographic Evidence")
179
+ if os.path.exists(heatmap_path):
180
+ report.image(heatmap_path, x=15, y=report.get_y(), w=180)
181
+
182
+ # 3. Page 3: Full Audit Trail
183
+ report.add_page()
184
+ report.add_transcription_audit(target_text, trans_text)
185
+ report.add_kinetic_audit(metrics, target=kwargs.get('writing_target', "Default"))
186
+
187
+ # 4. Page 4: Information Guide
188
+ report.add_interpretation_guide()
189
+
190
+ # Output to clinical artifact store
191
+ out_file = f"report_{session_id}.pdf"
192
+ report.output(out_file)
193
+ return out_file
engines/dyslexia/scanner.py ADDED
@@ -0,0 +1,239 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import os
2
+ import cv2
3
+ import asyncio
4
+ import time
5
+ import numpy as np
6
+ import random
7
+
8
+ from core.logger import log_clinical_event, monitor_perf, logger, log_debug
9
+ from core.base_scanner import BaseScanner, ScannerContext
10
+ from services.biometric_engine import biometric_engine
11
+ from services.speech_analysis import speech_engine
12
+ from services.email_service import email_service
13
+ from services.decision_engine import decision_engine
14
+ from core.secure_storage import shredder
15
+ from engines.dyslexia.analyzer import DyslexiaAnalyzer
16
+ from core.state import handwriting_cache
17
+ from engines.dyslexia.report import generate_dyslexia_report
18
+ from config import TEMP_DIR, DATA_PURGE_DELAY
19
+ from engines.dyslexia.logic import calculate_lexical_fidelity
20
+
21
+
22
+ class DyslexiaScanner(BaseScanner):
23
+ def __init__(self):
24
+ self.name = "LearnView Pro: Dyslexia Engine"
25
+ self.biometric_engine = biometric_engine
26
+ self.analyzer = DyslexiaAnalyzer()
27
+
28
+ async def synthesize_risk(self, session_data: dict) -> dict:
29
+ risk_score = self.analyzer.calculate_risk(session_data)
30
+ severity = "High" if risk_score > 70 else "Moderate" if risk_score > 30 else "Low"
31
+ return {"risk_score": risk_score, "severity": severity}
32
+
33
+ @monitor_perf
34
+ async def analyze(self, context: ScannerContext, background_tasks):
35
+ """Unified orchestrator with full clinical depth."""
36
+ log_clinical_event(context.session_id, "Full Synthesis Start")
37
+
38
+ # --- 📝 1. POLLING, RECOVERY & AUDIT HASH ---
39
+ hw_data = None
40
+ for _ in range(10): # Wait for Google OCR write
41
+ hw_data = handwriting_cache.get(context.session_id)
42
+ if hw_data and hw_data.get('detected_text') not in [None, "", "[Processing...]"]:
43
+ break
44
+ await asyncio.sleep(0.5)
45
+
46
+ if not hw_data and handwriting_cache:
47
+ latest_id = list(handwriting_cache.keys())[-1]
48
+ hw_data = handwriting_cache.get(latest_id)
49
+ logger.info(f"✅ Recovered OCR data from ID: {latest_id}")
50
+
51
+ hw_data = hw_data or {"detected_text": "[Extraction Delayed]", "basal_drift": 0.0, "slant": 0.0, "ocr_accuracy": 0.0}
52
+
53
+ # Calculate Strict Character Error Rate (CER)
54
+ detected_text = hw_data.get('detected_text', '')
55
+ target_writing = getattr(context, 'writing_target', "Default Task")
56
+
57
+ # This returns 0-100; a similarity of 80 means risk is now 20
58
+ fidelity_score = calculate_lexical_fidelity(detected_text, target_writing)
59
+ hw_data['ocr_accuracy'] = fidelity_score / 100.0
60
+
61
+ cer = self.biometric_engine.calculate_cer(target_writing, detected_text)
62
+ hw_data['ocr_accuracy'] = 1.0 - cer
63
+
64
+ # Process Strict Handwriting Kinetics
65
+ if hasattr(context, 'hw_path') and context.hw_path and os.path.exists(context.hw_path):
66
+ kinetics = self.biometric_engine.process_handwriting_kinetics(context.hw_path)
67
+ hw_data['basal_drift'] = kinetics.get('basal_drift', 0.0)
68
+ hw_data['slant'] = kinetics.get('slant', 0.0)
69
+ else:
70
+ hw_data['basal_drift'] = 0.0
71
+ hw_data['slant'] = 0.0
72
+
73
+ # --- 🎥 2. VIDEO BIOMETRIC PROCESSING (Restored Telemetry) ---
74
+ cap = cv2.VideoCapture(context.video_path)
75
+
76
+ # ✅ UPDATED: Added distance_logs for compliance audit
77
+ gaze_buffer, distance_logs, attentive_frames, total_frames, latency_samples = [], [], 0, 0, []
78
+ fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
79
+
80
+ while cap.isOpened():
81
+ start_tick = time.time()
82
+ ret, frame = cap.read()
83
+ if not ret: break
84
+ total_frames += 1
85
+
86
+ results = self.biometric_engine.process_frame(cv2.cvtColor(frame, cv2.COLOR_BGR2RGB))
87
+ if results.multi_face_landmarks:
88
+ lm = results.multi_face_landmarks[0].landmark
89
+ # 🎯 Iris depth tracking
90
+ iris_id = self.biometric_engine.calculate_iris_depth(results.multi_face_landmarks[0])
91
+
92
+ # ✅ UPDATED: Track physical distance per frame using the 15.5 clinical constant
93
+ current_dist = 15.5 / (iris_id + 0.00001)
94
+ distance_logs.append(current_dist)
95
+
96
+ gaze_buffer.append({"x": lm[468].x, "y": lm[468].y, "id": iris_id, "timestamp": total_frames/fps})
97
+ if abs(lm[1].x - 0.5) < 0.25: attentive_frames += 1
98
+
99
+ latency_samples.append(time.time() - start_tick) # 🎯 Performance jitter tracking
100
+ cap.release()
101
+
102
+ # --- 🎙️ 3. CLINICAL SYNTHESIS ---
103
+
104
+ # ✅ UPDATED: Execute clinical positioning audit based on recorded distance logs
105
+ compliance = self.biometric_engine.analyze_compliance(distance_logs)
106
+
107
+ speech_data = speech_engine.analyze_with_timestamps(context.video_path, context.target_text, context.session_id)
108
+ attentiveness = (attentive_frames / total_frames * 100) if total_frames > 0 else 0.0
109
+ ocular_metrics = self.biometric_engine.analyze_gaze_v2(gaze_buffer)
110
+ raw_wer = speech_data.get('accuracy', {}).get('wer', 1.0)
111
+
112
+ jitter = np.mean(np.abs(np.diff(latency_samples))) * 1000 if len(latency_samples) > 1 else 0
113
+ avg_latency = np.mean(latency_samples) * 1000 if latency_samples else 0
114
+
115
+ risk_data = await self.synthesize_risk({
116
+ "wer": raw_wer, "regressions": ocular_metrics.get('regression_count', 0),
117
+ "vision_attentiveness": attentiveness, "drift": hw_data.get('basal_drift', 0.0)
118
+ })
119
+
120
+ sync_data = decision_engine.synthesize_ocular_phonetic_sync(gaze_buffer, speech_data.get('word_alignment', []), fps=fps)
121
+
122
+ # Initialize Multi-Disability Markers
123
+ phonetic_delay_flag = False
124
+ num_latency_ms = 0.0
125
+
126
+ # --- 👁️ GAZE NORMALIZATION MATRIX ---
127
+ if len(gaze_buffer) > 0:
128
+ min_x = min(pt['x'] for pt in gaze_buffer)
129
+ max_x = max(pt['x'] for pt in gaze_buffer)
130
+ min_y = min(pt['y'] for pt in gaze_buffer)
131
+ max_y = max(pt['y'] for pt in gaze_buffer)
132
+
133
+ range_x = max((max_x - min_x), 0.0001)
134
+ range_y = max((max_y - min_y), 0.0001)
135
+
136
+ for pt in gaze_buffer:
137
+ norm_x = (pt['x'] - min_x) / range_x
138
+ norm_y = (pt['y'] - min_y) / range_y
139
+
140
+ # Push the coordinates down to where the text actually is
141
+ pt['x'] = 0.10 + (norm_x * 0.80)
142
+ pt['y'] = 0.50 + (norm_y * 0.30)
143
+
144
+ # Targeted Trigger Analysis
145
+ triggers = getattr(context, 'metadata', {}).get('triggers', {})
146
+ dyslexia_word = triggers.get('dyslexia')
147
+ dyscalculia_num = triggers.get('dyscalculia')
148
+
149
+ if dyslexia_word:
150
+ word_fixations = [pt for pt in gaze_buffer if self.biometric_engine.is_over_word(pt, dyslexia_word)]
151
+ if len(word_fixations) > (fps * 0.8):
152
+ phonetic_delay_flag = True
153
+ log_clinical_event(context.session_id, f"Phonetic Delay: {dyslexia_word}")
154
+
155
+ if dyscalculia_num:
156
+ num_fixations = [pt for pt in gaze_buffer if self.biometric_engine.is_over_word(pt, dyscalculia_num)]
157
+ num_latency_ms = (len(num_fixations) / fps) * 1000
158
+ if num_latency_ms > 1200:
159
+ log_clinical_event(context.session_id, f"Numerical Processing Delay: {dyscalculia_num}")
160
+
161
+ raw_biometric_data = {
162
+ "regression_count": int(ocular_metrics.get('regression_count', 0)),
163
+ "phonetic_delay_detected": phonetic_delay_flag,
164
+ "basal_drift": hw_data.get('basal_drift', 0.0),
165
+ "slant": hw_data.get('slant', 0.0),
166
+ "ocr_error_rate": 1.0 - hw_data.get('ocr_accuracy', 0.0),
167
+ "numerical_latency_ms": num_latency_ms,
168
+ "confidence_score": compliance["confidence_score"] # ✅ UPDATED: Passes strictly verified score
169
+ }
170
+
171
+ unified_diagnosis = decision_engine.synthesize_unified_report(
172
+ raw_biometric_data,
173
+ triggers=getattr(context, 'metadata', {}).get('triggers', {})
174
+ )
175
+
176
+ final_metrics = {
177
+ "risk_score": risk_data["risk_score"], "risk_level": risk_data["severity"],
178
+ "sync_score": sync_data.get("alignment_score", 100),
179
+ "confidence_score": int(compliance["confidence_score"]), # ✅ UPDATED
180
+ "is_reliable": compliance["is_reliable"], # ✅ UPDATED
181
+ "attentiveness": round(float(attentiveness), 1), "audit_hash": context.report_password,
182
+ "basal_drift": round(float(hw_data.get('basal_drift', 0.0)), 2),
183
+ "slant": round(float(hw_data.get('slant', 0.0)), 2),
184
+ "ocr_accuracy": round(float(fidelity_score / 100.0), 2),
185
+ "detected_handwriting": hw_data.get('detected_text', '[No Text Extracted]'),
186
+ "saccade_count": int(ocular_metrics.get('saccade_count', 0)),
187
+ "regression_count": int(ocular_metrics.get('regression_count', 0)),
188
+ "speech_accuracy": round(float(1.0 - raw_wer), 2), "latency": round(avg_latency, 2), "jitter": round(jitter, 2),
189
+ "struggle_words": [w['word'] if isinstance(w, dict) else str(w) for w in speech_data.get('struggle_words', [])],
190
+ "dyscalculia_marker": num_latency_ms > 1200,
191
+ "writing_target": context.writing_target,
192
+ "diagnosis_summary": unified_diagnosis
193
+ }
194
+
195
+ # --- 📄 4. ARTIFACTS & DISPATCH ---
196
+
197
+ text_canvas_path = self.biometric_engine.create_text_canvas(
198
+ context.target_text,
199
+ context.session_id,
200
+ bounding_box={"top": 0.50, "left": 0.10, "width": 0.80, "height": 0.30}
201
+ )
202
+
203
+ heatmap_file = self.biometric_engine.generate_heatmap(gaze_buffer,
204
+ text_canvas_path,
205
+ context.session_id,
206
+ jitter_log=latency_samples,
207
+ sigma=1.8)
208
+
209
+ pdf_path = generate_dyslexia_report(metrics=final_metrics, heatmap_path=os.path.join(TEMP_DIR, heatmap_file),
210
+ session_id=context.session_id, locale=context.locale,
211
+ target_text=context.target_text,
212
+ trans_text=speech_data.get('transcribed_text', ""),
213
+ context=context, writing_target=context.writing_target)
214
+
215
+ recipient_email = getattr(context, 'parent_email', 'arrowinthedust@gmail.com')
216
+ await email_service.send_report(recipient_email, pdf_path, session_id=context.session_id, metrics=final_metrics)
217
+
218
+ canvas_file = os.path.join(TEMP_DIR, f"canvas_{context.session_id}.png")
219
+ hw_file = os.path.join(TEMP_DIR, f"hw_{context.session_id}.png")
220
+
221
+ purge_list = [
222
+ context.video_path,
223
+ context.hw_path,
224
+ text_canvas_path,
225
+ pdf_path,
226
+ canvas_file,
227
+ hw_file,
228
+ os.path.join(TEMP_DIR, heatmap_file)
229
+ ]
230
+
231
+ valid_purge_list = [p for p in purge_list if p and os.path.exists(p)]
232
+
233
+ background_tasks.add_task(
234
+ shredder.deferred_purge,
235
+ valid_purge_list,
236
+ delay=DATA_PURGE_DELAY
237
+ )
238
+
239
+ return {"status": "success", "diagnosis": final_metrics}
google_ocr_key.json ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ {
2
+ "type": "service_account",
3
+ "project_id": "yoda-439408",
4
+ "private_key_id": "695dc3b70f91e54df81cb9797afb46bfdf1e32d4",
5
+ "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",
6
+ "client_email": "dyslexia-mvp-ocr@yoda-439408.iam.gserviceaccount.com",
7
+ "client_id": "110359517634267127941",
8
+ "auth_uri": "https://accounts.google.com/o/oauth2/auth",
9
+ "token_uri": "https://oauth2.googleapis.com/token",
10
+ "auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
11
+ "client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/dyslexia-mvp-ocr%40yoda-439408.iam.gserviceaccount.com",
12
+ "universe_domain": "googleapis.com"
13
+ }
main.py ADDED
@@ -0,0 +1,309 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from fastapi import FastAPI, UploadFile, File, Form, HTTPException, BackgroundTasks
2
+ from fastapi.middleware.cors import CORSMiddleware
3
+ from fastapi.responses import FileResponse
4
+ from fastapi.staticfiles import StaticFiles
5
+ from services.prompt_service import prompt_service
6
+
7
+ import os
8
+ import shutil
9
+ import logging
10
+ import cv2
11
+ import numpy as np
12
+ import time
13
+ import glob
14
+ import smtplib
15
+ from email.message import EmailMessage
16
+ from typing import Optional
17
+ from contextlib import asynccontextmanager
18
+ from fastapi_utils.tasks import repeat_every
19
+
20
+ from config import (
21
+ DEFAULT_REGION, TEMP_DIR, CORS_ORIGINS,
22
+ ASSESSMENT_PROMPTS, WRITING_PROMPTS,
23
+ SMTP_SERVER, SMTP_PORT, SMTP_USER, SMTP_PASSWORD,
24
+ DATA_PURGE_DELAY
25
+ )
26
+ from core.base_scanner import ScannerContext
27
+ from core.secure_storage import shredder
28
+ from core.logger import logger, monitor_perf, log_debug
29
+
30
+ from engines.dyslexia.scanner import DyslexiaScanner
31
+ from services.biometric_engine import biometric_engine
32
+ from core.state import handwriting_cache
33
+
34
+ # --- SILENCE VERBOSE LOGGERS ---
35
+ silenced = [
36
+ 'numba.core.byteflow', 'numba.core.interpreter', 'numba.core.ssa',
37
+ 'multipart', 'python_multipart', 'fpdf.output',
38
+ 'PIL.PngImagePlugin', 'pydub.converter', 'fpdf.fpdf'
39
+ ]
40
+ for logger_name in silenced:
41
+ logging.getLogger(logger_name).setLevel(logging.WARNING)
42
+
43
+ # --- LIFESPAN HANDLER (Modern FastAPI Standard) ---
44
+ @asynccontextmanager
45
+ async def lifespan(app: FastAPI):
46
+ # --- 🚀 STARTUP ---
47
+ try:
48
+ # Properly await the coroutine to prevent RuntimeWarning
49
+ await hourly_artifact_cleanup()
50
+ logger.info("Clinical Compliance Sweep: Initialized and Awaited.")
51
+ except Exception as e:
52
+ logger.error(f"Initial cleanup failed: {e}")
53
+
54
+ yield # Component remains active for requests
55
+
56
+ # --- 🛑 SHUTDOWN ---
57
+ # 1. Final Purge of all temporary artifacts
58
+ purged_count = 0
59
+ if os.path.exists(TEMP_DIR):
60
+ for f in os.listdir(TEMP_DIR):
61
+ path = os.path.join(TEMP_DIR, f)
62
+ try:
63
+ if os.path.isfile(path):
64
+ os.remove(path)
65
+ purged_count += 1
66
+ elif os.path.isdir(path):
67
+ shutil.rmtree(path)
68
+ purged_count += 1
69
+ except Exception as e:
70
+ logger.error(f"Shutdown purge error for {f}: {e}")
71
+
72
+ # 2. Security Heartbeat Email
73
+ try:
74
+ msg = EmailMessage()
75
+ msg['Subject'] = "🔒 LearnView Pro: Final Security Heartbeat"
76
+ msg['From'] = SMTP_USER
77
+ msg['To'] = SMTP_USER
78
+ msg.set_content(
79
+ f"Server Shutdown Protocol Complete.\n\n"
80
+ f"Final Audit: {purged_count} artifacts purged from HIPAA cache.\n"
81
+ f"Status: Zero-Persistence Integrity Maintained.\n"
82
+ f"Timestamp: {time.ctime()}"
83
+ )
84
+
85
+ with smtplib.SMTP_SSL(SMTP_SERVER, SMTP_PORT) as server:
86
+ server.login(SMTP_USER, SMTP_PASSWORD)
87
+ server.send_message(msg)
88
+ logger.info("📧 Security Heartbeat: Sent successfully.")
89
+ except Exception as e:
90
+ logger.error(f"Security Heartbeat failed: {e}")
91
+
92
+ logger.info("Clinical Hub: Shutdown and Final Purge Complete.")
93
+
94
+ # --- INITIALIZE APP ---
95
+ app = FastAPI(title="LearnView Pro: Diagnostic Hub", lifespan=lifespan)
96
+
97
+ app.add_middleware(
98
+ CORSMiddleware,
99
+ allow_origins=CORS_ORIGINS,
100
+ allow_credentials=True,
101
+ allow_methods=["*"],
102
+ allow_headers=["*"],
103
+ )
104
+
105
+ # Custom StaticFiles to prevent caching of clinical artifacts
106
+ class AccessibleStaticFiles(StaticFiles):
107
+ async def get_response(self, path: str, scope):
108
+ response = await super().get_response(path, scope)
109
+ response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
110
+ response.headers["Access-Control-Allow-Origin"] = "*"
111
+ return response
112
+
113
+ os.makedirs(TEMP_DIR, exist_ok=True)
114
+ app.mount("/temp_reports", AccessibleStaticFiles(directory=TEMP_DIR), name="temp_reports")
115
+
116
+ SCANNERS = {"dyslexia": DyslexiaScanner()}
117
+
118
+ # --- UTILITIES ---
119
+ def decode_frame(byte_data: bytes):
120
+ nparr = np.frombuffer(byte_data, np.uint8)
121
+ return cv2.imdecode(nparr, cv2.IMREAD_COLOR)
122
+
123
+ # --- DISPATCHER ENDPOINTS ---
124
+
125
+ @app.post("/purge/{session_id}")
126
+ async def purge_session_artifacts(session_id: str):
127
+ """Scans TEMP_DIR for files related to session_id and deletes them."""
128
+ try:
129
+ pattern = os.path.join(TEMP_DIR, f"*{session_id}*")
130
+ files_to_delete = glob.glob(pattern)
131
+
132
+ if not files_to_delete:
133
+ return {"status": "already_clean", "session_id": session_id}
134
+
135
+ for file_path in files_to_delete:
136
+ if os.path.isfile(file_path):
137
+ os.remove(file_path)
138
+ elif os.path.isdir(file_path):
139
+ shutil.rmtree(file_path)
140
+
141
+ return {"status": "success", "purged_count": len(files_to_delete)}
142
+ except Exception as e:
143
+ raise HTTPException(status_code=500, detail=f"Purge failed: {str(e)}")
144
+
145
+ @app.get("/health")
146
+ async def health_check():
147
+ """Heartbeat for telemetry and latency measurements."""
148
+ return {"status": "online", "version": "2.0.0"}
149
+
150
+ @app.get("/get-ocr-preview/{session_id}")
151
+ async def get_ocr_preview(session_id: str):
152
+ """Retrieves Google OCR preview for clinical intake."""
153
+ data = handwriting_cache.get(session_id)
154
+ if not data: return {"text": "Processing handwriting..."}
155
+ return {"text": data.get("detected_text", "No text detected")}
156
+
157
+ @app.get("/get-prompt")
158
+ async def get_prompt(level: str = "beginner"):
159
+ """Returns clinical reading and writing targets based on level."""
160
+ lvl = level.strip().lower()
161
+ session_package = prompt_service.generate_balanced_session(lvl)
162
+ return {
163
+ "level": lvl,
164
+ "reading_task": session_package["reading_task"],
165
+ "writing_task": session_package["writing_task"],
166
+ "triggers": session_package["metadata"]["triggers"]
167
+ }
168
+
169
+ @monitor_perf
170
+ @app.post("/analyze")
171
+ async def analyze_session(
172
+ background_tasks: BackgroundTasks,
173
+ video: UploadFile = File(...),
174
+ handwriting: Optional[UploadFile] = File(None),
175
+ session_id: str = Form("anonymous"),
176
+ full_name: str = Form("Unknown"),
177
+ child_class: str = Form("N/A"),
178
+ level: str = Form("beginner"),
179
+ target_text: str = Form("Default Task"),
180
+ parent_email: Optional[str] = Form(None),
181
+ adult_id: str = Form("anonymous"),
182
+ locale: str = Form(None),
183
+ scanner_type: str = Form("dyslexia"),
184
+ is_demo: bool = Form(False),
185
+ flatten: bool = Form(True),
186
+ latency: str = Form("0"),
187
+ writing_target: str = Form(""),
188
+ ):
189
+ """Clinical processing dispatcher with strict target enforcement."""
190
+ video_path = os.path.join(TEMP_DIR, f"vid_{session_id}.webm")
191
+ hw_path = os.path.join(TEMP_DIR, f"hw_{session_id}.png") if handwriting else None
192
+
193
+ if is_demo:
194
+ return {"status": "success", "diagnosis": {"risk_score": 45.0, "report_password": session_id}}
195
+
196
+ try:
197
+ with open(video_path, "wb") as buffer:
198
+ shutil.copyfileobj(video.file, buffer)
199
+ if handwriting:
200
+ with open(hw_path, "wb") as buffer:
201
+ shutil.copyfileobj(handwriting.file, buffer)
202
+
203
+ generated_hash = biometric_engine.generate_audit_hash()
204
+
205
+ # ✅ FIX: Strict Fallback to ensure Lexical Fidelity calculation doesn't fail
206
+ actual_writing_target = writing_target if writing_target and len(writing_target) > 2 else WRITING_PROMPTS.get(level.lower(), WRITING_PROMPTS["beginner"])
207
+
208
+ context = ScannerContext(
209
+ session_id=session_id, adult_id=adult_id, latency=latency,
210
+ child_name=full_name, child_class=child_class, level=level,
211
+ locale=locale or DEFAULT_REGION, target_text=target_text,
212
+ writing_target=actual_writing_target, # ✅ Passed to context
213
+ parent_email=parent_email, video_path=video_path, hw_path=hw_path,
214
+ report_password=generated_hash
215
+ )
216
+
217
+ scanner = SCANNERS.get(scanner_type, SCANNERS["dyslexia"])
218
+
219
+ # ✅ FIX: Ensure background tasks receive the writing_target for PDF generation
220
+ result = await scanner.analyze(context, background_tasks)
221
+ result["diagnosis"]["writing_target"] = actual_writing_target
222
+
223
+ diag = result.get("diagnosis", {})
224
+ diag["writing_target"] = actual_writing_target
225
+ if flatten:
226
+ diag["struggle_words"] = [w['word'] if isinstance(w, dict) else str(w) for w in diag.get("struggle_words", [])]
227
+
228
+ diag["session_id"] = session_id
229
+ diag["audit_hash"] = generated_hash
230
+ # Ensure writing_target is returned to frontend for the Interpretive View
231
+ diag["writing_target"] = actual_writing_target
232
+
233
+ return {"status": "success", "diagnosis": result["diagnosis"], "purge_delay": DATA_PURGE_DELAY}
234
+
235
+ except Exception as e:
236
+ logger.error(f"🔥 Dispatcher Failure: {str(e)}", exc_info=True)
237
+ shredder.instant_purge([video_path, hw_path or ""])
238
+ raise HTTPException(status_code=500, detail="Clinical processing engine failed.")
239
+
240
+
241
+ @app.post("/upload-handwriting/{session_id}")
242
+ async def upload_handwriting(session_id: str, file: UploadFile, background_tasks: BackgroundTasks):
243
+ """Handles separate handwriting upload for OCR preprocessing."""
244
+ file_path = os.path.join(TEMP_DIR, f"hw_{session_id}.png")
245
+ with open(file_path, "wb") as buffer:
246
+ shutil.copyfileobj(file.file, buffer)
247
+ background_tasks.add_task(run_async_ocr, session_id, file_path)
248
+ log_debug("Handwriting Uploaded")
249
+ return {"status": "processing"}
250
+
251
+ async def run_async_ocr(session_id, file_path):
252
+ """Background task for Google Vision analysis."""
253
+ logger.info(f"🛰️ OCR START: Session {session_id}")
254
+ try:
255
+ # Defaults to beginner prompt for extraction if none provided
256
+ results = biometric_engine.analyze_handwriting(file_path, session_id, WRITING_PROMPTS.get("beginner"))
257
+ handwriting_cache[session_id] = results
258
+ logger.info(f"✅ OCR COMPLETE: Session {session_id}")
259
+ except Exception as e:
260
+ logger.error(f"❌ OCR FAILURE: {str(e)}")
261
+
262
+ @app.post("/verify-quality")
263
+ async def verify_quality(frame: UploadFile = File(...)):
264
+ """Real-time environment and positioning verification."""
265
+ try:
266
+ contents = await frame.read()
267
+ results = biometric_engine.verify_environment(decode_frame(contents))
268
+ # 1: Too Far, 2: Too Close, 3: Poor Lighting, 4: Ready
269
+ step_code = 4 if results["ready"] else (1 if results["iris_dist"] < 0.075 else 2)
270
+ if not results.get("lighting_ok"): step_code = 3
271
+ return {**results, "step_code": step_code}
272
+ except Exception as e:
273
+ return {"ready": False, "step_code": 0, "status": "SYSTEM_ERROR"}
274
+
275
+ @app.get("/download-report/{filename}")
276
+ async def download_report(filename: str):
277
+ """Secure endpoint for downloading the clinical PDF."""
278
+ file_path = os.path.join(TEMP_DIR, filename)
279
+ if os.path.exists(file_path): return FileResponse(file_path)
280
+ raise HTTPException(status_code=404, detail="Artifact not found.")
281
+
282
+ @repeat_every(seconds=3600)
283
+ async def hourly_artifact_cleanup():
284
+ """🧹 Clinical Compliance Sweep: Deletes artifacts older than 1 hour."""
285
+ if not os.path.exists(TEMP_DIR):
286
+ return
287
+
288
+ now = time.time()
289
+ count = 0
290
+ for filename in os.listdir(TEMP_DIR):
291
+ file_path = os.path.join(TEMP_DIR, filename)
292
+ try:
293
+ if os.path.getmtime(file_path) < (now - 3600):
294
+ if os.path.isfile(file_path):
295
+ os.remove(file_path)
296
+ count += 1
297
+ elif os.path.isdir(file_path):
298
+ shutil.rmtree(file_path)
299
+ count += 1
300
+ except Exception as e:
301
+ logger.error(f"Cleanup error for {filename}: {e}")
302
+
303
+ if count > 0:
304
+ logger.info(f"Purged {count} expired clinical artifacts.")
305
+
306
+ if __name__ == "__main__":
307
+ import uvicorn
308
+ # Use 0.0.0.0 to allow LAN access for mobile stance testing
309
+ uvicorn.run(app, host="0.0.0.0", port=8000)
requirements.txt ADDED
@@ -0,0 +1,43 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # --- Core API & Server ---
2
+ fastapi==0.128.0
3
+ uvicorn[standard]
4
+ python-multipart
5
+ fastapi-utils
6
+ typing-inspect
7
+ mypy-extensions
8
+
9
+ # --- Security & Auth ---
10
+ cryptography
11
+ pyopenssl
12
+
13
+ # --- The "Plumbing" (CRITICAL: These stop the backtracking loop) ---
14
+ protobuf>=3.20.3,<5.0.0dev
15
+ grpcio>=1.51.1
16
+ grpcio-status>=1.51.1
17
+
18
+ # --- Biometrics & Vision ---
19
+ opencv-python-headless
20
+ mediapipe==0.10.9
21
+ google-cloud-vision
22
+
23
+ # --- Audio & Speech ---
24
+ librosa==0.11.0
25
+ openai-whisper
26
+ noisereduce
27
+ speechrecognition
28
+ jiwer
29
+
30
+ # --- ML & Math ---
31
+ torch --index-url https://download.pytorch.org/whl/cpu
32
+ numpy==2.2.6
33
+ scikit-learn
34
+ scipy
35
+ sympy
36
+
37
+ # --- Reporting & Utilities ---
38
+ fpdf2==2.8.5
39
+ pikepdf
40
+ matplotlib
41
+ email-validator
42
+ jinja2
43
+ pytest
services/__init__.py ADDED
File without changes
services/__pycache__/__init__.cpython-310.pyc ADDED
Binary file (157 Bytes). View file