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", docs_url="/docs", redoc_url="/redoc", openapi_url="/openapi.json", 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.get("/") async def root(): return {"message": "LearnView Pro Diagnostic Hub is Online", "docs": "/docs"} @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=7860)