File size: 6,250 Bytes
408b7e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
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()