Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
11 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
96 changes: 85 additions & 11 deletions ai-server/app/api/endpoints/pose.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,10 @@
import exercise_pb2
from app.config import settings
from app.core.analyzer_registry import get_analyzer
from app.core.lunge_analyzer import StreamingLungeAnalyzer, lunge_geometry
from app.core.angle_calculator import extract_angles
from app.core.mediapipe_detector import get_detector, lease_detector
from app.core.squat_analyzer import _torso_tilt_degrees
from app.core.squat_analyzer import StreamingSquatAnalyzer, _torso_tilt_degrees
from app.grpc import spring_client
from app.grpc.session_state import (
MIN_FRAME_INTERVAL_SEC,
Expand All @@ -28,7 +29,7 @@
elapsed_sec,
get_registry,
)
from app.models.pose import Landmark, PoseRequest, PoseResponse, PoseSkipReason
from app.models.pose import Landmark, PoseRequest, PoseResponse, PoseSkipReason, SquatProgress
from app.observability import frame_path
from app.utils.image_utils import base64_to_image

Expand Down Expand Up @@ -199,8 +200,22 @@ def _detect_pose(req: PoseRequest):
frame_path.mark_leased()
landmarks = detector.detect(image_rgb)
frame_path.mark_inferred()
image_aspect = image_rgb.shape[1] / image_rgb.shape[0]

if not landmarks:
# Only the owner may invalidate an in-flight repetition.
missing_state = get_registry().get(req.session_id) if req.session_id is not None else None
if (missing_state is not None and missing_state.exercise_type in ("lunge", "squat")
and (missing_state.session_nonce is None or
(req.session_nonce is not None and secrets.compare_digest(
req.session_nonce, missing_state.session_nonce)))):
with missing_state.state_lock:
if missing_state.lunge_state is not None:
missing_state.lunge_state.invalidate("전신을 찾을 수 없습니다. 원위치에서 다시 준비해주세요.")
missing_state.current_rep_frames.clear()
if missing_state.squat_counter is not None:
missing_state.squat_counter.invalidate()
missing_state.current_rep_frames.clear()
return PoseResponse(
success=False,
skip_reason=PoseSkipReason.NO_POSE,
Expand All @@ -209,8 +224,14 @@ def _detect_pose(req: PoseRequest):

# 세션 미지정 — 기존 stateless 동작 (각도만 반환)
if req.session_id is None:
if req.exercise_type == "lunge":
try:
_, _, angles = lunge_geometry(landmarks, image_rgb.shape[1] / image_rgb.shape[0])
except ValueError:
return PoseResponse(success=False, skip_reason=PoseSkipReason.LOW_VISIBILITY)
return PoseResponse(success=True, landmarks=landmarks, image_aspect_ratio=image_aspect, angles=angles)
angles = extract_angles(landmarks, req.exercise_type)
return PoseResponse(success=True, landmarks=landmarks, angles=angles)
return PoseResponse(success=True, landmarks=landmarks, image_aspect_ratio=image_aspect, angles=angles)

state = get_registry().get(req.session_id)
if state is None:
Expand Down Expand Up @@ -301,11 +322,29 @@ def _detect_pose(req: PoseRequest):
success=False,
skip_reason=PoseSkipReason.RATE_LIMITED,
landmarks=landmarks,
image_aspect_ratio=image_aspect,
message="유입 속도 상한 초과 — 분석 스킵",
rep_count=state.rep_count,
)

angles, smoothed_knee_angle, rep_event = analyzer.process_frame(state, landmarks)
if isinstance(analyzer, (StreamingLungeAnalyzer, StreamingSquatAnalyzer)):
angles, smoothed_knee_angle, rep_event, torso_tilt_deg, stagger_ratio = analyzer.process_frame(
state, landmarks, timestamp_sec=received_at,
image_aspect_ratio=image_rgb.shape[1] / image_rgb.shape[0],
)
else:
angles, smoothed_knee_angle, rep_event = analyzer.process_frame(state, landmarks)
torso_tilt_deg = None
stagger_ratio = None
lunge_progress = state.lunge_state.progress() if state.lunge_state is not None else None
# 앱이 «준비됐는지/지금 뭘 해야 하는지»를 화면에 보여주도록 스쿼트 단계와 안내를 같이 싣는다.
squat_progress = (
SquatProgress(stage=state.squat_counter.stage, guidance=state.squat_counter.guidance)
if state.exercise_type == "squat" and state.squat_counter is not None else None
)
coaching_message = (state.squat_counter.coaching_event
if state.exercise_type == "squat" and state.squat_counter is not None
else None)

if angles is None:
# visibility 부족 — 프레임 스킵. 🔴 success=False 다 (이슈 #267).
Expand All @@ -318,8 +357,11 @@ def _detect_pose(req: PoseRequest):
success=False,
skip_reason=PoseSkipReason.LOW_VISIBILITY,
landmarks=landmarks,
image_aspect_ratio=image_aspect,
message="가시성 부족으로 분석 스킵",
rep_count=state.rep_count,
lunge=lunge_progress,
squat=squat_progress,
)

# 프레임 시각은 **서버가 만든다** (이슈 #156). 예전에는 두 갈래였고 둘 다 틀렸다:
Expand All @@ -334,22 +376,31 @@ def _detect_pose(req: PoseRequest):
angles=angles,
smoothed_knee_angle=smoothed_knee_angle,
landmarks=landmarks,
torso_tilt_deg=torso_tilt_deg,
stagger_ratio=stagger_ratio,
)
state.current_rep_frames.append(frame)

if rep_event is None:
return PoseResponse(
success=True,
landmarks=landmarks,
image_aspect_ratio=image_aspect,
angles=angles,
rep_count=state.rep_count,
lunge=lunge_progress,
squat=squat_progress,
message=coaching_message,
)

# rep 완성 — Spring 전송·로컬 요약에 쓸 프레임을 **한 번만** 스냅샷한다. 락을 풀고
# gRPC 콜백을 부른 뒤 다시 잡아 completed_reps 에 넣을 때 current_rep_frames 를 다시
# 읽으면, 그 사이 끼어든 다음 요청이 버퍼에 새 프레임을 넣어 두 기록(Spring 전송분과
# 로컬 completed_reps)이 서로 달라질 수 있다 — 스냅샷 하나를 양쪽에 같이 쓴다.
rep_frames_snapshot = list(state.current_rep_frames)
if state.exercise_type == "lunge":
# 다음 런지가 콜백 대기 중 시작돼도 새 프레임을 지우지 않도록 분리한다.
state.current_rep_frames.clear()

# 락 밖 — Spring 전송(gRPC)은 다른 세션은 물론 이 세션의 다음 프레임도 막지 않는다.
pose_data_list = [
Expand All @@ -364,6 +415,24 @@ def _detect_pose(req: PoseRequest):
# 프레임을 남길지, 리포트에서 어느 프레임을 대표로 쓸지 고르는 기준이 이 값이다
# (decisions/worst-section-rep-resolution.md §4-ㄹ). 작을수록 깊게 앉은 것.
smoothed_knee_angle=f.smoothed_knee_angle,
# 런지 rep_event(LungeRepEvent)에만 있는 필드다. 스쿼트의 StreamingRepEvent는
# lead_leg가 없으므로 getattr 기본값(빈 문자열)이 그대로 나간다 — proto3 기본값과
# 같아 구버전 계약과도 구분되지 않는다(#156 등 다른 필드와 같은 규약).
lead_leg=getattr(rep_event, "lead_leg", "") or "",
# 체간 기울기 점수(백엔드 TrunkLeanAnalysisCalculator, 2026-09-28)용. 스쿼트·런지
# 공용이며 아래 BACK_BENT 실시간 판정과는 별개 경로다. None이면(landmark
# 가시성 부족 등으로 이번 프레임에서 계산 못 함) proto3 기본값 0.0이 나가는데, 이는
# "완전 직립"과 구분되지 않는다 — 백엔드가 이 필드를 nullable 컬럼에 그대로 못 박지
# 않고 0.0을 유효값으로 받아들이는 이유이기도 하다(어차피 세션 내내 계산 불가능한
# 프레임은 드물고, 드물게 섞여도 rep 평균에 0.0 하나가 끼는 정도라 왜곡이 작다).
torso_tilt_deg=f.torso_tilt_deg or 0.0,
# 보폭 점수(백엔드 LungeStepLengthAnalysisCalculator, 2026-09-28)용. 런지 전용 —
# 스쿼트 프레임은 항상 None이라 proto3 기본값 0.0이 나간다. 이 계산기는 런지
# 세션만 채점하므로(exercise_id 가드) 스쿼트 행에 0.0이 들어가도 소비되지 않는다.
# 런지 행에서 0.0은 이론상 "발이 완전히 붙음"이지만, 그 값이면 애초에 stagger_min
# 문턱을 못 넘어 "returning" 단계(=Spring 전송 구간)에 도달하지 못하므로 실제로는
# 나타나지 않는다.
stagger_ratio=f.stagger_ratio or 0.0,
)
for f in rep_frames_snapshot
]
Expand All @@ -375,7 +444,7 @@ def _detect_pose(req: PoseRequest):
# 만들기 위해서"). 그런데 이 프레임을 만들 때 이미 감지된 원본 landmarks 객체가 있는데
# 같은 요청 안에서 그걸 문자열로 만들었다가 도로 파싱하는 왕복이라, PerRepFrame에 필드
# 하나(landmarks)를 얹어 그 왕복 자체를 없앴다.
if rep_event.feedback_message != "자세 양호" and rep_frames_snapshot:
if state.exercise_type == "squat" and rep_event.feedback_message != "자세 양호" and rep_frames_snapshot:
tilts = []
for f in rep_frames_snapshot:
if not f.landmarks:
Expand Down Expand Up @@ -408,10 +477,11 @@ def _detect_pose(req: PoseRequest):
feedback_message=rep_event.feedback_message,
)
)
for _ in range(len(rep_frames_snapshot)):
if not state.current_rep_frames:
break
state.current_rep_frames.popleft()
if state.exercise_type != "lunge":
for _ in range(len(rep_frames_snapshot)):
if not state.current_rep_frames:
break
state.current_rep_frames.popleft()

logger.info(
"세션 %s rep %d 완성 (sync_rate=%.2f)",
Expand All @@ -423,8 +493,12 @@ def _detect_pose(req: PoseRequest):
return PoseResponse(
success=True,
landmarks=landmarks,
image_aspect_ratio=image_aspect,
angles=angles,
rep_count=state.rep_count,
rep_completed=True,
sync_rate=rep_event.sync_rate,
)
sync_rate=rep_event.sync_rate if state.exercise_type != "lunge" else None,
lunge=lunge_progress,
squat=squat_progress,
message=coaching_message,
)
13 changes: 8 additions & 5 deletions ai-server/app/core/analyzer_registry.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,19 +11,21 @@

⚠️ **판정 기준을 `EXERCISE_ANGLES` 로 잡으면 안 된다.** 그건 각도 «정의» 표라 `deadlift`·
`pullup` 이 들어 있지만, rep 카운팅은 그 표를 타지 않는다 —
`squat_analyzer._extract_raw_metrics` 가 무릎 랜드마크를 하드코딩해 세기 때문이다. 각도 표를
스쿼트 반복 분석기에는 해당 종목의 무릎·고관절 상태 규칙이 따로 있기 때문이다. 각도 표를
기준으로 통과시키면 데드리프트가 무릎 각도로 rep 을 세는, 정확히 이 이슈가 없애려던 실패가
다시 생긴다. 그래서 기준은 **분석기 보유 여부**(`_ANALYZERS`)다.
"""

from __future__ import annotations

from app.core.squat_analyzer import StreamingSquatAnalyzer
from app.core.lunge_analyzer import StreamingLungeAnalyzer

# 운동 유형별 분석기 — stateless 클래스라 공유 가능.
# 여기 없는 유형은 «분석할 수 없다» 는 뜻이고, 그것이 이 dict 의 유일한 의미다.
_ANALYZERS: dict[str, StreamingSquatAnalyzer] = {
_ANALYZERS: dict[str, StreamingSquatAnalyzer | StreamingLungeAnalyzer] = {
"squat": StreamingSquatAnalyzer("squat"),
"lunge": StreamingLungeAnalyzer(),
}

# exercises.id → 분석기 키.
Expand All @@ -37,9 +39,10 @@
# «되던 것이 안 되는» 쪽으로 틀리지, «안 될 것이 되는» 쪽으로 틀리지 않는다.
#
# 현재 시드(V2__seed_master_data.sql): 1=스쿼트 · 2=런지 · 3=플랭크.
# 런지·플랭크는 분석기가 없어 일부러 뺐다(squat-first).
# 플랭크는 아직 분석기가 없다. 런지는 전방 런지 횟수만 분석한다.
_EXERCISE_ID_TO_TYPE: dict[int, str] = {
1: "squat",
2: "lunge",
}


Expand All @@ -55,7 +58,7 @@ def resolve_exercise_type(exercise_id: int) -> str | None:
return exercise_type


def get_analyzer(exercise_type: str) -> StreamingSquatAnalyzer | None:
def get_analyzer(exercise_type: str) -> StreamingSquatAnalyzer | StreamingLungeAnalyzer | None:
"""분석기를 꺼낸다. 없으면 `None`."""
return _ANALYZERS.get(exercise_type)

Expand All @@ -66,4 +69,4 @@ def supported_exercise_ids() -> list[int]:
exercise_id
for exercise_id, exercise_type in _EXERCISE_ID_TO_TYPE.items()
if exercise_type in _ANALYZERS
)
)
Loading
Loading