File size: 12,375 Bytes
408b7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b7cc13b
 
 
 
 
79d89b0
b7cc13b
408b7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d581eda
 
 
 
 
408b7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
9b1eb70
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
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)