learningview / services /biometric_engine.py
ArrowDust's picture
LearnView Pro: Clean Production Build
408b7e6
Raw History Blame Contribute Delete
15.7 kB
import os
import cv2
import numpy as np
import mediapipe as mp
import math
import threading
from jiwer import cer
from core.logger import log_debug, logger
from config import TEMP_DIR
from config import CLINICAL_DISTANCE_MIN, CLINICAL_DISTANCE_MAX, STATIONARY_FRAME_THRESHOLD
from services.ocr_service import OCRService
import hashlib
import time
import difflib
class BiometricEngine:
_instance = None
_lock = threading.Lock()
def __new__(cls):
with cls._lock:
if cls._instance is None:
log_debug("πŸš€ Initializing Hybrid Clinical Engine (V8 Production)...")
cls._instance = super(BiometricEngine, cls).__new__(cls)
# πŸ›‘οΈ THE RAILWAY/CPU FIX: Force CPU mode
os.environ['MEDIAPIPE_DISABLE_GPU'] = '1'
cls._instance.mp_face_mesh = mp.solutions.face_mesh
cls._instance.face_mesh = cls._instance.mp_face_mesh.FaceMesh(
static_image_mode=False,
max_num_faces=1,
refine_landmarks=True,
min_detection_confidence=0.5,
min_tracking_confidence=0.5
)
# πŸ”Œ PLUG-AND-PLAY OCR
cls._instance.ocr_engine = OCRService(provider="google")
# ⚑ OCR PRE-WARM CACHE: Stores background results from Intake
cls._instance._ocr_cache = {}
return cls._instance
def process_frame(self, rgb_frame):
"""Thread-safe processing optimized for CPU execution."""
with self._lock:
return self.face_mesh.process(rgb_frame)
# --- πŸ“ HANDWRITING & DYSGRAPHIA ANALYSIS (V8) ---
def calculate_cer(self, target_text: str, detected_text: str) -> float:
"""
Calculates Character Error Rate (CER) using Levenshtein distance approximations.
Strictly penalizes mismatched or 'cheated' text.
"""
if not detected_text or detected_text in ["[No Text Extracted]", "[Processing...]"]:
return 1.0 # 100% error (Task Failure)
# Clean and normalize texts for comparison
t1 = target_text.lower().strip()
t2 = detected_text.lower().strip()
# SequenceMatcher ratio returns 1.0 for a perfect match
similarity = difflib.SequenceMatcher(None, t1, t2).ratio()
cer = 1.0 - similarity
# 🚨 CLINICAL PENALTY: Task Non-Compliance
if cer > 0.40:
return 1.0
return cer
def process_handwriting_kinetics(self, image_path: str) -> dict:
"""
Analyzes Basal Drift and Slant. Fails securely if handwriting is erratic.
"""
if not os.path.exists(image_path):
log_debug(f"⚠️ Kinetic error: File not found at {image_path}")
return {"basal_drift": 25.0, "slant": 30.0, "lines_detected": 0}
img = cv2.imread(image_path)
if img is None:
return {"basal_drift": 25.0, "slant": 30.0, "lines_detected": 0}
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
# Adaptive thresholding helps with poor lighting/shadows on phone uploads
blurred = cv2.GaussianBlur(gray, (5, 5), 0)
edges = cv2.Canny(blurred, 50, 150, apertureSize=3)
# Detect lines in the handwriting
lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=50, minLineLength=30, maxLineGap=10)
# 🚨 CLINICAL PENALTY: Illegible / Erratic Writing Fallback
if lines is None or len(lines) == 0:
return {
"basal_drift": 25.0, # Max clinical penalty for drift
"slant": 30.0, # Max clinical penalty for slant
"lines_detected": 0
}
# Calculate the median angle of all detected baselines
angles = []
for line in lines:
x1, y1, x2, y2 = line[0]
angle = math.degrees(math.atan2(y2 - y1, x2 - x1))
angles.append(angle)
basal_drift = np.median(angles)
# Calculate Character Slant using Vertical Projection Profile
slant = self.calculate_slant_v2(gray)
return {
"basal_drift": float(basal_drift),
"slant": float(slant),
"lines_detected": len(lines)
}
def calculate_iris_depth(self, face_landmarks, frame_height=720) -> float:
"""
βœ… FIXED: Matches Svelte 5 normalized coordinate math exactly to prevent 0% HW Confidence.
Estimates distance in cm, factoring in FOV and resolution.
"""
lm = face_landmarks.landmark
# Calculate raw normalized screen distance just like frontend JS
dx = lm[468].x - lm[473].x
dy = lm[468].y - lm[473].y
dz = lm[468].z - lm[473].z
ipd_screen = math.sqrt(dx*dx + dy*dy + dz*dz)
# Factor in 45-degree vertical FOV
v_fov_rad = math.radians(45)
focal_length = (frame_height / 2) / math.tan(v_fov_rad / 2)
# Real IPD average (6.3cm)
distance_cm = (6.3 * focal_length) / (ipd_screen * frame_height + 0.000001)
return distance_cm
def calculate_writing_risk(self, basal_drift, slant_angle, ocr_accuracy):
"""Clinical mapping for the Synthesis Risk Score."""
drift_score = min(abs(basal_drift) * 15, 40)
slant_score = min(abs(slant_angle) * 2, 30)
accuracy_penalty = (1.0 - ocr_accuracy) * 30
total_risk = drift_score + slant_score + accuracy_penalty
level = "Low"
if total_risk >= 55: level = "High"
elif total_risk >= 25: level = "Moderate"
return round(total_risk, 1), level
# --- πŸ‘οΈ OCULAR GAZE ANALYSIS ---
def verify_environment(self, frame):
"""Validates clinical distance and lighting."""
results = self.process_frame(frame)
if not results.multi_face_landmarks:
return {"ready": False, "status": "No face detected"}
lm = results.multi_face_landmarks[0].landmark
iris_dist = self.calculate_iris_depth(results.multi_face_landmarks[0])
dist_ok = bool(CLINICAL_DISTANCE_MIN < iris_dist < CLINICAL_DISTANCE_MAX)
lighting_ok = bool(np.mean(cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)) > 80)
status = "Ready"
if iris_dist > 0.13: status = "Too Close"
elif iris_dist < 0.075: status = "Too Far"
elif not lighting_ok: status = "Too Dark"
return {
"ready": bool(dist_ok and lighting_ok),
"iris_dist": round(float(iris_dist), 4),
"status": status
}
def analyze_gaze_v2(self, gaze_buffer):
"""Refined sensitivity to match pre-refactor ocular event tracking."""
if len(gaze_buffer) < 5:
return {"saccade_count": 0, "regression_count": 0, "phonetic_blocks": 0}
mean_id = np.mean([g.get('id', 0.1) for g in gaze_buffer])
scale = mean_id / 0.1
saccades, regressions = 0, 0
for i in range(1, len(gaze_buffer)):
dx = gaze_buffer[i]['x'] - gaze_buffer[i-1]['x']
if dx < (-0.0015 * scale) and abs(dx) < 0.35:
regressions += 1
elif dx > (0.004 * scale):
saccades += 1
return {
"saccade_count": saccades,
"regression_count": regressions,
"phonetic_blocks": len(gaze_buffer) // 18
}
# --- πŸ–ΌοΈ VISUALIZATION TOOLS ---
def generate_heatmap(self, gaze_buffer, canvas_path, session_id, jitter_log=None, sigma=1.8):
"""
Generates gaze heatmap with coordinate scaling, optional jitter timeline, and clinical blur.
"""
img = cv2.imread(canvas_path)
if img is None:
log_debug(f"❌ Heatmap Fail: Canvas not found at {canvas_path}")
return None
h, w = img.shape[:2]
heat_layer = np.zeros((h, w, 3), dtype=np.uint8)
# 1. Map Gaze Points (Scaled to canvas size)
for pt in gaze_buffer:
x = int(pt['x'] * w)
y = int(pt['y'] * h)
if 0 <= x < w and 0 <= y < h:
# Draw sharp points first
cv2.circle(heat_layer, (x, y), 15, (0, 0, 255), -1)
blur_kernel = int(sigma * 25)
if blur_kernel % 2 == 0: blur_kernel += 1 # Kernel must be odd
if blur_kernel > 1:
heat_layer = cv2.GaussianBlur(heat_layer, (blur_kernel, blur_kernel), sigmaX=sigma*15)
# Blend ONLY the colored heat pixels onto the white canvas (preserves white background)
mask = heat_layer > 0
img[mask] = cv2.addWeighted(img, 0.4, heat_layer, 0.8, 0)[mask]
# 2. Network Stability Overlay (Bottom 5% of image)
if jitter_log and len(jitter_log) > 0:
bar_h = int(h * 0.05)
for i, jitter_val in enumerate(jitter_log):
x_pos = int((i / len(jitter_log)) * w)
color_intensity = min(255, int((jitter_val * 1000) / 50 * 255))
cv2.line(img, (x_pos, h - bar_h), (x_pos, h), (0, 0, color_intensity), 1)
output_name = f"heatmap_{session_id}.png"
cv2.imwrite(os.path.join(TEMP_DIR, output_name), img)
return output_name
def create_text_canvas(self, text, session_id, canvas_width=1280, canvas_height=720, bounding_box=None):
"""
Dynamically positions the text based on the UI bounding box to ensure gaze coordinates align.
Uses Clinical Calm palette and left-aligned Sans-Serif font for Dyslexia accessibility.
"""
canvas = np.full((canvas_height, canvas_width, 3), (247, 251, 253), dtype=np.uint8)
font = cv2.FONT_HERSHEY_SIMPLEX
scale, thick = 1.1, 2
text_color = (85, 65, 51) # Slate-700
if bounding_box:
box_x = int(bounding_box.get("left", 0.1) * canvas_width)
box_y = int(bounding_box.get("top", 0.5) * canvas_height)
max_width = int(bounding_box.get("width", 0.8) * canvas_width)
y = box_y + 60
else:
box_x = 0
max_width = 1000
y = 300
words = text.split(' ')
line = ""
for word in words:
if cv2.getTextSize(line + " " + word, font, scale, thick)[0][0] < max_width:
line += " " + word
else:
start_x = box_x + 40
cv2.putText(canvas, line.strip(), (start_x, y), font, scale, text_color, thick, cv2.LINE_AA)
y += 60
line = word
start_x = box_x + 40
cv2.putText(canvas, line.strip(), (start_x, y), font, scale, text_color, thick, cv2.LINE_AA)
path = os.path.join(TEMP_DIR, f"canvas_{session_id}.png")
cv2.imwrite(path, canvas)
return path
def analyze_compliance(self, distance_logs: list) -> dict:
"""πŸ“ GLOBAL ENFORCEMENT: 80cm Max Permissible."""
if not distance_logs: return {"confidence_score": 0, "is_reliable": False}
total = len(distance_logs)
# Permissible zone strictly locked to 80cm
valid = [d for d in distance_logs if 40 <= d <= 80]
optimal = [d for d in distance_logs if 50 <= d <= 65]
score = (len(valid) / total) * 100
return {
"confidence_score": round(score, 1),
"is_reliable": score > 80, # High confidence requires 80% frames within bounds
"optimal_percentage": round((len(optimal) / total) * 100, 1)
}
def get_ui_metrics(self, biometric_results):
"""Formats drift and gaze data for the ResultsDashboard."""
drift = biometric_results.get('basal_drift', 0)
status_color = "green"
if abs(drift) > 5: status_color = "red"
elif abs(drift) > 2.5: status_color = "amber"
return {
"writing": {
"drift_value": f"{drift}Β°",
"drift_direction": "Ascending" if drift > 0 else "Descending",
"status_color": status_color,
"accuracy": f"{int(biometric_results.get('ocr_accuracy', 0)*100)}%",
"display_text": biometric_results.get('detected_text', "NONE")
},
"ocular": {
"sync_percentage": biometric_results.get('sync_score', 0),
"fixation_count": biometric_results.get('phonetic_blocks', 0),
"regression_warning": biometric_results.get('regression_count', 0) > 10
}
}
def calculate_slant_v2(self, gray_img):
"""Vertical Projection Profile to identify true character slant."""
_, thresh = cv2.threshold(gray_img, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)
best_angle = 0
max_variance = 0
for angle in range(-30, 31, 2):
m = np.float32([[1, np.tan(np.radians(angle)), 0], [0, 1, 0]])
sheared = cv2.warpAffine(thresh, m, (thresh.shape[1], thresh.shape[0]))
projection = np.sum(sheared, axis=0)
variance = np.var(projection)
if variance > max_variance:
max_variance = variance
best_angle = angle
return best_angle
# --- πŸ“ UNIFIED HANDWRITING & DYSGRAPHIA ANALYSIS (V8) ---
def analyze_handwriting(self, image_path: str, session_id: str, target_text: str = None):
"""Unified V8 Handwriting Pipeline."""
img = cv2.imread(image_path)
if img is None:
return {"slant": 0.0, "basal_drift": 0.0, "ocr_accuracy": 0.0, "detected_text": "[Error]"}
# 1. πŸ”‘ CLOUD OCR
raw_output = self.ocr_engine.extract_text(image_path)
# 2. πŸ“ KINETIC AUDIT
gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)
edges = cv2.Canny(gray, 50, 150)
lines = cv2.HoughLinesP(edges, 1, np.pi/180, 100, minLineLength=100, maxLineGap=10)
basal_drift_angle = 0.0
if lines is not None:
angles = [math.degrees(math.atan2(l[0][3]-l[0][1], l[0][2]-l[0][0])) for l in lines]
basal_drift_angle = np.median(angles)
slant_angle = self.calculate_slant_v2(gray)
# 3. πŸ“Š SCORING
accuracy = 0.0
if target_text and raw_output:
accuracy = round(max(0, 1.0 - cer(target_text.lower(), raw_output.lower())), 2)
result = {
"slant": round(float(slant_angle), 2),
"basal_drift": round(float(basal_drift_angle), 2),
"ocr_accuracy": accuracy,
"detected_text": raw_output if raw_output else "[Handwriting Unreadable]",
"ocr_confidence": 95 if raw_output else 0
}
# Sync with global cache for Scanner retrieval
from core.state import handwriting_cache
handwriting_cache[session_id] = result
return result
def generate_audit_hash(self) -> str:
"""🎯 RESTORED: Generates a 6-digit purely numeric Audit Key."""
seed = f"learnview_audit_{time.time()}"
hash_int = int(hashlib.sha256(seed.encode()).hexdigest(), 16)
numeric_code = str(hash_int % 1000000).zfill(6)
return numeric_code
biometric_engine = BiometricEngine()