Spaces:
Sleeping
Sleeping
Download services/decision_engine.py from clabs/learningview: direct link, hf CLI and curl.
- Browser
- Download file 6.25 kB
-
https://huggingface.co/spaces/clabs/learningview/resolve/main/services/decision_engine.py
- Command line
-
hf download hf://spaces/clabs/learningview/services/decision_engine.py
-
curl -L -o decision_engine.py https://huggingface.co/spaces/clabs/learningview/resolve/main/services/decision_engine.py
6.25 kB
| import threading | |
| import numpy as np | |
| import math | |
| from engines.dyslexia.logic import DyslexiaStrategy | |
| from core.logger import log_debug | |
| class DecisionEngine: | |
| _instance = None | |
| _lock = threading.Lock() | |
| _strategies = { | |
| "dyslexia": DyslexiaStrategy() | |
| } | |
| def __new__(cls): | |
| with cls._lock: | |
| if cls._instance is None: | |
| cls._instance = super(DecisionEngine, cls).__new__(cls) | |
| log_debug("⚖️ Unified Decision Engine Initialized") | |
| return cls._instance | |
| def calculate_risk(self, metrics: dict, profile: str = "dyslexia") -> dict: | |
| """Weights diverse signals and applies calibration offset [cite: 2026-03-01].""" | |
| strategy = self._strategies.get(profile, self._strategies["dyslexia"]) | |
| final_score = strategy.calculate(metrics) | |
| return { | |
| "risk_score": round(final_score, 1), | |
| "severity": "High" if final_score > 70 else "Moderate" if final_score > 35 else "Low" | |
| } | |
| def synthesize_ocular_phonetic_sync(self, gaze_buffer, word_alignment, fps=30): | |
| """Measures real-time lag between visual path and verbal output[cite: 6, 12].""" | |
| if not gaze_buffer or not word_alignment: | |
| return {"alignment_score": 0, "desync_events": 0, "phonetic_blocks": 0, "clinical_note": "Insufficient Data"} | |
| sync_matches, desync_events, total_checks = 0, 0, 0 | |
| for word in word_alignment: | |
| start_t = word['start'] | |
| end_t = word['end'] | |
| # Filter gaze points by absolute timestamp [cite: 55] | |
| word_gaze_points = [ | |
| p for p in gaze_buffer | |
| if start_t <= p.get('timestamp', 0) <= end_t | |
| ] | |
| if not word_gaze_points: | |
| continue | |
| # ✅ FIXED: Every word with valid gaze data counts as a Phonetic Fixation [cite: 12] | |
| total_checks += 1 | |
| x_coords = [p['x'] for p in word_gaze_points] | |
| # Dyslexia Marker: Regressive eye movements | |
| is_backtracking = any(x_coords[i] < x_coords[i-1] - 0.05 for i in range(1, len(x_coords))) | |
| if is_backtracking: | |
| desync_events += 1 | |
| else: | |
| sync_matches += 1 | |
| alignment_score = (sync_matches / total_checks * 100) if total_checks > 0 else 0 | |
| return { | |
| "alignment_score": round(alignment_score, 1), | |
| "desync_events": desync_events, | |
| "phonetic_blocks": total_checks, # 🎯 This populates the UI count [cite: 12] | |
| "clinical_note": "High" if alignment_score > 80 else "Critical Lag" | |
| } | |
| def calculate_confidence(self, quality_audit, gaze_buffer): | |
| """ | |
| Evaluates hardware performance and positional stability [cite: 2026-03-01]. | |
| GUARD CLAUSE: Prevents hardware quality overflow (e.g., 10000%). | |
| """ | |
| # Initialize at 100% [cite: 2026-03-01] | |
| confidence = 100 | |
| # 📡 1. Network/Processing Stability [cite: 2026-03-01] | |
| fps = quality_audit.get('fps', 30) | |
| jitter = quality_audit.get('jitter', 0) | |
| latency = quality_audit.get('avg_latency', 0) | |
| # Penalty for low frame rates [cite: 2026-03-01] | |
| if fps < 24: confidence -= 15 | |
| if fps > 15: confidence -= 30 | |
| # Penalty for high jitter (unstable data stream) [cite: 2026-03-01] | |
| if jitter > 20: confidence -= 10 | |
| if jitter > 50: confidence -= 20 | |
| # Penalty for extreme processing lag [cite: 2026-03-01] | |
| if latency > 150: confidence -= 15 | |
| # 👁️ 2. Biometric Stability [cite: 2026-03-01] | |
| if not gaze_buffer: | |
| return 10 # Minimal confidence if no data exists | |
| id_values = [g.get('id', 0.1) for g in gaze_buffer] | |
| # High IPD variance indicates excessive user movement or tracking loss [cite: 2026-03-01] | |
| if id_values and len(id_values) > 10: | |
| if np.var(id_values) > 0.005: | |
| confidence -= 20 | |
| # 🛡️ 3. Final Guardrail: Hard ceiling and floor [cite: 2026-03-01] | |
| # This prevents the 10000% error by forcing the result into 10-100 range. | |
| final_quality = int(max(min(confidence, 100), 10)) | |
| return int(final_quality) | |
| def synthesize_unified_report(self, metrics: dict, triggers: dict) -> dict: | |
| """ | |
| Synthesizes raw biometric data into specific learning disability risk scores. | |
| """ | |
| # 1. 👁️ DYSLEXIA SCORE (Ocular-Verbal Sync + Regressions) | |
| # Combines the regression count with gaze duration on phonetic triggers | |
| phonetic_delay = metrics.get('phonetic_delay_detected', False) | |
| dyslexia_risk = (metrics.get('regression_count', 0) * 5) + (25 if phonetic_delay else 0) | |
| # 2. ✍️ DYSGRAPHIA SCORE (Basal Drift + Kinetic Fatigue) | |
| # Measures the change in slant and horizontal drift over the 2-sentence task | |
| drift = abs(metrics.get('basal_drift', 0)) | |
| slant = abs(metrics.get('slant', 0)) | |
| dysgraphia_risk = (drift * 3.5) + (slant * 2.0) + (metrics.get('ocr_error_rate', 0) * 40) | |
| # 3. 🔢 DYSCALCULIA SCORE (Subitizing Latency) | |
| # Specifically uses the numerical trigger from the PromptGenerator | |
| num_latency = metrics.get('numerical_latency_ms', 0) | |
| dyscalculia_risk = 0 | |
| if num_latency > 1200: # Standard clinical threshold for subitizing delay | |
| dyscalculia_risk = min(100, (num_latency - 1000) / 10) | |
| return { | |
| "dyslexia": {"score": min(100, dyslexia_risk), "severity": self._get_severity(dyslexia_risk)}, | |
| "dysgraphia": {"score": min(100, dysgraphia_risk), "severity": self._get_severity(dysgraphia_risk)}, | |
| "dyscalculia": {"score": min(100, dyscalculia_risk), "severity": self._get_severity(dyscalculia_risk)}, | |
| "overall_confidence": metrics.get('confidence_score', 0) | |
| } | |
| def _get_severity(self, score: float) -> str: | |
| if score > 70: return "High" | |
| if score > 35: return "Moderate" | |
| return "Low" | |
| decision_engine = DecisionEngine() |