Update app.py
Browse files5 unmodified lines67891011121314151617187 unmodified lines2627282930313231 unmodified lines64656667686970717273747576777879808182838485868788181 unmodified lines27027127227327427558 unmodified lines3343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733741 unmodified line3763773783793803813829 unmodified lines39239339439539639739839940040140240340440540640740840941094 unmodified lines5055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725731 unmodified line5755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067075 unmodified linesPOST /predict/phrase β multiple JPEG frames β phrase + confidencePOST /predict/auto β 60 frames β auto decide letter or phraseGET /health β health checkRouting logic (v2):Old: single displacement threshold (wrist midpointβend >= 0.45)New: trajectory path length + mean velocity + confidence arbitration- Path length : sum of all frame-to-frame wrist distances (catches oscillating signs)- Mean velocity: average per-frame wrist movement (catches sustained motion)- Confidence arbitration: both CNN and LSTM scores compared before committing"""import os7 unmodified linesfrom fastapi import FastAPI, File, UploadFile, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import List, Tuple, Optionalimport mediapipe as mpfrom mediapipe.tasks import python as mp_pythonfrom mediapipe.tasks.python import vision as mp_vision31 unmodified lines# Fraction of processed frames with 2 hands to trigger automatic LSTMTWO_HAND_RATIO = 1 / 3# ββ Motion routing thresholds (v2) ββββββββββββββββββββββββββββββββββββββββββββ# Total wrist path (sum of frame-to-frame distances in normalized coords 0-1).# Signs like "THANK YOU" that move forward-then-back are caught here even though# their net displacement is near zero.STATIC_PATH_THRESHOLD = 0.15 # total path < this β treat as static letter# Mean per-frame wrist velocity in normalized coords.# Sustained slow motion (e.g. tracing letters in air) is caught here.STATIC_VELOCITY_MAX = 0.08 # mean velocity < this β treat as static letter# CNN vote confidence floor. Below this the CNN result is not trusted on its own.CNN_CONF_FLOOR = 0.65# If CNN is this confident it can override an LSTM result even during dynamic input.CNN_OVERRIDE_CONF = 0.85# LSTM confidence floor. Below this neither model is confident β not detected.LSTM_CONF_FLOOR = 0.65# ============================================================# Model Architectures# ============================================================181 unmodified linesarr = np.frombuffer(data, np.uint8)frame = cv2.imdecode(arr, cv2.IMREAD_COLOR)frame = cv2.flip(frame, 1)rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)return mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)58 unmodified linesreturn left_lms, right_lmsdef compute_motion_stats(wrist_positions: List[Tuple[float, float]]) -> Tuple[float, float, float]:"""Compute three motion statistics from a list of (x, y) wrist positionsin normalized MediaPipe coordinates (0.0 β 1.0).Returns:total_path : Sum of Euclidean distances between consecutive positions.Catches oscillating / circular signs that return near theirstart point (net displacement would be ~0 for those).mean_velocity : Average per-frame displacement. Catches sustained slowmotion such as tracing letters in the air.variance : Variance of per-frame displacements. High variance meansthe hand alternates between fast and slow β a hallmark ofphrase signs with distinct motion phases."""if len(wrist_positions) < 2:return 0.0, 0.0, 0.0deltas = [np.sqrt((wrist_positions[i][0] - wrist_positions[i-1][0]) ** 2 +(wrist_positions[i][1] - wrist_positions[i-1][1]) ** 2)for i in range(1, len(wrist_positions))]total_path = float(np.sum(deltas))mean_velocity = float(np.mean(deltas))variance = float(np.var(deltas))return total_path, mean_velocity, variancedef run_lstm(coord_buffer: list, vote_ratio: float) -> "AutoResponse":"""Run LSTM on coord_buffer and return an AutoResponse."""if len(coord_buffer) < MIN_COORD_FRAMES:return AutoResponse(result="", result_type="phrase",1 unmodified line)buf = np.array(coord_buffer)idx = np.linspace(0, len(buf) - 1, SEQ_LEN, dtype=int)seq = buf[idx]tensor = torch.tensor(seq, dtype=torch.float32).unsqueeze(0).to(device)9 unmodified linesdetected=True)def run_cnn_from_votes(votes: dict) -> Tuple[str, float]:"""Derive the best CNN letter and its vote ratio from the accumulated vote dict.Returns ("", 0.0) if votes is empty."""if not votes:return "", 0.0best_letter = max(votes, key=votes.get)vote_ratio = votes[best_letter] / sum(votes.values())return best_letter, vote_ratio# ============================================================# FastAPI App# ============================================================94 unmodified lines@app.post("/predict/auto", response_model=AutoResponse)async def predict_auto(files: List[UploadFile] = File(...)):"""Accepts 60 JPEG frames. Runs MediaPipe on every other frame (30 calls).Routing logic (v2 β motion stats + confidence arbitration):Step 1 β Hand presence gateIf fewer than 1/3 of processed frames have a detected hand β not detected.Unchanged from v1; this is a correct early-exit.Step 2 β Two-hands gateIf both hands appear in >= 1/3 of processed frames β go straight to LSTM.Two-handed signs are always phrases; no CNN vote needed.Step 3 β Motion statistics (replaces single displacement check)Compute trajectory path length and mean per-frame velocity from wristpositions across all processed frames.is_dynamic = total_path > STATIC_PATH_THRESHOLD (0.15)OR mean_velocity > STATIC_VELOCITY_MAX (0.008)Path length catches oscillating / circular signs (e.g. THANK YOU movesforward-then-back; net displacement β 0 but total path is large).Mean velocity catches sustained slow motion.Step 4 β Confidence arbitrationRather than hard-routing to one model, both CNN and LSTM scores arecompared and the more confident result wins, with guard rails:Dynamic input β LSTM is primary.CNN can still win if conf >= CNN_OVERRIDE_CONF (0.85)AND lstm_conf < LSTM_CONF_FLOOR (0.65).Static input β CNN is primary (vote_ratio >= CNN_CONF_FLOOR 0.65).Falls back to LSTM if CNN is not confident enough.Neither model confident β not detected."""if not files:raise HTTPException(status_code=400, detail="No frames provided")frame_data = [await f.read() for f in files]votes = {}total_processed_frames = 0total_hand_frames = 0two_hand_frames = 0wrist_positions: List[Tuple[float, float]] = []coord_buffer = []last_pose_vec = np.zeros(POSE_SIZE, dtype=np.float32)last_left_hand_vec = np.zeros(HAND_SIZE, dtype=np.float32)last_right_hand_vec = np.zeros(HAND_SIZE, dtype=np.float32)# ββ Per-frame processing ββββββββββββββββββββββββββββββββββfor i, data in enumerate(frame_data):if i % 2 == 0:total_processed_frames += 1mp_img = bytes_to_mp_image(data)# CNN path β single hand, alphabet skeletoncnn_result = hand_detector_alpha.detect(mp_img)hand_lms = cnn_result.hand_landmarks[0] \if cnn_result.hand_landmarks else Noneif hand_lms is not None:total_hand_frames += 1wrist_positions.append((hand_lms[WRIST].x, hand_lms[WRIST].y))skel = render_hand_skeleton(hand_lms)1 unmodified linewith torch.no_grad():probs = torch.softmax(alphabet_model(tensor), dim=1)[0]conf, idx = probs.max(dim=0)# Only count predictions the CNN is reasonably confident aboutif conf.item() >= 0.6:letter = ALPHA_CLASSES[idx.item()]votes[letter] = votes.get(letter, 0) + 1# LSTM path β pose + both handspose_result = pose_detector.detect(mp_img)pose_lms = pose_result.pose_landmarks[0] \if pose_result.pose_landmarks else Noneif pose_lms:last_pose_vec = normalize_pose(pose_lms)lstm_hand_result = hand_detector_phrase.detect(mp_img)left_lms, right_lms = get_hands_by_side(lstm_hand_result)if left_lms is not None: last_left_hand_vec = normalize_hand(left_lms)if right_lms is not None: last_right_hand_vec = normalize_hand(right_lms)if left_lms is not None and right_lms is not None:two_hand_frames += 1# Build coordinate vector for every frame (uses last-valid values for# frames where MediaPipe was not run, matching training pipeline)vec = np.concatenate([last_pose_vec, last_left_hand_vec, last_right_hand_vec])coord_buffer.append(vec)# ββ Step 1: Hand presence gate ββββββββββββββββββββββββββββmin_required = total_processed_frames * MIN_HAND_PRESENCE_RATIOif total_hand_frames < min_required:print(f"[auto] Hand presence too low: {total_hand_frames}/{total_processed_frames} "f"(need >= {min_required:.1f}) β not detected")return AutoResponse(result="", result_type="none",confidence=0.0, vote_ratio=0.0, detected=False)# ββ Step 2: Two-hands gate ββββββββββββββββββββββββββββββββtwo_hand_threshold = total_processed_frames * TWO_HAND_RATIOif two_hand_frames >= two_hand_threshold:print(f"[auto] Two hands in {two_hand_frames}/{total_processed_frames} frames β LSTM")return run_lstm(coord_buffer, vote_ratio=0.0)# ββ Step 3: Motion statistics βββββββββββββββββββββββββββββtotal_path, mean_velocity, variance = compute_motion_stats(wrist_positions)is_dynamic = (total_path > STATIC_PATH_THRESHOLD ormean_velocity > STATIC_VELOCITY_MAX)print(f"[auto] Motion stats β path: {total_path:.4f}, "f"mean_vel: {mean_velocity:.4f}, variance: {variance:.6f}, "f"is_dynamic: {is_dynamic}")# ββ Step 4: Confidence arbitration βββββββββββββββββββββββbest_letter, cnn_vote_ratio = run_cnn_from_votes(votes)lstm_response = run_lstm(coord_buffer, cnn_vote_ratio)lstm_conf = lstm_response.confidenceif is_dynamic:# Dynamic input β LSTM is primary# CNN can override only if it is overwhelmingly confident and LSTM is notif (best_letter andcnn_vote_ratio >= CNN_OVERRIDE_CONF andlstm_conf < LSTM_CONF_FLOOR):print(f"[auto] Dynamic but CNN override: '{best_letter}' "f"({cnn_vote_ratio:.2f}) > LSTM '{lstm_response.result}' "f"({lstm_conf:.2f})")return AutoResponse(result=best_letter,result_type="letter",confidence=cnn_vote_ratio,vote_ratio=cnn_vote_ratio,detected=True)# Normal dynamic case β trust LSTMif lstm_response.detected and lstm_conf >= LSTM_CONF_FLOOR:print(f"[auto] Dynamic β LSTM: '{lstm_response.result}' ({lstm_conf:.2f})")return lstm_response# LSTM not confident β try CNN as last resortif best_letter and cnn_vote_ratio >= CNN_CONF_FLOOR:print(f"[auto] Dynamic, LSTM low conf β CNN fallback: "f"'{best_letter}' ({cnn_vote_ratio:.2f})")return AutoResponse(result=best_letter,result_type="letter",confidence=cnn_vote_ratio,vote_ratio=cnn_vote_ratio,detected=True)print(f"[auto] Dynamic β neither model confident. "f"CNN: {cnn_vote_ratio:.2f}, LSTM: {lstm_conf:.2f}")return AutoResponse(result="", result_type="none",confidence=0.0, vote_ratio=cnn_vote_ratio, detected=False)else:# Static input β CNN is primaryif best_letter and cnn_vote_ratio >= CNN_CONF_FLOOR:print(f"[auto] Static β CNN: '{best_letter}' ({cnn_vote_ratio:.2f})")return AutoResponse(result=best_letter,result_type="letter",confidence=cnn_vote_ratio,vote_ratio=cnn_vote_ratio,detected=True)# CNN not confident enough β fall back to LSTM# (handles ambiguous static poses that resemble phrase start positions)if lstm_response.detected and lstm_conf >= LSTM_CONF_FLOOR:print(f"[auto] Static, CNN low conf β LSTM fallback: "f"'{lstm_response.result}' ({lstm_conf:.2f})")return lstm_responseprint(f"[auto] Static β neither model confident. "f"CNN: {cnn_vote_ratio:.2f}, LSTM: {lstm_conf:.2f}")return AutoResponse(result="", result_type="none",confidence=0.0, vote_ratio=cnn_vote_ratio, detected=False)@app.post("/predict/phrase", response_model=PhraseResponse)async def predict_phrase(files: List[UploadFile] = File(...)):5 unmodified lines678910117 unmodified lines1920212223242531 unmodified lines575859606162181 unmodified lines24424524624724824925058 unmodified lines3093103113123133143153161 unmodified line3183193203213223233249 unmodified lines33433533633733833994 unmodified lines4344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814821 unmodified line4844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705 unmodified linesPOST /predict/phrase β multiple JPEG frames β phrase + confidencePOST /predict/auto β 60 frames β auto decide letter or phraseGET /health β health check"""import os7 unmodified linesfrom fastapi import FastAPI, File, UploadFile, HTTPExceptionfrom fastapi.middleware.cors import CORSMiddlewarefrom pydantic import BaseModelfrom typing import Listimport mediapipe as mpfrom mediapipe.tasks import python as mp_pythonfrom mediapipe.tasks.python import vision as mp_vision31 unmodified lines# Fraction of processed frames with 2 hands to trigger automatic LSTMTWO_HAND_RATIO = 1 / 3# ============================================================# Model Architectures# ============================================================181 unmodified linesarr = np.frombuffer(data, np.uint8)frame = cv2.imdecode(arr, cv2.IMREAD_COLOR)frame = cv2.flip(frame, 1)#frame = cv2.convertScaleAbs(frame, alpha=1.3, beta=20)rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)return mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)58 unmodified linesreturn left_lms, right_lmsdef run_lstm(coord_buffer, vote_ratio):"""Run LSTM on coord buffer and return AutoResponse."""if len(coord_buffer) < MIN_COORD_FRAMES:return AutoResponse(result="", result_type="phrase",1 unmodified line)buf = np.array(coord_buffer)idx = np.linspace(0, len(buf)-1, SEQ_LEN, dtype=int)seq = buf[idx]tensor = torch.tensor(seq, dtype=torch.float32).unsqueeze(0).to(device)9 unmodified linesdetected=True)# ============================================================# FastAPI App# ============================================================94 unmodified lines@app.post("/predict/auto", response_model=AutoResponse)async def predict_auto(files: List[UploadFile] = File(...)):"""Accepts 60 JPEG frames.Runs MediaPipe on every other frame (30 calls).Decision logic:1. If hand presence < 1/3 of processed frames β not detected2. If 2 hands detected in >= 1/3 of processed frames β skip CNN, go straight to LSTM3. If CNN vote_ratio >= 0.50 β return letter4. Else β run LSTM β return phrase"""if not files:raise HTTPException(status_code=400, detail="No frames provided")frame_data = []for file in files:data = await file.read()frame_data.append(data)votes = {}total_processed_frames = 0total_hand_frames = 0two_hand_frames = 0# Movement tracking β store wrist position of each processed framewrist_positions = []coord_buffer = []last_pose_vec = np.zeros(POSE_SIZE, dtype=np.float32)last_left_hand_vec = np.zeros(HAND_SIZE, dtype=np.float32)last_right_hand_vec = np.zeros(HAND_SIZE, dtype=np.float32)for i, data in enumerate(frame_data):if i % 2 == 0:total_processed_frames += 1mp_img = bytes_to_mp_image(data)# CNN β single hand for alphabetcnn_result = hand_detector_alpha.detect(mp_img)hand_lms = cnn_result.hand_landmarks[0] \if cnn_result.hand_landmarks else Noneif hand_lms is not None:total_hand_frames += 1# Track wrist position for movement detectionwrist_positions.append((hand_lms[WRIST].x, hand_lms[WRIST].y))skel = render_hand_skeleton(hand_lms)1 unmodified linewith torch.no_grad():probs = torch.softmax(alphabet_model(tensor), dim=1)[0]conf, idx = probs.max(dim=0)if conf.item() >= 0.6: # only count confident predictionsletter = ALPHA_CLASSES[idx.item()]votes[letter] = votes.get(letter, 0) + 1# LSTM β pose + both handspose_result = pose_detector.detect(mp_img)pose_lms = pose_result.pose_landmarks[0] \if pose_result.pose_landmarks else Noneif pose_lms:last_pose_vec = normalize_pose(pose_lms)lstm_result = hand_detector_phrase.detect(mp_img)left_lms, right_lms = get_hands_by_side(lstm_result)if left_lms is not None: last_left_hand_vec = normalize_hand(left_lms)if right_lms is not None: last_right_hand_vec = normalize_hand(right_lms)if left_lms is not None and right_lms is not None:two_hand_frames += 1vec = np.concatenate([last_pose_vec, last_left_hand_vec, last_right_hand_vec])coord_buffer.append(vec)# ββ Step 1: Minimum hand presence check ββββββββββββββββββmin_required = total_processed_frames * MIN_HAND_PRESENCE_RATIOif total_hand_frames < min_required:print(f"[auto] Hand presence too low: {total_hand_frames}/{total_processed_frames} "f"(need >= {min_required:.1f}) β skipping")return AutoResponse(result="", result_type="none",confidence=0.0, vote_ratio=0.0, detected=False)# ββ Step 2: Two hands detected β LSTM directly βββββββββββtwo_hand_threshold = total_processed_frames * TWO_HAND_RATIOif two_hand_frames >= two_hand_threshold:print(f"[auto] Two hands in {two_hand_frames}/{total_processed_frames} frames β LSTM")return run_lstm(coord_buffer, vote_ratio=0.0)# ββ Step 3: Obvious movement detected β LSTM directly ββββ# Compare wrist position from midpoint to end of sequence.# Ignores initial arm raising to position the hand.if len(wrist_positions) >= 4:mid_idx = len(wrist_positions) // 2mid_pos = wrist_positions[mid_idx]end_pos = wrist_positions[-1]dx = end_pos[0] - mid_pos[0]dy = end_pos[1] - mid_pos[1]movement = (dx**2 + dy**2) ** 0.5print(f"[auto] Wrist movement (midβend): {movement:.4f}")MOVEMENT_THRESHOLD = 0.35 # ~20% of frame width, tunableif movement >= MOVEMENT_THRESHOLD:print(f"[auto] Significant movement ({movement:.4f}) β LSTM")return run_lstm(coord_buffer, vote_ratio=0.0)# ββ Step 4: CNN vote decision βββββββββββββββββββββββββββββvote_ratio = 0.0best_letter = ""if not votes:return AutoResponse(result="", result_type="none",confidence=0.0, vote_ratio=0.0, detected=False)best_letter = max(votes, key=votes.get)vote_ratio = votes[best_letter] / sum(votes.values())if vote_ratio >= 0.65 and best_letter:return AutoResponse(result=best_letter,result_type="letter",confidence=vote_ratio,vote_ratio=vote_ratio,detected=True)# ββ Step 4: LSTM βββββββββββββββββββββββββββββββββββββββββreturn run_lstm(coord_buffer, vote_ratio)@app.post("/predict/phrase", response_model=PhraseResponse)async def predict_phrase(files: List[UploadFile] = File(...)):
app.py+62-199