Update app.py
Browse files
app.py
CHANGED
|
@@ -6,13 +6,6 @@ Endpoints:
|
|
| 6 |
POST /predict/phrase β multiple JPEG frames β phrase + confidence
|
| 7 |
POST /predict/auto β 60 frames β auto decide letter or phrase
|
| 8 |
GET /health β health check
|
| 9 |
-
|
| 10 |
-
Routing logic (v2):
|
| 11 |
-
Old: single displacement threshold (wrist midpointβend >= 0.45)
|
| 12 |
-
New: trajectory path length + mean velocity + confidence arbitration
|
| 13 |
-
- Path length : sum of all frame-to-frame wrist distances (catches oscillating signs)
|
| 14 |
-
- Mean velocity: average per-frame wrist movement (catches sustained motion)
|
| 15 |
-
- Confidence arbitration: both CNN and LSTM scores compared before committing
|
| 16 |
"""
|
| 17 |
|
| 18 |
import os
|
|
@@ -26,7 +19,7 @@ from PIL import Image
|
|
| 26 |
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 27 |
from fastapi.middleware.cors import CORSMiddleware
|
| 28 |
from pydantic import BaseModel
|
| 29 |
-
from typing import List
|
| 30 |
import mediapipe as mp
|
| 31 |
from mediapipe.tasks import python as mp_python
|
| 32 |
from mediapipe.tasks.python import vision as mp_vision
|
|
@@ -64,25 +57,6 @@ MIN_HAND_PRESENCE_RATIO = 1 / 3
|
|
| 64 |
# Fraction of processed frames with 2 hands to trigger automatic LSTM
|
| 65 |
TWO_HAND_RATIO = 1 / 3
|
| 66 |
|
| 67 |
-
# ββ Motion routing thresholds (v2) ββββββββββββββββββββββββββββββββββββββββββββ
|
| 68 |
-
# Total wrist path (sum of frame-to-frame distances in normalized coords 0-1).
|
| 69 |
-
# Signs like "THANK YOU" that move forward-then-back are caught here even though
|
| 70 |
-
# their net displacement is near zero.
|
| 71 |
-
STATIC_PATH_THRESHOLD = 0.15 # total path < this β treat as static letter
|
| 72 |
-
|
| 73 |
-
# Mean per-frame wrist velocity in normalized coords.
|
| 74 |
-
# Sustained slow motion (e.g. tracing letters in air) is caught here.
|
| 75 |
-
STATIC_VELOCITY_MAX = 0.08 # mean velocity < this β treat as static letter
|
| 76 |
-
|
| 77 |
-
# CNN vote confidence floor. Below this the CNN result is not trusted on its own.
|
| 78 |
-
CNN_CONF_FLOOR = 0.65
|
| 79 |
-
|
| 80 |
-
# If CNN is this confident it can override an LSTM result even during dynamic input.
|
| 81 |
-
CNN_OVERRIDE_CONF = 0.85
|
| 82 |
-
|
| 83 |
-
# LSTM confidence floor. Below this neither model is confident β not detected.
|
| 84 |
-
LSTM_CONF_FLOOR = 0.65
|
| 85 |
-
|
| 86 |
# ============================================================
|
| 87 |
# Model Architectures
|
| 88 |
# ============================================================
|
|
@@ -270,6 +244,7 @@ def bytes_to_mp_image(data: bytes):
|
|
| 270 |
arr = np.frombuffer(data, np.uint8)
|
| 271 |
frame = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
| 272 |
frame = cv2.flip(frame, 1)
|
|
|
|
| 273 |
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 274 |
return mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
|
| 275 |
|
|
@@ -334,41 +309,8 @@ def get_hands_by_side(hand_result):
|
|
| 334 |
return left_lms, right_lms
|
| 335 |
|
| 336 |
|
| 337 |
-
def
|
| 338 |
-
|
| 339 |
-
) -> Tuple[float, float, float]:
|
| 340 |
-
"""
|
| 341 |
-
Compute three motion statistics from a list of (x, y) wrist positions
|
| 342 |
-
in normalized MediaPipe coordinates (0.0 β 1.0).
|
| 343 |
-
|
| 344 |
-
Returns:
|
| 345 |
-
total_path : Sum of Euclidean distances between consecutive positions.
|
| 346 |
-
Catches oscillating / circular signs that return near their
|
| 347 |
-
start point (net displacement would be ~0 for those).
|
| 348 |
-
mean_velocity : Average per-frame displacement. Catches sustained slow
|
| 349 |
-
motion such as tracing letters in the air.
|
| 350 |
-
variance : Variance of per-frame displacements. High variance means
|
| 351 |
-
the hand alternates between fast and slow β a hallmark of
|
| 352 |
-
phrase signs with distinct motion phases.
|
| 353 |
-
"""
|
| 354 |
-
if len(wrist_positions) < 2:
|
| 355 |
-
return 0.0, 0.0, 0.0
|
| 356 |
-
|
| 357 |
-
deltas = [
|
| 358 |
-
np.sqrt((wrist_positions[i][0] - wrist_positions[i-1][0]) ** 2 +
|
| 359 |
-
(wrist_positions[i][1] - wrist_positions[i-1][1]) ** 2)
|
| 360 |
-
for i in range(1, len(wrist_positions))
|
| 361 |
-
]
|
| 362 |
-
|
| 363 |
-
total_path = float(np.sum(deltas))
|
| 364 |
-
mean_velocity = float(np.mean(deltas))
|
| 365 |
-
variance = float(np.var(deltas))
|
| 366 |
-
|
| 367 |
-
return total_path, mean_velocity, variance
|
| 368 |
-
|
| 369 |
-
|
| 370 |
-
def run_lstm(coord_buffer: list, vote_ratio: float) -> "AutoResponse":
|
| 371 |
-
"""Run LSTM on coord_buffer and return an AutoResponse."""
|
| 372 |
if len(coord_buffer) < MIN_COORD_FRAMES:
|
| 373 |
return AutoResponse(
|
| 374 |
result="", result_type="phrase",
|
|
@@ -376,7 +318,7 @@ def run_lstm(coord_buffer: list, vote_ratio: float) -> "AutoResponse":
|
|
| 376 |
)
|
| 377 |
|
| 378 |
buf = np.array(coord_buffer)
|
| 379 |
-
idx = np.linspace(0, len(buf)
|
| 380 |
seq = buf[idx]
|
| 381 |
tensor = torch.tensor(seq, dtype=torch.float32).unsqueeze(0).to(device)
|
| 382 |
|
|
@@ -392,19 +334,6 @@ def run_lstm(coord_buffer: list, vote_ratio: float) -> "AutoResponse":
|
|
| 392 |
detected=True
|
| 393 |
)
|
| 394 |
|
| 395 |
-
|
| 396 |
-
def run_cnn_from_votes(votes: dict) -> Tuple[str, float]:
|
| 397 |
-
"""
|
| 398 |
-
Derive the best CNN letter and its vote ratio from the accumulated vote dict.
|
| 399 |
-
Returns ("", 0.0) if votes is empty.
|
| 400 |
-
"""
|
| 401 |
-
if not votes:
|
| 402 |
-
return "", 0.0
|
| 403 |
-
best_letter = max(votes, key=votes.get)
|
| 404 |
-
vote_ratio = votes[best_letter] / sum(votes.values())
|
| 405 |
-
return best_letter, vote_ratio
|
| 406 |
-
|
| 407 |
-
|
| 408 |
# ============================================================
|
| 409 |
# FastAPI App
|
| 410 |
# ============================================================
|
|
@@ -505,69 +434,49 @@ async def predict_alphabet_batch(files: List[UploadFile] = File(...)):
|
|
| 505 |
@app.post("/predict/auto", response_model=AutoResponse)
|
| 506 |
async def predict_auto(files: List[UploadFile] = File(...)):
|
| 507 |
"""
|
| 508 |
-
Accepts 60 JPEG frames.
|
| 509 |
-
|
| 510 |
-
|
| 511 |
-
|
| 512 |
-
|
| 513 |
-
|
| 514 |
-
|
| 515 |
-
|
| 516 |
-
Step 2 β Two-hands gate
|
| 517 |
-
If both hands appear in >= 1/3 of processed frames β go straight to LSTM.
|
| 518 |
-
Two-handed signs are always phrases; no CNN vote needed.
|
| 519 |
-
|
| 520 |
-
Step 3 β Motion statistics (replaces single displacement check)
|
| 521 |
-
Compute trajectory path length and mean per-frame velocity from wrist
|
| 522 |
-
positions across all processed frames.
|
| 523 |
-
|
| 524 |
-
is_dynamic = total_path > STATIC_PATH_THRESHOLD (0.15)
|
| 525 |
-
OR mean_velocity > STATIC_VELOCITY_MAX (0.008)
|
| 526 |
-
|
| 527 |
-
Path length catches oscillating / circular signs (e.g. THANK YOU moves
|
| 528 |
-
forward-then-back; net displacement β 0 but total path is large).
|
| 529 |
-
Mean velocity catches sustained slow motion.
|
| 530 |
-
|
| 531 |
-
Step 4 β Confidence arbitration
|
| 532 |
-
Rather than hard-routing to one model, both CNN and LSTM scores are
|
| 533 |
-
compared and the more confident result wins, with guard rails:
|
| 534 |
-
|
| 535 |
-
Dynamic input β LSTM is primary.
|
| 536 |
-
CNN can still win if conf >= CNN_OVERRIDE_CONF (0.85)
|
| 537 |
-
AND lstm_conf < LSTM_CONF_FLOOR (0.65).
|
| 538 |
-
Static input β CNN is primary (vote_ratio >= CNN_CONF_FLOOR 0.65).
|
| 539 |
-
Falls back to LSTM if CNN is not confident enough.
|
| 540 |
-
Neither model confident β not detected.
|
| 541 |
"""
|
| 542 |
if not files:
|
| 543 |
raise HTTPException(status_code=400, detail="No frames provided")
|
| 544 |
|
| 545 |
-
frame_data = [
|
|
|
|
|
|
|
|
|
|
| 546 |
|
| 547 |
votes = {}
|
| 548 |
total_processed_frames = 0
|
| 549 |
total_hand_frames = 0
|
| 550 |
two_hand_frames = 0
|
| 551 |
-
|
|
|
|
|
|
|
| 552 |
|
| 553 |
coord_buffer = []
|
| 554 |
last_pose_vec = np.zeros(POSE_SIZE, dtype=np.float32)
|
| 555 |
last_left_hand_vec = np.zeros(HAND_SIZE, dtype=np.float32)
|
| 556 |
last_right_hand_vec = np.zeros(HAND_SIZE, dtype=np.float32)
|
| 557 |
|
| 558 |
-
# ββ Per-frame processing ββββββββββββββββββββββββββββββββββ
|
| 559 |
for i, data in enumerate(frame_data):
|
| 560 |
if i % 2 == 0:
|
| 561 |
total_processed_frames += 1
|
| 562 |
mp_img = bytes_to_mp_image(data)
|
| 563 |
|
| 564 |
-
# CNN
|
| 565 |
cnn_result = hand_detector_alpha.detect(mp_img)
|
| 566 |
hand_lms = cnn_result.hand_landmarks[0] \
|
| 567 |
if cnn_result.hand_landmarks else None
|
| 568 |
|
| 569 |
if hand_lms is not None:
|
| 570 |
total_hand_frames += 1
|
|
|
|
| 571 |
wrist_positions.append((hand_lms[WRIST].x, hand_lms[WRIST].y))
|
| 572 |
|
| 573 |
skel = render_hand_skeleton(hand_lms)
|
|
@@ -575,133 +484,87 @@ async def predict_auto(files: List[UploadFile] = File(...)):
|
|
| 575 |
with torch.no_grad():
|
| 576 |
probs = torch.softmax(alphabet_model(tensor), dim=1)[0]
|
| 577 |
conf, idx = probs.max(dim=0)
|
| 578 |
-
|
| 579 |
-
if conf.item() >= 0.6:
|
| 580 |
letter = ALPHA_CLASSES[idx.item()]
|
| 581 |
votes[letter] = votes.get(letter, 0) + 1
|
| 582 |
|
| 583 |
-
# LSTM
|
| 584 |
pose_result = pose_detector.detect(mp_img)
|
| 585 |
pose_lms = pose_result.pose_landmarks[0] \
|
| 586 |
if pose_result.pose_landmarks else None
|
| 587 |
if pose_lms:
|
| 588 |
last_pose_vec = normalize_pose(pose_lms)
|
| 589 |
|
| 590 |
-
|
| 591 |
-
left_lms, right_lms
|
| 592 |
if left_lms is not None: last_left_hand_vec = normalize_hand(left_lms)
|
| 593 |
if right_lms is not None: last_right_hand_vec = normalize_hand(right_lms)
|
| 594 |
|
| 595 |
if left_lms is not None and right_lms is not None:
|
| 596 |
two_hand_frames += 1
|
| 597 |
|
| 598 |
-
# Build coordinate vector for every frame (uses last-valid values for
|
| 599 |
-
# frames where MediaPipe was not run, matching training pipeline)
|
| 600 |
vec = np.concatenate([last_pose_vec, last_left_hand_vec, last_right_hand_vec])
|
| 601 |
coord_buffer.append(vec)
|
| 602 |
|
| 603 |
-
# ββ Step 1:
|
| 604 |
min_required = total_processed_frames * MIN_HAND_PRESENCE_RATIO
|
| 605 |
if total_hand_frames < min_required:
|
| 606 |
print(f"[auto] Hand presence too low: {total_hand_frames}/{total_processed_frames} "
|
| 607 |
-
f"(need >= {min_required:.1f}) β
|
| 608 |
return AutoResponse(
|
| 609 |
result="", result_type="none",
|
| 610 |
confidence=0.0, vote_ratio=0.0, detected=False
|
| 611 |
)
|
| 612 |
|
| 613 |
-
# ββ Step 2: Two
|
| 614 |
two_hand_threshold = total_processed_frames * TWO_HAND_RATIO
|
| 615 |
if two_hand_frames >= two_hand_threshold:
|
| 616 |
print(f"[auto] Two hands in {two_hand_frames}/{total_processed_frames} frames β LSTM")
|
| 617 |
return run_lstm(coord_buffer, vote_ratio=0.0)
|
| 618 |
|
| 619 |
-
# ββ Step 3:
|
| 620 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 621 |
|
| 622 |
-
|
| 623 |
-
total_path > STATIC_PATH_THRESHOLD or
|
| 624 |
-
mean_velocity > STATIC_VELOCITY_MAX
|
| 625 |
-
)
|
| 626 |
|
| 627 |
-
|
| 628 |
-
|
| 629 |
-
|
| 630 |
-
|
| 631 |
-
|
|
|
|
|
|
|
|
|
|
| 632 |
|
| 633 |
-
|
| 634 |
-
best_letter, cnn_vote_ratio = run_cnn_from_votes(votes)
|
| 635 |
-
lstm_response = run_lstm(coord_buffer, cnn_vote_ratio)
|
| 636 |
-
lstm_conf = lstm_response.confidence
|
| 637 |
-
|
| 638 |
-
if is_dynamic:
|
| 639 |
-
# Dynamic input β LSTM is primary
|
| 640 |
-
# CNN can override only if it is overwhelmingly confident and LSTM is not
|
| 641 |
-
if (best_letter and
|
| 642 |
-
cnn_vote_ratio >= CNN_OVERRIDE_CONF and
|
| 643 |
-
lstm_conf < LSTM_CONF_FLOOR):
|
| 644 |
-
print(f"[auto] Dynamic but CNN override: '{best_letter}' "
|
| 645 |
-
f"({cnn_vote_ratio:.2f}) > LSTM '{lstm_response.result}' "
|
| 646 |
-
f"({lstm_conf:.2f})")
|
| 647 |
-
return AutoResponse(
|
| 648 |
-
result=best_letter,
|
| 649 |
-
result_type="letter",
|
| 650 |
-
confidence=cnn_vote_ratio,
|
| 651 |
-
vote_ratio=cnn_vote_ratio,
|
| 652 |
-
detected=True
|
| 653 |
-
)
|
| 654 |
-
|
| 655 |
-
# Normal dynamic case β trust LSTM
|
| 656 |
-
if lstm_response.detected and lstm_conf >= LSTM_CONF_FLOOR:
|
| 657 |
-
print(f"[auto] Dynamic β LSTM: '{lstm_response.result}' ({lstm_conf:.2f})")
|
| 658 |
-
return lstm_response
|
| 659 |
-
|
| 660 |
-
# LSTM not confident β try CNN as last resort
|
| 661 |
-
if best_letter and cnn_vote_ratio >= CNN_CONF_FLOOR:
|
| 662 |
-
print(f"[auto] Dynamic, LSTM low conf β CNN fallback: "
|
| 663 |
-
f"'{best_letter}' ({cnn_vote_ratio:.2f})")
|
| 664 |
-
return AutoResponse(
|
| 665 |
-
result=best_letter,
|
| 666 |
-
result_type="letter",
|
| 667 |
-
confidence=cnn_vote_ratio,
|
| 668 |
-
vote_ratio=cnn_vote_ratio,
|
| 669 |
-
detected=True
|
| 670 |
-
)
|
| 671 |
-
|
| 672 |
-
print(f"[auto] Dynamic β neither model confident. "
|
| 673 |
-
f"CNN: {cnn_vote_ratio:.2f}, LSTM: {lstm_conf:.2f}")
|
| 674 |
return AutoResponse(
|
| 675 |
result="", result_type="none",
|
| 676 |
-
confidence=0.0, vote_ratio=
|
| 677 |
)
|
| 678 |
|
| 679 |
-
|
| 680 |
-
|
| 681 |
-
|
| 682 |
-
|
| 683 |
-
return AutoResponse(
|
| 684 |
-
result=best_letter,
|
| 685 |
-
result_type="letter",
|
| 686 |
-
confidence=cnn_vote_ratio,
|
| 687 |
-
vote_ratio=cnn_vote_ratio,
|
| 688 |
-
detected=True
|
| 689 |
-
)
|
| 690 |
-
|
| 691 |
-
# CNN not confident enough β fall back to LSTM
|
| 692 |
-
# (handles ambiguous static poses that resemble phrase start positions)
|
| 693 |
-
if lstm_response.detected and lstm_conf >= LSTM_CONF_FLOOR:
|
| 694 |
-
print(f"[auto] Static, CNN low conf β LSTM fallback: "
|
| 695 |
-
f"'{lstm_response.result}' ({lstm_conf:.2f})")
|
| 696 |
-
return lstm_response
|
| 697 |
-
|
| 698 |
-
print(f"[auto] Static β neither model confident. "
|
| 699 |
-
f"CNN: {cnn_vote_ratio:.2f}, LSTM: {lstm_conf:.2f}")
|
| 700 |
return AutoResponse(
|
| 701 |
-
result=
|
| 702 |
-
|
|
|
|
|
|
|
|
|
|
| 703 |
)
|
| 704 |
|
|
|
|
|
|
|
|
|
|
| 705 |
|
| 706 |
@app.post("/predict/phrase", response_model=PhraseResponse)
|
| 707 |
async def predict_phrase(files: List[UploadFile] = File(...)):
|
|
|
|
| 6 |
POST /predict/phrase β multiple JPEG frames β phrase + confidence
|
| 7 |
POST /predict/auto β 60 frames β auto decide letter or phrase
|
| 8 |
GET /health β health check
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 9 |
"""
|
| 10 |
|
| 11 |
import os
|
|
|
|
| 19 |
from fastapi import FastAPI, File, UploadFile, HTTPException
|
| 20 |
from fastapi.middleware.cors import CORSMiddleware
|
| 21 |
from pydantic import BaseModel
|
| 22 |
+
from typing import List
|
| 23 |
import mediapipe as mp
|
| 24 |
from mediapipe.tasks import python as mp_python
|
| 25 |
from mediapipe.tasks.python import vision as mp_vision
|
|
|
|
| 57 |
# Fraction of processed frames with 2 hands to trigger automatic LSTM
|
| 58 |
TWO_HAND_RATIO = 1 / 3
|
| 59 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 60 |
# ============================================================
|
| 61 |
# Model Architectures
|
| 62 |
# ============================================================
|
|
|
|
| 244 |
arr = np.frombuffer(data, np.uint8)
|
| 245 |
frame = cv2.imdecode(arr, cv2.IMREAD_COLOR)
|
| 246 |
frame = cv2.flip(frame, 1)
|
| 247 |
+
#frame = cv2.convertScaleAbs(frame, alpha=1.3, beta=20)
|
| 248 |
rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
|
| 249 |
return mp.Image(image_format=mp.ImageFormat.SRGB, data=rgb)
|
| 250 |
|
|
|
|
| 309 |
return left_lms, right_lms
|
| 310 |
|
| 311 |
|
| 312 |
+
def run_lstm(coord_buffer, vote_ratio):
|
| 313 |
+
"""Run LSTM on coord buffer and return AutoResponse."""
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 314 |
if len(coord_buffer) < MIN_COORD_FRAMES:
|
| 315 |
return AutoResponse(
|
| 316 |
result="", result_type="phrase",
|
|
|
|
| 318 |
)
|
| 319 |
|
| 320 |
buf = np.array(coord_buffer)
|
| 321 |
+
idx = np.linspace(0, len(buf)-1, SEQ_LEN, dtype=int)
|
| 322 |
seq = buf[idx]
|
| 323 |
tensor = torch.tensor(seq, dtype=torch.float32).unsqueeze(0).to(device)
|
| 324 |
|
|
|
|
| 334 |
detected=True
|
| 335 |
)
|
| 336 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 337 |
# ============================================================
|
| 338 |
# FastAPI App
|
| 339 |
# ============================================================
|
|
|
|
| 434 |
@app.post("/predict/auto", response_model=AutoResponse)
|
| 435 |
async def predict_auto(files: List[UploadFile] = File(...)):
|
| 436 |
"""
|
| 437 |
+
Accepts 60 JPEG frames.
|
| 438 |
+
Runs MediaPipe on every other frame (30 calls).
|
| 439 |
+
|
| 440 |
+
Decision logic:
|
| 441 |
+
1. If hand presence < 1/3 of processed frames β not detected
|
| 442 |
+
2. If 2 hands detected in >= 1/3 of processed frames β skip CNN, go straight to LSTM
|
| 443 |
+
3. If CNN vote_ratio >= 0.50 β return letter
|
| 444 |
+
4. Else β run LSTM β return phrase
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 445 |
"""
|
| 446 |
if not files:
|
| 447 |
raise HTTPException(status_code=400, detail="No frames provided")
|
| 448 |
|
| 449 |
+
frame_data = []
|
| 450 |
+
for file in files:
|
| 451 |
+
data = await file.read()
|
| 452 |
+
frame_data.append(data)
|
| 453 |
|
| 454 |
votes = {}
|
| 455 |
total_processed_frames = 0
|
| 456 |
total_hand_frames = 0
|
| 457 |
two_hand_frames = 0
|
| 458 |
+
|
| 459 |
+
# Movement tracking β store wrist position of each processed frame
|
| 460 |
+
wrist_positions = []
|
| 461 |
|
| 462 |
coord_buffer = []
|
| 463 |
last_pose_vec = np.zeros(POSE_SIZE, dtype=np.float32)
|
| 464 |
last_left_hand_vec = np.zeros(HAND_SIZE, dtype=np.float32)
|
| 465 |
last_right_hand_vec = np.zeros(HAND_SIZE, dtype=np.float32)
|
| 466 |
|
|
|
|
| 467 |
for i, data in enumerate(frame_data):
|
| 468 |
if i % 2 == 0:
|
| 469 |
total_processed_frames += 1
|
| 470 |
mp_img = bytes_to_mp_image(data)
|
| 471 |
|
| 472 |
+
# CNN β single hand for alphabet
|
| 473 |
cnn_result = hand_detector_alpha.detect(mp_img)
|
| 474 |
hand_lms = cnn_result.hand_landmarks[0] \
|
| 475 |
if cnn_result.hand_landmarks else None
|
| 476 |
|
| 477 |
if hand_lms is not None:
|
| 478 |
total_hand_frames += 1
|
| 479 |
+
# Track wrist position for movement detection
|
| 480 |
wrist_positions.append((hand_lms[WRIST].x, hand_lms[WRIST].y))
|
| 481 |
|
| 482 |
skel = render_hand_skeleton(hand_lms)
|
|
|
|
| 484 |
with torch.no_grad():
|
| 485 |
probs = torch.softmax(alphabet_model(tensor), dim=1)[0]
|
| 486 |
conf, idx = probs.max(dim=0)
|
| 487 |
+
if conf.item() >= 0.6: # only count confident predictions
|
|
|
|
| 488 |
letter = ALPHA_CLASSES[idx.item()]
|
| 489 |
votes[letter] = votes.get(letter, 0) + 1
|
| 490 |
|
| 491 |
+
# LSTM β pose + both hands
|
| 492 |
pose_result = pose_detector.detect(mp_img)
|
| 493 |
pose_lms = pose_result.pose_landmarks[0] \
|
| 494 |
if pose_result.pose_landmarks else None
|
| 495 |
if pose_lms:
|
| 496 |
last_pose_vec = normalize_pose(pose_lms)
|
| 497 |
|
| 498 |
+
lstm_result = hand_detector_phrase.detect(mp_img)
|
| 499 |
+
left_lms, right_lms = get_hands_by_side(lstm_result)
|
| 500 |
if left_lms is not None: last_left_hand_vec = normalize_hand(left_lms)
|
| 501 |
if right_lms is not None: last_right_hand_vec = normalize_hand(right_lms)
|
| 502 |
|
| 503 |
if left_lms is not None and right_lms is not None:
|
| 504 |
two_hand_frames += 1
|
| 505 |
|
|
|
|
|
|
|
| 506 |
vec = np.concatenate([last_pose_vec, last_left_hand_vec, last_right_hand_vec])
|
| 507 |
coord_buffer.append(vec)
|
| 508 |
|
| 509 |
+
# ββ Step 1: Minimum hand presence check ββββββββββββββββββ
|
| 510 |
min_required = total_processed_frames * MIN_HAND_PRESENCE_RATIO
|
| 511 |
if total_hand_frames < min_required:
|
| 512 |
print(f"[auto] Hand presence too low: {total_hand_frames}/{total_processed_frames} "
|
| 513 |
+
f"(need >= {min_required:.1f}) β skipping")
|
| 514 |
return AutoResponse(
|
| 515 |
result="", result_type="none",
|
| 516 |
confidence=0.0, vote_ratio=0.0, detected=False
|
| 517 |
)
|
| 518 |
|
| 519 |
+
# ββ Step 2: Two hands detected β LSTM directly βββββββββββ
|
| 520 |
two_hand_threshold = total_processed_frames * TWO_HAND_RATIO
|
| 521 |
if two_hand_frames >= two_hand_threshold:
|
| 522 |
print(f"[auto] Two hands in {two_hand_frames}/{total_processed_frames} frames β LSTM")
|
| 523 |
return run_lstm(coord_buffer, vote_ratio=0.0)
|
| 524 |
|
| 525 |
+
# ββ Step 3: Obvious movement detected β LSTM directly ββββ
|
| 526 |
+
# Compare wrist position from midpoint to end of sequence.
|
| 527 |
+
# Ignores initial arm raising to position the hand.
|
| 528 |
+
if len(wrist_positions) >= 4:
|
| 529 |
+
mid_idx = len(wrist_positions) // 2
|
| 530 |
+
mid_pos = wrist_positions[mid_idx]
|
| 531 |
+
end_pos = wrist_positions[-1]
|
| 532 |
+
dx = end_pos[0] - mid_pos[0]
|
| 533 |
+
dy = end_pos[1] - mid_pos[1]
|
| 534 |
+
movement = (dx**2 + dy**2) ** 0.5
|
| 535 |
|
| 536 |
+
print(f"[auto] Wrist movement (midβend): {movement:.4f}")
|
|
|
|
|
|
|
|
|
|
| 537 |
|
| 538 |
+
MOVEMENT_THRESHOLD = 0.35 # ~20% of frame width, tunable
|
| 539 |
+
if movement >= MOVEMENT_THRESHOLD:
|
| 540 |
+
print(f"[auto] Significant movement ({movement:.4f}) β LSTM")
|
| 541 |
+
return run_lstm(coord_buffer, vote_ratio=0.0)
|
| 542 |
+
|
| 543 |
+
# ββ Step 4: CNN vote decision βββββββββββββββββββββββββββββ
|
| 544 |
+
vote_ratio = 0.0
|
| 545 |
+
best_letter = ""
|
| 546 |
|
| 547 |
+
if not votes:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 548 |
return AutoResponse(
|
| 549 |
result="", result_type="none",
|
| 550 |
+
confidence=0.0, vote_ratio=0.0, detected=False
|
| 551 |
)
|
| 552 |
|
| 553 |
+
best_letter = max(votes, key=votes.get)
|
| 554 |
+
vote_ratio = votes[best_letter] / sum(votes.values())
|
| 555 |
+
|
| 556 |
+
if vote_ratio >= 0.65 and best_letter:
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 557 |
return AutoResponse(
|
| 558 |
+
result=best_letter,
|
| 559 |
+
result_type="letter",
|
| 560 |
+
confidence=vote_ratio,
|
| 561 |
+
vote_ratio=vote_ratio,
|
| 562 |
+
detected=True
|
| 563 |
)
|
| 564 |
|
| 565 |
+
# ββ Step 4: LSTM βββββββββββββββββββββββββββββββββββββββββ
|
| 566 |
+
return run_lstm(coord_buffer, vote_ratio)
|
| 567 |
+
|
| 568 |
|
| 569 |
@app.post("/predict/phrase", response_model=PhraseResponse)
|
| 570 |
async def predict_phrase(files: List[UploadFile] = File(...)):
|