diff --git a/ai-server/app/api/endpoints/pose.py b/ai-server/app/api/endpoints/pose.py index 3a51bbdd..12044a21 100644 --- a/ai-server/app/api/endpoints/pose.py +++ b/ai-server/app/api/endpoints/pose.py @@ -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, @@ -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 @@ -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, @@ -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: @@ -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). @@ -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). 예전에는 두 갈래였고 둘 다 틀렸다: @@ -334,6 +376,8 @@ 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) @@ -341,8 +385,12 @@ def _detect_pose(req: PoseRequest): 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 전송·로컬 요약에 쓸 프레임을 **한 번만** 스냅샷한다. 락을 풀고 @@ -350,6 +398,9 @@ def _detect_pose(req: PoseRequest): # 읽으면, 그 사이 끼어든 다음 요청이 버퍼에 새 프레임을 넣어 두 기록(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 = [ @@ -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 ] @@ -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: @@ -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)", @@ -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, - ) \ No newline at end of file + sync_rate=rep_event.sync_rate if state.exercise_type != "lunge" else None, + lunge=lunge_progress, + squat=squat_progress, + message=coaching_message, + ) diff --git a/ai-server/app/core/analyzer_registry.py b/ai-server/app/core/analyzer_registry.py index 50206366..58979b99 100644 --- a/ai-server/app/core/analyzer_registry.py +++ b/ai-server/app/core/analyzer_registry.py @@ -11,7 +11,7 @@ ⚠️ **판정 기준을 `EXERCISE_ANGLES` 로 잡으면 안 된다.** 그건 각도 «정의» 표라 `deadlift`· `pullup` 이 들어 있지만, rep 카운팅은 그 표를 타지 않는다 — -`squat_analyzer._extract_raw_metrics` 가 무릎 랜드마크를 하드코딩해 세기 때문이다. 각도 표를 +스쿼트 반복 분석기에는 해당 종목의 무릎·고관절 상태 규칙이 따로 있기 때문이다. 각도 표를 기준으로 통과시키면 데드리프트가 무릎 각도로 rep 을 세는, 정확히 이 이슈가 없애려던 실패가 다시 생긴다. 그래서 기준은 **분석기 보유 여부**(`_ANALYZERS`)다. """ @@ -19,11 +19,13 @@ 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 → 분석기 키. @@ -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", } @@ -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) @@ -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 - ) \ No newline at end of file + ) diff --git a/ai-server/app/core/lunge_analyzer.py b/ai-server/app/core/lunge_analyzer.py new file mode 100644 index 00000000..a561c9c0 --- /dev/null +++ b/ai-server/app/core/lunge_analyzer.py @@ -0,0 +1,282 @@ +"""Side-view lunge counter. See docs/decisions/lunge-repetition-counting.md. + +100 degree bottom boundary follows Sousa et al. (2026). Timing and visibility +gates are engineering defaults requiring video validation. All mutable data +belongs to a session; this analyzer is safe to share. + +2026-09-22 재설계 (2단계): + +1단계 — 판정 축을 발 이동 거리에서 무릎 각도 사이클로 바꿨다. 예전에는 "두 발 모으고 +서 있다가 한쪽 발이 정해진 거리만큼 앞으로 이동"하는 것으로 1회를 판정했는데, 실촬영 +4개(정상·얕음·워킹·45도)를 검증해보니 전부 "이미 벌어진 스탠스에서 제자리로 무릎만 +굽혔다 폈다" 하는 동작이라 발 이동 문턱(0.65)을 못 넘어 전부 0회였다. 스쿼트 +(squat_counter.py)처럼 스탠스가 벌어져 있고 한쪽 무릎이 충분히 굽혀졌다 펴지면 1회로 +바꿨다 — 발이 원위치로 돌아오는지는 더 이상 보지 않는다. + +2단계 — "가만히 서 있는 준비 자세"를 기다리는 calibration 단계를 없앴다. 1단계 수정 +후에도, 실촬영에서 반복 사이 최고점이 무릎을 완전히 펴는 160도까지 못 미치고(130~170도 +사이로 들쭉날쭉) 다음 반복으로 넘어가는 경우가 많아, "완전히 일어서야 다음 반복을 받을 +준비가 된다"는 전제 자체가 반복 여러 개를 하나로 뭉개버렸다(lunge_normal_01에서 8초간 +5개 가까운 펄스가 1회로 합쳐짐). "런지가 보이면 바로 센다"는 사용자 확인에 따라, 준비 +단계 자체를 없애고 바닥(bottom_angle)에 닿았다가 어느 정도(recovered_angle) 다시 +펴지면 그 즉시 다음 반복을 받는다 — 완전한 직립을 요구하지 않는다. + +트레이드오프(사용자에게 명시적으로 확인함): +- 전방/후방/워킹 런지를 구분하지 못한다 — 발 이동 방향을 추적하지 않기 때문이다. 대신 + 스쿼트(양발 나란히)와는 스탠스 벌어짐 정도(stagger_min)로 구분한다. +- "준비 자세 확인"이 없으므로 영상·스트림이 이미 런지 바닥 자세로 시작해도 그 뒤로 + 다시 펴는 동작을 1회로 센다 — 시작 시점을 놓쳤다는 이유로 거부하지 않는다. +- recovered_angle(130)이 standing(160)보다 낮아, 무릎을 끝까지 펴지 않고 반복하는 + 얕은 펄스가 실제보다 여러 회로 쪼개질 여지가 있다. 반대로 너무 낮추면 반복 하나를 + 둘로 오카운트하므로, 이 값은 2026-09-22 실촬영 관찰(반복 사이 최고점이 130도 밑으로는 + 거의 안 내려감)에 맞춘 구현값이다 — 논문 검증치가 아니다. + +바닥 검출(반복이 셌는가)과 좌우 라벨(left_reps/right_reps 어느 쪽에 더할지)은 분리돼 +있다 — 바닥은 두 무릎 중 더 굽은 쪽으로 보고, 라벨은 발목-골반중심 거리로 따로 정한다. +**라벨 쪽은 완전 측면(옆) 촬영에서만 검증됐다.** 2026-09-22 실촬영 4개 중 완전 측면 +3개(정상·얕음·워킹)는 좌우 라벨이 실제 동작과 맞았지만, 45도 각도로 찍은 1개는 총 +횟수는 맞아도 좌우 라벨의 9/10이 틀렸다(전부 오른쪽 동작인 구간을 대부분 "왼쪽"으로 +잘못 붙임) — 발목-골반중심 거리 신호가 완전 측면이 아닌 각도에서는 신뢰할 수 없다는 +뜻이다. 그래서 **런지는 완전 측면 촬영만 지원 범위로 두고, 45도 등 비스듬한 각도는 +지원 범위 밖으로 명시한다** — 총 횟수는 맞을 수 있어도 좌우 구분은 보장하지 않는다. +""" +from __future__ import annotations + +import math +from dataclasses import dataclass, field +from typing import TYPE_CHECKING + +from app.core.stance import stance_features +from app.models.pose import Landmark, LungeProgress + +if TYPE_CHECKING: + from app.grpc.session_state import SessionState + + +@dataclass(frozen=True) +class LungeThresholds: + bottom_angle: float = 100.0 + # 바닥에서 이만큼 다시 펴지면 다음 반복을 받을 준비가 된 것으로 본다. 완전히 편 자세 + # (standing, 160도)까지 기다리지 않는다 — 위 모듈 docstring 2단계 참고. + recovered_angle: float = 130.0 + visibility: float = 0.6 + bottom_confirm_sec: float = 0.12 + recovery_confirm_sec: float = 0.12 + min_rep_sec: float = 0.6 + max_gap_sec: float = 1.2 + smoothing_sec: float = 0.06 + # 두 발목 사이 거리 / 어깨-골반 길이. 이 값으로 "런지 스탠스(다리가 앞뒤로 벌어짐)"와 + # "스쿼트 스탠스(발이 나란함)"를 가른다 — 발 이동 여부는 더 이상 보지 않으므로 이 값이 + # 사실상 유일한 구분 신호였다 — 2026-10-19부터는 바닥 근처의 허벅지 비대칭까지 함께 본다 + # (split_stance_* 아래, app/core/stance.py). + # + # 2026-09-22 실촬영 4개(lunge_normal_01·45degree_01·sallow_01·walking_01) 검증: 무릎이 + # 실제로 굽혀진 순간의 비율이 전부 0.74~1.70이었고, 가만히 선 자세는 0~0.45였다. 그 + # 사이인 0.55를 문턱으로 쓴다. 스쿼트(발이 나란한) 실촬영으로는 아직 재검증하지 않았다 + # — 발이 나란해도 몸통이 기울면 이 비율이 올라갈 수 있어, 오탐 여지가 남아 있다. + stagger_min: float = 0.55 + # 바닥 근처(가장 굽은 무릎이 bottom_angle + split_check_margin 이하)에서 한 번이라도 + # «발 간격 ≥ 0.74 그리고 허벅지 기울기 차이 ≥ 25°» 가 보여야 1회로 인정한다. + split_check_margin: float = 15.0 + + +@dataclass +class LungeState: + # "calibrating"은 더 이상 만들어지지 않는다 — 응답 스키마(LungeProgress.phase)와의 + # 호환을 위해 값 자체만 남겨둔다. 세션은 항상 "ready"에서 시작한다. + phase: str = "ready" + lead_leg: str | None = None + left_reps: int = 0 + right_reps: int = 0 + unassigned_reps: int = 0 + last_time: float | None = None + bottom_since: float | None = None + return_since: float | None = None + started_at: float | None = None + knees: list[float] = field(default_factory=list) + # 이번 반복의 바닥 근처에서 «앞뒤로 벌린 런지 자세»(app/core/stance.py)가 한 번이라도 + # 보였는가. 안 보였으면 다시 일어서도 세지 않는다 — 스쿼트를 런지로 세던 문제(2026-10-19). + split_seen: bool = False + guidance: str = "완전한 측면에서 런지 자세가 보이면 바로 인식합니다." + + def invalidate(self, message: str) -> None: + self.phase = "ready" + self.lead_leg = None + self.bottom_since = self.return_since = None + self.started_at = None + self.knees.clear() + self.split_seen = False + self.guidance = message + + def progress(self) -> LungeProgress: + return LungeProgress( + phase=self.phase, lead_leg=self.lead_leg, left_reps=self.left_reps, + right_reps=self.right_reps, unassigned_reps=self.unassigned_reps, + guidance=self.guidance, + ) + + +@dataclass(frozen=True) +class LungeRepEvent: + rep_number: int + lead_leg: str + # Existing protobuf requires a number. Spring treats lunge scores as unmeasured. + sync_rate: float = 0.0 + feedback_message: str = "" + + +def _angle(a, b, c) -> float: + u, v = (a[0] - b[0], a[1] - b[1]), (c[0] - b[0], c[1] - b[1]) + norm = math.hypot(*u) * math.hypot(*v) + if norm < 1e-8: + raise ValueError("degenerate joint") + cosine = max(-1.0, min(1.0, (u[0] * v[0] + u[1] * v[1]) / norm)) + return math.degrees(math.acos(cosine)) + + +def lunge_geometry(landmarks: list[Landmark], aspect_ratio: float = 1.0): + """Image-plane angles: correct normalized x for width/height, ignore noisy z.""" + required = (11, 12, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32) + lm = {p.index: p for p in landmarks} + if not math.isfinite(aspect_ratio) or aspect_ratio <= 0: + raise ValueError("invalid image shape") + if any(i not in lm or not all(math.isfinite(v) for v in + (lm[i].x, lm[i].y, lm[i].visibility)) for i in required): + raise ValueError("missing/nonfinite landmark") + points = {i: (lm[i].x * aspect_ratio, lm[i].y) for i in required} + angles = [_angle(points[h], points[k], points[a]) + for h, k, a in ((23, 25, 27), (24, 26, 28))] + return lm, points, angles + + +class StreamingLungeAnalyzer: + def __init__(self, thresholds: LungeThresholds | None = None): + self.thresholds = thresholds or LungeThresholds() + + def process_frame(self, state: SessionState, landmarks: list[Landmark], *, + timestamp_sec: float, image_aspect_ratio: float = 1.0): + if state.lunge_state is None: + state.lunge_state = LungeState(unassigned_reps=state.rep_count) + s, t = state.lunge_state, self.thresholds + now = timestamp_sec + if not math.isfinite(now) or (s.last_time is not None and now <= s.last_time): + return None, None, None, None, None + dt = now - s.last_time if s.last_time is not None else 0.0 + s.last_time = now + if dt > t.max_gap_sec: + s.invalidate("영상이 끊겼습니다. 다시 런지를 시작해주세요.") + state.current_rep_frames.clear() + try: + lm, p, angles = lunge_geometry(landmarks, image_aspect_ratio) + if any(lm[i].visibility < t.visibility for i in p): + raise ValueError("low visibility") + except ValueError: + s.invalidate("양쪽 무릎과 발끝이 모두 보이도록 위치를 조정해주세요.") + state.current_rep_frames.clear() + return None, None, None, None, None + + alpha = 1.0 - math.exp(-dt / t.smoothing_sec) if dt else 1.0 + s.knees = [old + alpha * (new - old) for old, new in zip(s.knees, angles)] \ + if s.knees else angles.copy() + mean_knee = sum(s.knees) / 2 + + ankles = [p[27], p[28]] + shoulder = ((p[11][0] + p[12][0]) / 2, (p[11][1] + p[12][1]) / 2) + hip = ((p[23][0] + p[24][0]) / 2, (p[23][1] + p[24][1]) / 2) + scale = math.dist(shoulder, hip) + stagger = abs(ankles[0][0] - ankles[1][0]) / scale if scale > 1e-6 else 0.0 + lunge_stance = stagger >= t.stagger_min + # 체간 기울기 점수(TrunkLeanAnalysisCalculator, 2026-09-28)용 — squat_analyzer.py의 + # _torso_tilt_degrees와 같은 공식이다(어깨 중점-엉덩이 중점 벡터가 수직에서 벗어난 + # 각도). shoulder/hip은 위 stagger 계산에 이미 있는 값을 재사용한다. + torso_tilt = round( + abs(math.degrees(math.atan2(shoulder[0] - hip[0], hip[1] - shoulder[1] + 1e-8))), 2 + ) + # 보폭 점수(LungeStepLengthAnalysisCalculator, 2026-09-28)용 — "런지 자세인가"만 + # 판정하던 stagger 값을 그대로 재사용해 내보낸다. 문헌(Escamilla et al. 계열)이 + # 짧은 보폭일수록 깊은 굴곡 구간에서 슬개대퇴 관절 부하가 커진다고 보고한다 — 발이 + # 원위치에 고정된 채 굽혔다 펴는 이 앱의 런지 특성상 한 rep 안에서 stagger는 거의 + # 변하지 않으므로 별도 최솟값 집계 없이 프레임값 그대로 대표로 쓴다. + stagger_ratio = round(stagger, 3) + near_bottom = min(s.knees) <= t.bottom_angle + t.split_check_margin + if near_bottom: + stance = stance_features(p) + if stance is not None and stance.is_split(): + s.split_seen = True + elif s.phase == "ready": + # 바닥 근처를 벗어난 준비 단계 — 이전 시도의 증거를 다음 반복으로 넘기지 않는다. + s.split_seen = False + + if s.phase == "ready": + if not lunge_stance: + s.bottom_since = None + return angles, mean_knee, None, torso_tilt, stagger_ratio + # "바닥에 닿았는가"는 두 무릎 중 더 굽은 쪽으로 판단한다 — 어느 다리를 lead로 + # 붙일지와는 분리한다. 워킹 런지 실측(lunge_walking_01, 2026-09-22)에서 두 + # 신호가 다른 다리를 가리키는 프레임이 실제로 나왔다: 발목이 골반 중심에서 + # 더 멀리 떨어진 다리(=앞다리로 보이는 쪽)보다 반대쪽 무릎이 더 깊이 굽은 + # 순간이 있었다(몸 전체가 전진하는 워킹 런지 특성상 뒷다리가 아직 이전 + # 자세에서 덜 펴진 채로 남아 있을 수 있다). lead 신호 하나로 바닥 검출까지 + # 묶으면 이런 프레임에서 진짜 반복을 통째로 놓친다. + if min(s.knees) > t.bottom_angle: + s.bottom_since = None + return angles, mean_knee, None, torso_tilt, stagger_ratio + if s.bottom_since is None: + s.bottom_since = now + # 표본 간격(dt)이 이미 확인창(bottom_confirm_sec)보다 크면, 이번 표본 하나가 + # 이 입력이 보여줄 수 있는 가장 촘촘한 체류 증거다 — 3fps(≈0.33초 간격)에서 + # 0.12초짜리 확인창을 "표본 2개"로 요구하면 한 표본만 바닥을 스친 진짜 반복이 + # 전부 씹힌다(2026-09-22 lunge_sallow_01 실측: 10.23초 등 여러 지점에서 정확히 + # 이 이유로 반복이 누락됐다). squat_counter.py의 standing_confirm 판정과 같은 + # 보정이다. + if now - s.bottom_since < t.bottom_confirm_sec and dt < t.bottom_confirm_sec: + return angles, mean_knee, None, torso_tilt, stagger_ratio + # lead(왼쪽/오른쪽 집계용 라벨)는 발목-골반중심 거리로 따로 정한다 — 바닥 + # 검출과 분리했으므로 여기서 잘못 골라도 반복 자체는 이미 세어진 뒤다. + hip_center_x = (p[23][0] + p[24][0]) / 2 + offsets = [abs(a[0] - hip_center_x) for a in ankles] + lead = 0 if offsets[0] >= offsets[1] else 1 + s.lead_leg = "left" if lead == 0 else "right" + s.started_at = s.bottom_since + s.phase = "returning" + s.bottom_since = None + s.guidance = "다시 일어서주세요." + state.current_rep_frames.clear() + return angles, mean_knee, None, torso_tilt, stagger_ratio + + # s.phase == "returning" — 이 단계에서 반환하는 깊이 지표는 두 무릎 평균이 아니라 + # **lead 다리의 무릎각 하나**다(2026-09-27). pose.py가 이 값을 그대로 + # PerRepFrame.smoothed_knee_angle에 실어 Spring에 보내고, 백엔드의 회차별 깊이 채점 + # (LungeDepthAnalysisCalculator)은 그 값의 rep 내 최솟값으로 "이 회차가 얼마나 + # 깊었는지"를 판정한다 — 평균을 쓰면 반대쪽(뒷)다리가 거의 안 굽는 런지 특성상 실제 + # 깊이보다 항상 얕게 보인다. current_rep_frames는 바닥이 확정되는 순간(위에서) 비워지고 + # 이 반환값으로 다시 채워지므로, 여기서부터가 실제로 Spring에 전송되는 구간이다 — + # 회복 판정(max, 어느 쪽이든 펴지면 됨)과 깊이 보고(lead 쪽만) 기준이 다른 것은 의도적. + lead = 0 if s.lead_leg == "left" else 1 + lead_knee = s.knees[lead] + if max(s.knees) < t.recovered_angle: + s.return_since = None + return angles, lead_knee, None, torso_tilt, stagger_ratio + if s.return_since is None: + s.return_since = now + if now - s.return_since < t.recovery_confirm_sec and dt < t.recovery_confirm_sec: + return angles, lead_knee, None, torso_tilt, stagger_ratio + event = None + if not s.split_seen: + # 무릎은 굽었다 폈지만 다리를 앞뒤로 벌린 자세가 한 번도 안 보였다 — 스쿼트 동작. + s.phase, s.lead_leg = "ready", None + s.bottom_since = s.return_since = None + s.guidance = "스쿼트 자세로 인식돼 이번 동작은 세지 않았어요. 다리를 앞뒤로 벌려주세요." + return angles, lead_knee, None, torso_tilt, stagger_ratio + if now - s.started_at >= t.min_rep_sec: + state.rep_count += 1 + if s.lead_leg == "left": + s.left_reps += 1 + else: + s.right_reps += 1 + event = LungeRepEvent(state.rep_count, s.lead_leg) + s.phase, s.lead_leg = "ready", None + s.bottom_since = s.return_since = None + s.split_seen = False + s.guidance = "다시 일어선 것을 확인했습니다. 다음 런지를 시작하세요." + return angles, lead_knee, event, torso_tilt, stagger_ratio diff --git a/ai-server/app/core/reference_builder.py b/ai-server/app/core/reference_builder.py index ff043a35..59170474 100644 --- a/ai-server/app/core/reference_builder.py +++ b/ai-server/app/core/reference_builder.py @@ -67,29 +67,19 @@ def _average_sequences(sequences: list[list[list[float]]]) -> list[list[float]]: def _segment_reps(frames: list[FrameResult]) -> list[RepSegment]: rep_segments: list[RepSegment] = [] current_frames: list[FrameResult] = [] - active = False - seen_bottom = False - rep_index = 0 + previous_count = 0 for frame in frames: metrics = frame.squat_metrics if metrics is None: + current_frames = [] continue - - knee_angle = metrics.knee_angle - if not active and knee_angle < 160: - active = True + if metrics.cycle_stage == "descending" and not current_frames: current_frames = [frame] - seen_bottom = knee_angle <= 100 - continue - - if active: + elif current_frames: current_frames.append(frame) - if knee_angle <= 100: - seen_bottom = True - - if seen_bottom and knee_angle >= 155: - rep_index += 1 + if metrics.rep_count > previous_count: + if current_frames: angles = [item.angles for item in current_frames] knee_angles = [item.squat_metrics.knee_angle for item in current_frames if item.squat_metrics] torso_tilts = [item.squat_metrics.torso_tilt for item in current_frames if item.squat_metrics] @@ -102,7 +92,7 @@ def _segment_reps(frames: list[FrameResult]) -> list[RepSegment]: rep_segments.append( RepSegment( - rep_index=rep_index, + rep_index=metrics.rep_count, start_frame_index=current_frames[0].frame_index, end_frame_index=current_frames[-1].frame_index, angles=angles, @@ -114,9 +104,10 @@ def _segment_reps(frames: list[FrameResult]) -> list[RepSegment]: score=score, ) ) - active = False - seen_bottom = False - current_frames = [] + previous_count = metrics.rep_count + current_frames = [] + elif metrics.cycle_stage in ("waiting_for_standing", "ready"): + current_frames = [] return rep_segments diff --git a/ai-server/app/core/squat_analyzer.py b/ai-server/app/core/squat_analyzer.py index 44ee8bca..292b015e 100644 --- a/ai-server/app/core/squat_analyzer.py +++ b/ai-server/app/core/squat_analyzer.py @@ -1,35 +1,23 @@ -"""Heuristic squat analysis built on top of pose landmarks.""" - +"""스쿼트 실시간/영상 분석. 반복 판정은 squat_counter 한 곳에서 수행한다.""" from __future__ import annotations import math -from dataclasses import dataclass +import time +from dataclasses import dataclass, replace -from app.core.angle_calculator import calculate_angle, extract_angles +from app.core.angle_calculator import extract_angles from app.core.dtw_calculator import compute_sync_rate +from app.core.squat_counter import DEPTH_MODE_THRESHOLDS, SquatCounter, SquatThresholds from app.models.pose import Landmark from app.models.video import SquatAnalysisResult, SquatFrameMetrics from app.utils.constants import LANDMARK, SYNC_THRESHOLDS -# 즉시 수정 필요 컷 / 양호 컷 비율. 기존 고정값(양호>=70, 즉시수정<40)의 비율을 유지한 채 -# 페르소나별 "양호" 기준(SYNC_THRESHOLDS)에 비례 스케일한다. _LOW_CUT_RATIO = 40 / 70 -@dataclass -class _RawSquatFrame: - knee_angle: float - hip_angle: float - torso_tilt: float - hip_height: float - - -def _mean_landmark( - landmarks_by_index: dict[int, Landmark], left_name: str, right_name: str -) -> tuple[float, float]: - left = landmarks_by_index[LANDMARK[left_name]] - right = landmarks_by_index[LANDMARK[right_name]] - return ((left.x + right.x) / 2.0, (left.y + right.y) / 2.0) +def _mean_landmark(landmarks_by_index: dict[int, Landmark], left_name: str, right_name: str): + left, right = (landmarks_by_index[LANDMARK[name]] for name in (left_name, right_name)) + return ((left.x + right.x) / 2, (left.y + right.y) / 2) def _torso_tilt_degrees(landmarks_by_index: dict[int, Landmark]) -> float: @@ -37,385 +25,140 @@ def _torso_tilt_degrees(landmarks_by_index: dict[int, Landmark]) -> float: landmarks_by_index, "LEFT_SHOULDER", "RIGHT_SHOULDER" ) hip_x, hip_y = _mean_landmark(landmarks_by_index, "LEFT_HIP", "RIGHT_HIP") - dx = shoulder_x - hip_x - dy = hip_y - shoulder_y - return abs(math.degrees(math.atan2(dx, dy + 1e-8))) - - -def _frame_visibility_score(landmarks: list[Landmark]) -> float: - tracked_points = ( - "LEFT_SHOULDER", - "RIGHT_SHOULDER", - "LEFT_HIP", - "RIGHT_HIP", - "LEFT_KNEE", - "RIGHT_KNEE", - "LEFT_ANKLE", - "RIGHT_ANKLE", - ) - scores = [landmarks[LANDMARK[name]].visibility for name in tracked_points] - return sum(scores) / len(scores) - - -def _extract_raw_metrics(landmarks: list[Landmark]) -> _RawSquatFrame: - lm_map = {lm.index: lm for lm in landmarks} - - left_knee_angle = calculate_angle( - lm_map[LANDMARK["LEFT_HIP"]], - lm_map[LANDMARK["LEFT_KNEE"]], - lm_map[LANDMARK["LEFT_ANKLE"]], - ) - right_knee_angle = calculate_angle( - lm_map[LANDMARK["RIGHT_HIP"]], - lm_map[LANDMARK["RIGHT_KNEE"]], - lm_map[LANDMARK["RIGHT_ANKLE"]], - ) - left_hip_angle = calculate_angle( - lm_map[LANDMARK["LEFT_SHOULDER"]], - lm_map[LANDMARK["LEFT_HIP"]], - lm_map[LANDMARK["LEFT_KNEE"]], - ) - right_hip_angle = calculate_angle( - lm_map[LANDMARK["RIGHT_SHOULDER"]], - lm_map[LANDMARK["RIGHT_HIP"]], - lm_map[LANDMARK["RIGHT_KNEE"]], - ) - - left_hip = lm_map[LANDMARK["LEFT_HIP"]] - right_hip = lm_map[LANDMARK["RIGHT_HIP"]] - - return _RawSquatFrame( - knee_angle=round((left_knee_angle + right_knee_angle) / 2.0, 2), - hip_angle=round((left_hip_angle + right_hip_angle) / 2.0, 2), - torso_tilt=round(_torso_tilt_degrees(lm_map), 2), - hip_height=round((left_hip.y + right_hip.y) / 2.0, 4), - ) - - -def _phase_from_angles( - current_angle: float, - delta: float, - *, - bottom_threshold: float, - standing_threshold: float, -) -> str: - """국면 이름표. **rep 판정과 같은 자를 쓴다** (이슈 #218). - - 예전에는 여기만 95/155 상수였고 rep 판정은 100/150 이라, 두 밴드에서 응답이 자기모순이었다: - - - 150~155° — rep 상태기계는 `standing` 으로 보고 **rep 을 세는데** 이름표는 아직 `ascending` - - 95~100° — 상태기계는 `bottom` 인데 이름표는 `descending`/`transition` - - `phase` 는 내부값이 아니라 응답 스키마에 나가므로(`models/video.py`), 「rep 은 올랐는데 - 국면은 아직 올라가는 중」이 그대로 밖으로 나갔다. - - 🔴 **자를 인자로 받는 것이 요점이다.** 같은 값을 두 군데 적어두면 한쪽만 바뀌었을 때 - 조용히 다시 갈라진다 — 호출부가 rep 판정에 쓰는 바로 그 변수를 넘기므로 구조적으로 못 갈린다. - `analyze_squat_frames` 의 두 인자를 호출자가 덮어써도 이름표가 같이 따라온다. - - delta 문턱(±4)은 그대로 둔다 — 저건 각도 축이 아니라 **속도 축**이고, rep 판정에 대응하는 - 상대가 없다. - """ - if current_angle <= bottom_threshold: - return "bottom" - if current_angle >= standing_threshold: - return "standing" - if delta <= -4: - return "descending" - if delta >= 4: - return "ascending" - return "transition" + return abs(math.degrees(math.atan2(shoulder_x - hip_x, hip_y - shoulder_y + 1e-8))) def analyze_squat_frames( - landmark_frames: list[list[Landmark] | None], - *, + landmark_frames: list[list[Landmark] | None], *, bottom_threshold: float = 100.0, - standing_threshold: float = 150.0, - min_rep_frames: int = 4, + standing_threshold: float = 160.0, + fps: float = 3.0, + timestamps_sec: list[float] | None = None, + image_aspect_ratio: float = 1.0, ) -> tuple[list[SquatFrameMetrics | None], SquatAnalysisResult]: - """Analyze a sequence of landmark frames and infer squat reps and feedback.""" - raw_metrics: list[_RawSquatFrame | None] = [] - valid_frames = 0 + """영상에서도 실시간과 같은 단계 기계를 사용한다. - for landmarks in landmark_frames: - if not landmarks or _frame_visibility_score(landmarks) < 0.55: - raw_metrics.append(None) + fps를 알면 전달해야 한다. 횟수 하한은 초 단위다. + """ + if not math.isfinite(fps) or fps <= 0: + raise ValueError("fps must be positive") + if timestamps_sec is not None and len(timestamps_sec) != len(landmark_frames): + raise ValueError("timestamps must match frames") + thresholds = replace(SquatThresholds(), bottom_knee=bottom_threshold, + standing_knee=standing_threshold) + counter = SquatCounter(thresholds) + result_frames: list[SquatFrameMetrics | None] = [] + valid_frames = 0 + deepest = 180.0 + tilt_samples = [] + for i, landmarks in enumerate(landmark_frames): + when = timestamps_sec[i] if timestamps_sec is not None else i / fps + obs, _ = counter.update(landmarks, when, image_aspect_ratio) + if obs is None: + result_frames.append(None) continue - raw_metrics.append(_extract_raw_metrics(landmarks)) valid_frames += 1 - - smoothed_knees: list[float | None] = [] - for index, metric in enumerate(raw_metrics): - if metric is None: - smoothed_knees.append(None) - continue - window = [ - candidate.knee_angle - for candidate in raw_metrics[max(0, index - 1) : index + 2] - if candidate is not None - ] - smoothed_knees.append(round(sum(window) / len(window), 2)) - - frame_metrics: list[SquatFrameMetrics | None] = [] - previous_angle: float | None = None - rep_count = 0 - rep_state = "waiting_for_standing" - last_rep_frame_index = -10_000 - deepest_knee = 180.0 - torso_samples: list[float] = [] - current_phase = "unknown" - - for frame_index, (metric, smooth_knee) in enumerate( - zip(raw_metrics, smoothed_knees, strict=False) - ): - if metric is None or smooth_knee is None: - frame_metrics.append(None) - continue - - delta = 0.0 if previous_angle is None else smooth_knee - previous_angle - phase = _phase_from_angles( - smooth_knee, - delta, - bottom_threshold=bottom_threshold, - standing_threshold=standing_threshold, - ) - - if rep_state == "waiting_for_standing": - if smooth_knee >= standing_threshold: - rep_state = "ready" - elif smooth_knee <= bottom_threshold: - rep_state = "bottom" - elif rep_state == "ready" and smooth_knee <= bottom_threshold: - rep_state = "bottom" - elif ( - rep_state == "bottom" - and smooth_knee >= standing_threshold - and frame_index - last_rep_frame_index >= min_rep_frames - ): - rep_count += 1 - rep_state = "ready" - last_rep_frame_index = frame_index - - previous_angle = smooth_knee - deepest_knee = min(deepest_knee, smooth_knee) - torso_samples.append(metric.torso_tilt) - current_phase = phase - - frame_metrics.append( - SquatFrameMetrics( - knee_angle=smooth_knee, - hip_angle=metric.hip_angle, - torso_tilt=metric.torso_tilt, - hip_height=metric.hip_height, - phase=phase, - rep_count=rep_count, - ) - ) - - valid_ratio = round(valid_frames / len(landmark_frames), 2) if landmark_frames else 0.0 - mean_torso = round(sum(torso_samples) / len(torso_samples), 2) if torso_samples else 0.0 - - feedback: list[str] = [] - quality_score = 100 - - if valid_ratio < 0.7: - feedback.append("Keep the full body in frame and improve lighting for steadier tracking.") - quality_score -= 20 - if deepest_knee > 115: - feedback.append("Go slightly deeper so the hip drops closer to knee level.") - quality_score -= 20 - if mean_torso > 35: - feedback.append("Lift the chest more to reduce excessive forward lean.") - quality_score -= 15 - if rep_count == 0 and valid_frames > 0: - feedback.append( - "No full squat rep was detected. Start from standing, go below parallel, and stand tall again." - ) - quality_score -= 25 - - if not feedback and valid_frames > 0: - feedback.append("Stable squat pattern detected. This video is good for a live demo.") - - summary = SquatAnalysisResult( - reps_detected=rep_count, - current_phase=current_phase, - deepest_knee_angle=round(deepest_knee if deepest_knee < 180 else 0.0, 2), - mean_torso_tilt=mean_torso, - quality_score=max(0, quality_score), - feedback=feedback, - valid_frame_ratio=valid_ratio, + deepest = min(deepest, obs.knee_angle) + tilt_samples.append(obs.torso_tilt) + result_frames.append(SquatFrameMetrics( + knee_angle=round(obs.knee_angle, 2), hip_angle=round(obs.hip_angle, 2), + torso_tilt=round(obs.torso_tilt, 2), hip_height=round(obs.hip_height, 4), + phase=counter.phase, cycle_stage=counter.stage, rep_count=counter.rep_count, + )) + ratio = round(valid_frames / len(landmark_frames), 2) if landmark_frames else 0. + feedback = [] + if valid_frames == 0: + feedback.append("관절이 보이는 프레임을 확보하지 못했습니다.") + elif counter.rep_count == 0: + feedback.append("서기, 굽히기, 다시 서기로 이어지는 완전한 스쿼트를 감지하지 못했습니다.") + if valid_frames and ratio < 0.7: + feedback.append("전신이 보이도록 촬영 위치를 조정해주세요.") + return result_frames, SquatAnalysisResult( + reps_detected=counter.rep_count, current_phase=counter.phase, + deepest_knee_angle=round(deepest, 2) if valid_frames else 0., + mean_torso_tilt=round(sum(tilt_samples) / len(tilt_samples), 2) if tilt_samples else 0., + quality_score=None, feedback=feedback, valid_frame_ratio=ratio, ) - return frame_metrics, summary - - -# --------------------------------------------------------------------------- -# Streaming(실시간) 분석기 -# --------------------------------------------------------------------------- @dataclass class StreamingRepEvent: - """rep 1회가 완성될 때마다 발행되는 이벤트. - - ⚠️ deepest_knee_angle · mean_torso_tilt 를 제거했다(이슈 #85). 둘 다 배치 경로의 - SquatAnalysisResult 에서 이름째 가져온 필드인데, 배치는 그 값을 HTTP 응답으로 실제로 - 돌려주는 반면 스트리밍은 pose.py 가 sync_rate·feedback_message·rep_number 만 읽어 - **한 번도 소비되지 않았다.** 소비처가 없으니 테스트도 붙지 않았고, 그래서 결함 2건이 - 그대로 남아 있었다: - - - mean_torso_tilt 는 평균이 아니었다 — 삼항 연산자의 양쪽이 글자까지 같아 어느 쪽으로 - 가도 마지막 프레임 한 점이었다. rep 의 마지막 프레임은 정의상 다시 선 자세라 - "그 rep 동안 얼마나 기울었나"에 가장 안 기운 순간으로 답하고 있었다 - - deepest_knee_angle 은 angles[0] 즉 **왼쪽 무릎만** 봤다. rep 경계를 판정하는 값은 - 좌우 평균인데(_extract_raw_metrics) 여기만 왼쪽이라, 한쪽으로 기우는 자세에서 둘이 갈렸다 - - 고치는 대신 지운 이유: 프레임별 깊이 지표(PerRepFrame.smoothed_knee_angle)를 Spring 으로 - 직접 보내게 되면서 rep 요약본이 필요 없어졌다. Spring 이 프레임들에서 직접 최소값을 고르므로 - 같은 사실이 두 곳에 저장되지 않는다. 배치 경로의 SquatAnalysisResult 는 소비처가 있으므로 - 그대로 둔다. - """ - rep_number: int sync_rate: float feedback_message: str class StreamingSquatAnalyzer: - """프레임 단위로 호출되는 stateful squat 분석기. - - 각 호출에서 (rep_state, smoothing window)를 SessionState 안에 보존하고, - rep 1회 완성 시 그 rep 구간의 user 각도들과 reference angle sequence를 - DTW로 비교해 sync_rate를 산출한다. - """ + """세션별 SquatCounter를 이용해 한 프레임씩 집계한다. - BOTTOM_THRESHOLD = 100.0 - STANDING_THRESHOLD = 150.0 - MIN_REP_FRAMES = 4 - VISIBILITY_FLOOR = 0.55 + 기준영상과의 DTW 유사도는 기존 호환 지표이며, 논문의 임상 자세 점수가 아니다. - # bottom 체류 상한 — 이만큼 넘게 앉아 있었으면 스쿼트가 아니라 "쉬고 있었다"로 본다 - # (이슈 #93). MIN_REP_FRAMES 가 하한이라면 이건 대칭이 되는 상한이다. - # - # 3fps 기준 5초. 실제 스쿼트의 바닥 체류는 1초 내외라 5배 여유이고, 홀드 스쿼트 같은 - # 변형까지 감안해도 넉넉하다. 오판 방향도 안전한 쪽이다 — 크게 잡으면 "덜 걸러짐"이지만 - # 작게 잡으면 정상 rep 이 사라진다. - # - # 왜 하강 속도가 아니라 체류 시간인가: 의자에 5초에 걸쳐 앉으면 프레임당 ~5.6° 라 - # descending 기준(delta <= -4)을 그냥 통과한다. 임계를 더 빡세게 잡으면 이번엔 천천히 - # 하는 초보자·재활 사용자의 정상 rep 이 걸린다. 두 행동은 속도 축에서 분리되지 않고, - # 바닥 체류 시간 축에서만 갈린다(스쿼트 ~1초 vs 앉아쉼 30~90초). - # - # ⚠️ 무엇을 세는지가 바뀌었다 (이슈 #159). 예전에는 bottom **진입~이탈 프레임 차이**를 - # 이 값과 비교했는데, 이탈 임계가 150° 라서 상승 중 100~150° 구간이 통째로 「체류」에 - # 포함됐다. 그 결과 위 주석이 지키려던 바로 그 사용자 — 천천히 하는 초보자·재활 — - # 가 걸렸다. 지금은 `state.bottom_frame_count`, 즉 **실제로 100° 아래에 있던 프레임 수** - # 를 센다. 값 15 는 그대로다(새 임계를 만들지 않으려고 기존 BOTTOM_THRESHOLD 를 재사용). - MAX_BOTTOM_FRAMES = 15 + 🔴 이 분석기 자체는 app/core/analyzer_registry.py가 모듈 로드 시점에 딱 하나 만들어 + 모든 세션이 공유하는 stateless 싱글턴이다. 그래서 `self.thresholds`를 세션마다 바꿀 수 + 없다 — 대신 스쿼트 깊이 모드(FULL/HALF, 2026-09-21)는 세션별 상태인 `state.depth_mode`에 + 저장되고, SquatCounter를 만드는 이 시점에만 그 값을 읽어 임계값을 고른다. + """ - def __init__(self, exercise_type: str = "squat") -> None: + def __init__(self, exercise_type: str = "squat", + thresholds: SquatThresholds | None = None) -> None: self.exercise_type = exercise_type - - def process_frame( - self, - state, - landmarks: list[Landmark], - ) -> tuple[list[float] | None, float | None, StreamingRepEvent | None]: - """단일 프레임을 처리. - - Returns: - (angles, smoothed_knee_angle, rep_event) — angles는 visibility 통과 시 계산된 - 각도 시퀀스, smoothed_knee_angle은 rep 경계 판정에 쓰는 것과 같은 값(좌우 평균을 - 3프레임 평활)으로 프레임별 깊이 지표다, rep_event는 이 프레임으로 rep 1회가 - 완성된 경우에만 채워진다. - - 깊이 지표를 state가 아니라 반환값으로 내보내는 이유: state.previous_smoothed_knee가 - 이미 같은 값을 담지만 그 이름은 "직전 프레임"을 뜻한다. 호출자 입장에서는 방금 처리한 - 프레임의 값이라 이름과 어긋나고, 이 프로젝트는 그런 자리에서 결함이 반복해 나왔다 - (#78·#79·#80·#85). - """ - if not landmarks or _frame_visibility_score(landmarks) < self.VISIBILITY_FLOOR: - state.frame_index += 1 - return None, None, None - - raw = _extract_raw_metrics(landmarks) - angles = extract_angles(landmarks, self.exercise_type) - - # 최근 3개 raw knee로 smoothing - state.recent_raw_knees.append(raw.knee_angle) - if len(state.recent_raw_knees) > 3: - state.recent_raw_knees.pop(0) - smooth_knee = round(sum(state.recent_raw_knees) / len(state.recent_raw_knees), 2) - - rep_event: StreamingRepEvent | None = None - - # 체류 계량 (이슈 #159). 전이 판정보다 **먼저** 온다 — 진입 프레임은 아직 이 블록에 - # 도달하기 전에 상태가 바뀌므로 세지 않고, 이탈 프레임은 이미 150° 위라 조건에 안 걸린다. - # 즉 여기서 세는 것은 «bottom 상태로 지낸 프레임 중 실제로 100° 아래였던 것» 뿐이다. - if state.rep_state == "bottom" and smooth_knee <= self.BOTTOM_THRESHOLD: - state.bottom_frame_count += 1 - - if state.rep_state == "waiting_for_standing": - if smooth_knee >= self.STANDING_THRESHOLD: - state.rep_state = "ready" - elif smooth_knee <= self.BOTTOM_THRESHOLD: - state.rep_state = "bottom" - state.bottom_frame_count = 0 - elif state.rep_state == "ready" and smooth_knee <= self.BOTTOM_THRESHOLD: - state.rep_state = "bottom" - state.bottom_frame_count = 0 - elif state.rep_state == "bottom" and smooth_knee >= self.STANDING_THRESHOLD: - if state.bottom_frame_count > self.MAX_BOTTOM_FRAMES: - # 바닥에 오래 머물렀다 — 운동이 아니라 휴식이었다(이슈 #93). - # rep 으로 세지 않되 상태는 되돌린다. 안 그러면 bottom 에 갇혀 다음 진짜 - # rep 을 놓친다 — "일어섰다"는 사실 자체는 그대로 반영해야 한다. - state.rep_state = "ready" - # 이 구간의 프레임은 운동이 아니므로 다음 rep 에 섞이면 안 된다. 두면 - # _summarize_rep 이 휴식 90프레임까지 넣고 DTW 를 돌려 sync_rate 가 - # 오염된다. (버퍼가 무한정 자라는 문제 자체는 별건 — 이슈 #91) - state.current_rep_frames.clear() - elif state.frame_index - state.last_rep_frame_index >= self.MIN_REP_FRAMES: - state.rep_count += 1 - state.rep_state = "ready" - state.last_rep_frame_index = state.frame_index - # 🔀 머지 해소(main ← feat/deepest-frame-resolution): 제어흐름은 main 의 - # 것(#93 휴식 감지)을 그대로 두고, 호출만 1인자로 되돌린다. main 이 - # 넘기던 last_raw 는 _summarize_rep 안에서 deepest_knee_angle · - # mean_torso_tilt 를 만드는 데만 쓰였는데, 이 브랜치가 그 두 필드를 - # **삭제**했다(이슈 #85 — 소비처가 없어 결함 2건이 잠복해 있었다). - # 인자를 남기면 정의(1인자)와 어긋나 TypeError 가 난다. - rep_event = self._summarize_rep(state) - # else: MIN_REP_FRAMES 미달 — 원래대로 bottom 을 유지한다. 이 하한은 rep 을 - # 거부하는 게 아니라 늦추는 장치라, 서 있는 동안 다음 프레임에서 다시 판정된다. - - state.previous_smoothed_knee = smooth_knee + self.thresholds = thresholds or SquatThresholds() + + def process_frame(self, state, landmarks: list[Landmark], *, + timestamp_sec: float | None = None, + image_aspect_ratio: float = 1.0 + ) -> tuple[list[float] | None, float | None, StreamingRepEvent | None, + float | None, float | None]: + now = time.monotonic() if timestamp_sec is None else timestamp_sec + if state.squat_counter is None: + # 세션의 depth_mode로 임계값을 고른다. 인식 못 하는 값(또는 이 필드가 없는 옛 + # 상태 객체)은 이 분석기 자신의 기본값(self.thresholds, 곧 FULL)으로 폴백한다. + thresholds = DEPTH_MODE_THRESHOLDS.get( + getattr(state, "depth_mode", "FULL"), self.thresholds + ) + state.squat_counter = SquatCounter(thresholds, rep_count=state.rep_count) + counter = state.squat_counter + before = counter.stage + obs, completed = counter.update(landmarks, now, image_aspect_ratio) + state.rep_state = counter.stage state.frame_index += 1 - return angles, smooth_knee, rep_event - - def _summarize_rep(self, state) -> StreamingRepEvent: - """현재까지 누적된 current_rep_frames로 rep 결과 산출.""" - user_angle_seq = [f.angles for f in state.current_rep_frames] - - if state.reference_angles and user_angle_seq: + if obs is None: + state.current_rep_frames.clear() + return None, None, None, None, None + if before != "waiting_for_standing" and counter.stage == "waiting_for_standing": + state.current_rep_frames.clear() + if (before == "ready" and counter.stage == "descending" + or before == "descending" and counter.stage == "ready" and not completed): + state.current_rep_frames.clear() + angles = extract_angles(landmarks, self.exercise_type) + knee = round(obs.knee_angle, 2) + state.previous_smoothed_knee = knee + # 체간 기울기 점수(TrunkLeanAnalysisCalculator)용 — obs.torso_tilt는 이미 매 프레임 + # 계산되고 있었지만(squat_counter.py) 지금까지는 버려졌다. BACK_BENT 실시간 판정 + # (pose.py)과는 별개 경로이니 여기서 새로 계산하지 않고 이미 있는 값만 흘려보낸다. + torso_tilt = round(obs.torso_tilt, 2) + # 스쿼트는 "보폭" 개념이 없다(양발이 나란함) — 5번째 자리는 런지 전용 + # LungeStepLengthAnalysisCalculator 몫이라 항상 None을 흘려보낸다. + if not completed: + return angles, knee, None, torso_tilt, None + state.rep_count = counter.rep_count + return angles, knee, self._summarize_rep(state, angles), torso_tilt, None + + def _summarize_rep(self, state, terminal_angles: list[float]) -> StreamingRepEvent: + # 최종 선 프레임은 HTTP 경로에서 process_frame 반환 후 버퍼에 들어간다. + user_angles = [f.angles for f in state.current_rep_frames] + [terminal_angles] + if state.reference_angles and user_angles: try: - sync_rate = compute_sync_rate(state.reference_angles, user_angle_seq) - except Exception: - sync_rate = 0.0 + score = compute_sync_rate(state.reference_angles, user_angles) + except (ValueError, IndexError, TypeError): + score = 0. else: - sync_rate = 0.0 - - pass_threshold = SYNC_THRESHOLDS.get(state.persona, SYNC_THRESHOLDS["BEGINNER"]) - low_threshold = pass_threshold * _LOW_CUT_RATIO - - if sync_rate >= pass_threshold: - msg = "자세 양호" - elif sync_rate >= low_threshold: - msg = "자세 보정 필요" + score = 0. + threshold = SYNC_THRESHOLDS.get(state.persona, SYNC_THRESHOLDS["BEGINNER"]) + if score >= threshold: + message = "자세 양호" + elif score >= threshold * _LOW_CUT_RATIO: + message = "자세 보정 필요" else: - msg = "즉시 자세 수정 필요" - - return StreamingRepEvent( - rep_number=state.rep_count, - sync_rate=sync_rate, - feedback_message=msg, - ) + message = "즉시 자세 수정 필요" + return StreamingRepEvent(state.rep_count, score, message) diff --git a/ai-server/app/core/squat_counter.py b/ai-server/app/core/squat_counter.py new file mode 100644 index 00000000..c5dbc9e5 --- /dev/null +++ b/ai-server/app/core/squat_counter.py @@ -0,0 +1,372 @@ +"""논문을 참고한 스쿼트 주기 판정. 실시간/영상 분석이 이 구현을 공유한다. + +근거: Sousa et al. (2026), doi:10.3390/jfmk11020162, Listing 1. +시간 후처리 원칙: Postlmayr et al. (2024), doi:10.1016/j.smhl.2024.100516. +전체 논문 알고리즘의 재현이 아니며 추가 설정의 출처·한계는 +docs/decisions/squat-repetition-counting.md에 구분한다. +""" +from __future__ import annotations + +import math +from dataclasses import dataclass, field, replace + +from app.core.stance import StanceFeatures, stance_features +from app.models.pose import Landmark + + +@dataclass(frozen=True) +class SquatThresholds: + # MDL Listing 1의 기본 각도. 2D 카메라 오차를 위한 여유값은 아래에 분리한다. + standing_knee: float = 160.0 + standing_hip: float = 160.0 + bottom_knee: float = 100.0 + bottom_hip: float = 150.0 + standing_knee_margin: float = 8.0 + initial_hip_margin: float = 10.0 + bottom_knee_margin: float = 15.0 + bottom_dwell_margin: float = 5.0 # 경계 통과 구간을 바닥 체류 시간에서 제외 + min_hip_drop: float = 0.25 # 선 자세 몸통 길이에 대한 골반 하강량 + hip_return_tolerance: float = 0.30 + ankle_outlier_grace_sec: float = 0.7 + # PersonalPT의 400ms 유효 동작 / 200ms 분리 원칙을 FSM에 적용. + # 그 논문의 GMM 상태와 여기의 동작 구간은 같지 않다. + min_active_sec: float = 0.4 + standing_confirm_sec: float = 0.2 + # 아래 값은 논문 검증값이 아닌 조정 가능한 구현 기본값이다. + bottom_confirm_sec: float = 0.12 + max_bottom_sec: float = 8.0 # Engineering guard against seated rests; not a paper threshold. + max_gap_sec: float = 1.2 + smoothing_sec: float = 0.12 + visibility: float = 0.55 + ankle_tolerance: float = 0.35 # 준비 자세 몸통 길이의 배수 + phase_velocity: float = 12.0 # 도/초; 표시용이며 카운트 조건은 아님 + + def __post_init__(self): + if not (0 < self.bottom_knee < self.standing_knee <= 180 + and 0 < self.bottom_hip < self.standing_hip <= 180): + raise ValueError("squat angle thresholds must be ordered in (0, 180]") + values = (self.min_active_sec, self.standing_confirm_sec, self.bottom_confirm_sec, + self.max_bottom_sec, self.max_gap_sec, self.smoothing_sec, + self.ankle_tolerance, self.phase_velocity, self.standing_knee_margin, + self.initial_hip_margin, self.bottom_knee_margin, self.bottom_dwell_margin, + self.min_hip_drop, + self.hip_return_tolerance, self.ankle_outlier_grace_sec) + if not all(math.isfinite(v) and v > 0 for v in values) or not 0 <= self.visibility <= 1: + raise ValueError("invalid squat timing/visibility thresholds") + if (self.standing_knee - self.standing_knee_margin <= + self.bottom_knee + self.bottom_knee_margin): + raise ValueError("squat standing and bottom knee bands must not overlap") + if self.bottom_dwell_margin >= self.bottom_knee: + raise ValueError("bottom dwell margin must be smaller than bottom knee angle") + + +# 하프 스쿼트 프리셋 (2026-09-21 사용자 확정: 무릎각 115~140도 밴드). +# bottom_knee=125 + margin(15, 풀 스쿼트와 동일 — 이 margin은 2D 랜드마크 잡음 흡수용이지 +# 목표 깊이와 무관하므로 모드별로 바꾸지 않는다) = 실질 진입 각도 140도. +# +# 🔴 bottom_hip·min_hip_drop은 실측이 아니라 풀 스쿼트 값에서 비례 추정한 값이다(VALIDATE). +# 풀 스쿼트의 무릎:고관절 굴곡은 서기(160/160)에서 바닥(100/150)까지 각각 60도/10도이고, +# 이 비율(10/60)을 하프 스쿼트의 무릎 굴곡 35도(160→125)에 적용하면 +# 고관절 굴곡 ≈ 5.8도 → bottom_hip ≈ 154도. min_hip_drop도 같은 방식으로 +# 0.25 × (35/60) ≈ 0.15로 비례 추정했다. 실촬영 하프 스쿼트 영상으로 재검증하기 전까지는 +# 이 두 값을 신뢰할 수 있는 기준으로 취급하지 않는다 — 2026-09-21 검증 보고서와 같은 방식으로 +# docs/verification/에 별도 검증 문서를 남긴 뒤에만 사용자에게 정확도를 주장한다. +HALF_SQUAT_THRESHOLDS: SquatThresholds = replace( + SquatThresholds(), + bottom_knee=125.0, + bottom_hip=154.0, # VALIDATE + min_hip_drop=0.15, # VALIDATE +) + +# 세션의 depth_mode 문자열 → 임계값 프리셋. 인식하지 못하는 문자열은 호출부가 "FULL"로 +# 취급한다(app/grpc/exercise_servicer.py의 StartAnalysis/ReattachAnalysis 참고). +DEPTH_MODE_THRESHOLDS: dict[str, SquatThresholds] = { + "FULL": SquatThresholds(), + "HALF": HALF_SQUAT_THRESHOLDS, +} + + +@dataclass(frozen=True) +class SquatObservation: + knees: tuple[float, float] + hips: tuple[float, float] + torso_tilt: float + hip_height: float + ankles: tuple[tuple[float, float] | None, tuple[float, float] | None] + torso_length: float + visible_sides: tuple[bool, bool] + # 양쪽 다리가 다 보일 때만 계산된다(한쪽만 보이면 None). 런지 동작을 걸러내는 데 쓴다 — + # app/core/stance.py 참고. + stance: StanceFeatures | None = None + + @property + def knee_angle(self) -> float: + return sum(self.knees) / 2 + + @property + def hip_angle(self) -> float: + return sum(self.hips) / 2 + + +def _angle(a, b, c): + u, v = (a[0] - b[0], a[1] - b[1]), (c[0] - b[0], c[1] - b[1]) + norm = math.hypot(*u) * math.hypot(*v) + if norm < 1e-8: + raise ValueError("degenerate joint") + return math.degrees(math.acos(max(-1., min(1., (u[0] * v[0] + u[1] * v[1]) / norm)))) + + +def observe_squat(landmarks: list[Landmark], aspect_ratio: float, visibility: float) -> SquatObservation: + """이미지 비율을 보정한 2D 내각. 정규화 z를 물리적 깊이로 섞지 않는다.""" + if not math.isfinite(aspect_ratio) or aspect_ratio <= 0: + raise ValueError("invalid image aspect ratio") + lm = {p.index: p for p in landmarks} + chains = ((11, 23, 25, 27), (12, 24, 26, 28)) + valid: list[tuple[int, float, float]] = [] + p: dict[int, tuple[float, float]] = {} + for side, chain in enumerate(chains): + if any(i not in lm or not all(math.isfinite(v) for v in + (lm[i].x, lm[i].y, lm[i].visibility)) or + lm[i].visibility < visibility for i in chain): + continue + for i in chain: + p[i] = (lm[i].x * aspect_ratio, lm[i].y) + try: + knee = _angle(p[chain[1]], p[chain[2]], p[chain[3]]) + hip = _angle(p[chain[0]], p[chain[1]], p[chain[2]]) + except ValueError: + continue + valid.append((side, knee, hip)) + if not valid: + raise ValueError("no visible leg chain") + + shoulders = tuple(sum(p[chains[side][0]][axis] for side, _, _ in valid) / len(valid) + for axis in (0, 1)) + hips = tuple(sum(p[chains[side][1]][axis] for side, _, _ in valid) / len(valid) + for axis in (0, 1)) + torso_length = math.dist(shoulders, hips) + if torso_length < 1e-8: + raise ValueError("degenerate torso") + knees = {side: knee for side, knee, _ in valid} + hip_angles = {side: hip for side, _, hip in valid} + if len(valid) == 1: + side = valid[0][0] + knees[1 - side] = knees[side] + hip_angles[1 - side] = hip_angles[side] + visible_sides = {side for side, _, _ in valid} + return SquatObservation( + knees=(knees[0], knees[1]), hips=(hip_angles[0], hip_angles[1]), + torso_tilt=abs(math.degrees(math.atan2(shoulders[0] - hips[0], hips[1] - shoulders[1]))), + hip_height=hips[1], ankles=(p.get(27), p.get(28)), torso_length=torso_length, + visible_sides=(0 in visible_sides, 1 in visible_sides), + stance=stance_features(p) if len(valid) == 2 else None, + ) + + +@dataclass +class SquatCounter: + thresholds: SquatThresholds = field(default_factory=SquatThresholds) + rep_count: int = 0 + stage: str = "waiting_for_standing" + phase: str = "unknown" + guidance: str = "정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요." + last_time: float | None = None + standing_since: float | None = None + started_at: float | None = None + bottom_since: float | None = None + bottom_band_since: float | None = None + filtered: SquatObservation | None = None + anchors: tuple = () + scale: float = 1.0 + top_hip_height: float | None = None + attempt_max_hip_drop: float = 0.0 + coaching_event: str | None = None + ankle_outlier_since: float | None = None + tracked_sides: tuple[bool, bool] = (False, False) + # 이번 시도 중 바닥 근처에서 «앞뒤로 벌린 런지 자세» 가 한 번이라도 보였는가. + # True 면 일어서도 횟수에 넣지 않는다(2026-10-19, 스쿼트 선택 후 런지를 하면 세지던 문제). + attempt_split_stance: bool = False + + def invalidate(self, message="영상이 끊겼습니다. 똑바로 서서 다시 준비해주세요."): + # 완성된 횟수와 시각 단조성은 보존한다. + self.stage, self.phase = "waiting_for_standing", "unknown" + self.standing_since = self.started_at = self.bottom_since = self.bottom_band_since = None + self.filtered = None + self.anchors = () + self.top_hip_height = self.ankle_outlier_since = None + self.attempt_max_hip_drop = 0.0 + self.coaching_event = None + self.tracked_sides = (False, False) + self.attempt_split_stance = False + self.guidance = message + + def update(self, landmarks: list[Landmark] | None, timestamp_sec: float, + aspect_ratio: float = 1.0) -> tuple[SquatObservation | None, bool]: + now, t = timestamp_sec, self.thresholds + self.coaching_event = None + if not math.isfinite(now) or (self.last_time is not None and now <= self.last_time): + return None, False + dt = now - self.last_time if self.last_time is not None else 0. + self.last_time = now + if dt > t.max_gap_sec: + self.invalidate() + try: + raw = observe_squat(landmarks or [], aspect_ratio, t.visibility) + except ValueError: + self.invalidate("어깨·골반·무릎·발목이 한쪽 다리에서 모두 보이도록 위치를 조정해주세요.") + return None, False + if self.anchors: + shared = tuple(was and now_visible for was, now_visible in + zip(self.tracked_sides, raw.visible_sides)) + if not any(shared): + self.invalidate("동작 중 추적하는 다리가 바뀌었습니다. 제자리에서 다시 준비해주세요.") + return raw, False + # A person may place a foot before the first descent. Keep calibrating + # the stance only while both leg angles still describe an upright pose. + # Once descent starts, the foot anchors are fixed for the whole rep. + if (self.stage == "ready" and + raw.knee_angle >= t.standing_knee and + raw.hip_angle >= t.standing_hip and + self.top_hip_height is not None and + raw.hip_height - self.top_hip_height <= t.hip_return_tolerance * self.scale): + self.anchors, self.scale = raw.ankles, raw.torso_length + self.ankle_outlier_since = None + if any(a is not None and b is not None and + math.dist(a, b) > t.ankle_tolerance * self.scale + for a, b, visible in zip(raw.ankles, self.anchors, + raw.visible_sides) if visible): + if self.ankle_outlier_since is None: + self.ankle_outlier_since = now + elif now - self.ankle_outlier_since >= t.ankle_outlier_grace_sec: + self.invalidate("발 위치가 바뀌었습니다. 제자리에서 다시 준비해주세요.") + return None, False + self.ankle_outlier_since = None + self.tracked_sides = shared + + previous = self.filtered + if previous is not None: + alpha = 1 - math.exp(-dt / t.smoothing_sec) + smooth = lambda before, after: tuple(a + alpha * (b - a) for a, b in zip(before, after)) + raw = replace(raw, knees=smooth(previous.knees, raw.knees), + hips=smooth(previous.hips, raw.hips), + hip_height=previous.hip_height + alpha * (raw.hip_height - previous.hip_height)) + self.filtered = raw + + knee_straight = raw.knee_angle >= t.standing_knee - t.standing_knee_margin + if self.top_hip_height is None: + standing = knee_straight and raw.hip_angle >= t.standing_hip - t.initial_hip_margin + bottom = False + else: + hip_drop = raw.hip_height - self.top_hip_height + standing = knee_straight and hip_drop <= t.hip_return_tolerance * self.scale + bottom = (raw.knee_angle <= t.bottom_knee + t.bottom_knee_margin and + raw.hip_angle <= t.bottom_hip and + hip_drop >= t.min_hip_drop * self.scale) + velocity = (raw.knee_angle - previous.knee_angle) / dt if previous is not None else 0. + self.phase = ("standing" if standing else "bottom" if bottom else + "descending" if velocity < -t.phase_velocity else + "ascending" if velocity > t.phase_velocity else "transition") + + if self.stage == "waiting_for_standing": + if standing: + self.stage = "ready" + self.anchors, self.scale = raw.ankles, raw.torso_length + self.top_hip_height = raw.hip_height + self.tracked_sides = raw.visible_sides + self.guidance = "준비됐습니다. 제자리에서 스쿼트를 시작하세요." + else: + self.standing_since = None + return raw, False + + if self.stage == "ready" and standing: + self.top_hip_height = 0.9 * self.top_hip_height + 0.1 * raw.hip_height + + if self.stage == "ready" and not standing: + self.stage, self.started_at = "descending", now + self.standing_since = self.bottom_since = self.bottom_band_since = None + self.attempt_max_hip_drop = 0.0 + self.attempt_split_stance = False + self.guidance = "편안한 범위에서 무릎과 고관절을 굽혀주세요." + + if (self.stage in ("descending", "bottom") and raw.stance is not None + and min(raw.knees) <= t.bottom_knee + t.bottom_knee_margin + and raw.stance.is_split()): + self.attempt_split_stance = True + + if self.stage == "descending": + self.attempt_max_hip_drop = max( + self.attempt_max_hip_drop, raw.hip_height - self.top_hip_height + ) + if bottom: + if self.bottom_since is None: + self.bottom_since = now + elif now - self.bottom_since >= t.bottom_confirm_sec: + self.stage = "bottom" + self.bottom_band_since, self.bottom_since = self.bottom_since, None + self.guidance = "굽힘을 확인했습니다. 다시 똑바로 서주세요." + else: + self.bottom_since = None + if standing: + if (self.started_at is not None and now - self.started_at >= t.min_active_sec + and self.attempt_max_hip_drop >= t.min_hip_drop * self.scale): + self.coaching_event = "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요." + self.stage = "ready" + self.top_hip_height = raw.hip_height + self.attempt_split_stance = False + self.guidance = "이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요." + return raw, False + + if self.stage == "bottom": + if bottom and self.bottom_band_since is None: + self.bottom_band_since = now + if bottom and now - self.bottom_band_since > t.max_bottom_sec: + self.invalidate("오래 앉아 있었습니다. 일어서서 다시 준비해주세요.") + return raw, False + if not bottom: + self.bottom_band_since = None + strict_bottom = (raw.knee_angle <= t.bottom_knee - t.bottom_dwell_margin and + raw.hip_angle <= t.bottom_hip) + if strict_bottom: + if self.bottom_since is None: + self.bottom_since = now + else: + self.bottom_since = None + if standing: + if self.standing_since is None: + self.standing_since = now + # update() only runs on sampled frames (e.g. the app's 3fps analysis + # rate), so a sample gap (dt) already at/beyond the confirm window is + # itself the finest dwell this input could ever show -- a single + # standing sample is as much confirmation as two would be. At a + # fast/continuous feed (dt well under the confirm window, e.g. a live + # camera stream) this still requires genuine multi-sample dwell, + # unchanged from before. See squat-repetition-counting.md's + # 2026-09-21 note for the real clips this was found on. + if ((now - self.standing_since >= t.standing_confirm_sec + or dt >= t.standing_confirm_sec) + and now - self.started_at >= t.min_active_sec): + if self.attempt_split_stance: + # 런지 자세로 굽혔다 편 동작 — 스쿼트 1회로 세지 않는다. + self.stage = "ready" + self.top_hip_height = raw.hip_height + self.anchors, self.scale = raw.ankles, raw.torso_length + self.tracked_sides = raw.visible_sides + self.standing_since = self.bottom_since = self.bottom_band_since = self.started_at = None + self.attempt_max_hip_drop = 0.0 + self.attempt_split_stance = False + self.coaching_event = "런지 자세로 인식돼 이번 동작은 세지 않았어요." + self.guidance = "두 발을 나란히 두고 스쿼트해주세요." + return raw, False + self.rep_count += 1 + self.stage = "ready" + self.top_hip_height = raw.hip_height + self.anchors, self.scale = raw.ankles, raw.torso_length + self.tracked_sides = raw.visible_sides + self.standing_since = self.bottom_since = self.bottom_band_since = self.started_at = None + self.attempt_max_hip_drop = 0.0 + self.coaching_event = "스쿼트 깊이를 확인하고 1회 기록했어요." + self.guidance = "서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요." + return raw, True + else: + self.standing_since = None + return raw, False diff --git a/ai-server/app/core/stance.py b/ai-server/app/core/stance.py new file mode 100644 index 00000000..03d36cbc --- /dev/null +++ b/ai-server/app/core/stance.py @@ -0,0 +1,84 @@ +"""스쿼트와 런지를 가르는 «앞뒤로 벌린 자세(split stance)» 판정 — 두 분석기가 공유한다. + +왜 필요한가 (2026-10-19): 앱에서 스쿼트를 고르고 런지를 해도, 런지를 고르고 스쿼트를 해도 +횟수와 점수가 나왔다. 두 분석기 모두 «무릎이 100° 근처까지 굽었다 펴졌는가» 를 세는데, +스쿼트와 런지 모두 그 조건을 만족하기 때문이다. + +- 스쿼트 분석기는 두 무릎의 **평균**만 봐서, 런지 바닥 자세(두 무릎이 다 굽음)도 통과했다. +- 런지 분석기의 유일한 구분 신호였던 발목 간격(stagger_min=0.55)은 45° 촬영 스쿼트에서도 + 0.6~0.7 이 나와 넘어갔다(squat_normal_02 · kkw_45-degree_frontview). + +판정 신호 두 개 (둘 다 만족해야 «런지 자세»): + +1. stance_ratio — 두 발목의 가로 간격 / 몸통 길이(어깨 중점↔골반 중점). 기존 stagger 와 같은 값. +2. thigh_asymmetry — 두 허벅지(골반→무릎)가 수직에서 기운 각도의 차이(도). + 런지 바닥에서는 앞 허벅지가 거의 수평, 뒤 허벅지가 거의 수직이라 차이가 크다. + 스쿼트는 두 허벅지가 같이 움직여 차이가 작다. + +정면 스쿼트는 발 간격(1.3~1.5)이 커도 허벅지 차이가 작고(≤5°), 45° 스쿼트는 원근 때문에 +허벅지 차이가 커질 수 있어도(최대 36°) 발 간격이 작다(≤0.69) — 한 신호로는 못 가르고 +두 신호를 함께 봐야 갈린다. + +문턱값 근거 — 저장소 실촬영 13개를 3fps 로 재생해, 바닥 근처 프레임(무릎 평균 ≤115° 또는 +한쪽 ≤100°)에서 측정 (scratch 측정, 2026-10-19): + +| 묶음 | 프레임 | 두 조건 동시 만족 | +|---|---|---| +| 런지 측면 3개(normal·sallow·walking) | 66 | 66 (100%) | +| 런지 45°(지원 범위 밖) | 29 | 27 | +| 스쿼트 9개(정면·45°·측면·얕음) | 97 | 0 | + +- 발 간격: 스쿼트 중 허벅지 차이 ≥25° 인 프레임의 최대 0.69, 런지 측면 최소 0.79 → 사이 0.74. +- 허벅지 차이: 발 간격 ≥0.74 인 스쿼트 프레임의 최대 9°, 런지 측면 바닥 대부분 ≥37° → 25°. + +MediaPipe 실행 방식이 앱(legacy solutions.Pose)과 측정(tasks PoseLandmarker, 같은 full 모델) +이 달라 수치가 조금 다를 수 있다. 표본도 촬영자 2명 수준이라 «검증 완료» 가 아니라 +«지금 가진 영상 전부에서 갈린다» 는 근거다. +""" +from __future__ import annotations + +import math +from dataclasses import dataclass + +# MediaPipe 랜드마크 인덱스 +_SHOULDERS = (11, 12) +_HIPS = (23, 24) +_KNEES = (25, 26) +_ANKLES = (27, 28) + +SPLIT_STANCE_MIN_RATIO = 0.74 +SPLIT_STANCE_MIN_THIGH_ASYMMETRY = 25.0 + + +@dataclass(frozen=True) +class StanceFeatures: + stance_ratio: float + thigh_asymmetry: float + + def is_split(self, min_ratio: float = SPLIT_STANCE_MIN_RATIO, + min_thigh_asymmetry: float = SPLIT_STANCE_MIN_THIGH_ASYMMETRY) -> bool: + return self.stance_ratio >= min_ratio and self.thigh_asymmetry >= min_thigh_asymmetry + + +def _tilt_from_vertical(top: tuple[float, float], bottom: tuple[float, float]) -> float: + return math.degrees(math.atan2(abs(top[0] - bottom[0]), abs(bottom[1] - top[1]))) + + +def stance_features(points: dict[int, tuple[float, float]]) -> StanceFeatures | None: + """가로 비율 보정이 끝난 이미지 좌표(points[index] = (x, y))에서 계산한다. + + 양쪽 다리(골반·무릎·발목)와 어깨가 모두 있어야 한다. 한쪽 다리만 보이면 None — + 그 경우 «런지인지 스쿼트인지 모른다» 이지 «스쿼트다» 가 아니다. + """ + needed = _SHOULDERS + _HIPS + _KNEES + _ANKLES + if any(i not in points for i in needed): + return None + shoulder = tuple((points[11][a] + points[12][a]) / 2 for a in (0, 1)) + hip = tuple((points[23][a] + points[24][a]) / 2 for a in (0, 1)) + torso = math.dist(shoulder, hip) + if torso < 1e-8: + return None + ratio = abs(points[27][0] - points[28][0]) / torso + left = _tilt_from_vertical(points[23], points[25]) + right = _tilt_from_vertical(points[24], points[26]) + return StanceFeatures(stance_ratio=ratio, thigh_asymmetry=abs(left - right)) diff --git a/ai-server/app/core/video_processor.py b/ai-server/app/core/video_processor.py index cee7d630..909a7e7e 100644 --- a/ai-server/app/core/video_processor.py +++ b/ai-server/app/core/video_processor.py @@ -39,6 +39,7 @@ def analyze_video(video_path: str, exercise_type: str) -> VideoAnalysisResult: frames: list[FrameResult] = [] landmark_frames: list[list[Landmark] | None] = [] frame_idx = 0 + image_aspect_ratio = 1.0 while True: ret, frame = cap.read() @@ -46,6 +47,7 @@ def analyze_video(video_path: str, exercise_type: str) -> VideoAnalysisResult: break if frame_idx % frame_interval == 0: + image_aspect_ratio = frame.shape[1] / frame.shape[0] rgb = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB) landmarks = pose_tracker.filter(detector.detect(rgb)) landmark_frames.append(landmarks) @@ -67,10 +69,10 @@ def analyze_video(video_path: str, exercise_type: str) -> VideoAnalysisResult: squat_summary = None if exercise_type == "squat": - min_rep_frames = max(4, int(processed_fps * 1.2)) squat_frame_metrics, squat_summary = analyze_squat_frames( landmark_frames, - min_rep_frames=min_rep_frames, + fps=processed_fps, + image_aspect_ratio=image_aspect_ratio, ) valid_metric_index = 0 for frame in frames: diff --git a/ai-server/app/grpc/exercise_servicer.py b/ai-server/app/grpc/exercise_servicer.py index c24357dc..aab3845c 100644 --- a/ai-server/app/grpc/exercise_servicer.py +++ b/ai-server/app/grpc/exercise_servicer.py @@ -34,6 +34,8 @@ def _parse_reference_poses( reference_poses, exercise_type: str ) -> list[list[float]]: """Spring이 보낸 reference PoseDataRequest 리스트 → 각도 시퀀스로 변환.""" + if exercise_type == "lunge": + return [] # Count-only: no validated lunge reference scorer yet. sequences: list[list[float]] = [] for ref in reference_poses: if not ref.joint_coordinates: @@ -117,11 +119,19 @@ def StartAnalysis(self, request, context): session_id = request.session_id exercise_id = request.exercise_id persona = request.persona or "BEGINNER" + depth_mode = request.depth_mode or "FULL" + if depth_mode not in ("FULL", "HALF"): + logger.warning( + "세션 %s — 알 수 없는 depth_mode %r, FULL로 대체", session_id, depth_mode, + ) + depth_mode = "FULL" logger.info( - "[Spring → AI] StartAnalysis 수신 (session=%s, exercise=%s, persona=%s, reference_frames=%d)", + "[Spring → AI] StartAnalysis 수신 (session=%s, exercise=%s, persona=%s, " + "depth_mode=%s, reference_frames=%d)", session_id, exercise_id, persona, + depth_mode, len(request.reference_poses), ) @@ -129,7 +139,7 @@ def StartAnalysis(self, request, context): # # 예전에는 exercise_type = "squat" 이 못박혀 있었다. 그러면 런지로 세션을 시작해도 # 스쿼트 분석기가 돌아 **조용히 틀린 점수**가 나온다 — rep 카운팅이 무릎 각도를 - # 하드코딩해 세기 때문이다(squat_analyzer._extract_raw_metrics). + # 스쿼트 고유의 무릎·고관절 규칙으로 세기 때문이다. exercise_type = resolve_exercise_type(exercise_id) if exercise_type is None: # abort 인 이유: Spring 의 onNext 는 success 필드를 보지 않고 세션 id 만 로깅한다 @@ -151,7 +161,7 @@ def StartAnalysis(self, request, context): request.reference_poses, exercise_type ) - if not reference_angles: + if not reference_angles and exercise_type != "lunge": logger.warning( "세션 %s에 reference 각도 시퀀스가 비어 있음 — sync_rate는 0으로 계산됨", session_id, @@ -167,11 +177,12 @@ def StartAnalysis(self, request, context): "더 받으려면 컨테이너 메모리 한도(AI_MEM_LIMIT)를 올릴 것.", session_id, used, cap, ) - return exercise_pb2.AnalyzeResponse( - success=False, - session_id=session_id, - exercise_id=exercise_id, - status=exercise_pb2.SessionStatus.FAILED, + # Spring 의 StartAnalysis onNext 는 success 필드를 읽지 않는다. success=False 를 + # 정상 응답으로 보내면 세션이 IN_PROGRESS 에 남아 클라는 SESSION_NOT_FOUND 만 + # 반복해서 받는다. onError 경로가 세션을 FAILED 로 정리하도록 명시적으로 거절한다. + context.abort( + grpc.StatusCode.RESOURCE_EXHAUSTED, + "동시 분석 세션 상한에 도달했습니다.", ) # 소유권 비밀값을 세션 상태에 보관한다 (#187 안 (d)). POST /pose 가 동봉한 값과 @@ -184,6 +195,7 @@ def StartAnalysis(self, request, context): exercise_type=exercise_type, persona=persona, session_nonce=request.session_nonce or None, + depth_mode=depth_mode, ) now = Timestamp() @@ -241,7 +253,7 @@ def ReattachAnalysis(self, request, context): reference_angles = _parse_reference_poses(request.reference_poses, exercise_type) - if not reference_angles: + if not reference_angles and exercise_type != "lunge": # 시작 경로는 경고만 하고 진행한다(sync_rate 0). 재부착은 다르게 취급한다 — 이미 rep 을 # 쌓아둔 세션을 sync_rate 가 전부 0 으로 나오는 상태로 이어붙이면, 사용자는 이어진 줄 # 알지만 뒷부분 기록만 조용히 망가진다. 차라리 실패로 돌려 새로 시작하게 한다. @@ -262,6 +274,13 @@ def ReattachAnalysis(self, request, context): message="동시 세션 상한에 걸렸습니다.", ) + depth_mode = request.depth_mode or "FULL" + if depth_mode not in ("FULL", "HALF"): + logger.warning( + "세션 %s 재부착 — 알 수 없는 depth_mode %r, FULL로 대체", session_id, depth_mode, + ) + depth_mode = "FULL" + state, already_active = get_registry().create_if_absent( session_id=session_id, exercise_id=request.exercise_id, @@ -270,6 +289,7 @@ def ReattachAnalysis(self, request, context): persona=request.persona or "BEGINNER", initial_rep_count=request.initial_rep_count, session_nonce=request.session_nonce or None, + depth_mode=depth_mode, ) if already_active: @@ -486,4 +506,4 @@ def _send_complete_analysis(state) -> None: max_sync_rate=max_v, min_sync_rate=min_v, calories_burned=0.0, # 칼로리 계산은 추후 - ) \ No newline at end of file + ) diff --git a/ai-server/app/grpc/session_state.py b/ai-server/app/grpc/session_state.py index 5f346483..5d7bcbb0 100644 --- a/ai-server/app/grpc/session_state.py +++ b/ai-server/app/grpc/session_state.py @@ -14,6 +14,8 @@ from dataclasses import dataclass, field from app.grpc import spring_client +from app.core.lunge_analyzer import LungeState +from app.core.squat_counter import SquatCounter from app.models.pose import Landmark logger = logging.getLogger(__name__) @@ -86,6 +88,21 @@ class PerRepFrame: # BACK_BENT 재판정(pose.py)이 joint_coordinates를 다시 파싱하지 않도록 원본 객체도 들고 있는다. landmarks: list[Landmark] = field(default_factory=list) + # 어깨 중점-엉덩이 중점 벡터가 수직에서 벗어난 각도(도). 0=완전 직립, 값이 클수록 전방/후방 + # 기울임이 크다(2026-09-28). 체간 자세 점수(TrunkLeanAnalysisCalculator, 백엔드)가 rep 내 + # 평균으로 "얼마나 무너졌는가"를 채점하는 근거값이다 — smoothed_knee_angle과 달리 이건 + # BACK_BENT 재판정(위 landmarks 재계산)과는 별개 경로다: 그쪽은 스쿼트 전용 실시간 이진 + # 판정이고, 이 필드는 스쿼트·런지 공용으로 세션 종료 후 점수화에 쓰인다. None이면 이 프레임에서 + # 계산되지 않았다는 뜻(예: 스쿼트/런지가 아닌 옛 경로). + torso_tilt_deg: float | None = None + + # 두 발목 사이 거리 / 어깨-엉덩이 길이 — "보폭이 얼마나 벌어졌는가" 비율(2026-09-28). + # 런지 전용(lunge_analyzer.py의 stagger_min 판정과 같은 값) — 스쿼트는 보폭 개념이 + # 없어 항상 None이다. 백엔드 LungeStepLengthAnalysisCalculator가 이 값으로 "보폭이 + # 짧아 무릎 부담이 커질 수 있는 rep"을 채점한다(짧은 보폭이 깊은 굴곡 구간에서 + # 슬개대퇴 관절 부하를 늘린다는 문헌 근거, Escamilla et al. 계열). + stagger_ratio: float | None = None + @dataclass class CompletedRep: @@ -101,6 +118,10 @@ class SessionState: exercise_id: int exercise_type: str = "squat" persona: str = "BEGINNER" + # 스쿼트 깊이 모드 "FULL"/"HALF" (2026-09-21). persona와 동일한 규약 — 세션 생성 시 + # 정해지고, 재부착에서는 덮어쓰지 않는다(create_if_absent의 "이미 살아있음" 분기가 + # 이 필드를 건드리지 않으므로 자동으로 보존된다). 스쿼트가 아니면 무의미하되 해롭지 않다. + depth_mode: str = "FULL" # 세션 소유권 검증용 비밀값 (이슈 #187 안 (d)). # # Spring 이 세션 생성 시 만들어 ① REST 응답으로 클라에, ② StartAnalysis/ReattachAnalysis 로 @@ -131,19 +152,11 @@ class SessionState: # 분석기 내부 상태 (StreamingSquatAnalyzer가 관리) rep_count: int = 0 + lunge_state: LungeState | None = None + squat_counter: SquatCounter | None = None rep_state: str = "waiting_for_standing" - last_rep_frame_index: int = -10_000 - # bottom 구간에서 **실제로 100° 아래에 있던** 프레임 수. 앉아서 쉬는 것과 스쿼트를 가르는 - # 축이다 (이슈 #93). - # - # 진입 프레임 인덱스가 아니라 카운터인 이유(이슈 #159): 진입~이탈 프레임 차이로 재면 이탈 - # 임계가 150° 라서 **상승 중 100~150° 구간이 통째로 「바닥 체류」에 포함된다.** 그러면 하강이 - # 느린 사용자일수록 체류 예산이 줄어, 속도를 안 보려고 만든 상수가 속도에 의존하게 된다. - # 측정: 3fps·체류 0.5초 고정에서 하강 5.1초부터 정상 rep 이 사라졌다. - bottom_frame_count: int = 0 frame_index: int = 0 previous_smoothed_knee: float | None = None - recent_raw_knees: list[float] = field(default_factory=list) # 완료된 rep 요약 (StopAnalysis 시 평균 계산용) completed_reps: list[CompletedRep] = field(default_factory=list) @@ -334,6 +347,7 @@ def create( persona: str = "BEGINNER", initial_rep_count: int = 0, session_nonce: str | None = None, + depth_mode: str = "FULL", ) -> SessionState: with self._lock: state = SessionState( @@ -344,6 +358,7 @@ def create( reference_angles=reference_angles, rep_count=initial_rep_count, session_nonce=session_nonce, + depth_mode=depth_mode, ) self._sessions[session_id] = state return state @@ -357,6 +372,7 @@ def create_if_absent( persona: str = "BEGINNER", initial_rep_count: int = 0, session_nonce: str | None = None, + depth_mode: str = "FULL", ) -> tuple[SessionState, bool]: """재부착 전용. 상태가 이미 있으면 **보존하고** 그대로 돌려준다. @@ -396,6 +412,7 @@ def create_if_absent( reference_angles=reference_angles, rep_count=initial_rep_count, session_nonce=session_nonce, + depth_mode=depth_mode, ) self._sessions[session_id] = state return state, False @@ -464,4 +481,4 @@ def exists(self, session_id: int) -> bool: def get_registry() -> SessionStateRegistry: - return _registry \ No newline at end of file + return _registry diff --git a/ai-server/app/models/pose.py b/ai-server/app/models/pose.py index 559666f2..9dc870a5 100644 --- a/ai-server/app/models/pose.py +++ b/ai-server/app/models/pose.py @@ -1,6 +1,7 @@ """포즈 관련 Pydantic 모델.""" from enum import StrEnum +from typing import Literal from pydantic import BaseModel, Field @@ -85,6 +86,29 @@ class PoseRequest(BaseModel): ) +class LungeProgress(BaseModel): + phase: Literal["calibrating", "ready", "descending", "returning"] + lead_leg: Literal["left", "right"] | None = None + left_reps: int = 0 + right_reps: int = 0 + # Restored totals have no side history in the current persistence contract. + unassigned_reps: int = 0 + guidance: str + score_available: bool = False + + +class SquatProgress(BaseModel): + """스쿼트 카운터의 현재 단계 — 앱이 «지금 뭘 해야 하는지»를 화면에 보여주려고 싣는다. + + stage 는 SquatCounter.stage 그대로다: waiting_for_standing(똑바로 선 자세를 아직 못 봄) → + ready(준비 완료, 스쿼트를 시작해도 됨) → descending → bottom. guidance 는 서버가 단계에 + 맞춰 만든 안내 문장이다(2026-10-06). + """ + + stage: str + guidance: str + + class PoseResponse(BaseModel): """포즈 감지 응답.""" @@ -101,8 +125,14 @@ class PoseResponse(BaseModel): # success=False 일 때 «왜» 다. 성공이면 None. skip_reason: PoseSkipReason | None = None landmarks: list[Landmark] | None = None + # landmarks 의 x 는 이미지 너비, y 는 높이로 정규화돼 있다. 각도·거리를 맞게 재려면 두 축의 + # 실제 길이 비(너비/높이)가 필요한데 앱은 서버가 디코딩한 이미지(EXIF 회전 반영)의 크기를 알 수 + # 없어서 같이 내려준다 (3D 운동 비교, 2026-10-20). + image_aspect_ratio: float | None = None angles: list[float] | None = None message: str | None = None rep_count: int | None = None rep_completed: bool = False sync_rate: float | None = None + lunge: LungeProgress | None = None + squat: SquatProgress | None = None diff --git a/ai-server/app/models/video.py b/ai-server/app/models/video.py index 070f8839..d4bd60ea 100644 --- a/ai-server/app/models/video.py +++ b/ai-server/app/models/video.py @@ -13,6 +13,7 @@ class SquatFrameMetrics(BaseModel): torso_tilt: float = Field(description="Torso tilt from vertical in degrees") hip_height: float = Field(description="Normalized hip height (0-1)") phase: str = Field(description="Estimated squat phase") + cycle_stage: str = Field(default="waiting_for_standing", description="Squat repetition state") rep_count: int = Field(description="Completed squat repetitions so far") @@ -33,7 +34,9 @@ class SquatAnalysisResult(BaseModel): current_phase: str = Field(description="Current or final phase at the end of analysis") deepest_knee_angle: float = Field(description="Lowest average knee angle reached") mean_torso_tilt: float = Field(description="Average torso tilt from vertical") - quality_score: int = Field(description="Heuristic squat quality score from 0 to 100") + quality_score: int | None = Field( + default=None, description="No validated scalar squat-quality score is available" + ) feedback: list[str] = Field(description="Human-readable coaching feedback") valid_frame_ratio: float = Field(description="Ratio of frames with reliable pose landmarks") diff --git a/ai-server/docs/squat_demo_guide.md b/ai-server/docs/squat_demo_guide.md index 070a2691..f67b1255 100644 --- a/ai-server/docs/squat_demo_guide.md +++ b/ai-server/docs/squat_demo_guide.md @@ -81,7 +81,7 @@ init/ai-server/reference_data/squat_20kg_bar_reference.json - `frames[].squat_metrics`: 무릎 각도, 골반 각도, 상체 기울기, 골반 높이, 동작 단계, 반복 횟수 - `squat_analysis.reps_detected`: 감지된 스쿼트 반복 수 - `squat_analysis.current_phase`: 현재 동작 단계 -- `squat_analysis.quality_score`: 자세 품질 점수 +- `squat_analysis.quality_score`: `null` (검증된 단일 자세 점수 없음) - `squat_analysis.feedback`: 교정 피드백 문구 ## 촬영 가이드 diff --git a/ai-server/exercise_pb2.py b/ai-server/exercise_pb2.py index ef892d2c..7d045ee2 100644 --- a/ai-server/exercise_pb2.py +++ b/ai-server/exercise_pb2.py @@ -15,7 +15,7 @@ from google.protobuf import timestamp_pb2 as google_dot_protobuf_dot_timestamp__pb2 -DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0e\x65xercise.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"e\n\x0e\x45xtractRequest\x12\x13\n\x0b\x65xercise_id\x18\x01 \x01(\x03\x12\x13\n\x0byoutube_url\x18\x02 \x01(\t\x12)\n\x0f\x65xtracted_poses\x18\x03 \x03(\x0b\x32\x10.PoseDataRequest\"b\n\x0f\x45xtractResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x13\n\x0b\x65xercise_id\x18\x02 \x01(\x03\x12)\n\x0f\x65xtracted_poses\x18\x03 \x03(\x0b\x32\x10.PoseDataRequest\"\xa6\x01\n\x0e\x41nalyzeRequest\x12\x13\n\x0b\x65xercise_id\x18\x01 \x01(\x03\x12\x12\n\nsession_id\x18\x03 \x01(\x03\x12\x18\n\x10reference_source\x18\x02 \x01(\t\x12)\n\x0freference_poses\x18\x04 \x03(\x0b\x32\x10.PoseDataRequest\x12\x0f\n\x07persona\x18\x05 \x01(\t\x12\x15\n\rsession_nonce\x18\x06 \x01(\t\"\x9b\x01\n\x0f\x41nalyzeResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x12\n\nsession_id\x18\x02 \x01(\x03\x12\x13\n\x0b\x65xercise_id\x18\x03 \x01(\x03\x12.\n\nstart_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1e\n\x06status\x18\x05 \x01(\x0e\x32\x0e.SessionStatus\"\xbd\x01\n\x0fReattachRequest\x12\x13\n\x0b\x65xercise_id\x18\x01 \x01(\x03\x12\x12\n\nsession_id\x18\x02 \x01(\x03\x12)\n\x0freference_poses\x18\x03 \x03(\x0b\x32\x10.PoseDataRequest\x12\x0f\n\x07persona\x18\x04 \x01(\t\x12\x19\n\x11initial_rep_count\x18\x05 \x01(\x05\x12\x13\n\x0b\x65lapsed_sec\x18\x06 \x01(\x01\x12\x15\n\rsession_nonce\x18\x07 \x01(\t\"s\n\x10ReattachResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x12\n\nsession_id\x18\x02 \x01(\x03\x12\x11\n\trep_count\x18\x03 \x01(\x05\x12\x16\n\x0e\x61lready_active\x18\x04 \x01(\x08\x12\x0f\n\x07message\x18\x05 \x01(\t\"\xb8\x01\n\x16SessionCompleteRequest\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12\x12\n\ntotal_reps\x18\x02 \x01(\x05\x12\x15\n\ravg_sync_rate\x18\x03 \x01(\x01\x12\x15\n\rmax_sync_rate\x18\x04 \x01(\x01\x12\x15\n\rmin_sync_rate\x18\x05 \x01(\x01\x12\x17\n\x0f\x63\x61lories_burned\x18\x06 \x01(\x01\x12\x18\n\x10\x64ifficulty_level\x18\x07 \x01(\x05\"{\n\x17SessionCompleteResponse\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12\x1e\n\x06status\x18\x02 \x01(\x0e\x32\x0e.SessionStatus\x12,\n\x08\x65nd_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\xa1\x01\n\x0fPoseDataRequest\x12\x15\n\rtimestamp_sec\x18\x01 \x01(\x01\x12\x19\n\x11joint_coordinates\x18\x02 \x01(\t\x12\x11\n\tsync_rate\x18\x03 \x01(\x01\x12\x18\n\x10\x66\x65\x65\x64\x62\x61\x63k_message\x18\x04 \x01(\t\x12\x12\n\nrep_number\x18\x05 \x01(\x05\x12\x1b\n\x13smoothed_knee_angle\x18\x06 \x01(\x01\"O\n\x14PoseDataBatchRequest\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12#\n\tpose_data\x18\x02 \x03(\x0b\x32\x10.PoseDataRequest\"i\n\x10PoseDataResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x12\n\nsession_id\x18\x02 \x01(\x03\x12\x15\n\rtimestamp_sec\x18\x03 \x01(\x01\x12\x19\n\x11joint_coordinates\x18\x04 \x01(\t\"!\n\x0bStopRequest\x12\x12\n\nsession_id\x18\x01 \x01(\x03\"D\n\x0cStopResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x12\n\nsession_id\x18\x03 \x01(\x03\"\x89\x01\n\rFeedbackEvent\x12\x15\n\rfeedback_type\x18\x01 \x01(\t\x12\x1c\n\x14sync_rate_at_trigger\x18\x02 \x01(\x01\x12/\n\x0boccurred_at\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\nrep_number\x18\x04 \x01(\x05\"l\n\x14\x46\x65\x65\x64\x62\x61\x63kBatchRequest\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12\x0e\n\x06set_no\x18\x02 \x01(\x05\x12\x10\n\x08is_final\x18\x03 \x01(\x08\x12\x1e\n\x06\x65vents\x18\x04 \x03(\x0b\x32\x0e.FeedbackEvent\"@\n\x15\x46\x65\x65\x64\x62\x61\x63kBatchResponse\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12\x13\n\x0bsaved_count\x18\x02 \x01(\x05*;\n\rSessionStatus\x12\x0f\n\x0bIN_PROGRESS\x10\x00\x12\r\n\tCOMPLETED\x10\x01\x12\n\n\x06\x46\x41ILED\x10\x02\x32\xb2\x03\n\x0f\x45xerciseService\x12\x39\n\x14\x45xtractReferenceData\x12\x0f.ExtractRequest\x1a\x10.ExtractResponse\x12\x32\n\rStartAnalysis\x12\x0f.AnalyzeRequest\x1a\x10.AnalyzeResponse\x12\x37\n\x10ReattachAnalysis\x12\x10.ReattachRequest\x1a\x11.ReattachResponse\x12=\n\x11SavePoseDataBatch\x12\x15.PoseDataBatchRequest\x1a\x11.PoseDataResponse\x12\x45\n\x10\x43ompleteAnalysis\x12\x17.SessionCompleteRequest\x1a\x18.SessionCompleteResponse\x12+\n\x0cStopAnalysis\x12\x0c.StopRequest\x1a\r.StopResponse\x12\x44\n\x13ReportFeedbackBatch\x12\x15.FeedbackBatchRequest\x1a\x16.FeedbackBatchResponseB%\n\x12\x63om.shadowfit.grpcB\rExerciseProtoP\x01\x62\x06proto3') +DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\n\x0e\x65xercise.proto\x1a\x1fgoogle/protobuf/timestamp.proto\"e\n\x0e\x45xtractRequest\x12\x13\n\x0b\x65xercise_id\x18\x01 \x01(\x03\x12\x13\n\x0byoutube_url\x18\x02 \x01(\t\x12)\n\x0f\x65xtracted_poses\x18\x03 \x03(\x0b\x32\x10.PoseDataRequest\"b\n\x0f\x45xtractResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x13\n\x0b\x65xercise_id\x18\x02 \x01(\x03\x12)\n\x0f\x65xtracted_poses\x18\x03 \x03(\x0b\x32\x10.PoseDataRequest\"\xba\x01\n\x0e\x41nalyzeRequest\x12\x13\n\x0b\x65xercise_id\x18\x01 \x01(\x03\x12\x12\n\nsession_id\x18\x03 \x01(\x03\x12\x18\n\x10reference_source\x18\x02 \x01(\t\x12)\n\x0freference_poses\x18\x04 \x03(\x0b\x32\x10.PoseDataRequest\x12\x0f\n\x07persona\x18\x05 \x01(\t\x12\x15\n\rsession_nonce\x18\x06 \x01(\t\x12\x12\n\ndepth_mode\x18\x07 \x01(\t\"\x9b\x01\n\x0f\x41nalyzeResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x12\n\nsession_id\x18\x02 \x01(\x03\x12\x13\n\x0b\x65xercise_id\x18\x03 \x01(\x03\x12.\n\nstart_time\x18\x04 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x1e\n\x06status\x18\x05 \x01(\x0e\x32\x0e.SessionStatus\"\xd1\x01\n\x0fReattachRequest\x12\x13\n\x0b\x65xercise_id\x18\x01 \x01(\x03\x12\x12\n\nsession_id\x18\x02 \x01(\x03\x12)\n\x0freference_poses\x18\x03 \x03(\x0b\x32\x10.PoseDataRequest\x12\x0f\n\x07persona\x18\x04 \x01(\t\x12\x19\n\x11initial_rep_count\x18\x05 \x01(\x05\x12\x13\n\x0b\x65lapsed_sec\x18\x06 \x01(\x01\x12\x15\n\rsession_nonce\x18\x07 \x01(\t\x12\x12\n\ndepth_mode\x18\x08 \x01(\t\"s\n\x10ReattachResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x12\n\nsession_id\x18\x02 \x01(\x03\x12\x11\n\trep_count\x18\x03 \x01(\x05\x12\x16\n\x0e\x61lready_active\x18\x04 \x01(\x08\x12\x0f\n\x07message\x18\x05 \x01(\t\"\xb8\x01\n\x16SessionCompleteRequest\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12\x12\n\ntotal_reps\x18\x02 \x01(\x05\x12\x15\n\ravg_sync_rate\x18\x03 \x01(\x01\x12\x15\n\rmax_sync_rate\x18\x04 \x01(\x01\x12\x15\n\rmin_sync_rate\x18\x05 \x01(\x01\x12\x17\n\x0f\x63\x61lories_burned\x18\x06 \x01(\x01\x12\x18\n\x10\x64ifficulty_level\x18\x07 \x01(\x05\"{\n\x17SessionCompleteResponse\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12\x1e\n\x06status\x18\x02 \x01(\x0e\x32\x0e.SessionStatus\x12,\n\x08\x65nd_time\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\"\xe2\x01\n\x0fPoseDataRequest\x12\x15\n\rtimestamp_sec\x18\x01 \x01(\x01\x12\x19\n\x11joint_coordinates\x18\x02 \x01(\t\x12\x11\n\tsync_rate\x18\x03 \x01(\x01\x12\x18\n\x10\x66\x65\x65\x64\x62\x61\x63k_message\x18\x04 \x01(\t\x12\x12\n\nrep_number\x18\x05 \x01(\x05\x12\x1b\n\x13smoothed_knee_angle\x18\x06 \x01(\x01\x12\x10\n\x08lead_leg\x18\x07 \x01(\t\x12\x16\n\x0etorso_tilt_deg\x18\x08 \x01(\x01\x12\x15\n\rstagger_ratio\x18\t \x01(\x01\"O\n\x14PoseDataBatchRequest\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12#\n\tpose_data\x18\x02 \x03(\x0b\x32\x10.PoseDataRequest\"i\n\x10PoseDataResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x12\n\nsession_id\x18\x02 \x01(\x03\x12\x15\n\rtimestamp_sec\x18\x03 \x01(\x01\x12\x19\n\x11joint_coordinates\x18\x04 \x01(\t\"!\n\x0bStopRequest\x12\x12\n\nsession_id\x18\x01 \x01(\x03\"D\n\x0cStopResponse\x12\x0f\n\x07success\x18\x01 \x01(\x08\x12\x0f\n\x07message\x18\x02 \x01(\t\x12\x12\n\nsession_id\x18\x03 \x01(\x03\"\x89\x01\n\rFeedbackEvent\x12\x15\n\rfeedback_type\x18\x01 \x01(\t\x12\x1c\n\x14sync_rate_at_trigger\x18\x02 \x01(\x01\x12/\n\x0boccurred_at\x18\x03 \x01(\x0b\x32\x1a.google.protobuf.Timestamp\x12\x12\n\nrep_number\x18\x04 \x01(\x05\"l\n\x14\x46\x65\x65\x64\x62\x61\x63kBatchRequest\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12\x0e\n\x06set_no\x18\x02 \x01(\x05\x12\x10\n\x08is_final\x18\x03 \x01(\x08\x12\x1e\n\x06\x65vents\x18\x04 \x03(\x0b\x32\x0e.FeedbackEvent\"@\n\x15\x46\x65\x65\x64\x62\x61\x63kBatchResponse\x12\x12\n\nsession_id\x18\x01 \x01(\x03\x12\x13\n\x0bsaved_count\x18\x02 \x01(\x05*;\n\rSessionStatus\x12\x0f\n\x0bIN_PROGRESS\x10\x00\x12\r\n\tCOMPLETED\x10\x01\x12\n\n\x06\x46\x41ILED\x10\x02\x32\xb2\x03\n\x0f\x45xerciseService\x12\x39\n\x14\x45xtractReferenceData\x12\x0f.ExtractRequest\x1a\x10.ExtractResponse\x12\x32\n\rStartAnalysis\x12\x0f.AnalyzeRequest\x1a\x10.AnalyzeResponse\x12\x37\n\x10ReattachAnalysis\x12\x10.ReattachRequest\x1a\x11.ReattachResponse\x12=\n\x11SavePoseDataBatch\x12\x15.PoseDataBatchRequest\x1a\x11.PoseDataResponse\x12\x45\n\x10\x43ompleteAnalysis\x12\x17.SessionCompleteRequest\x1a\x18.SessionCompleteResponse\x12+\n\x0cStopAnalysis\x12\x0c.StopRequest\x1a\r.StopResponse\x12\x44\n\x13ReportFeedbackBatch\x12\x15.FeedbackBatchRequest\x1a\x16.FeedbackBatchResponseB%\n\x12\x63om.shadowfit.grpcB\rExerciseProtoP\x01\x62\x06proto3') _globals = globals() _builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals) @@ -23,40 +23,40 @@ if _descriptor._USE_C_DESCRIPTORS == False: _globals['DESCRIPTOR']._options = None _globals['DESCRIPTOR']._serialized_options = b'\n\022com.shadowfit.grpcB\rExerciseProtoP\001' - _globals['_SESSIONSTATUS']._serialized_start=1975 - _globals['_SESSIONSTATUS']._serialized_end=2034 + _globals['_SESSIONSTATUS']._serialized_start=2080 + _globals['_SESSIONSTATUS']._serialized_end=2139 _globals['_EXTRACTREQUEST']._serialized_start=51 _globals['_EXTRACTREQUEST']._serialized_end=152 _globals['_EXTRACTRESPONSE']._serialized_start=154 _globals['_EXTRACTRESPONSE']._serialized_end=252 _globals['_ANALYZEREQUEST']._serialized_start=255 - _globals['_ANALYZEREQUEST']._serialized_end=421 - _globals['_ANALYZERESPONSE']._serialized_start=424 - _globals['_ANALYZERESPONSE']._serialized_end=579 - _globals['_REATTACHREQUEST']._serialized_start=582 - _globals['_REATTACHREQUEST']._serialized_end=771 - _globals['_REATTACHRESPONSE']._serialized_start=773 - _globals['_REATTACHRESPONSE']._serialized_end=888 - _globals['_SESSIONCOMPLETEREQUEST']._serialized_start=891 - _globals['_SESSIONCOMPLETEREQUEST']._serialized_end=1075 - _globals['_SESSIONCOMPLETERESPONSE']._serialized_start=1077 - _globals['_SESSIONCOMPLETERESPONSE']._serialized_end=1200 - _globals['_POSEDATAREQUEST']._serialized_start=1203 - _globals['_POSEDATAREQUEST']._serialized_end=1364 - _globals['_POSEDATABATCHREQUEST']._serialized_start=1366 - _globals['_POSEDATABATCHREQUEST']._serialized_end=1445 - _globals['_POSEDATARESPONSE']._serialized_start=1447 - _globals['_POSEDATARESPONSE']._serialized_end=1552 - _globals['_STOPREQUEST']._serialized_start=1554 - _globals['_STOPREQUEST']._serialized_end=1587 - _globals['_STOPRESPONSE']._serialized_start=1589 - _globals['_STOPRESPONSE']._serialized_end=1657 - _globals['_FEEDBACKEVENT']._serialized_start=1660 - _globals['_FEEDBACKEVENT']._serialized_end=1797 - _globals['_FEEDBACKBATCHREQUEST']._serialized_start=1799 - _globals['_FEEDBACKBATCHREQUEST']._serialized_end=1907 - _globals['_FEEDBACKBATCHRESPONSE']._serialized_start=1909 - _globals['_FEEDBACKBATCHRESPONSE']._serialized_end=1973 - _globals['_EXERCISESERVICE']._serialized_start=2037 - _globals['_EXERCISESERVICE']._serialized_end=2471 + _globals['_ANALYZEREQUEST']._serialized_end=441 + _globals['_ANALYZERESPONSE']._serialized_start=444 + _globals['_ANALYZERESPONSE']._serialized_end=599 + _globals['_REATTACHREQUEST']._serialized_start=602 + _globals['_REATTACHREQUEST']._serialized_end=811 + _globals['_REATTACHRESPONSE']._serialized_start=813 + _globals['_REATTACHRESPONSE']._serialized_end=928 + _globals['_SESSIONCOMPLETEREQUEST']._serialized_start=931 + _globals['_SESSIONCOMPLETEREQUEST']._serialized_end=1115 + _globals['_SESSIONCOMPLETERESPONSE']._serialized_start=1117 + _globals['_SESSIONCOMPLETERESPONSE']._serialized_end=1240 + _globals['_POSEDATAREQUEST']._serialized_start=1243 + _globals['_POSEDATAREQUEST']._serialized_end=1469 + _globals['_POSEDATABATCHREQUEST']._serialized_start=1471 + _globals['_POSEDATABATCHREQUEST']._serialized_end=1550 + _globals['_POSEDATARESPONSE']._serialized_start=1552 + _globals['_POSEDATARESPONSE']._serialized_end=1657 + _globals['_STOPREQUEST']._serialized_start=1659 + _globals['_STOPREQUEST']._serialized_end=1692 + _globals['_STOPRESPONSE']._serialized_start=1694 + _globals['_STOPRESPONSE']._serialized_end=1762 + _globals['_FEEDBACKEVENT']._serialized_start=1765 + _globals['_FEEDBACKEVENT']._serialized_end=1902 + _globals['_FEEDBACKBATCHREQUEST']._serialized_start=1904 + _globals['_FEEDBACKBATCHREQUEST']._serialized_end=2012 + _globals['_FEEDBACKBATCHRESPONSE']._serialized_start=2014 + _globals['_FEEDBACKBATCHRESPONSE']._serialized_end=2078 + _globals['_EXERCISESERVICE']._serialized_start=2142 + _globals['_EXERCISESERVICE']._serialized_end=2576 # @@protoc_insertion_point(module_scope) diff --git a/ai-server/scripts/diagnose_squat_tracking.py b/ai-server/scripts/diagnose_squat_tracking.py new file mode 100644 index 00000000..93d11dab --- /dev/null +++ b/ai-server/scripts/diagnose_squat_tracking.py @@ -0,0 +1,123 @@ +"""Diagnose pose-tracking and squat-counter stages in existing video clips. + +Usage: python scripts/diagnose_squat_tracking.py clip1.mp4 clip2.mp4 +The default 3 fps and visibility threshold match evaluate_squat.py. +""" + +from __future__ import annotations + +import argparse +from collections import Counter +from dataclasses import asdict, replace +import json +import math +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import cv2 + +from app.core.mediapipe_detector import PoseDetector +from app.core.squat_counter import SquatCounter, SquatThresholds, observe_squat + + +JOINTS = { + 11: "left_shoulder", 12: "right_shoulder", + 23: "left_hip", 24: "right_hip", + 25: "left_knee", 26: "right_knee", + 27: "left_ankle", 28: "right_ankle", +} + + +def diagnose(video_path: Path, sample_fps: float, visibility: float) -> dict: + video = cv2.VideoCapture(str(video_path)) + source_fps = video.get(cv2.CAP_PROP_FPS) + if not video.isOpened() or not math.isfinite(source_fps) or source_fps <= 0: + video.release() + raise ValueError(f"Could not read video FPS: {video_path}") + detector = PoseDetector() + counter = SquatCounter(replace(SquatThresholds(), visibility=visibility)) + counts: Counter[str] = Counter() + low_joints: Counter[str] = Counter() + stages: Counter[str] = Counter() + transitions: list[dict] = [] + index = 0 + next_time = 0.0 + width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH)) + height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT)) + try: + while True: + ok, image = video.read() + if not ok: + break + timestamp = index / source_fps + index += 1 + if timestamp + 1e-9 < next_time: + continue + next_time = timestamp + 1 / sample_fps + landmarks = detector.detect(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) + if landmarks is None: + reason = "no_pose" + else: + by_index = {point.index: point for point in landmarks} + missing = [name for number, name in JOINTS.items() if number not in by_index] + low = [name for number, name in JOINTS.items() + if number in by_index and by_index[number].visibility < visibility] + low_joints.update(low) + try: + observe_squat(landmarks, width / height, visibility) + except ValueError: + reason = "missing_joint" if missing else "low_visibility" if low else "invalid_geometry" + else: + reason = "usable" + before = counter.stage + observation, _ = counter.update(landmarks, timestamp, width / height) + counts[reason] += 1 + stages[counter.stage] += 1 + if before != counter.stage: + transitions.append({"time_sec": round(timestamp, 3), + "from": before, "to": counter.stage, + "knee": round(observation.knee_angle, 1) if observation else None, + "hip": round(observation.hip_angle, 1) if observation else None, + "reps": counter.rep_count, + "guidance": counter.guidance}) + finally: + video.release() + detector.close() + sampled = sum(counts.values()) + usable = counts["usable"] + calibrated = sampled - stages["waiting_for_standing"] + return { + "video": str(video_path), "width": width, "height": height, + "source_fps": source_fps, "sample_fps": sample_fps, + "visibility_threshold": visibility, "sampled_frames": sampled, + "reasons": dict(counts), "low_visibility_joints": dict(low_joints), + "valid_frame_ratio": round(usable / sampled, 3) if sampled else 0, + "calibrated_frames": calibrated, + "evaluation_valid": calibrated > 0 and usable / sampled >= 0.7 if sampled else False, + "stage_frames": dict(stages), "stage_transitions": transitions, + "final_stage": counter.stage, "reps": counter.rep_count, + "thresholds": asdict(counter.thresholds), + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("videos", type=Path, nargs="+") + parser.add_argument("--sample-fps", type=float, default=3.0) + parser.add_argument("--visibility", type=float, default=SquatThresholds.visibility) + args = parser.parse_args() + if not math.isfinite(args.sample_fps) or args.sample_fps <= 0: + parser.error("sample-fps must be positive") + if not 0 <= args.visibility <= 1: + parser.error("visibility must be between 0 and 1") + if any(not video.is_file() for video in args.videos): + parser.error("Every video must exist") + print(json.dumps([diagnose(video, args.sample_fps, args.visibility) + for video in args.videos], ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ai-server/scripts/e1_walkthrough.py b/ai-server/scripts/e1_walkthrough.py index 2dcc441e..3ec5405e 100644 --- a/ai-server/scripts/e1_walkthrough.py +++ b/ai-server/scripts/e1_walkthrough.py @@ -39,7 +39,9 @@ from __future__ import annotations import argparse +import atexit import base64 +import math import sys import time @@ -73,7 +75,19 @@ def main() -> int: p.add_argument("--ai-token", required=True, help="AI_PUBLIC_TOKEN") p.add_argument("--exercise-id", type=int, default=1) p.add_argument("--fps", type=float, default=3.0, help="전송 프레임률 (앱과 같은 3fps)") + p.add_argument("--expected-reps", type=int, help="사람이 센 완료 횟수") + p.add_argument("--expect-complete-coaching", action="store_true", + help="완료 이벤트마다 화면용 자세 안내가 있는지도 검사") + p.add_argument("--depth-mode", choices=["full", "half"], default="full", + help="스쿼트 깊이 모드 (2026-09-21). 생략하면 기존과 동일한 full") + p.add_argument("--expected-depth-score-min", type=int, + help="리포트 squatDepthAnalysis.depthScore가 이 값 이상이어야 한다") + p.add_argument("--expected-depth-grade", + choices=["EXCELLENT", "GOOD", "FAIR", "NEEDS_WORK", "POOR"], + help="리포트 squatDepthAnalysis.depthGrade가 이 값과 정확히 일치해야 한다") args = p.parse_args() + if not math.isfinite(args.fps) or args.fps <= 0 or (args.expected_reps is not None and args.expected_reps < 0): + p.error("fps must be positive and expected-reps must be nonnegative") # 매 판 새 계정을 쓴다 — 같은 계정을 재사용하면 «이미 진행 중인 세션»(W005)에 걸려 # 두 번째 판부터 다른 것을 재게 된다. @@ -117,7 +131,8 @@ def main() -> int: # ── ② 세션 시작 (여기서 Spring → AI gRPC StartAnalysis 가 일어난다) ────── r = http.post(f"{args.spring}/exercises/sessions", - json={"exerciseId": args.exercise_id}, headers=auth) + json={"exerciseId": args.exercise_id, "depthMode": args.depth_mode.upper()}, + headers=auth) if r.status_code not in (200, 202): log("세션 시작 실패", f"{r.status_code} {r.text[:200]}") return 1 @@ -134,6 +149,20 @@ def main() -> int: session_nonce = session_body.get("sessionNonce") log("세션 시작", f"{r.status_code} sessionId={session_id} aiWorker={ai_worker}") + # CLI 자체가 예외로 끝나더라도 AI 검출기 lease 를 남기지 않는다. 이전에는 출력 인코딩 + # 오류 하나로 세션이 정리되지 않아 같은 워커의 다음 E1 이 풀 소진으로 실패했다. + cleanup = {"needed": True} + + def _end_session_on_exit() -> None: + if not cleanup["needed"]: + return + try: + http.patch(f"{args.spring}/sessions/{session_id}/end", headers=auth, timeout=10.0) + except Exception as exc: # 종료 중에는 원래 실패 원인을 가리지 않는다. + log("세션 자동 정리 실패", str(exc)[:160]) + + atexit.register(_end_session_on_exit) + # ── ②-1 AI 세션 배정 대기 ─────────────────────────────────────────────── # 세션 시작은 202 다 — Spring 이 받았다는 뜻이지 AI 가 배정을 끝냈다는 뜻이 아니다. # 배정 전에 프레임을 보내면 AI 는 200 + success=false 로 답한다("배정된 분석기가 없습니다"). @@ -149,21 +178,25 @@ def main() -> int: return 1 src_fps = cap.get(cv2.CAP_PROP_FPS) or 30.0 - step = max(1, int(round(src_fps / args.fps))) - log("영상", f"{args.video} ({src_fps:.1f}fps → {step}프레임마다 전송)") + log("영상", f"{args.video} ({src_fps:.2f}fps → {args.fps:g}fps 시각 기준 추출)") sent = detected = judged = 0 max_rep = 0 + complete_coaching = partial_coaching = 0 + last_send_at = None idx = 0 + next_sample_time = 0.0 skipped_msgs: dict[str, int] = {} while True: ok, frame = cap.read() if not ok: break - if idx % step: + timestamp = idx / src_fps + if timestamp + 1e-9 < next_sample_time: idx += 1 continue idx += 1 + next_sample_time = timestamp + 1 / args.fps ok, buf = cv2.imencode(".jpg", frame) if not ok: @@ -177,6 +210,11 @@ def main() -> int: # 첫 프레임은 AI 배정이 끝날 때까지 재시도한다(위 ②-1 참고). attempts = 12 if sent == 0 else 1 for attempt in range(attempts): + if last_send_at is not None: + remaining = last_send_at + 1 / args.fps - time.monotonic() + if remaining > 0: + time.sleep(remaining) + last_send_at = time.monotonic() rr = http.post(f"{args.ai}/api/v1/pose", json=payload, headers=ai_headers) if rr.status_code != 200: log("프레임 전송 실패", f"{rr.status_code} {rr.text[:160]}") @@ -190,6 +228,9 @@ def main() -> int: if attempt == 0: log("AI 배정 대기", str(body.get("message"))[:90]) time.sleep(1.0) + if sent == 0 and body.get("skip_reason") in _NOT_ASSIGNED_YET: + log("AI 배정 실패", "12회 재시도 후에도 분석기가 배정되지 않았다") + return 1 sent += 1 # landmarks 는 **스킵된 프레임에도 들어 있다.** 그게 #196 이 속은 지점이라 스킵보다 @@ -204,6 +245,11 @@ def main() -> int: continue if body.get("angles"): judged += 1 + if body.get("message"): + if body.get("rep_completed"): + complete_coaching += 1 + else: + partial_coaching += 1 rep = body.get("rep_count") or 0 if rep > max_rep: max_rep = rep @@ -213,12 +259,16 @@ def main() -> int: # 「검출 N/N」이 아니라 «판정에 들어간 프레임» 을 따로 센다 — 가시성 미달·속도 상한 프레임은 # landmarks 는 들어 있고 angles 가 없다. 둘을 같은 숫자로 세면 #196 처럼 오독한다. log("프레임 유입", f"전송 {sent} · 랜드마크 {detected} · 판정에 들어감 {judged} · rep {max_rep}회") + log("자세 안내", f"완료 {complete_coaching}건 · 깊이 미확인 {partial_coaching}건") for reason, n in skipped_msgs.items(): log(" 스킵", f"{n}회 — {reason}") # ── ④ 세션 종료 ───────────────────────────────────────────────────────── r = http.patch(f"{args.spring}/sessions/{session_id}/end", headers=auth) log("세션 종료", f"{r.status_code}") + if r.status_code != 200: + return 1 + cleanup["needed"] = False # ── ⑤ 리포트 ──────────────────────────────────────────────────────────── # 종료 PATCH 는 «클라가 끝냈다» 까지다. 리포트는 그 뒤 아웃박스 → AI → CompleteAnalysis @@ -237,18 +287,58 @@ def main() -> int: return 1 for key in ("totalReps", "avgSyncRate", "workoutMinutes", "caloriesBurned"): print(f" {key:<18} {report.get(key)}") - print(f" worstSection {report.get('worstSection')}") + worst = report.get("worstSection") or {} + print(f" worstSection rep={worst.get('repNumber')} reason={worst.get('reason')}") print(f" repTrend {len(report.get('repTrend') or [])}건") + depth = report.get("squatDepthAnalysis") or {} + if depth: + print(f" squatDepthAnalysis mode={depth.get('depthMode')} " + f"score={depth.get('depthScore')} grade={depth.get('depthGrade')}") + for line in depth.get("narrative") or []: + print(f" - {line}") + # 2026-10-05: 런지 깊이·체간 기울기·보폭 카드도 같이 본다 — 시연 전 «새 채점이 리포트까지 나오는가» + extra_blocks = { + "lungeDepthAnalysis": ("depthScore", "depthGrade"), + "squatTrunkLeanAnalysis": ("tiltScore", "tiltGrade"), + "lungeTrunkLeanAnalysis": ("tiltScore", "tiltGrade"), + "lungeStepLengthAnalysis": ("stepScore", "stepGrade"), + } + present_blocks = [] + for name, (score_key, grade_key) in extra_blocks.items(): + block = report.get(name) + if block: + present_blocks.append(name) + print(f" {name} score={block.get(score_key)} grade={block.get(grade_key)}") + for line in block.get("narrative") or []: + print(f" - {line}") # ── 판정 ──────────────────────────────────────────────────────────────── # 200 을 세지 않는다. #196 은 «전 구간 200 인데 전부 0» 이었다. problems = [] if max_rep == 0: problems.append("AI 가 rep 을 한 번도 완성하지 못했다 (영상이 못 쓰는 것이거나 #217)") + if args.expected_reps is not None and max_rep != args.expected_reps: + problems.append(f"검출 {max_rep}회가 사람 기준 {args.expected_reps}회와 다르다") + if args.expect_complete_coaching and complete_coaching != max_rep: + problems.append(f"완료 안내 {complete_coaching}건이 완료 횟수 {max_rep}회와 다르다") if not report.get("totalReps"): problems.append("리포트 totalReps 가 0 이다 (rep→콜백→적재 구간이 안 돌았다)") - if not report.get("avgSyncRate"): + # 런지(exercise-id 2)는 횟수만 측정해 avgSyncRate 가 의도적으로 비어 있다(V22 repetition_only). + if args.exercise_id == 1 and not report.get("avgSyncRate"): problems.append("avgSyncRate 가 0 이다 (정답지가 비었을 수 있다 — #192)") + expected_blocks = (["squatTrunkLeanAnalysis"] if args.exercise_id == 1 + else ["lungeDepthAnalysis", "lungeTrunkLeanAnalysis", "lungeStepLengthAnalysis"]) + for name in expected_blocks: + if name not in present_blocks: + problems.append(f"리포트에 {name} 가 없다 (배관이 안 돌았거나 해당 데이터가 비었다)") + if args.expected_depth_score_min is not None: + if not depth: + problems.append("리포트에 squatDepthAnalysis 가 없다 (스쿼트가 아니거나 깊이 데이터 없음)") + elif (depth.get("depthScore") or 0) < args.expected_depth_score_min: + problems.append( + f"깊이 점수 {depth.get('depthScore')}가 기대 최소값 {args.expected_depth_score_min} 미만이다") + if args.expected_depth_grade is not None and depth.get("depthGrade") != args.expected_depth_grade: + problems.append(f"깊이 등급 {depth.get('depthGrade')}가 기대값 {args.expected_depth_grade}와 다르다") print() if problems: @@ -261,4 +351,6 @@ def main() -> int: if __name__ == "__main__": + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") sys.exit(main()) diff --git a/ai-server/scripts/evaluate_aihub_keypoints.py b/ai-server/scripts/evaluate_aihub_keypoints.py new file mode 100644 index 00000000..bd8084cb --- /dev/null +++ b/ai-server/scripts/evaluate_aihub_keypoints.py @@ -0,0 +1,130 @@ +"""Replay AI Hub CrossFit 2D keypoints through the squat counter. + +This checks the counter only: AI Hub keypoints have no MediaPipe visibility score, +and a labeled action interval is not necessarily a verified rep-count label. + +python scripts/evaluate_aihub_keypoints.py TL.zip sample_annotation.json +""" + +from __future__ import annotations + +import argparse +from collections import Counter, defaultdict +import csv +import io +import json +from pathlib import Path +import sys +import zipfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +from app.core.squat_counter import SquatCounter +from app.models.pose import Landmark + + +JOINTS = ( + ("LShoulder", 11), ("RShoulder", 12), + ("LHip", 23), ("RHip", 24), + ("LKnee", 25), ("RKnee", 26), + ("LAnkle", 27), ("RAnkle", 28), +) +WIDTH, HEIGHT, SOURCE_FPS = 1920, 1080, 30 + + +def replay(handle) -> tuple[int, int, int, dict[str, int]]: + counter = SquatCounter() + stage_changes: Counter[str] = Counter() + sampled = usable = 0 + rows = csv.DictReader(io.TextIOWrapper(handle, encoding="utf-8-sig", newline="")) + for row in rows: + frame = int(Path(row["image_filename"]).stem) + if frame % 10 != 0: # AI Hub source is 30 fps; ShadowFit evaluates 3 fps. + continue + try: + points = [Landmark(index=index, x=float(row[name + "_x"]) / WIDTH, + y=float(row[name + "_y"]) / HEIGHT, z=0., visibility=1.) + for name, index in JOINTS] + except (KeyError, ValueError): + points = [] + before = counter.stage + observation, _ = counter.update(points, frame / SOURCE_FPS, WIDTH / HEIGHT) + sampled += 1 + usable += observation is not None + if before != counter.stage: + stage_changes[f"{before}->{counter.stage}"] += 1 + return sampled, usable, counter.rep_count, dict(stage_changes) + + +def evaluate(zip_path: Path, reference_annotation: Path) -> dict: + reference = json.loads(reference_annotation.read_text(encoding="utf-8-sig")) + category = reference["annotations"][0]["motion_category3"] + result_counts: Counter[int] = Counter() + camera_results: dict[str, Counter[int]] = defaultdict(Counter) + category_results: dict[str, Counter[int]] = defaultdict(Counter) + transitions: Counter[str] = Counter() + sessions: dict[str, list[int]] = defaultdict(list) + matched = missing_csv = unreadable = 0 + with zipfile.ZipFile(zip_path) as archive: + files = set(archive.namelist()) + for info in archive.infolist(): + if not info.filename.endswith("/video/annotation.json"): + continue + try: + annotation = json.loads(archive.read(info).decode("utf-8-sig")) + motions = annotation["annotations"] + if len(motions) != 1 or motions[0]["motion_category3"] != category: + continue + matched += 1 + camera_path = info.filename.rsplit("/video/", 1)[0] + camera = camera_path.rsplit("/", 1)[-1] + session = camera_path.rsplit("/", 1)[0] + stem = Path(annotation["video_name"]).stem + csv_name = f"{camera_path}/local_keypoints/{stem}.csv" + if csv_name not in files: + missing_csv += 1 + continue + with archive.open(csv_name) as handle: + _, _, reps, changes = replay(handle) + except (ValueError, KeyError, UnicodeError, csv.Error) as exc: + unreadable += 1 + print(f"Could not read {info.filename}: {exc}", file=sys.stderr) + continue + sessions[session].append(reps) + result_counts[reps] += 1 + camera_results[camera][reps] += 1 + category_results[motions[0]["motion_category4"]][reps] += 1 + transitions.update(changes) + return { + "matched_camera_labels": matched, + "evaluated_camera_labels": sum(result_counts.values()), + "unique_recordings": len(sessions), + "one_rep_views_per_recording": dict(sorted(Counter( + sum(reps == 1 for reps in views) for views in sessions.values() + ).items())), + "missing_csv": missing_csv, "unreadable": unreadable, + "rep_counts": dict(sorted(result_counts.items())), + "by_camera": {camera: dict(sorted(counts.items())) + for camera, counts in sorted(camera_results.items())}, + "by_form_label": {label: dict(sorted(counts.items())) + for label, counts in sorted(category_results.items())}, + "stage_transitions": dict(transitions), + "interpretation": "One action interval is a proxy, not a verified one-repetition label.", + } + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("zip_path", type=Path) + parser.add_argument("reference_annotation", type=Path, + help="Sample annotation.json selecting a motion category") + args = parser.parse_args() + if not args.zip_path.is_file() or not args.reference_annotation.is_file(): + parser.error("Both the archive and reference annotation must exist") + print(json.dumps(evaluate(args.zip_path, args.reference_annotation), + ensure_ascii=False, indent=2)) + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ai-server/scripts/evaluate_constrained_squat_set.py b/ai-server/scripts/evaluate_constrained_squat_set.py new file mode 100644 index 00000000..9bc8376f --- /dev/null +++ b/ai-server/scripts/evaluate_constrained_squat_set.py @@ -0,0 +1,132 @@ +"""Evaluate the fixed-condition squat demo set declared in one JSON manifest. + +The runner reuses evaluate_squat.py so offline and batch acceptance use the same +MediaPipe detector and SquatCounter. Paths in the manifest are resolved from the +repository root. +""" +from __future__ import annotations + +import argparse +import json +import math +import os +from pathlib import Path +import subprocess +import sys + + +def _nonnegative_int(value, field: str) -> int: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + raise ValueError(f"{field} must be a nonnegative integer") + return value + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("manifest", type=Path) + parser.add_argument("--output", type=Path, help="Write the aggregate JSON result") + args = parser.parse_args() + + if not args.manifest.is_file(): + parser.error("manifest does not exist") + try: + # PowerShell 5 writes UTF-8 JSON with a BOM by default; accept both forms. + manifest = json.loads(args.manifest.read_text(encoding="utf-8-sig")) + except (OSError, json.JSONDecodeError) as exc: + parser.error(f"could not read manifest: {exc}") + sample_fps = manifest.get("sample_fps", 3.0) + if isinstance(sample_fps, bool) or not isinstance(sample_fps, (int, float)) \ + or not math.isfinite(sample_fps) or sample_fps <= 0: + parser.error("sample_fps must be positive") + clips = manifest.get("clips") + if not isinstance(clips, list) or not clips: + parser.error("clips must be a non-empty list") + + repo_root = Path(__file__).resolve().parents[2] + evaluator = Path(__file__).with_name("evaluate_squat.py") + rows = [] + all_passed = True + for index, clip in enumerate(clips, 1): + if not isinstance(clip, dict): + parser.error(f"clips[{index}] must be an object") + try: + name = str(clip["name"]) + video_rel = Path(clip["video"]) + expected_reps = _nonnegative_int(clip["expected_reps"], "expected_reps") + expected_complete = _nonnegative_int( + clip["expected_complete_events"], "expected_complete_events" + ) + expected_partial = _nonnegative_int( + clip["expected_partial_events"], "expected_partial_events" + ) + except (KeyError, TypeError, ValueError) as exc: + parser.error(f"invalid clips[{index}]: {exc}") + video = video_rel if video_rel.is_absolute() else repo_root / video_rel + mismatches = [] + result = None + if not video.is_file(): + mismatches.append("video file is missing") + else: + env = os.environ.copy() + env["PYTHONPATH"] = str(repo_root / "ai-server") + env["PYTHONIOENCODING"] = "utf-8" + env["DEBUG"] = "false" + completed = subprocess.run( + [sys.executable, str(evaluator), str(video), + "--sample-fps", str(sample_fps), "--expected", str(expected_reps)], + cwd=repo_root, env=env, capture_output=True, text=True, encoding="utf-8", + ) + try: + result = json.loads(completed.stdout) + except json.JSONDecodeError: + mismatches.append(f"evaluator returned invalid JSON (exit={completed.returncode})") + if result is not None: + events = result.get("coaching_events") or [] + previous_rep = 0 + complete_events = 0 + partial_events = 0 + for event in events: + current_rep = int(event.get("rep_count") or 0) + if current_rep > previous_rep: + complete_events += 1 + previous_rep = current_rep + else: + partial_events += 1 + if not result.get("evaluation_valid"): + mismatches.append("less than 70% of sampled frames were usable or standing calibration failed") + if result.get("reps") != expected_reps: + mismatches.append(f"reps {result.get('reps')} != {expected_reps}") + if complete_events != expected_complete: + mismatches.append(f"complete events {complete_events} != {expected_complete}") + if partial_events != expected_partial: + mismatches.append(f"partial events {partial_events} != {expected_partial}") + else: + complete_events = partial_events = None + passed = not mismatches + all_passed = all_passed and passed + rows.append({ + "name": name, + "video": str(video_rel), + "passed": passed, + "expected_reps": expected_reps, + "actual_reps": result.get("reps") if result else None, + "expected_complete_events": expected_complete, + "actual_complete_events": complete_events if result else None, + "expected_partial_events": expected_partial, + "actual_partial_events": partial_events if result else None, + "mismatches": mismatches, + }) + + output = {"passed": all_passed, "sample_fps": sample_fps, "clips": rows} + rendered = json.dumps(output, ensure_ascii=False, indent=2) + print(rendered) + if args.output: + args.output.parent.mkdir(parents=True, exist_ok=True) + args.output.write_text(rendered + "\n", encoding="utf-8") + return 0 if all_passed else 1 + + +if __name__ == "__main__": + if hasattr(sys.stdout, "reconfigure"): + sys.stdout.reconfigure(encoding="utf-8") + raise SystemExit(main()) diff --git a/ai-server/scripts/evaluate_dataset.py b/ai-server/scripts/evaluate_dataset.py new file mode 100644 index 00000000..236aa4f1 --- /dev/null +++ b/ai-server/scripts/evaluate_dataset.py @@ -0,0 +1,173 @@ +"""Evaluate labeled squat/forward-lunge clips with the existing per-video analyzers. + +python scripts/evaluate_dataset.py ../samples/validation/labels.csv +Only clips with usable tracking and a human count contribute to accuracy metrics. +""" + +from __future__ import annotations + +import argparse +import csv +import json +import math +from pathlib import Path +import subprocess +import sys + + +INPUT_FIELDS = ( + "subject_id", "video", "exercise", "view", "mirrored", + "expected_total", "expected_left", "expected_right", "notes", +) +OUTPUT_FIELDS = ( + *INPUT_FIELDS, "evaluation_valid", "sampled_frames", "usable_frames", + "valid_frame_ratio", "detected_total", "detected_left", "detected_right", + "absolute_error", "left_absolute_error", "right_absolute_error", "error", +) +MIN_VALID_FRAME_RATIO = 0.7 # 스쿼트 단일 영상 평가기와 같은 운영상 품질 기준 + + +def count(value: str, field: str, line: int) -> int | None: + if not value.strip(): + return None + try: + result = int(value) + except ValueError as exc: + raise ValueError(f"{line}행 {field}: 0 이상의 정수를 입력해주세요.") from exc + if result < 0: + raise ValueError(f"{line}행 {field}: 0 이상의 정수를 입력해주세요.") + return result + + +def load_manifest(path: Path) -> list[tuple[dict[str, str], Path, tuple[int | None, int | None, int | None]]]: + with path.open(newline="", encoding="utf-8-sig") as handle: + reader = csv.DictReader(handle) + missing = set(INPUT_FIELDS) - set(reader.fieldnames or []) + if missing: + raise ValueError(f"CSV 열이 없습니다: {', '.join(sorted(missing))}") + clips = [] + for line, source in enumerate(reader, start=2): + row = {field: (source[field] or "").strip() for field in INPUT_FIELDS} + if not all(row[field] for field in ("subject_id", "video", "exercise", "view")): + raise ValueError(f"{line}행: subject_id, video, exercise, view가 필요합니다.") + if row["exercise"] not in ("squat", "lunge"): + raise ValueError(f"{line}행 exercise: squat 또는 lunge만 지원합니다.") + if row["mirrored"].lower() not in ("true", "false"): + raise ValueError(f"{line}행 mirrored: true 또는 false를 입력해주세요.") + row["mirrored"] = row["mirrored"].lower() + expected = tuple(count(row[field], field, line) for field in + ("expected_total", "expected_left", "expected_right")) + total, left, right = expected + if row["exercise"] == "squat" and (left is not None or right is not None): + raise ValueError(f"{line}행: 스쿼트는 좌우 정답을 비워주세요.") + if row["exercise"] == "lunge" and ( + (left is None) != (right is None) + or (total is not None and (left is None or total != left + right)) + ): + raise ValueError(f"{line}행: 런지 좌우 정답을 모두 쓰고 총횟수를 합계와 맞춰주세요.") + if row["exercise"] == "lunge" and total is None and left is not None and right is not None: + row["expected_total"] = str(left + right) + expected = (left + right, left, right) + video = Path(row["video"]) + if not video.is_absolute(): + video = path.parent / video + if not video.is_file(): + raise ValueError(f"{line}행: 영상 파일이 없습니다: {video}") + clips.append((row, video, expected)) + if not clips: + raise ValueError("CSV에 영상 행이 없습니다.") + return clips + + +def evaluate(row: dict[str, str], video: Path, + expected: tuple[int | None, int | None, int | None], sample_fps: float) -> dict: + total, left, right = expected + script = Path(__file__).with_name( + "evaluate_squat.py" if row["exercise"] == "squat" else "evaluate_lunge.py" + ) + command = [sys.executable, str(script), str(video), "--sample-fps", str(sample_fps)] + if row["exercise"] == "squat" and total is not None: + command.extend(("--expected", str(total))) + if row["exercise"] == "lunge" and left is not None and right is not None: + command.extend(("--expected-left", str(left), "--expected-right", str(right))) + for attempt in range(2): + process = subprocess.run(command, capture_output=True, text=True, check=False) + try: + result = json.loads(process.stdout) + break + except json.JSONDecodeError: + if attempt == 1: + detail = (process.stderr or process.stdout)[-400:] or "평가 출력이 JSON이 아닙니다." + return {**row, "error": f"평가 프로세스 종료 코드 {process.returncode}: {detail}"} + sampled = result.get("sampled_frames", result.get("analyzed_frames", 0)) + usable = result.get("usable_frames", 0) + valid_ratio = usable / sampled if sampled else 0 + evaluation_valid = bool(result.get("evaluation_valid")) and valid_ratio >= MIN_VALID_FRAME_RATIO + output = { + **row, + "evaluation_valid": evaluation_valid, + "sampled_frames": sampled, + "usable_frames": usable, + "valid_frame_ratio": round(valid_ratio, 3), + "detected_total": result.get("reps", result.get("total_reps")), + "detected_left": result.get("left_reps", ""), + "detected_right": result.get("right_reps", ""), + "absolute_error": result.get("absolute_error", "") if evaluation_valid else "", + "left_absolute_error": result.get("left_absolute_error", "") if evaluation_valid else "", + "right_absolute_error": result.get("right_absolute_error", "") if evaluation_valid else "", + "error": "" if process.returncode in (0, 2) else process.stderr[-400:], + } + if row["exercise"] == "lunge" and row["mirrored"] == "true": + # 영상이 좌우 반전되면 탐지기의 좌우가 참가자의 실제 좌우와 바뀔 수 있다. + # 총횟수만 자동 비교하고 좌우 오차는 원본 방향 확인 후 수동으로 해석한다. + output["left_absolute_error"] = output["right_absolute_error"] = "" + return output + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("manifest", type=Path) + parser.add_argument("--output", type=Path) + parser.add_argument("--sample-fps", type=float, default=3.0) + args = parser.parse_args() + if not math.isfinite(args.sample_fps) or args.sample_fps <= 0: + parser.error("sample-fps는 양수여야 합니다.") + try: + clips = load_manifest(args.manifest.resolve()) + except (OSError, ValueError) as exc: + parser.error(str(exc)) + + results = [] + for row, video, expected in clips: + print(f"Evaluating: {row['video']} ({row['exercise']})", file=sys.stderr) + results.append(evaluate(row, video, expected, args.sample_fps)) + output = args.output or args.manifest.with_name("results.csv") + with output.open("w", newline="", encoding="utf-8-sig") as handle: + writer = csv.DictWriter(handle, fieldnames=OUTPUT_FIELDS) + writer.writeheader() + writer.writerows(results) + + labeled = [r for r in results if r.get("evaluation_valid") and not r.get("error") + and r["expected_total"].strip()] + errors = [int(r["absolute_error"]) for r in labeled] + sided = [r for r in labeled if r["exercise"] == "lunge" and r["mirrored"] == "false"] + left_errors = [int(r["left_absolute_error"]) for r in sided] + right_errors = [int(r["right_absolute_error"]) for r in sided] + print(json.dumps({ + "clips": len(results), + "evaluation_valid": sum(bool(r.get("evaluation_valid")) for r in results), + "labeled_valid_clips": len(labeled), + "exact_match_clips": sum(error == 0 for error in errors), + "mean_absolute_error": round(sum(errors) / len(errors), 3) if errors else None, + "lunge_side_labeled_clips": len(sided), + "lunge_both_sides_exact_clips": sum(l == 0 and r == 0 for l, r in zip(left_errors, right_errors)), + "mean_left_absolute_error": round(sum(left_errors) / len(left_errors), 3) if left_errors else None, + "mean_right_absolute_error": round(sum(right_errors) / len(right_errors), 3) if right_errors else None, + "processing_errors": sum(bool(r.get("error")) for r in results), + "output": str(output), + }, ensure_ascii=False, indent=2)) + return 1 if any(r.get("error") for r in results) else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ai-server/scripts/evaluate_lunge.py b/ai-server/scripts/evaluate_lunge.py new file mode 100644 index 00000000..ca5b3dba --- /dev/null +++ b/ai-server/scripts/evaluate_lunge.py @@ -0,0 +1,104 @@ +"""전방 런지 촬영본을 같은 분석기로 재생하고 수동 정답과 비교한다. + +python scripts/evaluate_lunge.py clip.mp4 --expected-left 5 --expected-right 5 +카메라를 열거나 영상을 외부로 전송하지 않는다. 고정 FPS 영상만 지원한다. +""" +import argparse +import csv +from dataclasses import asdict +import json +import math +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import cv2 + +from app.core.lunge_analyzer import StreamingLungeAnalyzer +from app.core.mediapipe_detector import PoseDetector +from app.grpc.session_state import SessionState + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("video", type=Path) + parser.add_argument("--sample-fps", type=float, default=3.0) + parser.add_argument("--expected-left", type=int) + parser.add_argument("--expected-right", type=int) + parser.add_argument("--trace", type=Path, help="프레임별 단계/각도/횟수 CSV 출력") + args = parser.parse_args() + if not args.video.is_file(): + parser.error("로컬 영상 파일이 필요합니다.") + if not math.isfinite(args.sample_fps) or args.sample_fps <= 0: + parser.error("sample-fps는 양수여야 합니다.") + if (args.expected_left is None) != (args.expected_right is None): + parser.error("좌우 정답을 모두 입력해주세요.") + if any(n is not None and n < 0 for n in (args.expected_left, args.expected_right)): + parser.error("정답 횟수는 0 이상이어야 합니다.") + + video = cv2.VideoCapture(str(args.video)) + fps = video.get(cv2.CAP_PROP_FPS) + if not video.isOpened() or not math.isfinite(fps) or fps <= 0: + video.release() + parser.error("영상 FPS를 읽지 못했습니다.") + state = SessionState(0, 2, exercise_type="lunge") + analyzer = StreamingLungeAnalyzer() + trace_file = args.trace.open("w", newline="", encoding="utf-8") if args.trace else None + writer = csv.writer(trace_file) if trace_file else None + if writer: + writer.writerow(["time_sec", "phase", "lead_leg", "left_knee", "right_knee", "total", "left", "right"]) + detector = None + index, accepted, skipped, calibrated, next_time = 0, 0, 0, 0, 0. + try: + detector = PoseDetector() + while True: + ok, image = video.read() + if not ok: + break + timestamp = index / fps + index += 1 + if timestamp + 1e-9 < next_time: + continue + next_time = timestamp + 1 / args.sample_fps + landmarks = detector.detect(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) or [] + angles, _, _, _, _ = analyzer.process_frame( + state, landmarks, timestamp_sec=timestamp, + image_aspect_ratio=image.shape[1] / image.shape[0], + ) + accepted += 1 + skipped += angles is None + s = state.lunge_state + calibrated += s.phase != "calibrating" + if writer: + writer.writerow([round(timestamp, 3), s.phase, s.lead_leg, + *(angles or [None, None]), state.rep_count, s.left_reps, s.right_reps]) + finally: + video.release() + if detector: + detector.close() + if trace_file: + trace_file.close() + if not accepted: + parser.error("읽을 수 있는 영상 프레임이 없습니다.") + progress = state.lunge_state.progress() + result = { + "video": str(args.video), "source_fps": fps, "sample_fps": args.sample_fps, + "analyzed_frames": accepted, "unusable_frames": skipped, + "usable_frames": accepted - skipped, "calibrated_frames": calibrated, + "evaluation_valid": calibrated > 0, + "total_reps": state.rep_count, "left_reps": progress.left_reps, + "right_reps": progress.right_reps, "thresholds": asdict(analyzer.thresholds), + } + if args.expected_left is not None: + result["expected_total"] = args.expected_left + args.expected_right + # 시작 자세를 한 번도 확보하지 못한 영상을 '정확도 100%, 0회'로 해석하지 않는다. + result["absolute_error"] = abs(state.rep_count - result["expected_total"]) if calibrated else None + result["left_absolute_error"] = abs(progress.left_reps - args.expected_left) if calibrated else None + result["right_absolute_error"] = abs(progress.right_reps - args.expected_right) if calibrated else None + print(json.dumps(result, ensure_ascii=False, indent=2)) + return 0 if calibrated else 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ai-server/scripts/evaluate_squat.py b/ai-server/scripts/evaluate_squat.py new file mode 100644 index 00000000..17e6a776 --- /dev/null +++ b/ai-server/scripts/evaluate_squat.py @@ -0,0 +1,108 @@ +"""Replay a labeled side-view squat clip through the streaming repetition counter. + +python scripts/evaluate_squat.py clip.mp4 --expected 5 --trace squat-trace.csv +""" +import argparse +import csv +from dataclasses import asdict +import json +import math +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import cv2 + +from app.core.mediapipe_detector import PoseDetector +from app.core.squat_counter import DEPTH_MODE_THRESHOLDS, SquatCounter + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("video", type=Path) + parser.add_argument("--sample-fps", type=float, default=3.0) + parser.add_argument("--expected", type=int, help="Human-counted repetitions") + parser.add_argument("--trace", type=Path, help="Per-sampled-frame CSV") + parser.add_argument("--depth-mode", choices=["FULL", "HALF"], default="FULL", + help="Squat depth mode thresholds (2026-09-21). HALF's bottom_hip/" + "min_hip_drop are unvalidated against real footage -- see " + "docs/decisions/squat-repetition-counting.md") + args = parser.parse_args() + if not args.video.is_file(): + parser.error("Video file does not exist") + if not math.isfinite(args.sample_fps) or args.sample_fps <= 0: + parser.error("sample-fps must be positive") + if args.expected is not None and args.expected < 0: + parser.error("expected count must be nonnegative") + + video = cv2.VideoCapture(str(args.video)) + fps = video.get(cv2.CAP_PROP_FPS) + if not video.isOpened() or not math.isfinite(fps) or fps <= 0: + video.release() + parser.error("Could not read video FPS") + detector = PoseDetector() + counter = SquatCounter(DEPTH_MODE_THRESHOLDS[args.depth_mode]) + trace = args.trace.open("w", newline="", encoding="utf-8") if args.trace else None + writer = csv.writer(trace) if trace else None + if writer: + writer.writerow(["time_sec", "stage", "phase", "left_knee", "right_knee", + "left_hip", "right_hip", "reps", "guidance", "coaching_event"]) + index = sampled = usable = calibrated = 0 + coaching_events = [] + next_time = 0.0 + try: + while True: + ok, image = video.read() + if not ok: + break + timestamp = index / fps + index += 1 + if timestamp + 1e-9 < next_time: + continue + next_time = timestamp + 1 / args.sample_fps + landmarks = detector.detect(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) + observation, _ = counter.update( + landmarks, timestamp, image.shape[1] / image.shape[0] + ) + sampled += 1 + usable += observation is not None + calibrated += counter.stage != "waiting_for_standing" + if counter.coaching_event: + coaching_events.append({"time_sec": round(timestamp, 3), + "message": counter.coaching_event, + "rep_count": counter.rep_count}) + if writer: + side_angles = ([round(observation.knees[side], 2) + if observation.visible_sides[side] else None + for side in (0, 1)] + + [round(observation.hips[side], 2) + if observation.visible_sides[side] else None + for side in (0, 1)]) if observation else [None] * 4 + writer.writerow([round(timestamp, 3), counter.stage, counter.phase, + *side_angles, + counter.rep_count, counter.guidance, + counter.coaching_event or ""]) + finally: + video.release() + detector.close() + if trace: + trace.close() + valid_ratio = usable / sampled if sampled else 0.0 + evaluation_valid = calibrated > 0 and valid_ratio >= 0.7 + result = {"video": str(args.video), "source_fps": fps, + "sample_fps": args.sample_fps, "sampled_frames": sampled, + "usable_frames": usable, "calibrated_frames": calibrated, + "valid_frame_ratio": round(valid_ratio, 3), + "evaluation_valid": evaluation_valid, "reps": counter.rep_count, + "coaching_events": coaching_events, + "thresholds": asdict(counter.thresholds)} + if args.expected is not None: + result["expected"] = args.expected + result["absolute_error"] = abs(counter.rep_count - args.expected) if evaluation_valid else None + print(json.dumps(result, ensure_ascii=False, indent=2)) + return 0 if evaluation_valid else 2 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ai-server/scripts/export_landmarks.py b/ai-server/scripts/export_landmarks.py new file mode 100644 index 00000000..d329bd48 --- /dev/null +++ b/ai-server/scripts/export_landmarks.py @@ -0,0 +1,91 @@ +"""실촬영 영상을 3fps 로 재생해 «앱이 받는 것과 같은 모양» 의 좌표 기록(JSON)으로 내보낸다. + +python scripts/export_landmarks.py squat ../samples/validation/2026-09-21/squat_normal_01.mp4 out.json +python scripts/export_landmarks.py lunge ../samples/validation/lunge_normal_01.mp4 out.json + +3D 운동 비교(frontend/lib/motion)를 «실제 데이터» 로 검증하려는 용도다. 앱은 AI 응답의 +landmarks·image_aspect_ratio·rep_count 를 프레임마다 기록하는데, 이 스크립트는 같은 분석기 +(SquatCounter / StreamingLungeAnalyzer)를 돌려 같은 값을 만든다 — 폰 없이 파이프라인을 시험한다. + +출력 형식 (frontend/lib/motion/types.ts 의 MotionRecording): + {"exercise": "squat", "source": "...", "aspect": 0.5625, + "frames": [{"t": 0.0, "lm": [[x,y,z,v] × 33], "reps": 0, "lead": null}, ...]} +""" +import json +import math +from pathlib import Path +import sys + +sys.path.insert(0, str(Path(__file__).resolve().parents[1])) + +import cv2 + +from app.core.lunge_analyzer import StreamingLungeAnalyzer +from app.core.mediapipe_detector import PoseDetector +from app.core.squat_counter import SquatCounter +from app.grpc.session_state import SessionState + +SAMPLE_FPS = 3.0 + + +def export(exercise: str, video_path: Path) -> dict: + video = cv2.VideoCapture(str(video_path)) + fps = video.get(cv2.CAP_PROP_FPS) + if not video.isOpened() or not math.isfinite(fps) or fps <= 0: + raise SystemExit(f"영상을 열 수 없습니다: {video_path}") + detector = PoseDetector() + counter = SquatCounter() if exercise == "squat" else None + state = SessionState(0, 2, exercise_type="lunge") if exercise == "lunge" else None + analyzer = StreamingLungeAnalyzer() if exercise == "lunge" else None + frames, aspect = [], None + index, next_time = 0, 0.0 + try: + while True: + ok, image = video.read() + if not ok: + break + timestamp = index / fps + index += 1 + if timestamp + 1e-9 < next_time: + continue + next_time = timestamp + 1 / SAMPLE_FPS + aspect = image.shape[1] / image.shape[0] + landmarks = detector.detect(cv2.cvtColor(image, cv2.COLOR_BGR2RGB)) + if exercise == "squat": + counter.update(landmarks, timestamp, aspect) + reps, lead = counter.rep_count, None + else: + analyzer.process_frame(state, landmarks or [], timestamp_sec=timestamp, + image_aspect_ratio=aspect) + reps, lead = state.rep_count, state.lunge_state.lead_leg + if not landmarks: + frames.append({"t": round(timestamp, 3), "lm": None, "reps": reps, "lead": lead}) + continue + frames.append({ + "t": round(timestamp, 3), + "lm": [[round(p.x, 4), round(p.y, 4), round(p.z, 4), round(p.visibility, 3)] + for p in landmarks], + "reps": reps, "lead": lead, + }) + finally: + video.release() + detector.close() + return {"exercise": exercise, "source": video_path.name, "aspect": round(aspect or 0, 4), + "frames": frames} + + +def main() -> int: + if len(sys.argv) != 4 or sys.argv[1] not in ("squat", "lunge"): + print(__doc__) + return 2 + result = export(sys.argv[1], Path(sys.argv[2])) + Path(sys.argv[3]).write_text(json.dumps(result, ensure_ascii=False, separators=(",", ":")), + encoding="utf-8") + detected = sum(f["lm"] is not None for f in result["frames"]) + print(f"{result['source']}: {len(result['frames'])}프레임 중 {detected} 검출, " + f"횟수 {result['frames'][-1]['reps']}, 비율 {result['aspect']}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/ai-server/scripts/run_squat_demo.py b/ai-server/scripts/run_squat_demo.py index 9ae971f7..96fa87ab 100644 --- a/ai-server/scripts/run_squat_demo.py +++ b/ai-server/scripts/run_squat_demo.py @@ -26,7 +26,7 @@ def main() -> None: print(f"Video: {Path(args.video).resolve()}") print(f"Detected reps: {summary.get('reps_detected', 0)}") print(f"Current phase: {summary.get('current_phase', 'unknown')}") - print(f"Quality score: {summary.get('quality_score', 0)}") + print("Quality score: unavailable (no validated scalar score)") print(f"Feedback: {', '.join(summary.get('feedback', []))}") if args.output: diff --git a/ai-server/tests/test_analyzer_registry.py b/ai-server/tests/test_analyzer_registry.py index 0771c3ff..be154cc0 100644 --- a/ai-server/tests/test_analyzer_registry.py +++ b/ai-server/tests/test_analyzer_registry.py @@ -12,6 +12,7 @@ from __future__ import annotations import grpc +from unittest.mock import patch import exercise_pb2 from app.core.analyzer_registry import ( @@ -22,7 +23,7 @@ from app.grpc.exercise_servicer import ExerciseServicer SQUAT_ID = 1 -LUNGE_ID = 2 # 시드에는 있지만 분석기가 없다 +PLANK_ID = 3 # 시드에는 있지만 분석기가 없다 class _FakeContext: @@ -67,16 +68,16 @@ def test_스쿼트는_분석기가_있다(): assert get_analyzer("squat") is not None -def test_런지는_분석기가_없어_None(): - assert resolve_exercise_type(LUNGE_ID) is None +def test_플랭크는_분석기가_없어_None(): + assert resolve_exercise_type(PLANK_ID) is None def test_매핑에_없는_id_는_None(): assert resolve_exercise_type(9999) is None -def test_지원_목록에_스쿼트만_들어_있다(): - assert supported_exercise_ids() == [SQUAT_ID] +def test_지원_목록에_스쿼트와_런지가_들어_있다(): + assert supported_exercise_ids() == [SQUAT_ID, 2] def test_각도_정의만_있는_종목은_통과하지_않는다(): @@ -103,13 +104,13 @@ def test_StartAnalysis_는_미지원_종목을_abort_로_거절한다(): servicer = ExerciseServicer() context = _FakeContext() request = exercise_pb2.AnalyzeRequest( - exercise_id=LUNGE_ID, session_id=1234, persona="BEGINNER" + exercise_id=PLANK_ID, session_id=1234, persona="BEGINNER" ) _assert_aborted(lambda: servicer.StartAnalysis(request, context)) assert context.abort_code == grpc.StatusCode.INVALID_ARGUMENT - assert str(LUNGE_ID) in context.abort_details + assert str(PLANK_ID) in context.abort_details def test_StartAnalysis_는_거절_시_세션_상태를_만들지_않는다(): @@ -120,7 +121,7 @@ def test_StartAnalysis_는_거절_시_세션_상태를_만들지_않는다(): context = _FakeContext() session_id = 4321 request = exercise_pb2.AnalyzeRequest( - exercise_id=LUNGE_ID, session_id=session_id, persona="BEGINNER" + exercise_id=PLANK_ID, session_id=session_id, persona="BEGINNER" ) _assert_aborted(lambda: servicer.StartAnalysis(request, context)) @@ -128,6 +129,29 @@ def test_StartAnalysis_는_거절_시_세션_상태를_만들지_않는다(): assert get_registry().get(session_id) is None +def test_StartAnalysis_는_검출기_풀_소진을_abort_로_거절한다(): + """success=False 응답은 Spring 이 성공으로 삼키므로 RESOURCE_EXHAUSTED 여야 한다.""" + + class _ExhaustedPool: + def status(self): + return 1, 1 + + def acquire(self, _session_id): + return False + + servicer = ExerciseServicer() + context = _FakeContext() + session_id = 9876 + request = exercise_pb2.AnalyzeRequest( + exercise_id=SQUAT_ID, session_id=session_id, persona="BEGINNER" + ) + + with patch("app.grpc.exercise_servicer.get_pool", return_value=_ExhaustedPool()): + _assert_aborted(lambda: servicer.StartAnalysis(request, context)) + + assert context.abort_code == grpc.StatusCode.RESOURCE_EXHAUSTED + + # ─── ReattachAnalysis — success=False 로 거절 ────────────────────────────────── @@ -140,10 +164,14 @@ def test_ReattachAnalysis_는_미지원_종목을_success_False_로_거절한다 servicer = ExerciseServicer() context = _FakeContext() request = exercise_pb2.ReattachRequest( - exercise_id=LUNGE_ID, session_id=555, initial_rep_count=3 + exercise_id=PLANK_ID, session_id=555, initial_rep_count=3 ) response = servicer.ReattachAnalysis(request, context) assert response.success is False - assert context.abort_code is None # abort 로 끊지 않았다 \ No newline at end of file + assert context.abort_code is None # abort 로 끊지 않았다 + +def test_forward_lunge_is_registered(): + assert resolve_exercise_type(2) == "lunge" + assert get_analyzer("lunge") is not None diff --git a/ai-server/tests/test_bottom_dwell_measurement.py b/ai-server/tests/test_bottom_dwell_measurement.py index 21303743..42472059 100644 --- a/ai-server/tests/test_bottom_dwell_measurement.py +++ b/ai-server/tests/test_bottom_dwell_measurement.py @@ -65,8 +65,8 @@ def _count_reps(descent: float, hold: float, ascent: float | None = None) -> int total = _LEAD_SEC + descent + hold + ascent + _TAIL_SEC for k in range(int(total * _FPS) + 1): now = k / _FPS - angles, _, rep_event = analyzer.process_frame( - state, _frame(_knee_angle_at(now, descent, hold, ascent)) + angles, _, rep_event, _, _ = analyzer.process_frame( + state, _frame(_knee_angle_at(now, descent, hold, ascent)), timestamp_sec=now ) if angles is not None: state.current_rep_frames.append( @@ -139,9 +139,11 @@ def _bottom_count(self, descent: float, hold: float) -> int: total = _LEAD_SEC + descent + hold + descent + _TAIL_SEC for k in range(int(total * _FPS) + 1): analyzer.process_frame( - state, _frame(_knee_angle_at(k / _FPS, descent, hold, descent)) + state, _frame(_knee_angle_at(k / _FPS, descent, hold, descent)), timestamp_sec=k / _FPS ) - peak = max(peak, state.bottom_frame_count) + counter = state.squat_counter + if counter.stage == "bottom" and counter.bottom_since is not None: + peak = max(peak, round((k / _FPS - counter.bottom_since) * _FPS) + 1) return peak def test_dwell_count_barely_moves_with_pace(self) -> None: @@ -171,4 +173,4 @@ def test_dwell_count_tracks_actual_hold(self) -> None: if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main() diff --git a/ai-server/tests/test_exercise_separation.py b/ai-server/tests/test_exercise_separation.py new file mode 100644 index 00000000..8129289d --- /dev/null +++ b/ai-server/tests/test_exercise_separation.py @@ -0,0 +1,134 @@ +"""스쿼트를 골랐을 때 런지를, 런지를 골랐을 때 스쿼트를 세지 않는지 (2026-10-19). + +시연 중 «런지 선택 → 스쿼트 동작» 과 «스쿼트 선택 → 런지 동작» 이 둘 다 횟수·점수로 +잡히던 문제의 회귀 테스트다. 판정 근거는 app/core/stance.py 의 docstring 참고. + +좌표는 합성이다 — 카메라 정확도를 재는 테스트가 아니라 «두 자세를 서로의 분석기가 +거절하는가» 를 고정하는 테스트다. 실촬영 확인은 stance.py 의 측정 표가 담당한다. +""" +import math + +from app.core.lunge_analyzer import StreamingLungeAnalyzer +from app.core.squat_analyzer import StreamingSquatAnalyzer +from app.core.squat_counter import SquatCounter, observe_squat +from app.core.stance import stance_features +from app.grpc.session_state import SessionState +from app.models.pose import Landmark + +# 몸통(어깨↔골반) 0.25, 측면에서 오른쪽(+x)을 보고 선 사람. +_LUNGE_STAND = { + 11: (.43, .25), 12: (.43, .25), 23: (.43, .50), 24: (.43, .50), + 25: (.525, .70), 26: (.335, .70), 27: (.62, .90), 28: (.24, .90), +} +_LUNGE_BOTTOM = { + 11: (.42, .45), 12: (.42, .45), 23: (.42, .70), 24: (.42, .70), + 25: (.62, .70), 26: (.42, .88), 27: (.62, .90), 28: (.24, .90), +} +# 45°쯤에서 찍은 스쿼트처럼 두 발목이 가로로 벌어져 보이지만(간격/몸통 ≈ 0.96) +# 두 허벅지는 같은 방향·같은 각도로 굽는다. +_SQUAT_STAND = { + 11: (.47, .25), 12: (.53, .25), 23: (.47, .50), 24: (.53, .50), + 25: (.44, .70), 26: (.62, .70), 27: (.40, .90), 28: (.64, .90), +} +_SQUAT_BOTTOM = { + 11: (.50, .47), 12: (.56, .47), 23: (.38, .68), 24: (.44, .68), + 25: (.56, .70), 26: (.62, .70), 27: (.40, .90), 28: (.64, .90), +} + + +def _frame(stand, bottom, depth): + points = {i: tuple(a + depth * (b - a) for a, b in zip(stand[i], bottom[i])) for i in stand} + # 런지 분석기는 발꿈치·발끝(29~32)도 요구한다 — 발목 바로 옆에 둔다. + for heel, toe, ankle in ((29, 31, 27), (30, 32, 28)): + x, y = points[ankle] + points[heel], points[toe] = (x - .02, y + .01), (x + .04, y + .01) + landmarks = [Landmark(index=i, x=.5, y=.5, z=0, visibility=.05) for i in range(33)] + for i, (x, y) in points.items(): + landmarks[i] = Landmark(index=i, x=x, y=y, z=0, visibility=.99) + return landmarks + + +def _cycle(stand, bottom, fps=10): + """서기 1초 → 내려가기 0.7초 → 바닥 0.5초 → 올라오기 0.7초 → 서기 1초, 2회.""" + out = [] + for _ in range(2): + out += [0.0] * fps + out += [k / (0.7 * fps) for k in range(1, int(0.7 * fps) + 1)] + out += [1.0] * (fps // 2) + out += [1 - k / (0.7 * fps) for k in range(1, int(0.7 * fps) + 1)] + out += [0.0] * fps + return [(i / fps, _frame(stand, bottom, d)) for i, d in enumerate(out, start=1)] + + +def _squat_reps(frames): + counter = SquatCounter() + for t, landmarks in frames: + counter.update(landmarks, t) + return counter.rep_count + + +def _lunge_reps(frames): + state = SessionState(1, 2, exercise_type="lunge") + analyzer = StreamingLungeAnalyzer() + for t, landmarks in frames: + analyzer.process_frame(state, landmarks, timestamp_sec=t) + return state.rep_count + + +def test_synthetic_poses_have_the_intended_shape(): + lunge = observe_squat(_frame(_LUNGE_STAND, _LUNGE_BOTTOM, 1), 1.0, .55) + squat = observe_squat(_frame(_SQUAT_STAND, _SQUAT_BOTTOM, 1), 1.0, .55) + # 둘 다 «무릎이 충분히 굽었다» 는 조건은 만족한다 — 그래서 예전에는 서로 세졌다. + assert max(lunge.knees) <= 115 and max(squat.knees) <= 115 + assert lunge.stance.is_split() + assert squat.stance.stance_ratio >= 0.55 # 기존 런지 구분 문턱(stagger_min)은 넘는다 + assert not squat.stance.is_split() + + +def test_each_analyzer_still_counts_its_own_exercise(): + assert _lunge_reps(_cycle(_LUNGE_STAND, _LUNGE_BOTTOM)) == 2 + assert _squat_reps(_cycle(_SQUAT_STAND, _SQUAT_BOTTOM)) == 2 + + +def test_squat_selected_lunge_performed_is_not_counted(): + counter = SquatCounter() + messages = set() + for t, landmarks in _cycle(_LUNGE_STAND, _LUNGE_BOTTOM): + counter.update(landmarks, t) + if counter.coaching_event: + messages.add(counter.coaching_event) + assert counter.rep_count == 0 + assert any("런지" in m for m in messages) + + +def test_lunge_selected_squat_performed_is_not_counted(): + state = SessionState(1, 2, exercise_type="lunge") + analyzer = StreamingLungeAnalyzer() + guidance = set() + for t, landmarks in _cycle(_SQUAT_STAND, _SQUAT_BOTTOM): + analyzer.process_frame(state, landmarks, timestamp_sec=t) + guidance.add(state.lunge_state.guidance) + assert state.rep_count == 0 + assert any("스쿼트 자세" in g for g in guidance) + + +def test_streaming_squat_session_ignores_lunges(): + """실시간 경로(pose.py 가 부르는 StreamingSquatAnalyzer)도 같은 판정을 탄다.""" + state = SessionState(1, 1, exercise_type="squat") + analyzer = StreamingSquatAnalyzer("squat") + events = [] + for t, landmarks in _cycle(_LUNGE_STAND, _LUNGE_BOTTOM): + _, _, event, _, _ = analyzer.process_frame(state, landmarks, timestamp_sec=t) + if event: + events.append(event) + assert events == [] and state.rep_count == 0 + + +def test_one_visible_leg_is_not_treated_as_lunge(): + """측면 스쿼트처럼 한쪽 다리만 보이면 판정 불가(None) — 스쿼트를 잘못 막지 않는다.""" + landmarks = _frame(_SQUAT_STAND, _SQUAT_BOTTOM, 1) + for i in (12, 24, 26, 28): + landmarks[i] = Landmark(index=i, x=landmarks[i].x, y=landmarks[i].y, z=0, visibility=.1) + assert observe_squat(landmarks, 1.0, .55).stance is None + assert stance_features({11: (0, 0)}) is None + assert math.isfinite(observe_squat(landmarks, 1.0, .55).knee_angle) diff --git a/ai-server/tests/test_frame_rate_limit.py b/ai-server/tests/test_frame_rate_limit.py index 283b7d97..5e40ae40 100644 --- a/ai-server/tests/test_frame_rate_limit.py +++ b/ai-server/tests/test_frame_rate_limit.py @@ -87,8 +87,8 @@ def _count_reps(fps: float, hold_sec: float, *, limiter: bool) -> int: if limiter and not accept_frame(state, now): continue - angles, _, rep_event = analyzer.process_frame( - state, _frame(_knee_angle_at(now, hold_sec)) + angles, _, rep_event, _, _ = analyzer.process_frame( + state, _frame(_knee_angle_at(now, hold_sec)), timestamp_sec=now ) if angles is not None: state.current_rep_frames.append( @@ -108,39 +108,12 @@ class FrameRateLimitReproductionTests(unittest.TestCase): FPS_CASES = (3.0, 10.0, 30.0) HOLD_CASES = (0.5, 1.0, 1.5, 2.0, 3.0) - def test_without_limiter_reproduces_the_defect(self) -> None: - """상한이 없으면 높은 fps 에서 rep 이 사라진다 — 이 테스트가 헛돌지 않는다는 증거. - - ⚠️ **기준선이 한 번 바뀌었다.** 처음 이 검사를 넣었을 때는 10·30fps × 체류 5종 = 10 조합이 - 전부 사라졌다. #159(체류를 «밴드 통과 + 체류» 가 아니라 실제 100° 아래 프레임으로 계량)를 - 고친 뒤로는 **8 조합**이다 — 10fps · 체류 0.5s·1.0s 는 상한이 없어도 살아남는다. - - 두 결함이 같은 예산을 놓고 겹쳐 있었기 때문이다. #159 가 예산에서 밴드 통과 시간을 빼면서 - fps 상승에 대한 여유도 같이 늘었다. **#143 이 사라진 것은 아니다** — 30fps 는 여전히 전부 - 사라지고, 그것이 상한이 필요한 이유다. - - 그래서 «10 조합 전부» 를 고정하지 않는다. 30fps 행만 전부 사라지는 것으로 고정하고, - 10fps 행은 #159 같은 인접 수정이 들어올 때마다 깨지지 않게 하한만 둔다. - """ - vanished_30 = [ - hold for hold in self.HOLD_CASES if _count_reps(30.0, hold, limiter=False) == 0 - ] - self.assertEqual( - len(vanished_30), - len(self.HOLD_CASES), - f"30fps 에서 #143 재현이 안 됐다 — 상한 없이 살아남은 체류: " - f"{set(self.HOLD_CASES) - set(vanished_30)}", - ) - - vanished_10 = [ - hold for hold in self.HOLD_CASES if _count_reps(10.0, hold, limiter=False) == 0 - ] - self.assertGreaterEqual( - len(vanished_10), - 1, - "10fps 에서도 상한 없이 사라지는 조합이 하나는 있어야 한다 " - f"(현재 사라지는 체류: {vanished_10})", - ) + def test_without_limiter_counts_at_every_fps(self) -> None: + """초 단위 상태 판정은 프레임 수와 무관하게 같은 동작을 센다.""" + for fps in self.FPS_CASES: + for hold in self.HOLD_CASES: + with self.subTest(fps=fps, hold_sec=hold): + self.assertEqual(_count_reps(fps, hold, limiter=False), 1) def test_limiter_restores_reps_at_every_fps(self) -> None: """상한이 있으면 fps 가 얼마든 정상 스쿼트 1회는 1회로 집계된다.""" @@ -274,7 +247,7 @@ class HoldBoundaryTests(unittest.TestCase): def _boundary(self, fps: float) -> float: """rep 이 사라지기 시작하는 바닥 체류 시간 (0.1초 해상도).""" - hold = 0.1 + hold = 0.5 while hold < 10.0: if _count_reps(fps, round(hold, 1), limiter=True) == 0: return round(hold, 1) @@ -282,19 +255,14 @@ def _boundary(self, fps: float) -> float: return 10.0 def test_hold_boundary_is_no_longer_fps_dependent(self) -> None: - """변경 전 3fps 4.3s / 10fps 0.5s / 30fps 0.2s → 변경 후 셋이 한 자리로 모인다. - - 완전히 같아지지는 않는다. 상한은 3.33fps 이고 native 클라는 3.03fps 라, 깎인 스트림이 - 약간 더 촘촘하고 예산(4.5s)도 native(5.0s)보다 짧다. 그 잔차를 «같다» 로 적지 않고 - 범위로 고정한다. - """ + """앉아서 쉬는 경우를 거르는 8초 상한이 fps에 크게 흔들리지 않는다.""" boundaries = {fps: self._boundary(fps) for fps in (3.0, 10.0, 30.0)} for fps, boundary in boundaries.items(): with self.subTest(fps=fps): self.assertGreaterEqual( boundary, - 3.0, + 7.0, f"{fps}fps 의 체류 임계가 {boundary}s — 실제 체류 ~1초 대비 여유가 없다 " f"(전체: {boundaries})", ) @@ -375,4 +343,4 @@ def spy_accept(state, now): if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main() diff --git a/ai-server/tests/test_lunge_analyzer.py b/ai-server/tests/test_lunge_analyzer.py new file mode 100644 index 00000000..9c7a5af6 --- /dev/null +++ b/ai-server/tests/test_lunge_analyzer.py @@ -0,0 +1,238 @@ +"""Deterministic trajectory tests; these do not measure camera accuracy. + +2026-09-22: 판정 축을 발 이동 거리에서 무릎 각도 사이클(+ 스탠스 벌어짐)로 바꿨다. 그래서 +예전에는 "발이 원위치로 안 돌아온다"는 이유로 거부하던 워킹·후방 런지 스타일도 이제는 +스쿼트와만 구분되면(스탠스가 벌어져 있으면) 센다 — 실촬영 검증에서 실제로 촬영된 동작 +(제자리에서 벌린 다리로 펄싱)이 이 방식이었기 때문이다(사용자 확인 후 반영). +""" +import math +from dataclasses import replace + +import pytest + +from app.core.lunge_analyzer import StreamingLungeAnalyzer +from app.grpc.session_state import SessionState +from app.models.pose import Landmark + + +def frame(left=175, right=175, left_step=0.0, right_step=0.0, *, mirror=False, aspect=1.0): + points = {11: (.48, .23), 12: (.50, .23), 23: (.48, .48), 24: (.50, .48)} + for hip, knee, ankle, heel, toe, angle, x in ( + (23, 25, 27, 29, 31, left, .46 + left_step), + (24, 26, 28, 30, 32, right, .51 + right_step), + ): + a, c = points[hip], (x, .9) + dx, dy = c[0] - a[0], c[1] - a[1] + offset = 1 / (2 * math.tan(math.radians(angle / 2))) + points[knee] = ((a[0] + c[0]) / 2 + dy * offset, + (a[1] + c[1]) / 2 - dx * offset) + points[ankle], points[heel], points[toe] = c, (x - .025, .91), (x + .04, .91) + return [Landmark(index=i, x=(1 - x if mirror else x) / aspect, + y=y, z=0, visibility=1) for i, (x, y) in points.items()] + + +class Run: + def __init__(self, fps=10, initial=0, **geometry): + self.state = SessionState(123, 2, exercise_type="lunge", rep_count=initial) + self.analyzer = StreamingLungeAnalyzer() + self.now, self.dt, self.geometry = 0., 1 / fps, geometry + self.events = [] + + def hold(self, seconds, *args, **kwargs): + for _ in range(math.ceil(seconds / self.dt)): + self.now += self.dt + _, _, event, _, _ = self.analyzer.process_frame( + self.state, frame(*args, **kwargs, **self.geometry), timestamp_sec=self.now, + image_aspect_ratio=self.geometry.get("aspect", 1.), + ) + if event: + self.events.append(event) + + def rep(self, leg="left", bottom=90, back_bottom=85): + step = {f"{leg}_step": .3} + self.hold(.7, 150, 150, **step) + angles = (bottom, back_bottom) if leg == "left" else (back_bottom, bottom) + self.hold(.7, *angles, **step) + before = self.state.rep_count + # 무릎만 다시 펴면 완성된다 — 발이 원위치로 돌아왔는지는 더 이상 보지 않는다. + self.hold(.7, 175, 175, **step) + assert self.state.rep_count == len(self.events) + self.state.lunge_state.unassigned_reps + return self.state.rep_count - before + + +@pytest.mark.parametrize("fps", [3, 10, 30]) +@pytest.mark.parametrize("mirror,aspect", [(False, 1.), (True, 1.), (False, 16/9), (True, 9/16)]) +def test_alternating_forward_lunges(fps, mirror, aspect): + run = Run(fps, mirror=mirror, aspect=aspect) + run.hold(1) + assert run.rep("left") == 1 + assert run.rep("right") == 1 + assert run.state.rep_count == 2 + assert [e.lead_leg for e in run.events] == ["left", "right"] + progress = run.state.lunge_state.progress() + assert (progress.left_reps, progress.right_reps) == (1, 1) + + +@pytest.mark.parametrize("kind", ["squat", "walking", "shallow", "partial"]) +def test_non_lunge_cycles_are_not_counted(kind): + """스탠스가 벌어지지 않거나(스쿼트·평행 이동) 깊이가 부족하면 세지 않는다.""" + run = Run() + run.hold(1) + if kind == "squat": + run.hold(1, 90, 90) # 발이 나란함 — 스탠스 벌어짐 신호가 없다 + elif kind == "walking": + run.hold(.6, left_step=.3) + # 두 발이 같이 움직이면 서로 간 거리(stagger)는 그대로다 — 런지 스탠스가 아니다. + run.hold(1, 90, 90, left_step=.3, right_step=.3) + elif kind == "shallow": + run.rep(bottom=125, back_bottom=125) + elif kind == "partial": + run.hold(1, 150, 150, left_step=.3) + run.hold(1) + assert run.state.rep_count == 0 + + +@pytest.mark.parametrize("kind", ["reverse", "split_stance"]) +def test_stance_based_cycles_now_count(kind): + """2026-09-22 재설계: 발 이동 방향·원위치 복귀를 더 이상 보지 않으므로, 스탠스가 + 벌어진 채(방향 무관) 무릎이 굽혔다 펴지면 워킹·후방 런지 스타일도 센다 — 실촬영에서 + 실제로 촬영된 "제자리 벌린 스탠스로 펄싱"하는 동작이 이 모양이었다(사용자 확인 후 + 반영, docs/decisions/lunge-repetition-counting.md 참고). + """ + run = Run() + if kind == "split_stance": + run.hold(1, left_step=.3) + run.hold(1, 90, 85, left_step=.3) + run.hold(1, left_step=.3) + elif kind == "reverse": + run.hold(1) + run.hold(1, 90, 90, right_step=-.3) + run.hold(1) + assert run.state.rep_count == 1 + + +@pytest.mark.parametrize("failure", ["gap", "visibility", "missing", "nan"]) +def test_interrupted_rep_is_discarded_and_next_rep_works(failure): + run = Run() + run.hold(1) + run.hold(.7, 145, 145, left_step=.3) + run.hold(.7, 90, 85, left_step=.3) + if failure == "gap": + run.now += 3 + else: + bad = frame(90, 85, left_step=.3) + if failure == "visibility": + bad[0].visibility = .1 + elif failure == "missing": + bad = bad[:-1] + else: + bad[0].x = float("nan") + run.now += .1 + assert run.analyzer.process_frame(run.state, bad, timestamp_sec=run.now)[0] is None + run.hold(1) + assert run.state.rep_count == 0 + assert run.rep() == 1 + + +def test_process_frame_returns_torso_tilt(): + """체간 기울기 점수(TrunkLeanAnalysisCalculator, 2026-09-28)용 4번째 반환값 — squat과 + 같은 공식으로 어깨/엉덩이 중점 벡터의 수직 이탈각을 낸다. frame()의 어깨(11/12)·엉덩이 + (23/24)는 항상 같은 x좌표라 거의 직립(0도 근처)이어야 한다.""" + run = Run() + run.hold(.3) + _, _, _, torso_tilt, _ = run.analyzer.process_frame( + run.state, frame(150, 150, left_step=.3), timestamp_sec=run.now + .1 + ) + assert torso_tilt is not None + assert torso_tilt < 5.0 + + +def test_process_frame_returns_stagger_ratio(): + """보폭 점수(LungeStepLengthAnalysisCalculator, 2026-09-28)용 5번째 반환값 — "런지 + 자세인가"를 판정하던 stagger 값을 그대로 재사용한다. left_step=.3인 frame()은 두 발목이 + 벌어져 있으므로 stagger_ratio가 stagger_min(0.55)보다 뚜렷이 커야 한다.""" + run = Run() + run.hold(.3) + _, _, _, _, stagger_ratio = run.analyzer.process_frame( + run.state, frame(150, 150, left_step=.3), timestamp_sec=run.now + .1 + ) + assert stagger_ratio is not None + assert stagger_ratio > 0.55 + + +@pytest.mark.parametrize("failure", ["visibility", "missing", "nan"]) +def test_invalid_frame_returns_none_extras_too(failure): + """가시성 부족·랜드마크 누락·NaN — 무릎각(angles)이 None이 되는 경로는 체간 기울기·보폭 + 비율도 같이 None이어야 한다(pose.py가 angles is None일 때 PerRepFrame을 아예 안 만드므로, + 이 값들이 항상 같이 유효/무효여야 한다).""" + run = Run() + bad = frame(150, 150, left_step=.3) + if failure == "visibility": + bad[0].visibility = .1 + elif failure == "missing": + bad = bad[:-1] + else: + bad[0].x = float("nan") + angles, _, _, torso_tilt, stagger_ratio = run.analyzer.process_frame( + run.state, bad, timestamp_sec=run.now + .1 + ) + assert angles is None + assert torso_tilt is None + assert stagger_ratio is None + + +def test_resume_counts_total_without_inventing_historical_sides(): + run = Run(initial=7) + run.hold(1) + run.rep("right") + assert run.state.rep_count == 8 + assert run.state.lunge_state.progress().model_dump() | {} == { + "phase": "ready", "lead_leg": None, "left_reps": 0, "right_reps": 1, + "unassigned_reps": 7, "score_available": False, + "guidance": "다시 일어선 것을 확인했습니다. 다음 런지를 시작하세요.", + } + + +def test_starting_already_at_bottom_still_counts_the_recovery(): + """2026-09-22 재설계: 준비 자세(calibration)를 더 이상 기다리지 않는다 — 스트림이 + 이미 런지 바닥 자세로 시작해도, 그 뒤로 다시 펴면 1회로 센다. "시작하는 순간을 + 놓쳤다"는 이유로 거부하지 않는 것이 이번 재설계의 요점이다.""" + run = Run() + run.hold(1, 90, 85, left_step=.3) + run.hold(1) + assert run.state.rep_count == 1 + + +def test_out_of_order_frame_does_not_change_state(): + run = Run() + run.hold(1, 90, 85, left_step=.3) + before = replace(run.state.lunge_state) + run.analyzer.process_frame(run.state, frame(90, 85, left_step=.3), timestamp_sec=run.now - 1) + assert run.state.lunge_state == before + + +def test_long_bottom_hold_is_one_rep_and_standing_does_not_repeat(): + run = Run() + run.hold(1) + run.hold(.7, 145, 145, left_step=.3) + run.hold(20, 90, 85, left_step=.3) + run.hold(10) + assert run.state.rep_count == 1 + + +def test_low_fps_can_skip_intermediate_descent_frames(): + run = Run(fps=3) + run.hold(1) + run.hold(1, 90, 85, left_step=.3) + run.hold(1) + assert run.state.rep_count == 1 + + +def test_single_bad_depth_frame_does_not_count(): + run = Run() + run.hold(1) + run.hold(.7, 140, 140, left_step=.3) + run.hold(.1, 70, 70, left_step=.3) + run.hold(.5, 140, 140, left_step=.3) + run.hold(1) + assert run.state.rep_count == 0 diff --git a/ai-server/tests/test_lunge_integration.py b/ai-server/tests/test_lunge_integration.py new file mode 100644 index 00000000..6d3b4743 --- /dev/null +++ b/ai-server/tests/test_lunge_integration.py @@ -0,0 +1,84 @@ +from unittest.mock import Mock + +import numpy as np +import pytest + +import exercise_pb2 +from app.api.endpoints import pose +from app.grpc import exercise_servicer +from app.grpc.session_state import PerRepFrame, get_registry +from app.models.pose import PoseRequest, PoseSkipReason +from tests.test_lunge_analyzer import frame +from tests.test_pose_response_contract import _fake_lease + + +@pytest.fixture +def session(monkeypatch): + sid = 92501 + get_registry().remove(sid) + monkeypatch.setattr(exercise_servicer, "get_pool", lambda: Mock(acquire=lambda _: True, status=lambda: (0, 4))) + request = exercise_pb2.AnalyzeRequest(exercise_id=2, session_id=sid, session_nonce="owner") + assert exercise_servicer.ExerciseServicer().StartAnalysis(request, Mock()).success + state = get_registry().get(sid) + yield state + get_registry().remove(sid) + + +def test_lunge_http_frames_emit_one_persistable_rep_and_no_squat_feedback(session, monkeypatch): + monkeypatch.setattr(pose, "base64_to_image", lambda _: np.zeros((100, 100, 3), dtype=np.uint8)) + report = Mock(return_value=True) + concurrent_frame = PerRepFrame(99, "[]", [175, 175]) + def accept_next_frame_during_callback(*_): + with session.state_lock: + session.current_rep_frames.append(concurrent_frame) + return True + report.side_effect = accept_next_frame_during_callback + feedback = Mock(return_value=True) + monkeypatch.setattr(pose.spring_client, "report_pose_data_batch", report) + monkeypatch.setattr(pose, "flush_pending_feedback", feedback) + req = PoseRequest(image="", session_id=session.session_id, session_nonce="owner", exercise_type="squat") + # Request type must not override the authoritative session exercise type. + now = 0. + for kwargs in ({}, {"left_step": .3, "left": 145, "right": 145}, + {"left_step": .3, "left": 90, "right": 85}, {"left_step": .3}, {}): + for _ in range(3): + now += .34 + monkeypatch.setattr(pose.time, "monotonic", lambda: now) + monkeypatch.setattr(pose, "lease_detector", _fake_lease(lambda _: frame(**kwargs))) + response = pose.detect_pose(req) + assert response.success + assert response.lunge is not None + assert response.sync_rate is None + assert response.rep_count == 1 + assert response.lunge.left_reps == 1 + report.assert_called_once() + frames = report.call_args.args[1] + assert frames and all(f.rep_number == 1 for f in frames) + # 2026-09-27: 좌우별 깊이 채점을 백엔드에서 하려면 어느 다리인지가 프레임 단위로 + # pose_data까지 내려가야 한다 — left_step을 준 이 rep은 "left"가 나가야 한다. + assert all(f.lead_leg == "left" for f in frames) + assert not session.pending_feedback_events + assert concurrent_frame in session.current_rep_frames + + +def test_no_pose_from_nonowner_cannot_reset_lunge(session, monkeypatch): + from app.core.lunge_analyzer import LungeState + session.lunge_state = LungeState(phase="returning", lead_leg="left") + monkeypatch.setattr(pose, "base64_to_image", lambda _: np.zeros((4, 4, 3), dtype=np.uint8)) + monkeypatch.setattr(pose, "lease_detector", _fake_lease(lambda _: [])) + response = pose.detect_pose(PoseRequest(image="", session_id=session.session_id, session_nonce="wrong")) + assert response.skip_reason == PoseSkipReason.NO_POSE + assert session.lunge_state.phase == "returning" + pose.detect_pose(PoseRequest(image="", session_id=session.session_id, session_nonce="owner")) + assert session.lunge_state.phase == "ready" + + +def test_lunge_reattach_without_reference_restores_total_and_preserves_live_state(session): + servicer = exercise_servicer.ExerciseServicer() + req = exercise_pb2.ReattachRequest(exercise_id=2, session_id=session.session_id, + initial_rep_count=7, session_nonce="owner") + live = servicer.ReattachAnalysis(req, Mock()) + assert live.success and live.already_active and live.rep_count == 0 + get_registry().remove(session.session_id) + restored = servicer.ReattachAnalysis(req, Mock()) + assert restored.success and not restored.already_active and restored.rep_count == 7 diff --git a/ai-server/tests/test_phase_label_matches_rep_ruler.py b/ai-server/tests/test_phase_label_matches_rep_ruler.py index f6f2e6fd..84826c44 100644 --- a/ai-server/tests/test_phase_label_matches_rep_ruler.py +++ b/ai-server/tests/test_phase_label_matches_rep_ruler.py @@ -1,108 +1,18 @@ -"""국면 이름표와 rep 판정이 **같은 자**를 쓰는가 (이슈 #218). - -`phase` 는 내부값이 아니라 응답 스키마에 나간다(`models/video.py:15,33`). 예전에는 이름표만 -95/155 상수였고 rep 판정은 100/150 이라, 두 밴드에서 응답이 자기모순이었다: - -| 무릎 각도 | rep 상태기계 | 옛 이름표 | 결과 | -|---|---|---|---| -| 150~155° | `standing` → **rep 을 센다** | `ascending`/`transition` | rep 은 올랐는데 국면은 «아직 올라가는 중» | -| 95~100° | `bottom` | `descending`/`transition` | 바닥에 닿았는데 «아직 내려가는 중» | - -어느 쪽을 고칠지는 정해져 있다 — **rep 자를 움직이면 그동안의 측정·기준이 전부 흔들린다.** -그래서 이름표를 rep 자에 맞췄고, 같은 값을 두 군데 적는 대신 **호출부가 rep 판정에 쓰는 그 -변수를 그대로 넘긴다.** 아래 마지막 테스트가 그 «구조적으로 못 갈린다» 를 고정한다. -""" -import unittest - -from app.core.squat_analyzer import _phase_from_angles, analyze_squat_frames +"""The offline phase label and repetition counter must describe the same cycle.""" +from app.core.squat_analyzer import analyze_squat_frames from tests.test_squat_analyzer import _frame -_BOTTOM = 100.0 -_STANDING = 150.0 - - -def _phase(angle: float, delta: float, bottom=_BOTTOM, standing=_STANDING) -> str: - return _phase_from_angles( - angle, delta, bottom_threshold=bottom, standing_threshold=standing - ) - - -class PhaseLabelMatchesRepRulerTest(unittest.TestCase): - def test_150_에서_155_밴드가_standing_이다(self) -> None: - """rep 을 세는 구간인데 «아직 올라가는 중» 으로 나가던 자리.""" - for angle in (150.0, 152.0, 154.9): - with self.subTest(angle=angle): - self.assertEqual( - _phase(angle, +5.0), - "standing", - f"{angle}° 는 rep 상태기계가 standing 으로 보는 각도다", - ) - - def test_95_에서_100_밴드가_bottom_이다(self) -> None: - for angle in (95.1, 97.0, 100.0): - with self.subTest(angle=angle): - self.assertEqual(_phase(angle, -5.0), "bottom") - - def test_밴드_밖은_속도로_가른다(self) -> None: - """delta 문턱(±4)은 각도 축이 아니라 속도 축이라 그대로 둔다.""" - self.assertEqual(_phase(120.0, -5.0), "descending") - self.assertEqual(_phase(120.0, +5.0), "ascending") - self.assertEqual(_phase(120.0, 0.0), "transition") - - def test_옛_상수였다면_어긋난다는_것을_증인으로_남긴다(self) -> None: - """이 테스트들이 «고쳐진 뒤에도 통과하는 무의미한 단언» 이 아님을 보인다. - - 위 두 밴드 테스트는 지금 코드에서 당연히 통과한다. 문제의 밴드가 **실재했다** 는 것은 - 옛 자(95/155)를 명시적으로 넘겨봐야 보인다 — 같은 각도가 다른 이름표를 받는다. - """ - self.assertEqual(_phase(152.0, +5.0, standing=155.0), "ascending") # 옛 이름표 - self.assertEqual(_phase(152.0, +5.0, standing=_STANDING), "standing") # rep 자 - self.assertEqual(_phase(97.0, -5.0, bottom=95.0), "descending") # 옛 이름표 - self.assertEqual(_phase(97.0, -5.0, bottom=_BOTTOM), "bottom") # rep 자 - - def test_자를_바꾸면_이름표가_따라온다(self) -> None: - """호출자가 문턱을 덮으면 이름표도 같이 움직여야 한다 — 상수였으면 안 따라온다.""" - self.assertEqual(_phase(140.0, +5.0, standing=135.0), "standing") - self.assertEqual(_phase(140.0, +5.0, standing=160.0), "ascending") - - def test_전_프레임에서_이름표와_rep_자가_안_어긋난다(self) -> None: - """실제 분석 경로로 돌려 «자기모순 프레임이 0개» 를 고정한다. - - 이게 이 파일의 본체다 — 위 단위 테스트들은 함수 하나를 보지만, 여기서는 - `analyze_squat_frames` 가 실제로 내보내는 프레임 전부를 훑는다. - """ - # 서 있다 → 바닥 → 다시 서기. 경계 밴드(95~100 · 150~155)를 반드시 지나가게 짠다. - angles = [ - 170.0, 160.0, 154.0, 148.0, 130.0, 110.0, 99.0, 92.0, - 99.0, 110.0, 130.0, 148.0, 152.0, 160.0, 170.0, - ] - frames = [_frame(a) for a in angles] - - frame_metrics, result = analyze_squat_frames( - frames, bottom_threshold=_BOTTOM, standing_threshold=_STANDING - ) - - self.assertEqual(result.reps_detected, 1, "전제: 이 궤적은 rep 1회다") - - mismatches = [] - for index, metric in enumerate(frame_metrics): - if metric is None: - continue - knee = metric.knee_angle - # rep 상태기계가 쓰는 판정을 그대로 다시 적는다 — 이름표가 그 판정과 같아야 한다. - if knee <= _BOTTOM and metric.phase != "bottom": - mismatches.append((index, knee, metric.phase, "bottom")) - if knee >= _STANDING and metric.phase != "standing": - mismatches.append((index, knee, metric.phase, "standing")) - - self.assertEqual( - mismatches, - [], - "rep 판정과 국면 이름표가 어긋난 프레임이 있다 " - "(index, knee, 이름표, 기대): " + repr(mismatches), - ) +def test_phase_labels_match_counting_thresholds(): + angles = [175] * 3 + [145, 120, 90, 85, 90, 120, 145] + [175] * 4 + metrics, summary = analyze_squat_frames([_frame(angle) for angle in angles], fps=3) -if __name__ == "__main__": - unittest.main() + assert summary.reps_detected == 1 + assert metrics[-1].rep_count == 1 + assert any(metric.phase == "bottom" for metric in metrics) + for metric in metrics: + if metric.knee_angle <= 100 and metric.hip_angle <= 150: + assert metric.phase == "bottom" + if metric.knee_angle >= 160 and metric.hip_angle >= 160: + assert metric.phase == "standing" diff --git a/ai-server/tests/test_pose_feedback_callback.py b/ai-server/tests/test_pose_feedback_callback.py index 33af7a5c..e8fc4931 100644 --- a/ai-server/tests/test_pose_feedback_callback.py +++ b/ai-server/tests/test_pose_feedback_callback.py @@ -33,28 +33,38 @@ def _session(self, session_id: int): return state def _run_rep(self, session_id: int, torso_tilt: float): - frames = iter(_frame(angle, torso_tilt=torso_tilt) for angle in _REP_SEQUENCE) + frames = iter(_frame(angle, torso_tilt=torso_tilt if angle == _BOTTOM else 5.0) + for angle in _REP_SEQUENCE) + clock = {"now": 0.0} req = PoseRequest(image="", session_id=session_id, exercise_type="squat") with mock.patch.object(pose_endpoint, "base64_to_image", lambda _: _BLANK_IMAGE), \ mock.patch.object( pose_endpoint, "lease_detector", _fake_lease(lambda _img: next(frames)) ), \ mock.patch.object(pose_endpoint, "accept_frame", lambda _s, _n: True), \ + mock.patch.object(pose_endpoint.time, "monotonic", lambda: clock["now"]), \ mock.patch.object(pose_endpoint.spring_client, "report_pose_data_batch"), \ mock.patch.object(pose_endpoint.spring_client, "report_feedback_batch") as mock_fb: # flush_pending_feedback 이 outcome 을 언패킹한다 — 기본 반환을 성공으로 둬서 # 버퍼가 정상적으로 비워지는 경로를 태운다(그래야 무한루프 없이 한 번에 끝난다). mock_fb.return_value = (spring_client.FeedbackBatchOutcome.OK, 1) - responses = [pose_endpoint.detect_pose(req) for _ in _REP_SEQUENCE] + responses = [] + for i in range(len(_REP_SEQUENCE)): + clock["now"] = i / 3 + responses.append(pose_endpoint.detect_pose(req)) return responses, mock_fb def test_기울기가_35도를_넘고_게이트도_실패하면_BACK_BENT_를_보낸다(self) -> None: self._session(9301) - responses, mock_fb = self._run_rep(9301, torso_tilt=45.0) + responses, mock_fb = self._run_rep(9301, torso_tilt=75.0) self.assertTrue( any(r.rep_completed for r in responses), "테스트 전제: rep 이 완성돼야 한다" ) + self.assertEqual( + [r.message for r in responses if r.message], + ["스쿼트 깊이를 확인하고 1회 기록했어요."], + ) mock_fb.assert_called_once() session_id, set_no, is_final, events = mock_fb.call_args.args self.assertEqual(session_id, 9301) @@ -70,6 +80,70 @@ def test_기울기가_35도_밑이면_유형을_안_보낸다(self) -> None: self.assertTrue(any(r.rep_completed for r in responses)) mock_fb.assert_not_called() + def test_얕은_동작은_카운트하지_않고_화면용_안내를_한번_보낸다(self) -> None: + self._session(9303) + sequence = [172.0] * 4 + [120.0] * 4 + [172.0] * 4 + frames = iter(_frame(angle) for angle in sequence) + clock = {"now": 0.0} + req = PoseRequest(image="", session_id=9303, exercise_type="squat") + with mock.patch.object(pose_endpoint, "base64_to_image", lambda _: _BLANK_IMAGE), \ + mock.patch.object(pose_endpoint, "lease_detector", _fake_lease(lambda _img: next(frames))), \ + mock.patch.object(pose_endpoint, "accept_frame", lambda _s, _n: True), \ + mock.patch.object(pose_endpoint.time, "monotonic", lambda: clock["now"]), \ + mock.patch.object(pose_endpoint.spring_client, "report_pose_data_batch") as mock_pose: + responses = [] + for i in range(len(sequence)): + clock["now"] = i / 3 + responses.append(pose_endpoint.detect_pose(req)) + self.assertTrue(all(not r.rep_completed for r in responses)) + self.assertEqual([r.message for r in responses if r.message], + ["이번 동작에서 충분히 내려간 장면을 확인하지 못했어요."]) + mock_pose.assert_not_called() + + +class SquatProgressInResponseTest(unittest.TestCase): + """앱이 «준비됐는지/지금 뭘 해야 하는지»를 화면에 보여주려면 응답에 스쿼트 단계가 실려야 한다.""" + + def test_응답에_스쿼트_단계가_실리고_서면_준비_완료가_된다(self) -> None: + state = get_registry().create(session_id=9304, exercise_id=1, reference_angles=[]) + self.addCleanup(get_registry().remove, 9304) + sequence = [172.0] * 4 + [90.0] * 6 + [172.0] * 4 + frames = iter(_frame(angle) for angle in sequence) + clock = {"now": 0.0} + req = PoseRequest(image="", session_id=9304, exercise_type="squat") + with mock.patch.object(pose_endpoint, "base64_to_image", lambda _: _BLANK_IMAGE), \ + mock.patch.object(pose_endpoint, "lease_detector", _fake_lease(lambda _img: next(frames))), \ + mock.patch.object(pose_endpoint, "accept_frame", lambda _s, _n: True), \ + mock.patch.object(pose_endpoint.time, "monotonic", lambda: clock["now"]), \ + mock.patch.object(pose_endpoint.spring_client, "report_pose_data_batch"), \ + mock.patch.object(pose_endpoint.spring_client, "report_feedback_batch") as mock_fb: + mock_fb.return_value = (spring_client.FeedbackBatchOutcome.OK, 1) + responses = [] + for i in range(len(sequence)): + clock["now"] = i / 3 + responses.append(pose_endpoint.detect_pose(req)) + stages = [r.squat.stage for r in responses if r.squat is not None] + self.assertTrue(stages, "스쿼트 응답에 squat 진행 상태가 없다") + self.assertIn("ready", stages) + self.assertTrue(all(r.squat.guidance for r in responses if r.squat is not None)) + + def test_응답에_이미지_가로세로_비율이_실린다(self) -> None: + # 앱이 좌표(x=너비 기준, y=높이 기준)로 각도를 재려면 서버가 디코딩한 이미지의 비율이 필요하다. + get_registry().create(session_id=9305, exercise_id=1, reference_angles=[]) + self.addCleanup(get_registry().remove, 9305) + frames = iter(_frame(172.0) for _ in range(3)) + clock = {"now": 0.0} + req = PoseRequest(image="", session_id=9305, exercise_type="squat") + with mock.patch.object(pose_endpoint, "base64_to_image", lambda _: _BLANK_IMAGE), mock.patch.object(pose_endpoint, "lease_detector", _fake_lease(lambda _img: next(frames))), mock.patch.object(pose_endpoint, "accept_frame", lambda _s, _n: True), mock.patch.object(pose_endpoint.time, "monotonic", lambda: clock["now"]), mock.patch.object(pose_endpoint.spring_client, "report_pose_data_batch"): + responses = [] + for i in range(3): + clock["now"] = i / 3 + responses.append(pose_endpoint.detect_pose(req)) + expected = _BLANK_IMAGE.shape[1] / _BLANK_IMAGE.shape[0] + for r in responses: + self.assertIsNotNone(r.landmarks) + self.assertAlmostEqual(r.image_aspect_ratio, expected) + if __name__ == "__main__": unittest.main() diff --git a/ai-server/tests/test_session_reattach.py b/ai-server/tests/test_session_reattach.py index f1307a2c..98f92782 100644 --- a/ai-server/tests/test_session_reattach.py +++ b/ai-server/tests/test_session_reattach.py @@ -55,7 +55,7 @@ def test_상태가_없으면_주입된_rep_카운트로_생성된다(): # 분석기 내부 상태는 복원되지 않는다(§4-0). 초기값이어야 한다. assert state.rep_state == "waiting_for_standing" assert state.frame_index == 0 - assert state.recent_raw_knees == [] + assert state.squat_counter is None def test_상태가_살아있으면_아무것도_덮어쓰지_않는다(): @@ -79,6 +79,36 @@ def test_상태가_살아있으면_아무것도_덮어쓰지_않는다(): assert len(state.current_rep_frames) == 1 +def test_create_는_depth_mode_기본값이_FULL이고_지정하면_저장한다(): + registry = SessionStateRegistry() + + default_state = registry.create(session_id=1, exercise_id=1, reference_angles=_REF) + assert default_state.depth_mode == "FULL" + + half_state = registry.create( + session_id=2, exercise_id=1, reference_angles=_REF, depth_mode="HALF", + ) + assert half_state.depth_mode == "HALF" + + +def test_재부착은_기존_세션의_depth_mode를_덮어쓰지_않는다(): + """persona와 동일한 규약 — Spring이 재부착에서 다른 값을 보내도 진행 중이던 세션의 + 깊이 모드를 바꾸면, 이미 그 모드로 판정 중이던 SquatCounter와 어긋난다.""" + registry, _ = _registry_with_live_session() + registry._sessions[1].depth_mode = "HALF" + + state, already_active = registry.create_if_absent( + session_id=1, + exercise_id=1, + reference_angles=_REF, + persona="BEGINNER", + depth_mode="FULL", # DB 값이 뒤처져 있거나 다르게 와도 + ) + + assert already_active is True + assert state.depth_mode == "HALF" # 보관값 유지 + + def test_create_는_여전히_덮어쓴다(): """create 의 기존 동작은 그대로다 — 재부착만 다른 규칙을 쓴다는 것을 고정한다.""" registry, _ = _registry_with_live_session() diff --git a/ai-server/tests/test_squat_analyzer.py b/ai-server/tests/test_squat_analyzer.py index 096b508f..576c8e9c 100644 --- a/ai-server/tests/test_squat_analyzer.py +++ b/ai-server/tests/test_squat_analyzer.py @@ -44,6 +44,7 @@ def _frame(knee_angle: float, torso_tilt: float = 5.0) -> list[Landmark]: class SquatAnalyzerTests(unittest.TestCase): def test_analyze_squat_frames_counts_rep(self) -> None: frames = [ + _frame(175), _frame(175), _frame(160), _frame(120), @@ -53,12 +54,13 @@ def test_analyze_squat_frames_counts_rep(self) -> None: _frame(120), _frame(160), _frame(175), + _frame(175), ] per_frame, summary = analyze_squat_frames(frames) self.assertGreaterEqual(summary.reps_detected, 1) - self.assertGreater(summary.quality_score, 0) + self.assertIsNone(summary.quality_score) self.assertIsNotNone(per_frame[-1]) def test_analyze_squat_frames_flags_low_visibility(self) -> None: @@ -69,12 +71,8 @@ def test_analyze_squat_frames_flags_low_visibility(self) -> None: _, summary = analyze_squat_frames([frame, frame, frame]) self.assertEqual(summary.reps_detected, 0) - self.assertTrue( - any( - "frame" in message.lower() or "lighting" in message.lower() - for message in summary.feedback - ) - ) + self.assertEqual(summary.valid_frame_ratio, 0) + self.assertTrue(summary.feedback) if __name__ == "__main__": diff --git a/ai-server/tests/test_squat_counter.py b/ai-server/tests/test_squat_counter.py new file mode 100644 index 00000000..33b18b7a --- /dev/null +++ b/ai-server/tests/test_squat_counter.py @@ -0,0 +1,180 @@ +"""Repetition boundaries that cannot be inferred from the final count alone.""" + +from app.core.squat_analyzer import analyze_squat_frames +from app.core.squat_counter import SquatCounter, observe_squat +from app.core.reference_builder import _segment_reps +from app.models.pose import Landmark +from app.models.video import FrameResult +from tests.test_squat_analyzer import _frame + + +def _run(sequence, fps=3): + counter = SquatCounter() + for index, landmarks in enumerate(sequence): + counter.update(landmarks, index / fps) + return counter + + +def _hide_side(frame, side): + for index in ((11, 23, 25, 27) if side == "left" else (12, 24, 26, 28)): + frame[index].visibility = 0.1 + return frame + + +def _shift_side(frame, side, x): + for index in ((11, 23, 25, 27) if side == "left" else (12, 24, 26, 28)): + original = frame[index] + frame[index] = Landmark(index=index, x=original.x + x, + y=original.y, z=original.z, + visibility=original.visibility) + return frame + + +def test_entering_video_at_bottom_does_not_create_a_rep(): + counter = _run([_frame(85)] * 5 + [_frame(175)] * 4) + assert counter.rep_count == 0 + assert counter.stage == "ready" + + +def test_partial_depth_does_not_create_a_rep(): + counter = SquatCounter() + events = [] + for index, landmarks in enumerate([_frame(175)] * 3 + [_frame(120)] * 4 + [_frame(175)] * 4): + counter.update(landmarks, index / 3) + if counter.coaching_event: + events.append(counter.coaching_event) + assert counter.rep_count == 0 + assert events == ["이번 동작에서 충분히 내려간 장면을 확인하지 못했어요."] + + +def test_squat_depth_feedback_is_emitted_once_per_completed_rep(): + counter = SquatCounter() + events = [] + for index, landmarks in enumerate([_frame(175)] * 3 + [_frame(85)] * 4 + [_frame(175)] * 5): + counter.update(landmarks, index / 3) + if counter.coaching_event: + events.append(counter.coaching_event) + assert counter.rep_count == 1 + assert events == ["스쿼트 깊이를 확인하고 1회 기록했어요."] + + +def test_lost_tracking_aborts_only_the_inflight_rep(): + rep = [_frame(175)] * 3 + [_frame(85)] * 4 + [_frame(175)] * 4 + counter = _run(rep + [_frame(85)] * 3 + [None] + [_frame(175)] * 4) + assert counter.rep_count == 1 + + +def test_one_frame_ankle_glitch_does_not_erase_squat_cycle(): + moved = _frame(85) + for ankle in (27, 28): + original = moved[ankle] + moved[ankle] = Landmark(index=ankle, x=original.x + 0.3, + y=original.y, z=original.z, visibility=original.visibility) + counter = _run([_frame(175)] * 3 + [_frame(85)] * 3 + [moved] + [_frame(175)] * 4) + assert counter.rep_count == 1 + + +def test_foot_repositioning_before_descent_updates_stance_anchor(): + sequence = ([_frame(175)] * 3 + + [_shift_side(_frame(175), "right", 0.3) for _ in range(3)] + + [_shift_side(_frame(85), "right", 0.3) for _ in range(4)] + + [_shift_side(_frame(175), "right", 0.3) for _ in range(4)]) + assert _run(sequence).rep_count == 1 + + +def test_persistent_foot_step_aborts_squat_cycle(): + moved = _frame(85) + for ankle in (27, 28): + original = moved[ankle] + moved[ankle] = Landmark(index=ankle, x=original.x + 0.3, + y=original.y, z=original.z, visibility=original.visibility) + counter = _run([_frame(175)] * 3 + [_frame(85)] * 3 + [moved] * 4 + [_frame(175)] * 4) + assert counter.rep_count == 0 + + +def test_one_visible_leg_can_complete_a_rep(): + sequence = ([_hide_side(_frame(175), "right") for _ in range(3)] + + [_hide_side(_frame(85), "right") for _ in range(4)] + + [_hide_side(_frame(175), "right") for _ in range(4)]) + counter = _run(sequence) + assert counter.rep_count == 1 + assert observe_squat(sequence[0], 1.0, 0.55).visible_sides == (True, False) + + +def test_switching_the_only_visible_leg_aborts_inflight_rep(): + sequence = ([_hide_side(_frame(175), "right") for _ in range(3)] + + [_hide_side(_frame(85), "right") for _ in range(3)] + + [_hide_side(_frame(85), "left") for _ in range(3)] + + [_hide_side(_frame(175), "left") for _ in range(4)]) + assert _run(sequence).rep_count == 0 + + +def test_visible_leg_persistent_step_still_aborts_squat_cycle(): + moved = _hide_side(_frame(85), "right") + original = moved[27] + moved[27] = Landmark(index=27, x=original.x + 0.3, + y=original.y, z=original.z, visibility=original.visibility) + sequence = ([_hide_side(_frame(175), "right") for _ in range(3)] + + [_hide_side(_frame(85), "right") for _ in range(3)] + + [moved] * 4 + + [_hide_side(_frame(175), "right") for _ in range(4)]) + assert _run(sequence).rep_count == 0 + + +def test_both_leg_chains_occluded_still_abort_inflight_rep(): + hidden = _frame(85) + hidden[25].visibility = hidden[26].visibility = 0.1 + counter = _run([_frame(175)] * 3 + [_frame(85)] * 3 + + [hidden] + [_frame(175)] * 4) + assert counter.rep_count == 0 + + +def test_reference_segments_follow_completed_repetitions(): + sequence = [_frame(175)] * 3 + [_frame(85)] * 4 + [_frame(175)] * 4 + metrics, summary = analyze_squat_frames(sequence, fps=3) + frames = [FrameResult(frame_index=i, timestamp=i / 3, landmarks=landmarks, + angles=[float(i)], squat_metrics=metrics[i]) + for i, landmarks in enumerate(sequence)] + segments = _segment_reps(frames) + assert summary.reps_detected == 1 + assert len(segments) == 1 + assert segments[0].rep_index == 1 + # At fps=3 the sample gap (1/3 s) already exceeds standing_confirm_sec (0.2s), + # so the very first standing sample after the bottom (frame 7) is itself enough + # dwell evidence and completes the rep -- a second standing sample is no longer + # required. See squat-repetition-counting.md's time-based-sampling note. + assert segments[0].end_frame_index == 7 + + +# ── 스쿼트 깊이 모드 (FULL/HALF, 2026-09-21) ──────────────────────────────── +# HALF_SQUAT_THRESHOLDS의 bottom_hip/min_hip_drop은 실촬영 검증 전이라(VALIDATE 주석 +# 참고) 여기서는 "FSM이 두 모드를 다르게 취급하는가"만 고정한다 — 정확한 깊이 판정 +# 기준 자체의 검증은 docs/verification/의 하프 스쿼트 실촬영 리포트가 담당한다. + +from app.core.squat_counter import DEPTH_MODE_THRESHOLDS, HALF_SQUAT_THRESHOLDS # noqa: E402 + + +def test_half_squat_thresholds_are_internally_consistent(): + # __post_init__이 통과한다는 것 자체가 검증 — 생성이 실패하면 여기서 예외가 난다. + assert HALF_SQUAT_THRESHOLDS.bottom_knee + HALF_SQUAT_THRESHOLDS.bottom_knee_margin == 140.0 + assert DEPTH_MODE_THRESHOLDS["FULL"].bottom_knee == 100.0 + assert DEPTH_MODE_THRESHOLDS["HALF"] is HALF_SQUAT_THRESHOLDS + + +def test_half_depth_completes_under_half_thresholds_but_not_full_thresholds(): + # 무릎 130도까지만 내려가는 시퀀스 — 하프 밴드(115~140) 안, 풀 스쿼트 기준(<=115)엔 못 미침. + sequence = [_frame(175)] * 3 + [_frame(130)] * 4 + [_frame(175)] * 4 + + half_counter = SquatCounter(HALF_SQUAT_THRESHOLDS) + for index, landmarks in enumerate(sequence): + half_counter.update(landmarks, index / 3) + assert half_counter.rep_count == 1 + assert half_counter.stage == "ready" + + full_counter = SquatCounter(DEPTH_MODE_THRESHOLDS["FULL"]) + for index, landmarks in enumerate(sequence): + full_counter.update(landmarks, index / 3) + assert full_counter.rep_count == 0 + # 바닥 조건(무릎<=115)을 한 번도 못 만족해 "bottom" 단계에 들어가지 못한다 — + # test_partial_depth_does_not_create_a_rep과 같은 경로(얕음 피드백)를 탄다. + assert full_counter.stage == "ready" diff --git a/ai-server/tests/test_streaming_depth_metric.py b/ai-server/tests/test_streaming_depth_metric.py index 9222d41b..d4ed4a99 100644 --- a/ai-server/tests/test_streaming_depth_metric.py +++ b/ai-server/tests/test_streaming_depth_metric.py @@ -65,24 +65,39 @@ def test_process_frame_returns_smoothed_knee_angle(self) -> None: analyzer = StreamingSquatAnalyzer() state = _state() - angles, smoothed, rep_event = analyzer.process_frame(state, _frame(170)) + angles, smoothed, rep_event, torso_tilt, stagger_ratio = analyzer.process_frame(state, _frame(170)) self.assertIsNotNone(angles) self.assertIsNotNone(smoothed) self.assertIsNone(rep_event) # 1프레임으로는 rep 이 완성되지 않는다 self.assertGreater(smoothed, 0.0) + self.assertIsNotNone(torso_tilt) + self.assertIsNone(stagger_ratio) # 스쿼트는 보폭 개념이 없다 — 항상 None - def test_visibility_skip_returns_none_for_all_three(self) -> None: - """가시성 미달 프레임은 세 값 모두 None — 호출자가 프레임을 버릴 수 있어야 한다.""" + def test_visibility_skip_returns_none_for_all_five(self) -> None: + """가시성 미달 프레임은 다섯 값 모두 None — 호출자가 프레임을 버릴 수 있어야 한다.""" analyzer = StreamingSquatAnalyzer() state = _state() invisible = [_landmark(i, 0.5, 0.5, visibility=0.1) for i in range(33)] - angles, smoothed, rep_event = analyzer.process_frame(state, invisible) + angles, smoothed, rep_event, torso_tilt, stagger_ratio = analyzer.process_frame(state, invisible) self.assertIsNone(angles) self.assertIsNone(smoothed) self.assertIsNone(rep_event) + self.assertIsNone(torso_tilt) + self.assertIsNone(stagger_ratio) + + def test_process_frame_returns_torso_tilt_matching_geometry(self) -> None: + """체간 기울기 점수(TrunkLeanAnalysisCalculator)용 4번째 반환값 — _frame의 torso_tilt + 인자로 만든 기하와 process_frame이 돌려주는 값이 실제로 일치하는지 고정한다.""" + analyzer = StreamingSquatAnalyzer() + + _, _, _, upright_tilt, _ = analyzer.process_frame(_state(), _frame(170, torso_tilt=2.0)) + _, _, _, leaned_tilt, _ = analyzer.process_frame(_state(), _frame(90, torso_tilt=30.0)) + + self.assertAlmostEqual(upright_tilt, 2.0, delta=0.5) + self.assertAlmostEqual(leaned_tilt, 30.0, delta=0.5) def test_depth_metric_varies_within_a_rep(self) -> None: """★ 핵심 — 깊이 지표는 rep 안에서 프레임마다 다르다. @@ -96,8 +111,8 @@ def test_depth_metric_varies_within_a_rep(self) -> None: descent = [175, 160, 130, 110, 90, 85] measured = [] - for knee_angle in descent: - _, smoothed, _ = analyzer.process_frame(state, _frame(knee_angle)) + for i, knee_angle in enumerate(descent): + _, smoothed, _, _, _ = analyzer.process_frame(state, _frame(knee_angle), timestamp_sec=i / 3) measured.append(smoothed) self.assertEqual(len(set(measured)), len(measured), "프레임마다 값이 달라야 한다") @@ -114,9 +129,9 @@ def test_depth_metric_is_smoothed_not_raw(self) -> None: analyzer = StreamingSquatAnalyzer() state = _state() - for knee_angle in (170, 170): - analyzer.process_frame(state, _frame(knee_angle)) - _, smoothed, _ = analyzer.process_frame(state, _frame(80)) # 한 프레임만 급락 + for i, knee_angle in enumerate((170, 170)): + analyzer.process_frame(state, _frame(knee_angle), timestamp_sec=i / 30) + _, smoothed, _, _, _ = analyzer.process_frame(state, _frame(80), timestamp_sec=2 / 30) # 원시값이면 ~80 이 나와야 하지만 최근 3프레임 평균이라 훨씬 완만하다 self.assertGreater(smoothed, 100.0) @@ -137,8 +152,8 @@ def test_depth_metric_uses_both_knees(self) -> None: right_ankle = asymmetric[28] asymmetric[28] = _landmark(28, right_ankle.x + 0.12, right_ankle.y) - _, symmetric_value, _ = analyzer.process_frame(_state(), symmetric) - _, asymmetric_value, _ = analyzer.process_frame(_state(), asymmetric) + _, symmetric_value, _, _, _ = analyzer.process_frame(_state(), symmetric) + _, asymmetric_value, _, _, _ = analyzer.process_frame(_state(), asymmetric) self.assertNotAlmostEqual( symmetric_value, diff --git a/ai-server/tests/test_streaming_rep_counting.py b/ai-server/tests/test_streaming_rep_counting.py index 09cfc5b3..33a62dfd 100644 --- a/ai-server/tests/test_streaming_rep_counting.py +++ b/ai-server/tests/test_streaming_rep_counting.py @@ -34,11 +34,12 @@ def _count_reps(knee_sequence: list[float]) -> int: analyzer = StreamingSquatAnalyzer("squat") reps = 0 - for knee_angle in knee_sequence: - # process_frame 은 (angles, smoothed_knee_angle, rep_event) 3-튜플이다. 가운데 - # 깊이 지표는 이 테스트가 검증하는 대상이 아니라(test_streaming_depth_metric.py 담당) - # 버린다 — rep 집계는 이 값에 의존하지 않는다. - angles, _, rep_event = analyzer.process_frame(state, _frame(knee_angle)) + for i, knee_angle in enumerate(knee_sequence): + # process_frame 은 (angles, smoothed_knee_angle, rep_event, torso_tilt_deg) 4-튜플이다. + # 가운데 깊이 지표와 체간 기울기는 이 테스트가 검증하는 대상이 아니라 + # (각각 test_streaming_depth_metric.py, 체간 기울기 전용 테스트 담당) 버린다 — rep + # 집계는 이 값들에 의존하지 않는다. + angles, _, rep_event, _, _ = analyzer.process_frame(state, _frame(knee_angle), timestamp_sec=i / 3) if angles is not None: state.current_rep_frames.append( PerRepFrame(timestamp_sec=0.0, joint_coordinates="{}", angles=angles) @@ -108,8 +109,8 @@ def test_idle_frames_do_not_pile_into_next_rep(self) -> None: sequence = [170.0] * idle_frames + _ramp(170, 85, 5) + [85.0] + _ramp(85, 170, 5) + _STANDING_TAIL batch_sizes = [] - for knee_angle in sequence: - angles, _, rep_event = analyzer.process_frame(state, _frame(knee_angle)) + for i, knee_angle in enumerate(sequence): + angles, _, rep_event, _, _ = analyzer.process_frame(state, _frame(knee_angle), timestamp_sec=i / 3) if angles is not None: state.current_rep_frames.append( PerRepFrame(timestamp_sec=0.0, joint_coordinates="{}", angles=angles) @@ -139,5 +140,33 @@ def test_real_squat_after_sitting_rest_still_counts(self) -> None: self.assertEqual(_count_reps(rest + squat), 1) +# ── 스쿼트 깊이 모드 선택 (2026-09-21) ────────────────────────────────────── +# StreamingSquatAnalyzer는 세션마다 새로 만들어지지 않는 stateless 싱글턴이므로( +# app/core/analyzer_registry.py), 임계값 선택은 세션별 state.depth_mode를 통해서만 +# 이뤄져야 한다 — 이 테스트가 그 배선을 고정한다. +def test_process_frame_picks_thresholds_from_state_depth_mode(): + from app.core.squat_counter import DEPTH_MODE_THRESHOLDS + + analyzer = StreamingSquatAnalyzer("squat") + + half_state = SessionState(session_id=1, exercise_id=1, depth_mode="HALF") + analyzer.process_frame(half_state, _frame(175), timestamp_sec=0.0) + assert half_state.squat_counter.thresholds is DEPTH_MODE_THRESHOLDS["HALF"] + + full_state = SessionState(session_id=2, exercise_id=1, depth_mode="FULL") + analyzer.process_frame(full_state, _frame(175), timestamp_sec=0.0) + assert full_state.squat_counter.thresholds is DEPTH_MODE_THRESHOLDS["FULL"] + + # 기본값(필드를 아예 안 준 옛 상태)과 인식 못 하는 문자열은 분석기 자신의 기본값으로 + # 폴백한다 — 둘 다 FULL과 같은 임계값이다. + default_state = SessionState(session_id=3, exercise_id=1) + analyzer.process_frame(default_state, _frame(175), timestamp_sec=0.0) + assert default_state.squat_counter.thresholds == DEPTH_MODE_THRESHOLDS["FULL"] + + unknown_state = SessionState(session_id=4, exercise_id=1, depth_mode="BOGUS") + analyzer.process_frame(unknown_state, _frame(175), timestamp_sec=0.0) + assert unknown_state.squat_counter.thresholds == DEPTH_MODE_THRESHOLDS["FULL"] + + if __name__ == "__main__": unittest.main() diff --git a/backend/src/main/java/com/shadowfit/dto/coaching/TrainerRepEventDto.java b/backend/src/main/java/com/shadowfit/dto/coaching/TrainerRepEventDto.java index 25203116..6ee65619 100644 --- a/backend/src/main/java/com/shadowfit/dto/coaching/TrainerRepEventDto.java +++ b/backend/src/main/java/com/shadowfit/dto/coaching/TrainerRepEventDto.java @@ -10,7 +10,7 @@ */ public record TrainerRepEventDto( int repNumber, - double syncRate, + Double syncRate, boolean danger, String message ) { diff --git a/backend/src/main/java/com/shadowfit/dto/exercises/VideoRequestDto.java b/backend/src/main/java/com/shadowfit/dto/exercises/VideoRequestDto.java index 6ab45f86..4a1e9bd2 100644 --- a/backend/src/main/java/com/shadowfit/dto/exercises/VideoRequestDto.java +++ b/backend/src/main/java/com/shadowfit/dto/exercises/VideoRequestDto.java @@ -1,5 +1,6 @@ package com.shadowfit.dto.exercises; +import com.shadowfit.model.exercise.SquatDepthMode; import io.swagger.v3.oas.annotations.media.Schema; import jakarta.validation.constraints.NotNull; import lombok.AllArgsConstructor; @@ -31,4 +32,11 @@ public class VideoRequestDto { requiredMode = Schema.RequiredMode.REQUIRED) private Long exerciseId; + /** + * 스쿼트 깊이 모드(2026-09-21). 스쿼트가 아니거나 생략하면 FULL로 취급한다. + * 종목 선택과 같은 화면에서 고르므로 별도 검증은 없다. + */ + @Schema(description = "스쿼트 깊이 모드 (FULL/HALF, 생략 시 FULL)") + private SquatDepthMode depthMode; + } diff --git a/backend/src/main/java/com/shadowfit/dto/report/PoseFrameGrouping.java b/backend/src/main/java/com/shadowfit/dto/report/PoseFrameGrouping.java new file mode 100644 index 00000000..02290cac --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/PoseFrameGrouping.java @@ -0,0 +1,33 @@ +package com.shadowfit.dto.report; + +import java.util.ArrayList; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; + +/** + * {@code pose_data} 프레임을 rep 번호로 묶는 공용 규칙 — {@code SessionAnalysisCalculator}와 + * {@code SquatDepthAnalysisCalculator}가 똑같이 필요로 해서 뽑았다(2026-09-21). + * + *

{@code repNumber <= 0}은 "미상"이라 제외한다 — 컬럼이 생기기 전에 저장된 행과, rep_number를 + * 안 보내는 구버전 AI의 행이 여기 해당한다. 섞으면 서로 다른 rep이 하나로 뭉뚱그려진다 + * (자세한 배경은 {@code SessionAnalysisCalculator}의 원래 주석 참고 — 이슈 #74·#75). + */ +public final class PoseFrameGrouping { + + private PoseFrameGrouping() { + } + + /** rep 번호로 묶는다. 입력이 rep 오름차순이면 반환값의 순회 순서도 rep 오름차순이다. */ + public static Map> byRep(List poseFrames) { + Map> framesByRep = new LinkedHashMap<>(); + for (PoseFrameProjection frame : poseFrames) { + Integer repNumber = frame.repNumber(); + if (repNumber == null || repNumber <= 0) { + continue; + } + framesByRep.computeIfAbsent(repNumber, key -> new ArrayList<>()).add(frame); + } + return framesByRep; + } +} diff --git a/backend/src/main/java/com/shadowfit/dto/report/PoseFrameProjection.java b/backend/src/main/java/com/shadowfit/dto/report/PoseFrameProjection.java index 0058fdbe..f0ca6073 100644 --- a/backend/src/main/java/com/shadowfit/dto/report/PoseFrameProjection.java +++ b/backend/src/main/java/com/shadowfit/dto/report/PoseFrameProjection.java @@ -21,10 +21,29 @@ *

{@code id} 는 P5 Tier 0(32-deferred-items.md)로 추가됐다. 대표 프레임이 정해진 뒤 그 * 프레임의 {@code jointCoordinates} 하나만 PK로 다시 조회하기 위한 열쇠다 — 여기서 * 값을 직접 싣지 않는 이유는 그대로다(대부분의 프레임은 대표로 안 뽑혀 그 비용이 버려진다). + * + *

{@code leadLeg} 는 V24(2026-09-27)로 추가됐다 — 런지에서 {@code smoothedKneeAngle} 이 + * "앞다리 무릎각"이 되면서(좌우 평균이 아니라), 그 값이 어느 다리의 것인지 없이는 좌/우로 나눠 + * 채점할 수 없다. {@code "left"}·{@code "right"} 둘 중 하나거나, 스쿼트·구버전 행이면 {@code null} + * 이다. + * + *

{@code torsoTiltDeg} 는 V25(2026-09-28)로 추가됐다 — 어깨 중점-엉덩이 중점 벡터가 수직에서 + * 벗어난 각도(도), 스쿼트·런지 공용. {@link com.shadowfit.service.report.SquatTrunkLeanAnalysisCalculator}/ + * {@link com.shadowfit.service.report.LungeTrunkLeanAnalysisCalculator} 가 rep 내 평균으로 + * "그 회차 내내 체간 자세가 얼마나 무너졌는가"를 채점하는 근거값이다. 구버전 행이면 + * {@code null}(0과 구분 — 0은 "완전 직립"이라는 유효한 각도값이라 별도 미상 마커가 필요하다). + * + *

{@code staggerRatio} 는 V26(2026-09-28)로 추가됐다 — 두 발목 사이 거리 / 어깨-엉덩이 길이, + * 런지 전용("보폭이 얼마나 벌어졌는가"). {@link com.shadowfit.service.report.LungeStepLengthAnalysisCalculator} + * 가 짧은 보폭일수록 깊은 무릎 굴곡 구간에서 슬개대퇴 관절 부하가 커진다는 문헌 근거로 채점한다. + * 스쿼트·구버전 행이면 {@code null}이다. */ public record PoseFrameProjection( Long id, Double timestampSec, Double syncRate, Integer repNumber, - Double smoothedKneeAngle) {} + Double smoothedKneeAngle, + String leadLeg, + Double torsoTiltDeg, + Double staggerRatio) {} diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/ExerciseSessionDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/ExerciseSessionDto.java index 00742b2b..0482d8ee 100644 --- a/backend/src/main/java/com/shadowfit/dto/report/detailreport/ExerciseSessionDto.java +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/ExerciseSessionDto.java @@ -6,6 +6,7 @@ @Getter @Setter public class ExerciseSessionDto { + private boolean scoreAvailable; private Long sessionId; // 클릭 시 이동을 위한 ID private String exerciseName; // "숄더프레스" private String setSummary; // "4세트 x 10회" diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeDepthAnalysisDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeDepthAnalysisDto.java new file mode 100644 index 00000000..6f7e09cf --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeDepthAnalysisDto.java @@ -0,0 +1,33 @@ +package com.shadowfit.dto.report.detailreport; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.List; + +/** + * 런지 깊이 정확도 리포트 (2026-09-27) — {@code LungeDepthAnalysisCalculator}가 만들고 + * {@link SessionDetailedAnalysis}에 실려 precompute-on-write로 저장된다. + * + *

런지 세션(exercise_id=2)이면서 유효한 좌우 구분 깊이 데이터가 있을 때만 만들어진다 — + * 스쿼트 세션·구버전 데이터·좌우 정보가 없는 세션(V24 이전에 완료된 런지 등)은 이 필드 + * 자체가 null이다({@link SessionReportResponseDto}의 {@code scoreAvailable}과 같은 널 가드 규약). + * + *

목표선(100도)의 근거는 {@code docs/decisions/lunge-repetition-counting.md} §2·§3 — + * Sousa et al.(2026)이 런지 "진입" 단계를 양 무릎 100도 미만으로 정의한 것과 같은 값이다. + * 채점 자체는 앞다리(lead) 무릎각 하나만 본다 — 뒷다리는 판정에 들어가지 않는다. + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class LungeDepthAnalysisDto { + private int depthScore; // 회차별 depthScore의 평균, 0-100 + private String depthGrade; // "EXCELLENT" | "GOOD" | "FAIR" | "NEEDS_WORK" | "POOR" + private Double leftAvgKneeAngle; // 왼쪽 회차 평균 최저 무릎각 — 왼쪽 회차가 없으면 null + private Double rightAvgKneeAngle; // 오른쪽 회차 평균 최저 무릎각 — 오른쪽 회차가 없으면 null + private List repDepths; + private List narrative; // 회차별 한국어 코멘트, 최대 4문장 +} diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeRepDepthDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeRepDepthDto.java new file mode 100644 index 00000000..20668d54 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeRepDepthDto.java @@ -0,0 +1,31 @@ +package com.shadowfit.dto.report.detailreport; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * 회차(rep) 하나의 깊이 정확도 — {@link RepDepthDto}의 런지 버전 (2026-09-27). + * + *

{@link RepDepthDto}를 그대로 재사용하지 않은 이유: 런지는 좌/우 어느 다리인지가 + * 채점만큼 중요한 정보라({@code side}), 스쿼트 전용 DTO에 필드를 얹어 결합시키는 대신 + * 형제 DTO로 분리했다 — {@link LungeDepthAnalysisCalculator}가 + * {@link com.shadowfit.service.report.SquatDepthAnalysisCalculator}의 형제 클래스로 분리된 것과 + * 같은 이유(각 종목의 계산이 서로의 가정을 안 타게 한다). + * + *

{@code minKneeAngle}은 그 rep에서 앞다리가 가장 깊게 굽혀진 순간의 무릎각이다 — 런지 + * 반복 판정 자체가 그 값(lead 다리 무릎각)으로 바닥을 확인하므로, "이 rep의 바닥"과 "채점 + * 대상 프레임"이 서로 다른 근거를 갖지 않는다(ai-server app/core/lunge_analyzer.py). + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class LungeRepDepthDto { + private int repNumber; + private String side; // "left" | "right" + private double minKneeAngle; + private int depthScore; // 0-100 + private String timeStamp; // "01:15" — 가장 깊었던 프레임 기준 +} diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeStepLengthAnalysisDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeStepLengthAnalysisDto.java new file mode 100644 index 00000000..9c35357a --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/LungeStepLengthAnalysisDto.java @@ -0,0 +1,29 @@ +package com.shadowfit.dto.report.detailreport; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.List; + +/** + * 런지 보폭 정확도 리포트 (2026-09-28). 런지 전용 — 스쿼트는 보폭 개념이 없어 대응 필드가 + * 없다(깊이·체간 기울기와 달리 스쿼트 형제 계산기가 존재하지 않는다). + * + *

🔴 아래 임계값(1.0/0.6)은 실촬영 4개 중 검증된 3개(정상·얕음·워킹)에서 관찰한 stagger + * 분포와 문헌(Escamilla et al. 계열의 짧은 보폭-슬개대퇴 부하 연구)을 근거로 잡은 잠정값이다. + * "얕음"으로 이미 확인된 영상이 "정상" 영상보다 stagger도 독립적으로 낮게 나와(중앙값 0.88 vs + * 1.12) 우연이 아닌 실제 상관관계로 보이지만, 표본이 3개뿐이라 확정 임계값은 아니다 — 스쿼트 + * 하프 모드·런지 체간 기울기와 같은 검증 절차(실촬영 확보 후 재검토)를 거쳐야 한다. + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class LungeStepLengthAnalysisDto { + private int stepScore; // 세션 평균, 0-100 + private String stepGrade; // EXCELLENT/GOOD/FAIR/NEEDS_WORK/POOR + private List repStepLengths; + private List narrative; // 회차별 한국어 코멘트, 최대 4문장 +} diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepDepthDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepDepthDto.java new file mode 100644 index 00000000..9c7f5e98 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepDepthDto.java @@ -0,0 +1,25 @@ +package com.shadowfit.dto.report.detailreport; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * 회차(rep) 하나의 깊이 정확도 — {@link RepSyncRateDto}의 깊이 버전 (2026-09-21). + * + *

{@code minKneeAngle}은 그 rep에서 가장 깊게 앉은 순간의 무릎각 + * ({@code SessionAnalysisCalculator.pickRepresentative}가 쓰는 것과 같은 선택 기준 — + * 스쿼트 반복 판정 자체가 그 값으로 바닥을 확인하므로, "이 rep의 바닥"과 "채점 대상 프레임"이 + * 서로 다른 근거를 갖지 않는다). + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class RepDepthDto { + private int repNumber; + private double minKneeAngle; + private int depthScore; // 0-100 + private String timeStamp; // "01:15" — 가장 깊었던 프레임 기준 +} diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepStepLengthDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepStepLengthDto.java new file mode 100644 index 00000000..ebdc0e44 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepStepLengthDto.java @@ -0,0 +1,23 @@ +package com.shadowfit.dto.report.detailreport; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * 회차(rep) 하나의 보폭 정확도 — 런지 전용(2026-09-28). {@code staggerRatio}는 두 발목 사이 + * 거리 / 어깨-엉덩이 길이다. 이 앱의 런지는 발 위치가 고정된 채 굽혔다 펴는 방식이라(제자리 + * 펄싱, docs/decisions/lunge-repetition-counting.md 참고) rep 안에서 값이 거의 변하지 + * 않는다 — 깊이·체간 축처럼 최솟값/평균을 따로 집계하지 않고 대표 프레임 값을 그대로 쓴다. + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class RepStepLengthDto { + private int repNumber; + private double staggerRatio; + private int stepScore; // 0-100 + private String timeStamp; // "01:15" +} diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepTrunkLeanDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepTrunkLeanDto.java new file mode 100644 index 00000000..bae59dc1 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/RepTrunkLeanDto.java @@ -0,0 +1,25 @@ +package com.shadowfit.dto.report.detailreport; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +/** + * 회차(rep) 하나의 체간 자세 정확도 — {@link RepDepthDto}의 체간 기울기 버전 (2026-09-28). + * + *

{@code avgTiltDeg}는 이 rep에 속한 프레임들의 {@code torsoTiltDeg} 평균이다. + * 깊이 점수가 "최솟값 프레임"(가장 깊었던 한 순간)을 쓰는 것과 다른 기준이다 — 깊이는 "얼마나 + * 갔는가"(정점 하나가 의미 있음)이고 체간 자세는 "그 rep 내내 얼마나 무너졌는가"(평균이 + * 의미 있음)이기 때문이다. 기존 실시간 BACK_BENT 판정(pose.py)도 이미 rep 전체 평균을 쓴다. + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class RepTrunkLeanDto { + private int repNumber; + private double avgTiltDeg; + private int tiltScore; // 0-100 + private String timeStamp; // "01:15" — 그 rep의 첫 프레임 기준 +} diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/SessionDetailedAnalysis.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/SessionDetailedAnalysis.java index b67e2b76..0f2f4e85 100644 --- a/backend/src/main/java/com/shadowfit/dto/report/detailreport/SessionDetailedAnalysis.java +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/SessionDetailedAnalysis.java @@ -33,4 +33,35 @@ public class SessionDetailedAnalysis { /** 회차별 싱크로율(rep 오름차순). 측정된 rep 이 없으면 빈 리스트. */ private List repTrend; + + /** + * 스쿼트 깊이 정확도 리포트 (2026-09-21). 스쿼트가 아니거나 깊이 데이터가 없으면 null — + * 구버전으로 저장된 행을 이 타입으로 읽어도 필드가 없으니 자동으로 null이 된다(하위호환). + */ + private SquatDepthAnalysisDto squatDepthAnalysis; + + /** + * 런지 깊이 정확도 리포트 (2026-09-27). 런지가 아니거나 좌우 구분 깊이 데이터가 없으면 + * null — 위와 같은 하위호환 규약(V24 이전에 완료된 런지 세션도 이 필드가 null이 된다). + */ + private LungeDepthAnalysisDto lungeDepthAnalysis; + + /** + * 스쿼트 체간 기울기 정확도 리포트 (2026-09-28). 스쿼트가 아니거나 체간 기울기 데이터가 + * 없으면 null — 위와 같은 하위호환 규약(V25 이전에 완료된 세션도 이 필드가 null이 된다). + */ + private TrunkLeanAnalysisDto squatTrunkLeanAnalysis; + + /** + * 런지 체간 기울기 정확도 리포트 (2026-09-28). 런지가 아니거나 체간 기울기 데이터가 + * 없으면 null — 위와 같은 하위호환 규약. + */ + private TrunkLeanAnalysisDto lungeTrunkLeanAnalysis; + + /** + * 런지 보폭 정확도 리포트 (2026-09-28). 런지가 아니거나 보폭 데이터가 없으면 null — + * 위와 같은 하위호환 규약(V26 이전에 완료된 세션도 이 필드가 null이 된다). 스쿼트는 + * 보폭 개념이 없어 대응 필드 자체가 없다. + */ + private LungeStepLengthAnalysisDto lungeStepLengthAnalysis; } diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/SessionReportResponseDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/SessionReportResponseDto.java index d7d063a5..d09a0393 100644 --- a/backend/src/main/java/com/shadowfit/dto/report/detailreport/SessionReportResponseDto.java +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/SessionReportResponseDto.java @@ -16,6 +16,8 @@ public class SessionReportResponseDto { private Long sessionId; private int avgSyncRate; + // 횟수만 측정한 운동의 0 기본값을 점수로 표시하지 않도록 구분한다. + private boolean scoreAvailable; private int totalReps; private int workoutMinutes; private int caloriesBurned; @@ -32,6 +34,36 @@ public class SessionReportResponseDto { */ private List repTrend; + /** + * 스쿼트 깊이 정확도 리포트(2026-09-21). 런지 세션·구버전 세션·깊이 데이터가 없는 세션은 + * null — {@code worstSection}과 같은 널 가드 규약이다. + */ + private SquatDepthAnalysisDto squatDepthAnalysis; + + /** + * 런지 깊이 정확도 리포트(2026-09-27). 스쿼트 세션·구버전 세션(V24 이전)·좌우 구분 깊이 + * 데이터가 없는 세션은 null — 위와 같은 널 가드 규약이다. + */ + private LungeDepthAnalysisDto lungeDepthAnalysis; + + /** + * 스쿼트 체간 기울기 정확도 리포트(2026-09-28). 런지 세션·구버전 세션(V25 이전)·체간 기울기 + * 데이터가 없는 세션은 null — 위와 같은 널 가드 규약이다. + */ + private TrunkLeanAnalysisDto squatTrunkLeanAnalysis; + + /** + * 런지 체간 기울기 정확도 리포트(2026-09-28). 스쿼트 세션·구버전 세션·체간 기울기 데이터가 + * 없는 세션은 null — 위와 같은 널 가드 규약이다. + */ + private TrunkLeanAnalysisDto lungeTrunkLeanAnalysis; + + /** + * 런지 보폭 정확도 리포트(2026-09-28). 스쿼트 세션(보폭 개념 없음)·구버전 세션(V26 이전)· + * 보폭 데이터가 없는 세션은 null — 위와 같은 널 가드 규약이다. + */ + private LungeStepLengthAnalysisDto lungeStepLengthAnalysis; + private List syncRateDetails; private ComparisonWithPreviousDto comparisonWithPrevious; @@ -56,6 +88,7 @@ public static SessionReportResponseDto of(Session session, Report report) { SessionReportResponseDto dto = new SessionReportResponseDto(); dto.setSessionId(session.getId()); dto.setAvgSyncRate(intOrZero(session.getAvgSyncRate())); + dto.setScoreAvailable(session.getAvgSyncRate() != null); dto.setTotalReps(session.getTotalReps() == null ? 0 : session.getTotalReps()); dto.setWorkoutMinutes((int) java.time.Duration.between(session.getStartTime(), session.getEndTime()).toMinutes()); dto.setCaloriesBurned(intOrZero(session.getCaloriesBurned())); diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/SquatDepthAnalysisDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/SquatDepthAnalysisDto.java new file mode 100644 index 00000000..db0fce1e --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/SquatDepthAnalysisDto.java @@ -0,0 +1,32 @@ +package com.shadowfit.dto.report.detailreport; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.List; + +/** + * 스쿼트 깊이 정확도 리포트 (2026-09-21) — {@code SquatDepthAnalysisCalculator}가 만들고 + * {@link SessionDetailedAnalysis}에 실려 precompute-on-write로 저장된다. + * + *

스쿼트 세션(exercise_id=1)이면서 유효한 {@code smoothedKneeAngle} 데이터가 있을 때만 + * 만들어진다 — 런지 세션이나 구버전 데이터는 이 필드 자체가 null이다 + * ({@link com.shadowfit.dto.report.detailreport.SessionReportResponseDto}의 {@code scoreAvailable}과 + * 같은 널 가드 규약). + * + *

깊이 임계값(115/140도)은 실촬영 하프 스쿼트 영상으로 검증되기 전까지 잠정값이다 — + * {@code docs/decisions/squat-repetition-counting.md}의 2026-09-21 절 참고. + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class SquatDepthAnalysisDto { + private String depthMode; // "FULL" | "HALF" — 세션 완료 시점의 squatDepthMode + private int depthScore; // 회차별 depthScore의 평균, 0-100 + private String depthGrade; // "EXCELLENT" | "GOOD" | "FAIR" | "NEEDS_WORK" | "POOR" + private List repDepths; + private List narrative; // 회차별 한국어 코멘트, 최대 4문장 +} diff --git a/backend/src/main/java/com/shadowfit/dto/report/detailreport/TrunkLeanAnalysisDto.java b/backend/src/main/java/com/shadowfit/dto/report/detailreport/TrunkLeanAnalysisDto.java new file mode 100644 index 00000000..45c8acc2 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/dto/report/detailreport/TrunkLeanAnalysisDto.java @@ -0,0 +1,30 @@ +package com.shadowfit.dto.report.detailreport; + +import lombok.AllArgsConstructor; +import lombok.Getter; +import lombok.NoArgsConstructor; +import lombok.Setter; + +import java.util.List; + +/** + * 체간(몸통) 기울기 정확도 리포트 (2026-09-28). 스쿼트·런지 공용 셰이프 — 좌우·모드 구분이 + * 필요한 깊이 DTO(SquatDepthAnalysisDto/LungeDepthAnalysisDto)와 달리 이 축은 두 운동이 + * 같은 계산(rep 평균 체간 기울기)을 쓰므로 공유해도 "다른 운동의 가정을 상속"하지 않는다. + * 실제 채점 임계값은 {@link com.shadowfit.service.report.SquatTrunkLeanAnalysisCalculator}/ + * {@code LungeTrunkLeanAnalysisCalculator}가 운동별로 따로 정의한다. + * + *

스쿼트 세션이면 {@code SessionDetailedAnalysis.squatTrunkLeanAnalysis}에, 런지 세션이면 + * {@code lungeTrunkLeanAnalysis}에 실린다 — 두 필드 중 세션의 운동에 맞는 하나만 non-null이다 + * (squatDepthAnalysis/lungeDepthAnalysis와 같은 null 가드 규약). + */ +@Getter +@Setter +@NoArgsConstructor +@AllArgsConstructor +public class TrunkLeanAnalysisDto { + private int tiltScore; // 세션 평균, 0-100 + private String tiltGrade; // EXCELLENT/GOOD/FAIR/NEEDS_WORK/POOR — 깊이 등급과 같은 5단계 + private List repTrunkLeans; + private List narrative; // 회차별 한국어 코멘트, 최대 4문장 +} diff --git a/backend/src/main/java/com/shadowfit/model/exercise/Exercise.java b/backend/src/main/java/com/shadowfit/model/exercise/Exercise.java index 8bed1870..bbf99bda 100644 --- a/backend/src/main/java/com/shadowfit/model/exercise/Exercise.java +++ b/backend/src/main/java/com/shadowfit/model/exercise/Exercise.java @@ -77,6 +77,11 @@ public class Exercise { @Column(name = "analysis_supported", nullable = false) private Boolean analysisSupported = false; + /** 기준 자세 채점 없이 반복 횟수만 측정하는 종목. */ + @Builder.Default + @Column(name = "repetition_only", nullable = false) + private Boolean repetitionOnly = false; + @CreationTimestamp @Column(nullable = false, updatable = false) private LocalDateTime createdAt; @@ -119,4 +124,4 @@ public boolean changeAnalysisSupport(boolean supported) { this.analysisSupported = supported; return before; } -} \ No newline at end of file +} diff --git a/backend/src/main/java/com/shadowfit/model/exercise/PoseData.java b/backend/src/main/java/com/shadowfit/model/exercise/PoseData.java index 766d3a30..67772985 100644 --- a/backend/src/main/java/com/shadowfit/model/exercise/PoseData.java +++ b/backend/src/main/java/com/shadowfit/model/exercise/PoseData.java @@ -73,6 +73,35 @@ public class PoseData { @Builder.Default private Double smoothedKneeAngle = 0.0; + /** + * 이 프레임(rep)이 속한 앞다리 — {@code "left"} | {@code "right"}, 스쿼트·구버전 행은 + * {@code null}(V24, 2026-09-27). 런지에서는 {@link #smoothedKneeAngle}이 좌우 평균이 아니라 + * 이 다리의 무릎각이라(ai-server app/core/lunge_analyzer.py), 좌/우로 나눠 채점하려면 + * 이 값이 있어야 한다. proto3 빈 문자열은 저장 계층(PoseDataService)에서 null로 접는다 — + * "런지인데 판정 전"과 "이 개념 자체가 없음(스쿼트)"을 구분하기 위해서다. + */ + @Column(name = "lead_leg", length = 5) + private String leadLeg; + + /** + * 어깨 중점-엉덩이 중점 벡터가 수직에서 벗어난 각도(도). 0=완전 직립, 스쿼트·런지 공용 + * (V25, 2026-09-28). {@link com.shadowfit.service.report.SquatTrunkLeanAnalysisCalculator}/ + * {@code LungeTrunkLeanAnalysisCalculator}가 rep 내 평균으로 체간 자세 점수를 매기는 근거값이다. + * 구버전 행이면 {@code null} — 0은 "완전 직립"이라는 유효한 값이라 leadLeg처럼 빈 문자열을 + * null로 접는 변환이 필요 없다(proto3 기본값 0.0을 그대로 저장해도 뜻이 통한다). + */ + @Column(name = "torso_tilt_deg") + private Double torsoTiltDeg; + + /** + * 두 발목 사이 거리 / 어깨-엉덩이 길이 — 런지 전용 "보폭이 얼마나 벌어졌는가" 비율 + * (V26, 2026-09-28). {@link com.shadowfit.service.report.LungeStepLengthAnalysisCalculator}가 + * 짧은 보폭일수록 깊은 무릎 굴곡 구간에서 슬개대퇴 관절 부하가 커진다는 문헌 근거로 채점한다. + * 스쿼트·구버전 행이면 {@code null}. + */ + @Column(name = "stagger_ratio") + private Double staggerRatio; + @Column(length = 500) private String feedbackMessage; // AI가 주는 실시간 피드백 diff --git a/backend/src/main/java/com/shadowfit/model/exercise/Session.java b/backend/src/main/java/com/shadowfit/model/exercise/Session.java index 896bf311..bce83277 100644 --- a/backend/src/main/java/com/shadowfit/model/exercise/Session.java +++ b/backend/src/main/java/com/shadowfit/model/exercise/Session.java @@ -74,6 +74,16 @@ public class Session { @Builder.Default private Status status = Status.IN_PROGRESS; + /** + * 스쿼트 깊이 모드 FULL/HALF (2026-09-21). 종목 선택과 같은 화면에서 세션 시작 시 고른다. + * 스쿼트가 아닌 세션에는 의미가 없지만 항상 채워진다(V23이 NOT NULL DEFAULT 'FULL') — + * {@code SquatDepthAnalysisCalculator}가 스쿼트 세션에서만 이 값을 읽는다. + */ + @Enumerated(EnumType.STRING) + @Builder.Default + @Column(nullable = false, length = 10) + private SquatDepthMode squatDepthMode = SquatDepthMode.FULL; + /** * 세션 소유권 검증용 비밀값 (#187 안 (d)). 생성은 {@code SessionNonceGenerator} 가 한다. * diff --git a/backend/src/main/java/com/shadowfit/model/exercise/SquatDepthMode.java b/backend/src/main/java/com/shadowfit/model/exercise/SquatDepthMode.java new file mode 100644 index 00000000..3a66b747 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/model/exercise/SquatDepthMode.java @@ -0,0 +1,10 @@ +package com.shadowfit.model.exercise; + +/** + * 스쿼트 깊이 모드. 운동 시작 전 종목 선택과 같은 화면에서 사용자가 고른다(2026-09-21). + * 스쿼트가 아닌 세션에서는 의미가 없다 — 항상 FULL로 채워지지만 무시된다. + */ +public enum SquatDepthMode { + FULL, // 무릎각 <=115도 — 기존 기본 판정, 변경 없음 + HALF // 무릎각 115~140도 밴드 +} diff --git a/backend/src/main/java/com/shadowfit/repository/exercise/PoseDataRepository.java b/backend/src/main/java/com/shadowfit/repository/exercise/PoseDataRepository.java index f86d596c..7da3cda7 100644 --- a/backend/src/main/java/com/shadowfit/repository/exercise/PoseDataRepository.java +++ b/backend/src/main/java/com/shadowfit/repository/exercise/PoseDataRepository.java @@ -46,7 +46,7 @@ public interface PoseDataRepository extends JpaRepository { * "프레임이 아예 없다"와 "rep 을 알 수 없는 프레임뿐이다"를 계산기가 구분해 다룰 수 있다. */ @Query("SELECT new com.shadowfit.dto.report.PoseFrameProjection(" + - "p.id, p.timestampSec, p.syncRate, p.repNumber, p.smoothedKneeAngle) " + + "p.id, p.timestampSec, p.syncRate, p.repNumber, p.smoothedKneeAngle, p.leadLeg, p.torsoTiltDeg, p.staggerRatio) " + "FROM PoseData p WHERE p.session.id = :sessionId AND p.createdAt = :sessionAnchor " + "ORDER BY p.repNumber ASC, p.timestampSec ASC") List findFramesBySessionId(@Param("sessionId") Long sessionId, @@ -107,7 +107,7 @@ int findMaxRepNumberBySessionId(@Param("sessionId") Long sessionId, * DB 에서 한 번에 접으려면 파생 테이블(native)이 필요한데, 그 대가로 얻는 게 없다. */ @Query("SELECT AVG(p.syncRate) FROM PoseData p " + - "WHERE p.session.id = :sessionId AND p.createdAt = :sessionAnchor AND p.repNumber > 0 " + + "WHERE p.session.id = :sessionId AND p.createdAt = :sessionAnchor AND p.repNumber > 0 AND p.syncRate IS NOT NULL " + "GROUP BY p.repNumber ORDER BY p.repNumber") List findRepAverageSyncRates(@Param("sessionId") Long sessionId, @Param("sessionAnchor") LocalDateTime sessionAnchor); @@ -128,4 +128,4 @@ List findRepAverageSyncRates(@Param("sessionId") Long sessionId, // 핫패스에 비용이 얹힌다"를 근거로 이 방식을 골랐는데, 그 UPDATE 는 이미 다른 이유로 // 존재한다(session-liveness-vs-elapsed-time.md ㄷ안 — 타임아웃·재부착 판정의 앵커). // 즉 피하려던 비용은 이미 내고 있고, 근거가 사라졌다. -} \ No newline at end of file +} diff --git a/backend/src/main/java/com/shadowfit/service/exercise/ExerciseAnalysisCapabilities.java b/backend/src/main/java/com/shadowfit/service/exercise/ExerciseAnalysisCapabilities.java new file mode 100644 index 00000000..1e69327e --- /dev/null +++ b/backend/src/main/java/com/shadowfit/service/exercise/ExerciseAnalysisCapabilities.java @@ -0,0 +1,14 @@ +package com.shadowfit.service.exercise; + +/** 미측정 점수를 실제 0점으로 취급하지 않도록 종목의 분석 범위를 확인한다. */ +public final class ExerciseAnalysisCapabilities { + private ExerciseAnalysisCapabilities() {} + + public static boolean isCountOnly(com.shadowfit.model.exercise.Exercise exercise) { + return exercise != null && Boolean.TRUE.equals(exercise.getRepetitionOnly()); + } + + public static boolean isCountOnly(com.shadowfit.model.exercise.Session session) { + return isCountOnly(session.getExercise()); + } +} diff --git a/backend/src/main/java/com/shadowfit/service/exercise/ExerciseAnalysisService.java b/backend/src/main/java/com/shadowfit/service/exercise/ExerciseAnalysisService.java index b66b0e19..0983afba 100644 --- a/backend/src/main/java/com/shadowfit/service/exercise/ExerciseAnalysisService.java +++ b/backend/src/main/java/com/shadowfit/service/exercise/ExerciseAnalysisService.java @@ -319,15 +319,21 @@ public StartedSession startAnalysis(VideoRequestDto appDto, Long currentMemberId Member member = memberRepository.findById(currentMemberId) .orElseThrow(() -> new BusinessException(ErrorCode.USER_NOT_FOUND)); - String finalUrl = member.getPreferredUrl(); + boolean countOnly = exercisesRepository.findByIdCached(appDto.getExerciseId()) + .map(ExerciseAnalysisCapabilities::isCountOnly).orElse(false); + String finalUrl = countOnly ? "" : member.getPreferredUrl(); - if (finalUrl == null || finalUrl.isEmpty()) { + if (!countOnly && (finalUrl == null || finalUrl.isEmpty())) { throw new BusinessException(ErrorCode.INVALID_INPUT_VALUE); } Session savedSession = sessionService.createSession(appDto, currentMemberId, finalUrl); Long sessionId = savedSession.getId(); String persona = member.getSelectedPersona().name(); + // 저장된 엔티티에서 읽는다(persona와 동일한 이유) — appDto.getDepthMode()가 null이어도 + // createSession이 이미 FULL로 기본값을 채워 저장했으므로, 클라가 받는 값과 AI가 받는 + // 값이 어긋나지 않는다. + String squatDepthMode = savedSession.getSquatDepthMode().name(); // 비동기로 FastAPI에 분석 요청 — self를 거쳐야 @Async가 Spring 프록시를 타고 실제로 // 비동기 실행됨. this.로 호출하면 자기호출(self-invocation)이라 AOP 프록시를 우회해서 @@ -343,7 +349,7 @@ public StartedSession startAnalysis(VideoRequestDto appDto, Long currentMemberId @Override public void afterCommit() { self.sendAnalysisRequestToFastApi(sessionId, appDto, finalUrl, persona, - savedSession.getSessionNonce()); + savedSession.getSessionNonce(), squatDepthMode); } } ); @@ -362,7 +368,7 @@ public void afterCommit() { @Async("applicationTaskExecutor") @Transactional(readOnly = true) public void sendAnalysisRequestToFastApi(Long sessionId, VideoRequestDto appDto, String finalUrl, String persona, - String sessionNonce) { + String sessionNonce, String squatDepthMode) { // 여기는 이미 @Async 워커 스레드 — cid 는 AsyncConfig 의 TaskDecorator 가 넘겨줬고, // 세션 id 는 이 흐름의 시작점인 여기서 얹는다. try (CorrelationIds.Scope ignored = CorrelationIds.withSession(sessionId)) { @@ -382,7 +388,8 @@ public void sendAnalysisRequestToFastApi(Long sessionId, VideoRequestDto appDto, .setSessionId(sessionId) .setReferenceSource(finalUrl) .setPersona(persona) - .setSessionNonce(sessionNonce == null ? "" : sessionNonce); + .setSessionNonce(sessionNonce == null ? "" : sessionNonce) + .setDepthMode(squatDepthMode == null ? "" : squatDepthMode); for (ExerciseReference ref : referencePoses) { requestBuilder.addReferencePoses(PoseDataRequest.newBuilder() diff --git a/backend/src/main/java/com/shadowfit/service/exercise/PoseDataService.java b/backend/src/main/java/com/shadowfit/service/exercise/PoseDataService.java index ca027905..82a7ad9b 100644 --- a/backend/src/main/java/com/shadowfit/service/exercise/PoseDataService.java +++ b/backend/src/main/java/com/shadowfit/service/exercise/PoseDataService.java @@ -55,8 +55,8 @@ public class PoseDataService { // ODKU 는 중복 키만 흡수하고 NOT NULL 위반은 그대로 터뜨린다. private static final String INSERT_POSE_SQL = "INSERT INTO pose_data " + - "(session_id, rep_number, timestamp_sec, joint_coordinates, sync_rate, smoothed_knee_angle, feedback_message, created_at) " + - "VALUES (?, ?, ?, ?, ?, ?, ?, ?) " + + "(session_id, rep_number, timestamp_sec, joint_coordinates, sync_rate, smoothed_knee_angle, feedback_message, created_at, lead_leg, torso_tilt_deg, stagger_ratio) " + + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?) " + "ON DUPLICATE KEY UPDATE session_id = session_id"; // 다운샘플 윈도우 크기 — R-sweep 실측(docs/decisions/pose-ingest-downsampling.md §5-1(4))에서 @@ -172,13 +172,35 @@ public void setValues(PreparedStatement ps, int i) throws SQLException { ps.setInt(2, grpc.getRepNumber()); ps.setDouble(3, grpc.getTimestampSec()); ps.setString(4, grpc.getJointCoordinates()); - ps.setDouble(5, grpc.getSyncRate()); + if (ExerciseAnalysisCapabilities.isCountOnly(session)) { + ps.setNull(5, java.sql.Types.DECIMAL); + } else { + ps.setDouble(5, grpc.getSyncRate()); + } // 구버전 AI 는 이 필드를 안 보내 0(미상)이 들어온다 — rep_number 와 같은 방식이라 // 배포 순서를 맞추지 않아도 깨지지 않는다. 스쿼트 무릎각은 0 이 될 수 없으므로 // 유효값과 구분되고, 대표 프레임 선택에서 후보에서 빠진다. ps.setDouble(6, grpc.getSmoothedKneeAngle()); ps.setString(7, grpc.getFeedbackMessage()); ps.setObject(8, sessionAnchor); + // proto3 는 "안 보냄"을 빈 문자열로 표현한다 — 스쿼트 프레임과 구버전 AI가 전부 + // 여기 해당한다. 빈 문자열을 그대로 저장하면 "런지인데 판정 전"과 "이 개념 자체가 + // 없음"이 안 갈리므로 NULL로 접는다(PoseData.leadLeg 주석과 같은 이유). + String leadLeg = grpc.getLeadLeg(); + if (leadLeg == null || leadLeg.isBlank()) { + ps.setNull(9, java.sql.Types.VARCHAR); + } else { + ps.setString(9, leadLeg); + } + // torso_tilt_deg는 leadLeg와 달리 0.0 자체가 유효값(완전 직립)이라 접을 필요가 + // 없다 — proto3 미전송 구버전 AI도 그냥 0.0이 들어오고, 이는 TrunkLeanAnalysis + // Calculator가 "체간 자세 완벽"과 구분 없이 그대로 채점에 반영한다(감수한 왜곡, + // proto 필드 주석 참고). + ps.setDouble(10, grpc.getTorsoTiltDeg()); + // stagger_ratio는 런지 전용 — torso_tilt_deg와 같은 이유로 0.0을 그대로 저장한다 + // (LungeStepLengthAnalysisCalculator가 런지 세션만 채점하므로 스쿼트 행의 0은 + // 소비되지 않는다). + ps.setDouble(11, grpc.getStaggerRatio()); } @Override @@ -254,7 +276,9 @@ private void registerTrainerRelay(Session session, List downsam .findFirst() .orElse(null); TrainerRepEventDto event = new TrainerRepEventDto( - representative.getRepNumber(), representative.getSyncRate(), message != null, message); + representative.getRepNumber(), + ExerciseAnalysisCapabilities.isCountOnly(session) ? null : representative.getSyncRate(), + message != null, message); Long userId = session.getMember().getId(); TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronization() { @@ -361,4 +385,4 @@ public void saveReferencePoses(Long exerciseId, List repAverages = poseDataRepository.findRepAverageSyncRates(session.getId(), session.getStartTime()); if (repAverages.isEmpty()) { @@ -168,16 +181,23 @@ private void precomputeReport(Session session) { List poseFrames = poseDataRepository.findFramesBySessionId(session.getId(), session.getStartTime()); WorstSectionDto worstSection = sessionAnalysisCalculator.calculate(session, poseFrames); List repTrend = sessionAnalysisCalculator.calculateRepTrend(poseFrames); + SquatDepthAnalysisDto squatDepthAnalysis = squatDepthAnalysisCalculator.calculate(session, poseFrames); + LungeDepthAnalysisDto lungeDepthAnalysis = lungeDepthAnalysisCalculator.calculate(session, poseFrames); + TrunkLeanAnalysisDto squatTrunkLeanAnalysis = squatTrunkLeanAnalysisCalculator.calculate(session, poseFrames); + TrunkLeanAnalysisDto lungeTrunkLeanAnalysis = lungeTrunkLeanAnalysisCalculator.calculate(session, poseFrames); + LungeStepLengthAnalysisDto lungeStepLengthAnalysis = lungeStepLengthAnalysisCalculator.calculate(session, poseFrames); Report report = new Report(); report.setMember(session.getMember()); report.setSession(session); - // 둘 다 비면 컬럼을 비워 둔다 — 읽기 경로가 "저장된 게 없다"로 보고 재계산을 시도하는데, + // 일곱 다 비면 컬럼을 비워 둔다 — 읽기 경로가 "저장된 게 없다"로 보고 재계산을 시도하는데, // 프레임이 없어서 비었던 것이라면 재계산도 같은 결과라 손해가 없다. - if (worstSection != null || !repTrend.isEmpty()) { + if (worstSection != null || !repTrend.isEmpty() || squatDepthAnalysis != null || lungeDepthAnalysis != null + || squatTrunkLeanAnalysis != null || lungeTrunkLeanAnalysis != null || lungeStepLengthAnalysis != null) { try { report.setDetailedAnalysis(objectMapper.writeValueAsString( - new SessionDetailedAnalysis(worstSection, repTrend))); + new SessionDetailedAnalysis(worstSection, repTrend, squatDepthAnalysis, lungeDepthAnalysis, + squatTrunkLeanAnalysis, lungeTrunkLeanAnalysis, lungeStepLengthAnalysis))); } catch (JsonProcessingException e) { throw new IllegalStateException("리포트 분석 직렬화 실패 - 세션 " + session.getId(), e); } diff --git a/backend/src/main/java/com/shadowfit/service/exercise/SessionService.java b/backend/src/main/java/com/shadowfit/service/exercise/SessionService.java index 79aa01a2..9be1b94d 100644 --- a/backend/src/main/java/com/shadowfit/service/exercise/SessionService.java +++ b/backend/src/main/java/com/shadowfit/service/exercise/SessionService.java @@ -21,6 +21,7 @@ import com.shadowfit.repository.outbox.OutboxEventRepository; import com.shadowfit.model.exercise.Exercise; import com.shadowfit.model.exercise.Session; +import com.shadowfit.model.exercise.SquatDepthMode; import com.shadowfit.model.exercise.Status; import com.shadowfit.model.member.Member; import com.shadowfit.repository.exercise.ExercisesRepository; @@ -130,6 +131,7 @@ public Session createSession(VideoRequestDto appDto, Long currentMemberId, Strin .startTime(LocalDateTime.now().withNano(0)) .status(Status.IN_PROGRESS) .sessionNonce(sessionNonceGenerator.generate()) + .squatDepthMode(appDto.getDepthMode() != null ? appDto.getDepthMode() : SquatDepthMode.FULL) .build(); return sessionRepository.save(session); diff --git a/backend/src/main/java/com/shadowfit/service/report/LungeDepthAnalysisCalculator.java b/backend/src/main/java/com/shadowfit/service/report/LungeDepthAnalysisCalculator.java new file mode 100644 index 00000000..67257d7a --- /dev/null +++ b/backend/src/main/java/com/shadowfit/service/report/LungeDepthAnalysisCalculator.java @@ -0,0 +1,220 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameGrouping; +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.LungeDepthAnalysisDto; +import com.shadowfit.dto.report.detailreport.LungeRepDepthDto; +import com.shadowfit.model.exercise.Session; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.List; +import java.util.Map; + +/** + * 런지 깊이 정확도 채점 + 회차별 한국어 코멘트 (2026-09-27). + * + *

{@link SquatDepthAnalysisCalculator}의 형제 클래스다 — 같은 이유로 분리했다: rep 그룹핑 + * 규칙만 {@link PoseFrameGrouping#byRep}로 공유하고, 채점·코멘트 로직은 종목마다 독립적으로 + * 둔다. 스쿼트와 다른 점 두 가지가 이 분리를 요구한다 — ① FULL/HALF 모드 구분이 없다(런지는 + * 깊이 모드 선택 자체가 없음), ② 좌/우 어느 다리인지가 채점 결과의 일부다(스쿼트는 좌우 + * 대칭이라 이 축이 없다). + * + *

목표선(100도)의 근거는 {@code docs/decisions/lunge-repetition-counting.md} 참고 — 이 + * 저장소가 이미 인용하는 Sousa et al.(2026)이 런지 "진입" 단계를 양 무릎 100도 미만으로 + * 정의한 것과 같은 값이며, ai-server의 {@code LungeThresholds.bottom_angle}과도 같다. 채점은 + * 스쿼트 FULL 모드와 같은 모양(100도 이하 만점, 100~115도 선형, 그 너머 방어적 감점)을 쓴다 — + * 별도 문헌(슬개대퇴 관절 부하 연구, JOSPT 2008;38(1))이 "더 깊이 굽힐수록, 특히 보폭이 + * 짧을수록 무릎 부담이 커진다"고 보고해 "더 깊을수록 무조건 좋다"로 설계하지 않았다. + */ +@Component +public class LungeDepthAnalysisCalculator { + + // V2__seed_master_data.sql: 2=전방 런지. analyzer_registry.py의 _EXERCISE_ID_TO_TYPE와 + // 같은 결합 취약성을 그대로 안는다 — 시드가 바뀌면 이 값도 같이 고쳐야 한다. + private static final long LUNGE_EXERCISE_ID = 2L; + + private static final double TARGET = 100.0; + private static final double ENTRY = 115.0; // ai-server bottom_angle(100) + margin(15, 스쿼트와 동일 여유) + + // 회차 평균이 이보다 깊지 않으면(목표선에 가까우면) 통과해도 "아슬아슬" 코멘트를 남긴다. + // 2026-09-22 실촬영 lunge_sallow_01(좌89도·우98도 평균)이 정확히 이 경우였다 — 전부 + // 100점으로 통과했지만 목표선에 바짝 붙어 있었다. + private static final double CLOSE_CALL_KNEE = 85.0; + + // 좌우 평균 최저 무릎각 차이가 이보다 크면 비대칭으로 본다. 2026-09-22 실촬영 3개(정상·얕음· + // 워킹)는 전부 6.5~8.7도라 이 문턱을 넘지 않았다 — 실측 근거는 "이 사람은 균형이 맞았다"는 + // 확인이지 "10도가 맞는 경계"라는 검증은 아니다. 구현 기본값이다. + private static final double ASYMMETRY_THRESHOLD = 10.0; + + public LungeDepthAnalysisDto calculate(Session session, List poseFrames) { + if (session.getExercise().getId() != LUNGE_EXERCISE_ID) { + return null; + } + if (poseFrames == null || poseFrames.isEmpty()) { + return null; + } + + List repDepths = new ArrayList<>(); + for (Map.Entry> entry : PoseFrameGrouping.byRep(poseFrames).entrySet()) { + LungeRepDepthDto repDepth = scoreRep(entry.getKey(), entry.getValue()); + if (repDepth != null) { + repDepths.add(repDepth); + } + } + if (repDepths.isEmpty()) { + return null; // 유효한 무릎각 데이터가 있는 rep이 하나도 없음 + } + + int sessionScore = (int) Math.round( + repDepths.stream().mapToInt(LungeRepDepthDto::getDepthScore).average().orElse(0.0)); + + Double leftAvg = averageKneeAngle(repDepths, "left"); + Double rightAvg = averageKneeAngle(repDepths, "right"); + + LungeDepthAnalysisDto dto = new LungeDepthAnalysisDto(); + dto.setDepthScore(sessionScore); + dto.setDepthGrade(gradeOf(sessionScore)); + dto.setLeftAvgKneeAngle(leftAvg); + dto.setRightAvgKneeAngle(rightAvg); + dto.setRepDepths(repDepths); + dto.setNarrative(buildNarrative(repDepths, leftAvg, rightAvg)); + return dto; + } + + /** 이 rep에서 앞다리가 가장 깊게 굽혀진 순간(최소 smoothedKneeAngle)을 채점한다. 유효값이 없으면 null. */ + private LungeRepDepthDto scoreRep(int repNumber, List frames) { + PoseFrameProjection deepest = null; + String side = null; + for (PoseFrameProjection frame : frames) { + if (side == null && frame.leadLeg() != null) { + side = frame.leadLeg(); + } + Double kneeAngle = frame.smoothedKneeAngle(); + if (kneeAngle == null || kneeAngle <= 0.0) { + continue; + } + if (deepest == null || kneeAngle < deepest.smoothedKneeAngle()) { + deepest = frame; + } + } + if (deepest == null) { + return null; + } + double minKnee = deepest.smoothedKneeAngle(); + return new LungeRepDepthDto(repNumber, side, minKnee, scoreFull(minKnee), formatTimestamp(deepest.timestampSec())); + } + + /** 100도 이하는 만점, 100~115도는 100→60 선형, 그 너머는 방어적으로 계속 깎는다(스쿼트 FULL과 같은 모양). */ + private int scoreFull(double minKnee) { + if (minKnee <= TARGET) { + return 100; + } + if (minKnee <= ENTRY) { + return (int) Math.round(100 - (minKnee - TARGET) / (ENTRY - TARGET) * 40); + } + return (int) Math.max(0, Math.round(60 - (minKnee - ENTRY) * 2)); + } + + private String gradeOf(int score) { + if (score >= 90) return "EXCELLENT"; + if (score >= 75) return "GOOD"; + if (score >= 60) return "FAIR"; + if (score >= 40) return "NEEDS_WORK"; + return "POOR"; + } + + private Double averageKneeAngle(List repDepths, String side) { + List matching = repDepths.stream() + .filter(rep -> side.equals(rep.getSide())) + .map(LungeRepDepthDto::getMinKneeAngle) + .toList(); + if (matching.isEmpty()) { + return null; + } + return matching.stream().mapToDouble(Double::doubleValue).average().orElse(0.0); + } + + /** + * 회차별 한국어 코멘트, 최대 4문장. 리포트를 짧게 유지하려고 트리거된 것만 우선순위 순으로 채운다. + * + *

우선순위: ① 좌우 비대칭(스쿼트에는 없는 런지 전용 축) > ② 같은 다리 안에서 인접 회차 + * 대비(앞 회차 ≥85점, 바로 다음 같은 다리 회차가 15점 이상 낮음) > ③ 통과는 했지만 목표선에 + * 아슬아슬(세션 평균 무릎각이 얕은 쪽) > ④ 회차 간 편차가 큼(stddev > 10도) > + * ⑤ 전부 양호(다른 트리거가 없을 때만, 폴백). + */ + private List buildNarrative(List repDepths, Double leftAvg, Double rightAvg) { + List sentences = new ArrayList<>(); + + // ① 좌우 비대칭 — 양쪽 다 데이터가 있을 때만 비교할 수 있다. + if (leftAvg != null && rightAvg != null && Math.abs(leftAvg - rightAvg) >= ASYMMETRY_THRESHOLD) { + String shallowerSide = leftAvg > rightAvg ? "왼쪽" : "오른쪽"; + sentences.add(String.format( + "%s 다리가 반대쪽보다 덜 앉았어요(왼쪽 평균 %.0f도, 오른쪽 평균 %.0f도) — 균형을 맞춰보세요.", + shallowerSide, leftAvg, rightAvg)); + } + + // ② 같은 다리 안에서 인접 회차 대비 — 가장 큰 낙차 한 쌍만. 다른 다리로 넘어가는 지점은 + // 비교하지 않는다(워킹 런지처럼 좌우 번갈아 진행하면 서로 다른 다리라 비교 자체가 의미 없다). + if (sentences.size() < 4) { + LungeRepDepthDto dropFrom = null, dropTo = null; + int biggestDrop = 0; + for (int i = 0; i + 1 < repDepths.size(); i++) { + LungeRepDepthDto a = repDepths.get(i), b = repDepths.get(i + 1); + if (a.getSide() == null || !a.getSide().equals(b.getSide())) continue; + int drop = a.getDepthScore() - b.getDepthScore(); + boolean gotShallower = b.getMinKneeAngle() > a.getMinKneeAngle(); + if (a.getDepthScore() >= 85 && drop >= 15 && gotShallower && drop > biggestDrop) { + biggestDrop = drop; + dropFrom = a; + dropTo = b; + } + } + if (dropFrom != null) { + sentences.add(String.format( + "%d회차 자세는 좋았는데, %d회차는 조금 덜 앉았어요.", + dropFrom.getRepNumber(), dropTo.getRepNumber())); + } + } + + // ③ 통과는 했지만 목표선에 아슬아슬 — 세션 전체 평균이 얕은 쪽일 때 한 줄. + if (sentences.size() < 4) { + double overallAvg = repDepths.stream().mapToDouble(LungeRepDepthDto::getMinKneeAngle).average().orElse(0); + boolean allPassed = repDepths.stream().allMatch(rep -> rep.getMinKneeAngle() <= TARGET); + if (allPassed && overallAvg > CLOSE_CALL_KNEE) { + sentences.add("목표선은 넘었지만 여유 있게 통과하지는 않았어요 — 조금만 더 앉아보세요."); + } + } + + // ④ 회차 간 편차가 큼. + if (sentences.size() < 4 && repDepths.size() >= 3) { + double mean = repDepths.stream().mapToDouble(LungeRepDepthDto::getMinKneeAngle).average().orElse(0); + double variance = repDepths.stream() + .mapToDouble(r -> Math.pow(r.getMinKneeAngle() - mean, 2)).average().orElse(0); + double stddev = Math.sqrt(variance); + if (stddev > 10.0) { + LungeRepDepthDto shallowest = repDepths.stream() + .max(Comparator.comparingDouble(LungeRepDepthDto::getMinKneeAngle)).orElseThrow(); + LungeRepDepthDto deepest = repDepths.stream() + .min(Comparator.comparingDouble(LungeRepDepthDto::getMinKneeAngle)).orElseThrow(); + sentences.add(String.format( + "회차마다 앉는 깊이가 들쭉날쭉했어요 — %d회차가 가장 얕았고 %d회차가 가장 깊었어요.", + shallowest.getRepNumber(), deepest.getRepNumber())); + } + } + + // ⑤ 폴백 — 다른 트리거가 하나도 없을 때만. + if (sentences.isEmpty()) { + sentences.add(String.format("%d회 모두 목표 깊이를 안정적으로 지켰어요.", repDepths.size())); + } + + return sentences.size() > 4 ? sentences.subList(0, 4) : sentences; + } + + private String formatTimestamp(Double timestampSec) { + if (timestampSec == null) return "00:00"; + int totalSeconds = timestampSec.intValue(); + return String.format("%02d:%02d", totalSeconds / 60, totalSeconds % 60); + } +} diff --git a/backend/src/main/java/com/shadowfit/service/report/LungeStepLengthAnalysisCalculator.java b/backend/src/main/java/com/shadowfit/service/report/LungeStepLengthAnalysisCalculator.java new file mode 100644 index 00000000..00c511b7 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/service/report/LungeStepLengthAnalysisCalculator.java @@ -0,0 +1,156 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameGrouping; +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.LungeStepLengthAnalysisDto; +import com.shadowfit.dto.report.detailreport.RepStepLengthDto; +import com.shadowfit.model.exercise.Session; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +/** + * 런지 보폭 정확도 채점 + 회차별 한국어 코멘트 (2026-09-28). 런지 전용 — 스쿼트는 보폭 + * 개념이 없어(양발이 나란함) 형제 계산기가 없다. + * + *

근거: Escamilla et al. 계열 연구(이미 인용된 슬개대퇴 관절 부하 연구와 같은 계보)가 + * 짧은 보폭 런지일수록 깊은 무릎 굴곡 구간(50~100도)에서 슬개대퇴 관절 부하가 유의하게 + * 커진다고 반복 보고한다 — "무릎이 발끝을 넘는가" 자체(최근 재활 문헌에서 근거 없는 통념으로 + * 반박됨)가 아니라 보폭 대비 깊이가 핵심 메커니즘이다. + * + *

이 rep의 대표값은 {@link LungeDepthAnalysisCalculator}와 같은 프레임(그 rep에서 무릎이 + * 가장 깊게 굽혀진 순간)의 {@code staggerRatio}를 쓴다 — 이 앱의 런지는 발 위치가 고정된 채 + * 굽혔다 펴는 방식이라 rep 안에서 stagger가 거의 변하지 않으므로, 새 대표 프레임 규칙을 + * 만들지 않고 이미 검증된 "가장 깊었던 순간" 선택을 재사용한다. + * + *

🔴 임계값 근거와 미검증 범위는 {@link LungeStepLengthAnalysisDto} 참고. + */ +@Component +public class LungeStepLengthAnalysisCalculator { + + // V2__seed_master_data.sql: 2=전방 런지. + private static final long LUNGE_EXERCISE_ID = 2L; + + // VALIDATE — 실촬영 3개(정상·얕음·워킹) 관찰 + 문헌 근거의 잠정값. 상세 근거는 + // LungeStepLengthAnalysisDto 참고. + private static final double ADEQUATE_STEP = 1.0; + private static final double SHORT_ENTRY = 0.6; + + public LungeStepLengthAnalysisDto calculate(Session session, List poseFrames) { + if (session.getExercise().getId() != LUNGE_EXERCISE_ID) { + return null; + } + if (poseFrames == null || poseFrames.isEmpty()) { + return null; + } + + List repStepLengths = new ArrayList<>(); + for (Map.Entry> entry : PoseFrameGrouping.byRep(poseFrames).entrySet()) { + RepStepLengthDto rep = scoreRep(entry.getKey(), entry.getValue()); + if (rep != null) { + repStepLengths.add(rep); + } + } + if (repStepLengths.isEmpty()) { + return null; // 유효한 보폭 데이터가 있는 rep이 하나도 없음(구버전 행뿐이거나 전부 미계산) + } + + int sessionScore = (int) Math.round( + repStepLengths.stream().mapToInt(RepStepLengthDto::getStepScore).average().orElse(0.0)); + + LungeStepLengthAnalysisDto dto = new LungeStepLengthAnalysisDto(); + dto.setStepScore(sessionScore); + dto.setStepGrade(gradeOf(sessionScore)); + dto.setRepStepLengths(repStepLengths); + dto.setNarrative(buildNarrative(repStepLengths, sessionScore)); + return dto; + } + + /** + * 이 rep에서 무릎이 가장 깊게 굽혀진 순간(최소 smoothedKneeAngle)의 staggerRatio를 채점한다. + * 그 프레임의 staggerRatio가 없으면(구버전 행) null. + */ + private RepStepLengthDto scoreRep(int repNumber, List frames) { + PoseFrameProjection deepest = null; + for (PoseFrameProjection frame : frames) { + Double kneeAngle = frame.smoothedKneeAngle(); + if (kneeAngle == null || kneeAngle <= 0.0) { + continue; + } + if (deepest == null || kneeAngle < deepest.smoothedKneeAngle()) { + deepest = frame; + } + } + if (deepest == null || deepest.staggerRatio() == null) { + return null; + } + double stagger = deepest.staggerRatio(); + return new RepStepLengthDto(repNumber, stagger, scoreStep(stagger), formatTimestamp(deepest.timestampSec())); + } + + /** 1.0 이상은 만점, 0.6~1.0은 100→60 선형, 그 너머는 방어적으로 계속 깎는다. */ + private int scoreStep(double stagger) { + if (stagger >= ADEQUATE_STEP) { + return 100; + } + if (stagger >= SHORT_ENTRY) { + return (int) Math.round(100 - (ADEQUATE_STEP - stagger) / (ADEQUATE_STEP - SHORT_ENTRY) * 40); + } + return (int) Math.max(0, Math.round(60 - (SHORT_ENTRY - stagger) * 100)); + } + + private String gradeOf(int score) { + if (score >= 90) return "EXCELLENT"; + if (score >= 75) return "GOOD"; + if (score >= 60) return "FAIR"; + if (score >= 40) return "NEEDS_WORK"; + return "POOR"; + } + + /** + * 회차별 한국어 코멘트, 최대 4문장. + * + *

우선순위: ① 인접 회차 대비(앞 회차 ≥85점, 바로 다음 회차가 15점 이상 낮고 실제로 더 + * 짧아짐) > ② 세션 전체 등급이 낮음(FAIR 미만) > ③ 전부 양호(폴백). + */ + private List buildNarrative(List repStepLengths, int sessionScore) { + List sentences = new ArrayList<>(); + + RepStepLengthDto dropFrom = null, dropTo = null; + int biggestDrop = 0; + for (int i = 0; i + 1 < repStepLengths.size(); i++) { + RepStepLengthDto a = repStepLengths.get(i), b = repStepLengths.get(i + 1); + int drop = a.getStepScore() - b.getStepScore(); + boolean gotShorter = b.getStaggerRatio() < a.getStaggerRatio(); + // b가 75점 미만일 때만 경고한다 — 점수와 코멘트가 모순되지 않도록. + if (a.getStepScore() >= 85 && b.getStepScore() < 75 && drop >= 15 && gotShorter && drop > biggestDrop) { + biggestDrop = drop; + dropFrom = a; + dropTo = b; + } + } + if (dropFrom != null) { + sentences.add(String.format( + "%d회차까지는 보폭이 넉넉했는데, %d회차부터 보폭이 짧아져 무릎에 부담이 갈 수 있어요.", + dropFrom.getRepNumber(), dropTo.getRepNumber())); + } + + if (sentences.size() < 4 && sessionScore < 60) { + sentences.add("전반적으로 보폭이 짧았어요 — 앞발을 조금 더 앞으로 내디뎌보세요."); + } + + if (sentences.isEmpty()) { + sentences.add(String.format("%d회 모두 보폭이 안정적이었어요.", repStepLengths.size())); + } + + return sentences.size() > 4 ? sentences.subList(0, 4) : sentences; + } + + private String formatTimestamp(Double timestampSec) { + if (timestampSec == null) return "00:00"; + int totalSeconds = timestampSec.intValue(); + return String.format("%02d:%02d", totalSeconds / 60, totalSeconds % 60); + } +} diff --git a/backend/src/main/java/com/shadowfit/service/report/LungeTrunkLeanAnalysisCalculator.java b/backend/src/main/java/com/shadowfit/service/report/LungeTrunkLeanAnalysisCalculator.java new file mode 100644 index 00000000..d55e37d2 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/service/report/LungeTrunkLeanAnalysisCalculator.java @@ -0,0 +1,150 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameGrouping; +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.RepTrunkLeanDto; +import com.shadowfit.dto.report.detailreport.TrunkLeanAnalysisDto; +import com.shadowfit.model.exercise.Session; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * 런지 체간(몸통) 기울기 채점 + 회차별 한국어 코멘트 (2026-09-28). + * + *

{@link SquatTrunkLeanAnalysisCalculator}의 형제 클래스다 — 계산 방식(rep 평균 torsoTiltDeg)은 + * 같지만 임계값은 다르다. 스쿼트와 달리 런지의 전방 기울임은 의도적인 정상 기법일 수 + * 있다 — Farrokhi et al. 2008(JOSPT 38(7):403-409, Powers lab — 이미 인용한 슬개대퇴 + * 논문(JOSPT 2008;38(1))과 같은 연구 그룹)이 직립/전방기울임 조건을 비교했는데, 전방 기울임이 + * 둔근·햄스트링 활성을 높이는 정상적 변형이었다. 그래서 "직립=정답"으로 채점하지 않고, 오직 + * 초보자의 보상성 과도한 전방 기울임(코어 약화 → 무릎 과전방 이동 → 슬개건 스트레스 + * 증가)만 걸러내도록 스쿼트보다 훨씬 관대한 밴드를 쓴다. + * + *

🔴 아래 35도/55도 경계는 이 경계를 특정하는 실측 문헌을 찾지 못해 잠정값이다. + * {@code SquatDepthAnalysisCalculator}의 HALF 모드 밴드와 같은 사정 — 실촬영 검증(다음 + * 하프 스쿼트 검증과 함께 진행 예정) 전까지 "런지 체간 자세 점수"를 사용자에게 확정적으로 + * 주장하지 않는다. 자세한 근거는 {@code docs/decisions/}에 검증 후 기록한다. + */ +@Component +public class LungeTrunkLeanAnalysisCalculator { + + // V2__seed_master_data.sql: 2=전방 런지. analyzer_registry.py의 _EXERCISE_ID_TO_TYPE와 + // 같은 결합 취약성을 그대로 안는다 — 시드가 바뀌면 이 값도 같이 고쳐야 한다. + private static final long LUNGE_EXERCISE_ID = 2L; + + // VALIDATE — 스쿼트(20/35)보다 훨씬 관대하다. 의도적 전방 기울임이 정상 기법이라 명백한 + // 보상성 붕괴만 잡도록 경계를 높게 잡은 잠정값이다. + private static final double NATURAL_LIMIT = 35.0; + private static final double EXCESSIVE_THRESHOLD = 55.0; + + public TrunkLeanAnalysisDto calculate(Session session, List poseFrames) { + if (session.getExercise().getId() != LUNGE_EXERCISE_ID) { + return null; + } + if (poseFrames == null || poseFrames.isEmpty()) { + return null; + } + + List repTrunkLeans = new ArrayList<>(); + for (Map.Entry> entry : PoseFrameGrouping.byRep(poseFrames).entrySet()) { + RepTrunkLeanDto rep = scoreRep(entry.getKey(), entry.getValue()); + if (rep != null) { + repTrunkLeans.add(rep); + } + } + if (repTrunkLeans.isEmpty()) { + return null; // 유효한 체간 기울기 데이터가 있는 rep이 하나도 없음(구버전 행뿐이거나 전부 미계산) + } + + int sessionScore = (int) Math.round( + repTrunkLeans.stream().mapToInt(RepTrunkLeanDto::getTiltScore).average().orElse(0.0)); + + TrunkLeanAnalysisDto dto = new TrunkLeanAnalysisDto(); + dto.setTiltScore(sessionScore); + dto.setTiltGrade(gradeOf(sessionScore)); + dto.setRepTrunkLeans(repTrunkLeans); + dto.setNarrative(buildNarrative(repTrunkLeans, sessionScore)); + return dto; + } + + /** 이 rep에 속한 프레임들의 torsoTiltDeg 평균을 채점한다. 유효값이 없으면 null. */ + private RepTrunkLeanDto scoreRep(int repNumber, List frames) { + List tilts = frames.stream() + .map(PoseFrameProjection::torsoTiltDeg) + .filter(Objects::nonNull) + .toList(); + if (tilts.isEmpty()) { + return null; + } + double avgTilt = tilts.stream().mapToDouble(Double::doubleValue).average().orElse(0.0); + int score = scoreTilt(avgTilt); + return new RepTrunkLeanDto(repNumber, avgTilt, score, formatTimestamp(frames.get(0).timestampSec())); + } + + /** 35도 이하는 만점, 35~55도는 100→60 선형, 그 너머는 방어적으로 계속 깎는다. */ + private int scoreTilt(double avgTilt) { + if (avgTilt <= NATURAL_LIMIT) { + return 100; + } + if (avgTilt <= EXCESSIVE_THRESHOLD) { + return (int) Math.round(100 - (avgTilt - NATURAL_LIMIT) / (EXCESSIVE_THRESHOLD - NATURAL_LIMIT) * 40); + } + return (int) Math.max(0, Math.round(60 - (avgTilt - EXCESSIVE_THRESHOLD) * 3)); + } + + private String gradeOf(int score) { + if (score >= 90) return "EXCELLENT"; + if (score >= 75) return "GOOD"; + if (score >= 60) return "FAIR"; + if (score >= 40) return "NEEDS_WORK"; + return "POOR"; + } + + /** + * 회차별 한국어 코멘트, 최대 4문장. + * + *

우선순위: ① 인접 회차 대비(앞 회차 ≥85점, 바로 다음 회차가 15점 이상 낮고 실제로 더 + * 기울어짐) > ② 세션 전체 등급이 낮음(FAIR 미만) > ③ 전부 양호(폴백). + */ + private List buildNarrative(List repTrunkLeans, int sessionScore) { + List sentences = new ArrayList<>(); + + RepTrunkLeanDto dropFrom = null, dropTo = null; + int biggestDrop = 0; + for (int i = 0; i + 1 < repTrunkLeans.size(); i++) { + RepTrunkLeanDto a = repTrunkLeans.get(i), b = repTrunkLeans.get(i + 1); + int drop = a.getTiltScore() - b.getTiltScore(); + boolean gotMoreBent = b.getAvgTiltDeg() > a.getAvgTiltDeg(); + // b가 75점 미만일 때만 경고한다 — 점수와 코멘트가 모순되지 않도록(스쿼트 계산기 주석 참고). + if (a.getTiltScore() >= 85 && b.getTiltScore() < 75 && drop >= 15 && gotMoreBent && drop > biggestDrop) { + biggestDrop = drop; + dropFrom = a; + dropTo = b; + } + } + if (dropFrom != null) { + sentences.add(String.format( + "%d회차까지는 상체를 잘 세웠는데, %d회차부터 상체가 많이 숙여졌어요.", + dropFrom.getRepNumber(), dropTo.getRepNumber())); + } + + if (sentences.size() < 4 && sessionScore < 60) { + sentences.add("상체가 과도하게 앞으로 쏠렸어요 — 코어에 힘을 주고 상체를 조금 더 세워보세요."); + } + + if (sentences.isEmpty()) { + sentences.add(String.format("%d회 모두 상체 자세를 잘 유지했어요.", repTrunkLeans.size())); + } + + return sentences.size() > 4 ? sentences.subList(0, 4) : sentences; + } + + private String formatTimestamp(Double timestampSec) { + if (timestampSec == null) return "00:00"; + int totalSeconds = timestampSec.intValue(); + return String.format("%02d:%02d", totalSeconds / 60, totalSeconds % 60); + } +} diff --git a/backend/src/main/java/com/shadowfit/service/report/ReportService.java b/backend/src/main/java/com/shadowfit/service/report/ReportService.java index f7d23be5..9fe5d141 100644 --- a/backend/src/main/java/com/shadowfit/service/report/ReportService.java +++ b/backend/src/main/java/com/shadowfit/service/report/ReportService.java @@ -32,6 +32,11 @@ public class ReportService { private final SessionRepository sessionRepository; private final PoseDataRepository poseDataRepository; private final SessionAnalysisCalculator sessionAnalysisCalculator; + private final SquatDepthAnalysisCalculator squatDepthAnalysisCalculator; + private final LungeDepthAnalysisCalculator lungeDepthAnalysisCalculator; + private final SquatTrunkLeanAnalysisCalculator squatTrunkLeanAnalysisCalculator; + private final LungeTrunkLeanAnalysisCalculator lungeTrunkLeanAnalysisCalculator; + private final LungeStepLengthAnalysisCalculator lungeStepLengthAnalysisCalculator; private final ObjectMapper objectMapper; @Transactional(readOnly = true) @@ -68,6 +73,11 @@ private SessionReportResponseDto buildReportResponse(Session session, Report rep attachJointCoordinates(worstSection, session); responseDto.setWorstSection(worstSection); responseDto.setRepTrend(analysis.getRepTrend() == null ? List.of() : analysis.getRepTrend()); + responseDto.setSquatDepthAnalysis(analysis.getSquatDepthAnalysis()); + responseDto.setLungeDepthAnalysis(analysis.getLungeDepthAnalysis()); + responseDto.setSquatTrunkLeanAnalysis(analysis.getSquatTrunkLeanAnalysis()); + responseDto.setLungeTrunkLeanAnalysis(analysis.getLungeTrunkLeanAnalysis()); + responseDto.setLungeStepLengthAnalysis(analysis.getLungeStepLengthAnalysis()); responseDto.setSyncRateDetails(buildSyncRateDetails(session)); lastSession.ifPresent(last -> responseDto.setComparisonWithPrevious(buildComparisonWithPrevious(session, last)) @@ -96,7 +106,12 @@ private SessionDetailedAnalysis resolveDetailedAnalysis(Session session, Report SessionDetailedAnalysis parsed = objectMapper.readValue(detailedAnalysis, SessionDetailedAnalysis.class); if (parsed.getWorstSection() != null - || (parsed.getRepTrend() != null && !parsed.getRepTrend().isEmpty())) { + || (parsed.getRepTrend() != null && !parsed.getRepTrend().isEmpty()) + || parsed.getSquatDepthAnalysis() != null + || parsed.getLungeDepthAnalysis() != null + || parsed.getSquatTrunkLeanAnalysis() != null + || parsed.getLungeTrunkLeanAnalysis() != null + || parsed.getLungeStepLengthAnalysis() != null) { return parsed; } log.warn("세션 {} detailed_analysis 가 구버전 형식으로 판단됨 — pose_data 즉석 재계산으로 대체", @@ -108,7 +123,12 @@ private SessionDetailedAnalysis resolveDetailedAnalysis(Session session, Report List poseFrames = poseDataRepository.findFramesBySessionId(session.getId(), session.getStartTime()); return new SessionDetailedAnalysis( sessionAnalysisCalculator.calculate(session, poseFrames), - sessionAnalysisCalculator.calculateRepTrend(poseFrames)); + sessionAnalysisCalculator.calculateRepTrend(poseFrames), + squatDepthAnalysisCalculator.calculate(session, poseFrames), + lungeDepthAnalysisCalculator.calculate(session, poseFrames), + squatTrunkLeanAnalysisCalculator.calculate(session, poseFrames), + lungeTrunkLeanAnalysisCalculator.calculate(session, poseFrames), + lungeStepLengthAnalysisCalculator.calculate(session, poseFrames)); } /** diff --git a/backend/src/main/java/com/shadowfit/service/report/SessionAnalysisCalculator.java b/backend/src/main/java/com/shadowfit/service/report/SessionAnalysisCalculator.java index 907d6e0d..6117df6c 100644 --- a/backend/src/main/java/com/shadowfit/service/report/SessionAnalysisCalculator.java +++ b/backend/src/main/java/com/shadowfit/service/report/SessionAnalysisCalculator.java @@ -1,5 +1,6 @@ package com.shadowfit.service.report; +import com.shadowfit.dto.report.PoseFrameGrouping; import com.shadowfit.dto.report.PoseFrameProjection; import com.shadowfit.dto.report.detailreport.RepSyncRateDto; import com.shadowfit.dto.report.detailreport.WorstSectionDto; @@ -7,7 +8,6 @@ import org.springframework.stereotype.Component; import java.util.ArrayList; -import java.util.LinkedHashMap; import java.util.List; import java.util.Map; @@ -127,27 +127,16 @@ public List calculateRepTrend(List poseFram } /** - * rep 번호로 묶는다. 입력이 rep 오름차순이라 LinkedHashMap 의 순회 순서도 rep 오름차순이다. - * - *

{@code repNumber <= 0} 은 "미상"이라 제외한다 — 컬럼이 생기기 전에 저장된 행과, - * rep_number 를 안 보내는 구버전 AI 의 행이 여기 해당한다(마이그레이션 - * {@code 2026-07-31-add-pose-data-rep-number.sql}). 섞으면 서로 다른 rep 이 하나로 뭉뚱그려져, - * 고치려던 것과 똑같은 결함이 다시 생긴다. #75 의 {@code findRepAverageSyncRates} 도 같은 기준이다. + * rep 번호로 묶는다. 규칙 자체는 {@link PoseFrameGrouping#byRep}로 뽑혀 있다(2026-09-21, + * {@code SquatDepthAnalysisCalculator}와 공유) — {@code repNumber <= 0}인 "미상" 행을 제외하는 + * 이유 등 자세한 배경은 그쪽 주석 참고. * *

그 결과 미상 행만 있는 세션은 worst 를 못 낸다(null). 예전 코드는 rep 을 안 봤으므로 * 뭔가를 내놓긴 했지만, 그 값이 어느 rep 의 것인지 말할 수 없었다 — 틀린 값을 내놓느니 없다고 * 하는 편이 낫다는 판단이다. 실사용 데이터에서는 #74 이후 저장분이 모두 rep 을 싣는다. */ private Map> groupByRep(List poseFrames) { - Map> framesByRep = new LinkedHashMap<>(); - for (PoseFrameProjection frame : poseFrames) { - Integer repNumber = frame.repNumber(); - if (repNumber == null || repNumber <= 0) { - continue; - } - framesByRep.computeIfAbsent(repNumber, key -> new ArrayList<>()).add(frame); - } - return framesByRep; + return PoseFrameGrouping.byRep(poseFrames); } /** diff --git a/backend/src/main/java/com/shadowfit/service/report/SquatDepthAnalysisCalculator.java b/backend/src/main/java/com/shadowfit/service/report/SquatDepthAnalysisCalculator.java new file mode 100644 index 00000000..2779ac2e --- /dev/null +++ b/backend/src/main/java/com/shadowfit/service/report/SquatDepthAnalysisCalculator.java @@ -0,0 +1,224 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameGrouping; +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.RepDepthDto; +import com.shadowfit.dto.report.detailreport.SquatDepthAnalysisDto; +import com.shadowfit.model.exercise.Session; +import com.shadowfit.model.exercise.SquatDepthMode; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.Comparator; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * 스쿼트 깊이 정확도 채점 + 회차별 한국어 코멘트 (2026-09-21). + * + *

{@link SessionAnalysisCalculator}의 형제 클래스로 따로 뒀다 — 그 클래스는 rep으로 묶는 것 말고는 + * 종목을 모르는(exercise-agnostic) 설계라(어느 운동이든 sync_rate 최저 rep을 고를 뿐이다), 스쿼트 + * 전용 깊이 밴드·모드 판정을 끼워 넣으면 그 중립성이 깨진다. rep 그룹핑 규칙만 + * {@link PoseFrameGrouping#byRep}로 공유한다. + * + *

🔴 HALF 모드의 목표 밴드(115~140도)는 실촬영 하프 스쿼트 영상으로 검증되기 전까지 + * 잠정값이다. ai-server의 {@code HALF_SQUAT_THRESHOLDS}(bottom_hip·min_hip_drop)와 마찬가지로 + * 비례 추정이며, 두 값이 서로 다른 숫자를 매기지 않도록 개념적으로 연결돼 있다는 점만 여기 남긴다 — + * 밴드가 바뀌면 {@code ai-server/app/core/squat_counter.py}의 프리셋도 함께 재검토해야 한다. + * 자세한 근거는 {@code docs/decisions/squat-repetition-counting.md}의 2026-09-21 절 참고. + */ +@Component +public class SquatDepthAnalysisCalculator { + + // V2__seed_master_data.sql: 1=스쿼트. analyzer_registry.py의 _EXERCISE_ID_TO_TYPE와 같은 결합 + // 취약성을 그대로 안는다 — 시드가 바뀌면 이 값도 같이 고쳐야 한다. + private static final long SQUAT_EXERCISE_ID = 1L; + + private static final double FULL_TARGET = 100.0; + private static final double FULL_ENTRY = 115.0; // ai-server bottom_knee(100) + margin(15) + private static final double HALF_CENTER = 127.5; // (115+140)/2 + private static final double HALF_HALF_WIDTH = 12.5; + + public SquatDepthAnalysisDto calculate(Session session, List poseFrames) { + if (session.getExercise().getId() != SQUAT_EXERCISE_ID) { + return null; + } + if (poseFrames == null || poseFrames.isEmpty()) { + return null; + } + + SquatDepthMode mode = session.getSquatDepthMode(); + List repDepths = new ArrayList<>(); + for (Map.Entry> entry : PoseFrameGrouping.byRep(poseFrames).entrySet()) { + RepDepthDto repDepth = scoreRep(entry.getKey(), entry.getValue(), mode); + if (repDepth != null) { + repDepths.add(repDepth); + } + } + if (repDepths.isEmpty()) { + return null; // 유효한 무릎각 데이터가 있는 rep이 하나도 없음 + } + + int sessionScore = (int) Math.round( + repDepths.stream().mapToInt(RepDepthDto::getDepthScore).average().orElse(0.0)); + + SquatDepthAnalysisDto dto = new SquatDepthAnalysisDto(); + dto.setDepthMode(mode.name()); + dto.setDepthScore(sessionScore); + dto.setDepthGrade(gradeOf(sessionScore)); + dto.setRepDepths(repDepths); + dto.setNarrative(buildNarrative(repDepths, mode)); + return dto; + } + + /** 이 rep에서 가장 깊게 앉은 순간(최소 smoothedKneeAngle)을 채점한다. 유효값이 없으면 null. */ + private RepDepthDto scoreRep(int repNumber, List frames, SquatDepthMode mode) { + PoseFrameProjection deepest = null; + for (PoseFrameProjection frame : frames) { + Double kneeAngle = frame.smoothedKneeAngle(); + if (kneeAngle == null || kneeAngle <= 0.0) { + continue; + } + if (deepest == null || kneeAngle < deepest.smoothedKneeAngle()) { + deepest = frame; + } + } + if (deepest == null) { + return null; + } + double minKnee = deepest.smoothedKneeAngle(); + int score = mode == SquatDepthMode.HALF ? scoreHalf(minKnee) : scoreFull(minKnee); + return new RepDepthDto(repNumber, minKnee, score, formatTimestamp(deepest.timestampSec())); + } + + /** FULL: 100도 이하는 만점, 100~115도는 100→60 선형, 그 너머는 방어적으로 계속 깎는다. */ + private int scoreFull(double minKnee) { + if (minKnee <= FULL_TARGET) { + return 100; + } + if (minKnee <= FULL_ENTRY) { + return (int) Math.round(100 - (minKnee - FULL_TARGET) / (FULL_ENTRY - FULL_TARGET) * 40); + } + return (int) Math.max(0, Math.round(60 - (minKnee - FULL_ENTRY) * 2)); + } + + /** HALF: 115~140도 밴드 중심(127.5)에서 만점, 밴드 경계(±12.5)에서 70점, 그 너머는 계속 깎는다. */ + private int scoreHalf(double minKnee) { + double dist = Math.abs(minKnee - HALF_CENTER); + if (dist <= HALF_HALF_WIDTH) { + return (int) Math.round(100 - dist / HALF_HALF_WIDTH * 30); + } + return (int) Math.max(0, Math.round(70 - (dist - HALF_HALF_WIDTH) * 2)); + } + + private String gradeOf(int score) { + if (score >= 90) return "EXCELLENT"; + if (score >= 75) return "GOOD"; + if (score >= 60) return "FAIR"; + if (score >= 40) return "NEEDS_WORK"; + return "POOR"; + } + + /** + * 회차별 한국어 코멘트, 최대 4문장. 리포트를 짧게 유지하려고 트리거된 것만 우선순위 순으로 채운다. + * + *

우선순위: ① 인접 회차 대비(앞 회차 ≥85점, 바로 다음 회차가 15점 이상 낮음) > + * ② HALF 모드에서 풀 스쿼트급으로 더 깊이 앉은 회차(minKnee < 115) > + * ③ 밴드 얕은 쪽 경계 근접 회차(①에서 이미 다룬 회차는 제외) > + * ④ 회차 간 편차가 큼(stddev > 10도) > ⑤ 전부 양호(다른 트리거가 없을 때만, 폴백). + */ + private List buildNarrative(List repDepths, SquatDepthMode mode) { + List sentences = new ArrayList<>(); + Set mentioned = new HashSet<>(); + String modeLabel = mode == SquatDepthMode.HALF ? "하프 스쿼트" : "풀 스쿼트"; + + // ① 인접 회차 대비 — 가장 큰 낙차 한 쌍만. 점수만 보면 안 된다: HALF 모드는 밴드에서 멀어질수록 + // (얕아지든 깊어지든) 점수가 떨어지는 대칭 공식이라, 점수 하락만으로는 "더 깊이 앉아서" 떨어진 + // 경우까지 "덜 앉았어요"로 잘못 말할 수 있다 — minKneeAngle이 실제로 더 커진(=더 얕아진) + // 경우에만 이 문구를 쓴다. 더 깊어져서 떨어진 경우는 ②(HALF 전용)가 담당한다. + RepDepthDto dropFrom = null, dropTo = null; + int biggestDrop = 0; + for (int i = 0; i + 1 < repDepths.size(); i++) { + RepDepthDto a = repDepths.get(i), b = repDepths.get(i + 1); + int drop = a.getDepthScore() - b.getDepthScore(); + boolean gotShallower = b.getMinKneeAngle() > a.getMinKneeAngle(); + if (a.getDepthScore() >= 85 && drop >= 15 && gotShallower && drop > biggestDrop) { + biggestDrop = drop; + dropFrom = a; + dropTo = b; + } + } + if (dropFrom != null) { + sentences.add(String.format( + "%d회차 자세는 좋았는데, %d회차는 %s보다 조금 덜 앉았어요.", + dropFrom.getRepNumber(), dropTo.getRepNumber(), modeLabel)); + mentioned.add(dropFrom.getRepNumber()); + mentioned.add(dropTo.getRepNumber()); + } + + // ② HALF 모드에서 풀 스쿼트급으로 더 깊이 앉은 회차 — 가장 깊었던 한 회차만. + if (mode == SquatDepthMode.HALF && sentences.size() < 4) { + RepDepthDto deepest = null; + for (RepDepthDto rep : repDepths) { + if (rep.getMinKneeAngle() < FULL_ENTRY && !mentioned.contains(rep.getRepNumber()) + && (deepest == null || rep.getMinKneeAngle() < deepest.getMinKneeAngle())) { + deepest = rep; + } + } + if (deepest != null) { + sentences.add(String.format( + "%d회차는 하프 스쿼트 목표보다 더 깊이 앉았어요. 풀 스쿼트에 가까운 깊이였어요.", + deepest.getRepNumber())); + mentioned.add(deepest.getRepNumber()); + } + } + + // ③ 밴드 얕은 쪽 경계에 가장 가까운(=가장 얕은) 회차 — ①에서 다룬 회차는 제외. + if (sentences.size() < 4) { + RepDepthDto shallowest = null; + for (RepDepthDto rep : repDepths) { + if (mentioned.contains(rep.getRepNumber())) continue; + if (rep.getDepthScore() < 60 + && (shallowest == null || rep.getMinKneeAngle() > shallowest.getMinKneeAngle())) { + shallowest = rep; + } + } + if (shallowest != null) { + sentences.add(String.format("%d회차는 목표 깊이보다 얕았어요.", shallowest.getRepNumber())); + mentioned.add(shallowest.getRepNumber()); + } + } + + // ④ 회차 간 편차가 큼. + if (sentences.size() < 4 && repDepths.size() >= 3) { + double mean = repDepths.stream().mapToDouble(RepDepthDto::getMinKneeAngle).average().orElse(0); + double variance = repDepths.stream() + .mapToDouble(r -> Math.pow(r.getMinKneeAngle() - mean, 2)).average().orElse(0); + double stddev = Math.sqrt(variance); + if (stddev > 10.0) { + RepDepthDto shallowest = repDepths.stream() + .max(Comparator.comparingDouble(RepDepthDto::getMinKneeAngle)).orElseThrow(); + RepDepthDto deepest = repDepths.stream() + .min(Comparator.comparingDouble(RepDepthDto::getMinKneeAngle)).orElseThrow(); + sentences.add(String.format( + "회차마다 앉는 깊이가 들쭉날쭉했어요 — %d회차가 가장 얕았고 %d회차가 가장 깊었어요.", + shallowest.getRepNumber(), deepest.getRepNumber())); + } + } + + // ⑤ 폴백 — 다른 트리거가 하나도 없을 때만. + if (sentences.isEmpty()) { + sentences.add(String.format("%d회 모두 목표 깊이를 안정적으로 지켰어요.", repDepths.size())); + } + + return sentences.size() > 4 ? sentences.subList(0, 4) : sentences; + } + + private String formatTimestamp(Double timestampSec) { + if (timestampSec == null) return "00:00"; + int totalSeconds = timestampSec.intValue(); + return String.format("%02d:%02d", totalSeconds / 60, totalSeconds % 60); + } +} diff --git a/backend/src/main/java/com/shadowfit/service/report/SquatTrunkLeanAnalysisCalculator.java b/backend/src/main/java/com/shadowfit/service/report/SquatTrunkLeanAnalysisCalculator.java new file mode 100644 index 00000000..98e3be42 --- /dev/null +++ b/backend/src/main/java/com/shadowfit/service/report/SquatTrunkLeanAnalysisCalculator.java @@ -0,0 +1,160 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameGrouping; +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.RepTrunkLeanDto; +import com.shadowfit.dto.report.detailreport.TrunkLeanAnalysisDto; +import com.shadowfit.model.exercise.Session; +import org.springframework.stereotype.Component; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * 스쿼트 체간(몸통) 기울기 채점 + 회차별 한국어 코멘트 (2026-09-28). + * + *

{@link SquatDepthAnalysisCalculator}의 형제 클래스다 — 깊이(얼마나 앉았는가)와는 별개 + * 축이라 따로 뒀다. rep 그룹핑만 {@link PoseFrameGrouping#byRep}로 공유한다. + * + *

이 rep의 점수는 프레임별 {@code torsoTiltDeg}의 평균이다 — 깊이 점수가 최솟값 프레임 + * (정점 하나)을 쓰는 것과 다른 기준인 이유는 {@link RepTrunkLeanDto} 참고. 기존 실시간 BACK_BENT + * 판정(ai-server app/api/endpoints/pose.py)도 이미 이 방식(rep 전체 평균)을 쓰고 있어 그대로 + * 계승했다 — 같은 35도가 실시간 피드백과 세션 후 점수 양쪽에서 "감점 시작 경계"로 일관된다. + * + *

근거: FMS(Functional Movement Screen) Deep Squat 만점 조건에 "torso stays upright"· + * "tibia and torso parallel"이 명시돼 있고, 몸통-정강이 각도 40도는 "다소 과함", 45도를 넘으면 + * 무게중심이 지지 기반을 벗어나는 명백한 과도 전방 기울임으로 문헌에 정리돼 있다(Straub, + * A Biomechanical Review of the Squat Exercise, IJSPT). 40도 전후 전방 기울임이 ACL + * 부담을 16~24% 낮추지만 햄스트링 부하를 35% 늘리는 트레이드오프도 있어 "직립일수록 무조건 + * 좋다"로 설계하지 않았다. + * + *

🔄 2026-10-05 실측 보정: 처음엔 20도까지 만점으로 잡았는데, 실촬영 정상 스쿼트 3개 + * (squat_normal_01·02·side_01)의 rep 중 체간 기울기 평균이 29.8·31.1·31.3도로 나와 멀쩡한 + * 스쿼트가 FAIR("상체가 많이 숙여졌어요")로 깎였다. 그래서 만점 경계를 기존 실시간 BACK_BENT + * 경계인 35도로 올리고, 문헌상 "명백한 과도"인 45도에서 60점이 되게 했다. + */ +@Component +public class SquatTrunkLeanAnalysisCalculator { + + // V2__seed_master_data.sql: 1=스쿼트. analyzer_registry.py의 _EXERCISE_ID_TO_TYPE와 같은 + // 결합 취약성을 그대로 안는다 — 시드가 바뀌면 이 값도 같이 고쳐야 한다. + private static final long SQUAT_EXERCISE_ID = 1L; + + // ai-server pose.py의 _BACK_BENT_TILT_THRESHOLD와 같은 값 — 실시간 피드백과 세션 후 점수가 + // 같은 경계를 말하도록 의도적으로 맞췄다. 값이 어긋나면 두 경로가 "등 굽음"을 다른 기준으로 + // 판정하게 되니 둘 중 하나만 바꾸지 말 것. + private static final double NATURAL_LIMIT = 35.0; + // 문헌(Straub, IJSPT)이 "명백한 과도 전방 기울임"으로 꼽는 경계. + private static final double EXCESSIVE_THRESHOLD = 45.0; + + public TrunkLeanAnalysisDto calculate(Session session, List poseFrames) { + if (session.getExercise().getId() != SQUAT_EXERCISE_ID) { + return null; + } + if (poseFrames == null || poseFrames.isEmpty()) { + return null; + } + + List repTrunkLeans = new ArrayList<>(); + for (Map.Entry> entry : PoseFrameGrouping.byRep(poseFrames).entrySet()) { + RepTrunkLeanDto rep = scoreRep(entry.getKey(), entry.getValue()); + if (rep != null) { + repTrunkLeans.add(rep); + } + } + if (repTrunkLeans.isEmpty()) { + return null; // 유효한 체간 기울기 데이터가 있는 rep이 하나도 없음(구버전 행뿐이거나 전부 미계산) + } + + int sessionScore = (int) Math.round( + repTrunkLeans.stream().mapToInt(RepTrunkLeanDto::getTiltScore).average().orElse(0.0)); + + TrunkLeanAnalysisDto dto = new TrunkLeanAnalysisDto(); + dto.setTiltScore(sessionScore); + dto.setTiltGrade(gradeOf(sessionScore)); + dto.setRepTrunkLeans(repTrunkLeans); + dto.setNarrative(buildNarrative(repTrunkLeans, sessionScore)); + return dto; + } + + /** 이 rep에 속한 프레임들의 torsoTiltDeg 평균을 채점한다. 유효값이 없으면 null. */ + private RepTrunkLeanDto scoreRep(int repNumber, List frames) { + List tilts = frames.stream() + .map(PoseFrameProjection::torsoTiltDeg) + .filter(Objects::nonNull) + .toList(); + if (tilts.isEmpty()) { + return null; + } + double avgTilt = tilts.stream().mapToDouble(Double::doubleValue).average().orElse(0.0); + int score = scoreTilt(avgTilt); + return new RepTrunkLeanDto(repNumber, avgTilt, score, formatTimestamp(frames.get(0).timestampSec())); + } + + /** 35도 이하는 만점, 35~45도는 100→60 선형, 그 너머는 방어적으로 계속 깎는다. */ + private int scoreTilt(double avgTilt) { + if (avgTilt <= NATURAL_LIMIT) { + return 100; + } + if (avgTilt <= EXCESSIVE_THRESHOLD) { + return (int) Math.round(100 - (avgTilt - NATURAL_LIMIT) / (EXCESSIVE_THRESHOLD - NATURAL_LIMIT) * 40); + } + return (int) Math.max(0, Math.round(60 - (avgTilt - EXCESSIVE_THRESHOLD) * 3)); + } + + private String gradeOf(int score) { + if (score >= 90) return "EXCELLENT"; + if (score >= 75) return "GOOD"; + if (score >= 60) return "FAIR"; + if (score >= 40) return "NEEDS_WORK"; + return "POOR"; + } + + /** + * 회차별 한국어 코멘트, 최대 4문장. + * + *

우선순위: ① 인접 회차 대비(앞 회차 ≥85점, 바로 다음 회차가 15점 이상 낮고 실제로 더 + * 기울어짐) > ② 세션 전체 등급이 낮음(FAIR 미만) > ③ 전부 양호(폴백). + */ + private List buildNarrative(List repTrunkLeans, int sessionScore) { + List sentences = new ArrayList<>(); + + RepTrunkLeanDto dropFrom = null, dropTo = null; + int biggestDrop = 0; + for (int i = 0; i + 1 < repTrunkLeans.size(); i++) { + RepTrunkLeanDto a = repTrunkLeans.get(i), b = repTrunkLeans.get(i + 1); + int drop = a.getTiltScore() - b.getTiltScore(); + boolean gotMoreBent = b.getAvgTiltDeg() > a.getAvgTiltDeg(); + // b가 75점 미만일 때만 경고한다 — 낙차만 보면 93점대 세션에서도 "많이 숙여졌어요"가 + // 떠서 점수(EXCELLENT)와 코멘트가 모순된다(2026-10-05 실측 e2e에서 확인). + if (a.getTiltScore() >= 85 && b.getTiltScore() < 75 && drop >= 15 && gotMoreBent && drop > biggestDrop) { + biggestDrop = drop; + dropFrom = a; + dropTo = b; + } + } + if (dropFrom != null) { + sentences.add(String.format( + "%d회차까지는 상체를 잘 세웠는데, %d회차부터 상체가 많이 숙여졌어요.", + dropFrom.getRepNumber(), dropTo.getRepNumber())); + } + + if (sentences.size() < 4 && sessionScore < 60) { + sentences.add("전반적으로 상체가 많이 숙여졌어요 — 시선을 살짝 위로 두고 가슴을 펴보세요."); + } + + if (sentences.isEmpty()) { + sentences.add(String.format("%d회 모두 상체 자세를 잘 유지했어요.", repTrunkLeans.size())); + } + + return sentences.size() > 4 ? sentences.subList(0, 4) : sentences; + } + + private String formatTimestamp(Double timestampSec) { + if (timestampSec == null) return "00:00"; + int totalSeconds = timestampSec.intValue(); + return String.format("%02d:%02d", totalSeconds / 60, totalSeconds % 60); + } +} diff --git a/backend/src/main/resources/db/migration/V22__enable_forward_lunge.sql b/backend/src/main/resources/db/migration/V22__enable_forward_lunge.sql new file mode 100644 index 00000000..031e3929 --- /dev/null +++ b/backend/src/main/resources/db/migration/V22__enable_forward_lunge.sql @@ -0,0 +1,6 @@ +-- 전방 런지는 횟수만 측정한다. AI 런지 분석기를 먼저 배포한 뒤 적용한다. +-- 미측정 점수를 0점으로 저장하면 리포트 평균을 오염시키므로 NULL을 허용한다. +ALTER TABLE pose_data MODIFY COLUMN sync_rate DECIMAL(5,2) NULL; +ALTER TABLE exercises ADD COLUMN repetition_only BOOLEAN NOT NULL DEFAULT FALSE; + +UPDATE exercises SET analysis_supported = TRUE, repetition_only = TRUE WHERE id = 2; diff --git a/backend/src/main/resources/db/migration/V23__add_squat_depth_mode.sql b/backend/src/main/resources/db/migration/V23__add_squat_depth_mode.sql new file mode 100644 index 00000000..031bace0 --- /dev/null +++ b/backend/src/main/resources/db/migration/V23__add_squat_depth_mode.sql @@ -0,0 +1,5 @@ +-- 스쿼트 깊이 모드(풀/하프) — 세션 시작 시 선택, 종목 선택과 같은 화면(exercise.tsx). +-- 스쿼트가 아닌 세션(런지 등)에는 의미가 없다 — 항상 채워져 있지만 그 종목의 리포트 계산은 +-- 이 컬럼을 읽지 않는다(SquatDepthAnalysisCalculator의 exercise_id 가드 참고). +ALTER TABLE exercise_sessions + ADD COLUMN squat_depth_mode VARCHAR(10) NOT NULL DEFAULT 'FULL'; diff --git a/backend/src/main/resources/db/migration/V24__add_pose_data_lead_leg.sql b/backend/src/main/resources/db/migration/V24__add_pose_data_lead_leg.sql new file mode 100644 index 00000000..28213b6d --- /dev/null +++ b/backend/src/main/resources/db/migration/V24__add_pose_data_lead_leg.sql @@ -0,0 +1,14 @@ +-- 런지 좌우별 깊이 채점을 위해 프레임이 속한 앞다리를 저장한다 (2026-09-27). +-- +-- 지금까지 smoothed_knee_angle은 스쿼트에서만 의미가 고정돼 있었다(좌우 평균, 작을수록 +-- 깊음). 런지는 좌우 무릎각이 크게 갈리는 운동이라 평균을 쓰면 실제 깊이보다 항상 얕게 +-- 보인다 — ai-server가 이 컬럼에 "앞다리(lead) 무릎각"을 보내도록 바뀌었다 +-- (app/core/lunge_analyzer.py, PerRepFrame). 그런데 어느 다리인지는 여기 없으면 rep을 +-- 좌/우로 나눠 채점할 방법이 없다 — 이 컬럼이 그 정보다. +-- +-- NULL 허용: 스쿼트 프레임과 이 배포 이전 프레임은 전부 NULL이다(이 필드 개념이 없음). +-- 구버전 AI(필드 미전송)에서는 proto3 빈 문자열이 오는데, 빈 문자열을 그대로 저장하면 +-- "런지인데 판정 전(빈 문자열)"과 "애초에 이 개념이 없음(NULL)"이 안 갈린다 — 저장 계층 +-- (PoseDataService)에서 빈 문자열을 NULL로 접어 넣는다. +ALTER TABLE pose_data + ADD COLUMN lead_leg VARCHAR(5) NULL DEFAULT NULL; diff --git a/backend/src/main/resources/db/migration/V25__add_pose_data_torso_tilt.sql b/backend/src/main/resources/db/migration/V25__add_pose_data_torso_tilt.sql new file mode 100644 index 00000000..b73a638c --- /dev/null +++ b/backend/src/main/resources/db/migration/V25__add_pose_data_torso_tilt.sql @@ -0,0 +1,5 @@ +-- 체간(몸통) 기울기 점수(TrunkLeanAnalysisCalculator, 2026-09-28)용. 어깨 중점-엉덩이 중점 +-- 벡터가 수직에서 벗어난 각도(도) — 스쿼트·런지 공용. leadLeg(V24)와 달리 0이 "완전 직립"이라는 +-- 유효한 값이라 NULL은 순수하게 "구버전 행이라 이 컬럼 자체가 없었다"만 뜻한다. +ALTER TABLE pose_data + ADD COLUMN torso_tilt_deg DOUBLE NULL; diff --git a/backend/src/main/resources/db/migration/V26__add_pose_data_stagger_ratio.sql b/backend/src/main/resources/db/migration/V26__add_pose_data_stagger_ratio.sql new file mode 100644 index 00000000..c187a3b0 --- /dev/null +++ b/backend/src/main/resources/db/migration/V26__add_pose_data_stagger_ratio.sql @@ -0,0 +1,6 @@ +-- 런지 보폭 점수(LungeStepLengthAnalysisCalculator, 2026-09-28)용. 두 발목 사이 거리 / +-- 어깨-엉덩이 길이 — 런지 전용이라 스쿼트 행은 항상 0(보폭 개념 없음)이지만, 그 계산기는 +-- 런지 세션만 채점하므로 소비되지 않는다. NULL은 순수하게 "구버전 행이라 이 컬럼 자체가 +-- 없었다"만 뜻한다. +ALTER TABLE pose_data + ADD COLUMN stagger_ratio DOUBLE NULL; diff --git a/backend/src/test/java/com/shadowfit/repository/report/WeeklySummaryBLayerRaceTest.java b/backend/src/test/java/com/shadowfit/repository/report/WeeklySummaryBLayerRaceTest.java index 19e53c0a..ded7b54d 100644 --- a/backend/src/test/java/com/shadowfit/repository/report/WeeklySummaryBLayerRaceTest.java +++ b/backend/src/test/java/com/shadowfit/repository/report/WeeklySummaryBLayerRaceTest.java @@ -127,7 +127,7 @@ private void seedWithReport(Member owner, LocalDateTime startTime, Status status report.setSession(s); try { report.setDetailedAnalysis( - objectMapper.writeValueAsString(new SessionDetailedAnalysis(worstSection, repTrend))); + objectMapper.writeValueAsString(new SessionDetailedAnalysis(worstSection, repTrend, null, null, null, null, null))); } catch (Exception e) { throw new IllegalStateException(e); } diff --git a/backend/src/test/java/com/shadowfit/service/exercise/LungeSessionTest.java b/backend/src/test/java/com/shadowfit/service/exercise/LungeSessionTest.java new file mode 100644 index 00000000..d31fb72b --- /dev/null +++ b/backend/src/test/java/com/shadowfit/service/exercise/LungeSessionTest.java @@ -0,0 +1,87 @@ +package com.shadowfit.service.exercise; + +import com.shadowfit.dto.exercises.VideoRequestDto; +import com.shadowfit.grpc.PoseDataRequest; +import com.shadowfit.grpc.SessionCompleteRequest; +import com.shadowfit.model.exercise.Category; +import com.shadowfit.model.exercise.Exercise; +import com.shadowfit.model.exercise.Session; +import com.shadowfit.model.exercise.Status; +import com.shadowfit.model.member.Member; +import com.shadowfit.model.member.SelectedPersona; +import com.shadowfit.model.member.UserRole; +import com.shadowfit.repository.exercise.CategoryRepository; +import com.shadowfit.repository.exercise.ExercisesRepository; +import com.shadowfit.repository.exercise.PoseDataRepository; +import com.shadowfit.repository.exercise.SessionRepository; +import com.shadowfit.repository.member.MemberRepository; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.jdbc.core.JdbcTemplate; +import org.springframework.test.context.bean.override.mockito.MockitoBean; +import org.springframework.transaction.annotation.Transactional; + +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +@SpringBootTest +@Transactional +class LungeSessionTest { + @Autowired ExerciseAnalysisService analysis; + @Autowired PoseDataService poses; + @Autowired SessionCompletionTx completion; + @Autowired ReattachRequestBuilder reattach; + @Autowired MemberRepository members; + @Autowired ExercisesRepository exercises; + @Autowired CategoryRepository categories; + @Autowired SessionRepository sessions; + @Autowired PoseDataRepository poseRepository; + @Autowired JdbcTemplate jdbc; + @Autowired SessionActivityQueryService activities; + @MockitoBean OutboxPublisher publisher; + + @Test + void countOnlySessionStartsWithoutReferenceAndRestoresRepsWithoutScores() { + Member member = members.saveAndFlush(Member.builder() + .email("lunge-test@example.com").username("lunge").password("unused") + .selectedPersona(SelectedPersona.BEGINNER).role(UserRole.USER).build()); + Category category = categories.saveAndFlush(Category.builder().name("LOWER").build()); + Exercise exercise = exercises.saveAndFlush(Exercise.builder() + .name("전방 런지").category(category).analysisSupported(true).repetitionOnly(true).build()); + + // 회원의 기준 영상 URL이 없어도 횟수 측정 세션은 시작할 수 있다. + var started = analysis.startAnalysis( + VideoRequestDto.builder().exerciseId(exercise.getId()).build(), member.getId()); + Session session = sessions.findById(started.sessionId()).orElseThrow(); + assertThat(started.sessionNonce()).isNotBlank(); + assertThat(session.getStatus()).isEqualTo(Status.IN_PROGRESS); + + poses.savePoseDataBatch(session.getId(), List.of(PoseDataRequest.newBuilder() + .setTimestampSec(1).setJointCoordinates("[]").setRepNumber(1) + .setSmoothedKneeAngle(90).setSyncRate(0).build())); + + assertThat(jdbc.queryForObject("SELECT sync_rate FROM pose_data WHERE session_id = ?", + Double.class, session.getId())).isNull(); + assertThat(poseRepository.findRepAverageSyncRates(session.getId(), session.getStartTime())).isEmpty(); + var restored = reattach.build(session.getId(), member.getId()); + assertThat(restored.getInitialRepCount()).isEqualTo(1); + assertThat(restored.getReferencePosesCount()).isZero(); + + completion.applyComplete(SessionCompleteRequest.newBuilder().setSessionId(session.getId()) + .setTotalReps(1).setAvgSyncRate(0).build()); + assertThat(session.getTotalReps()).isEqualTo(1); + assertThat(session.getStatus()).isEqualTo(Status.COMPLETED); + assertThat(session.getAvgSyncRate()).isNull(); + assertThat(session.getMaxSyncRate()).isNull(); + assertThat(session.getMinSyncRate()).isNull(); + assertThat(activities.getDailyActivity(member.getId(), session.getStartTime().toLocalDate()) + .getSessions()).singleElement().satisfies(detail -> { + assertThat(detail.isScoreAvailable()).isFalse(); + assertThat(detail.getSetSummary()).contains("1회"); + }); + assertThat(com.shadowfit.dto.report.detailreport.SessionReportResponseDto + .of(session, new com.shadowfit.model.report.Report()).isScoreAvailable()).isFalse(); + } +} diff --git a/backend/src/test/java/com/shadowfit/service/exercise/SessionMetricsRecordingTest.java b/backend/src/test/java/com/shadowfit/service/exercise/SessionMetricsRecordingTest.java index b950c192..2e50551c 100644 --- a/backend/src/test/java/com/shadowfit/service/exercise/SessionMetricsRecordingTest.java +++ b/backend/src/test/java/com/shadowfit/service/exercise/SessionMetricsRecordingTest.java @@ -144,7 +144,7 @@ void circuitOpen_recordsFailedTransition() { circuitBreakerRegistry.circuitBreaker("aiServer-0").transitionToOpenState(); when(sessionService.markAsFailedIfStillInProgress(eq(1L), any(LocalDateTime.class))).thenReturn(true); - service.sendAnalysisRequestToFastApi(1L, dto(), "https://youtu.be/dummy", "BEGINNER", "test-nonce"); + service.sendAnalysisRequestToFastApi(1L, dto(), "https://youtu.be/dummy", "BEGINNER", "test-nonce", "FULL"); assertThat(transitions(Status.FAILED, "circuit-open")).isEqualTo(1.0); // 원인이 다른 FAILED와 섞이면 안 된다 — source 태그가 존재 이유이므로 @@ -157,11 +157,35 @@ void circuitOpen_alreadyFinished_recordsNothing() { circuitBreakerRegistry.circuitBreaker("aiServer-0").transitionToOpenState(); when(sessionService.markAsFailedIfStillInProgress(eq(1L), any(LocalDateTime.class))).thenReturn(false); - service.sendAnalysisRequestToFastApi(1L, dto(), "https://youtu.be/dummy", "BEGINNER", "test-nonce"); + service.sendAnalysisRequestToFastApi(1L, dto(), "https://youtu.be/dummy", "BEGINNER", "test-nonce", "FULL"); assertThat(transitions(Status.FAILED, "circuit-open")).isZero(); } + @Test + @DisplayName("squatDepthMode 인자가 AnalyzeRequest.depth_mode로 그대로 실린다 (2026-09-21)") + void sendAnalysisRequest_setsDepthModeOnAnalyzeRequest() { + org.mockito.ArgumentCaptor captor = + org.mockito.ArgumentCaptor.forClass(AnalyzeRequest.class); + + service.sendAnalysisRequestToFastApi(3L, dto(), "https://youtu.be/dummy", "BEGINNER", "test-nonce", "HALF"); + + verify(stub).startAnalysis(captor.capture(), any()); + assertThat(captor.getValue().getDepthMode()).isEqualTo("HALF"); + } + + @Test + @DisplayName("squatDepthMode가 null이면 AnalyzeRequest.depth_mode는 빈 문자열(AI측 FULL 취급)") + void sendAnalysisRequest_nullDepthMode_sendsEmptyString() { + org.mockito.ArgumentCaptor captor = + org.mockito.ArgumentCaptor.forClass(AnalyzeRequest.class); + + service.sendAnalysisRequestToFastApi(4L, dto(), "https://youtu.be/dummy", "BEGINNER", "test-nonce", null); + + verify(stub).startAnalysis(captor.capture(), any()); + assertThat(captor.getValue().getDepthMode()).isEmpty(); + } + @Test @DisplayName("gRPC onError로 세션을 걷어내면 FAILED 전이가 source=grpc-error 로 기록된다") void grpcError_recordsFailedTransition() { @@ -177,7 +201,7 @@ void grpcError_recordsFailedTransition() { return null; }).when(stub).startAnalysis(any(AnalyzeRequest.class), any()); - service.sendAnalysisRequestToFastApi(2L, dto(), "https://youtu.be/dummy", "BEGINNER", "test-nonce"); + service.sendAnalysisRequestToFastApi(2L, dto(), "https://youtu.be/dummy", "BEGINNER", "test-nonce", "FULL"); assertThat(transitions(Status.FAILED, "grpc-error")).isEqualTo(1.0); assertThat(transitions(Status.FAILED, "circuit-open")).isZero(); diff --git a/backend/src/test/java/com/shadowfit/service/report/LungeDepthAnalysisCalculatorTest.java b/backend/src/test/java/com/shadowfit/service/report/LungeDepthAnalysisCalculatorTest.java new file mode 100644 index 00000000..003a6c19 --- /dev/null +++ b/backend/src/test/java/com/shadowfit/service/report/LungeDepthAnalysisCalculatorTest.java @@ -0,0 +1,233 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.LungeDepthAnalysisDto; +import com.shadowfit.model.exercise.Category; +import com.shadowfit.model.exercise.Exercise; +import com.shadowfit.model.exercise.Session; +import com.shadowfit.model.exercise.Status; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * LungeDepthAnalysisCalculator 단위 테스트 (2026-09-27). + * + *

회귀 대상은 SquatDepthAnalysisCalculatorTest와 같은 세 가지에 더해, 런지 전용 축 하나 — + * ① 채점 공식의 경계값, ② 등급 5단계 경계, ③ 코멘트 우선순위(어떤 회차를 지목했는가), + * ④ 좌우 평균·비대칭 판정(스쿼트에는 없는 축). + */ +@DisplayName("LungeDepthAnalysisCalculator 테스트") +class LungeDepthAnalysisCalculatorTest { + + private LungeDepthAnalysisCalculator calculator; + private Session lungeSession; + private long nextPoseDataId; + + @BeforeEach + void setUp() { + calculator = new LungeDepthAnalysisCalculator(); + nextPoseDataId = 1L; + lungeSession = session(2L); + } + + private Session session(long exerciseId) { + Category category = Category.builder().id(1L).name("LOWER").build(); + Exercise exercise = Exercise.builder() + .id(exerciseId).name(exerciseId == 1L ? "스쿼트" : "전방 런지").category(category) + .expectedDurationMinutes(15) + .syncThresholdBeginner(new BigDecimal("60.00")).syncThresholdAdvanced(new BigDecimal("85.00")) + .build(); + return Session.builder() + .id(1L).exercise(exercise).startTime(LocalDateTime.now()) + .status(Status.COMPLETED) + .build(); + } + + private PoseFrameProjection frame(int repNumber, String side, double minKneeAngle) { + return new PoseFrameProjection(nextPoseDataId++, (double) repNumber, null, repNumber, minKneeAngle, side, null, null); + } + + // ── 가드 ──────────────────────────────────────────────────────────── + + @Test + @DisplayName("런지가 아니면(exercise_id != 2) null") + void nonLungeExercise_returnsNull() { + Session squatSession = session(1L); + List frames = List.of(frame(1, "left", 90.0)); + + assertThat(calculator.calculate(squatSession, frames)).isNull(); + } + + @Test + @DisplayName("프레임이 없으면 null") + void emptyFrames_returnsNull() { + assertThat(calculator.calculate(lungeSession, List.of())).isNull(); + } + + @Test + @DisplayName("유효한 무릎각(>0)이 있는 rep이 하나도 없으면 null") + void noValidKneeAngle_returnsNull() { + List frames = List.of( + new PoseFrameProjection(1L, 1.0, null, 1, 0.0, "left", null, null), + new PoseFrameProjection(2L, 1.0, null, 1, null, "left", null, null)); + + assertThat(calculator.calculate(lungeSession, frames)).isNull(); + } + + // ── 채점 경계값 (스쿼트 FULL과 같은 모양) ───────────────────────────── + + @Test + @DisplayName("무릎 100도 이하는 만점") + void atOrBelowTarget_scoresMax() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, "left", 90.0))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(100); + } + + @Test + @DisplayName("무릎 115도(실질 진입 경계)는 60점") + void atEntryBoundary_scores60() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, "left", 115.0))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(60); + } + + @Test + @DisplayName("무릎 107.5도(100~115 중간)는 80점") + void atMidpoint_scores80() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, "left", 107.5))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(80); + } + + // ── 등급 5단계 ────────────────────────────────────────────────────── + + @Test + @DisplayName("등급: 세션 평균 점수에 따라 EXCELLENT~POOR 5단계") + void grade_fiveTiers() { + assertThat(gradeFor(95)).isEqualTo("EXCELLENT"); + assertThat(gradeFor(80)).isEqualTo("GOOD"); + assertThat(gradeFor(65)).isEqualTo("FAIR"); + assertThat(gradeFor(45)).isEqualTo("NEEDS_WORK"); + assertThat(gradeFor(20)).isEqualTo("POOR"); + } + + private String gradeFor(int targetScore) { + double knee = targetScore >= 60 + ? 100 + (100 - targetScore) / 40.0 * 15 + : 115 + (60 - targetScore) / 2.0; + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, "left", knee))); + return result.getDepthGrade(); + } + + // ── 세션 평균 ─────────────────────────────────────────────────────── + + @Test + @DisplayName("세션 점수는 회차별 점수의 평균(반올림)") + void sessionScore_isAverageOfRepScores() { + LungeDepthAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, "left", 90.0), frame(2, "right", 115.0))); + assertThat(result.getDepthScore()).isEqualTo(80); + } + + // ── 좌우 평균·비대칭 (런지 전용) ──────────────────────────────────── + + @Test + @DisplayName("좌우 평균은 그 다리로 시작한 회차만으로 계산한다") + void sideAverages_onlyIncludeMatchingSide() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of( + frame(1, "left", 60.0), frame(2, "left", 70.0), frame(3, "right", 80.0))); + + assertThat(result.getLeftAvgKneeAngle()).isEqualTo(65.0); + assertThat(result.getRightAvgKneeAngle()).isEqualTo(80.0); + } + + @Test + @DisplayName("한쪽 다리로 시작한 회차가 없으면 그쪽 평균은 null") + void sideAverage_nullWhenNoRepsOnThatSide() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, "left", 60.0))); + + assertThat(result.getLeftAvgKneeAngle()).isEqualTo(60.0); + assertThat(result.getRightAvgKneeAngle()).isNull(); + } + + @Test + @DisplayName("좌우 평균 차이가 10도 이상이면 비대칭 코멘트를 낸다") + void narrative_asymmetry_mentionsBothSides() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of( + frame(1, "left", 60.0), frame(2, "right", 90.0))); + + assertThat(result.getNarrative()).anySatisfy(line -> + assertThat(line).contains("오른쪽").contains("왼쪽")); + } + + @Test + @DisplayName("좌우 평균 차이가 10도 미만이면 비대칭 코멘트를 내지 않는다") + void narrative_balanced_noAsymmetryComment() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of( + frame(1, "left", 60.0), frame(2, "right", 65.0))); + + assertThat(result.getNarrative()).noneSatisfy(line -> + assertThat(line).contains("균형을 맞춰보세요")); + } + + // ── 회차별 코멘트 우선순위 ─────────────────────────────────────────── + + @Test + @DisplayName("코멘트: 같은 다리 안에서 앞 회차 좋고 바로 다음 회차가 크게 떨어지면 그 두 회차를 지목한다") + void narrative_adjacentDrop_sameLeg_mentionsBothReps() { + // rep1(left,90=100점) -> rep2(left,118=54점, 낙차 46) -> 트리거. 둘 다 왼쪽이라 + // rightAvg가 null이 되어 비대칭 코멘트(우선순위 ①)는 애초에 계산되지 않는다. + LungeDepthAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, "left", 90.0), frame(2, "left", 118.0))); + + assertThat(result.getNarrative()).anySatisfy(line -> + assertThat(line).contains("1회차").contains("2회차")); + } + + @Test + @DisplayName("코멘트: 다리가 바뀌는 지점은 인접 회차 대비에서 비교하지 않는다(워킹 런지)") + void narrative_adjacentDrop_doesNotCompareAcrossLegs() { + // rep1(left,100=100점) -> rep2(right,106=84점, 낙차 16) — 같은 다리였다면 ②가 트리거될 + // 낙차지만 다리가 다르므로 비교하지 않는다. 좌우 평균 차이도 6도로 10도 미만이라 + // 비대칭 코멘트(①)도 안 섞여 이 테스트의 관심사(② 하나)만 본다. + LungeDepthAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, "left", 100.0), frame(2, "right", 106.0))); + + assertThat(result.getNarrative()).noneSatisfy(line -> + assertThat(line).contains("1회차").contains("2회차")); + } + + @Test + @DisplayName("코멘트: 통과했지만 평균 깊이가 얕으면(85도 초과) 아슬아슬 코멘트") + void narrative_closeCall_whenShallowButPassing() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of( + frame(1, "left", 89.0), frame(2, "left", 88.0))); + + assertThat(result.getNarrative().get(0)).contains("여유 있게 통과하지는 않았어요"); + } + + @Test + @DisplayName("코멘트: 모든 회차가 고르게 깊고 좌우도 균형이면 회차 언급 없는 한 줄로 폴백한다") + void narrative_allGood_fallsBackToSingleLine() { + LungeDepthAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, "left", 60.0), frame(2, "right", 62.0), frame(3, "left", 61.0))); + + assertThat(result.getNarrative()).hasSize(1); + assertThat(result.getNarrative().get(0)).contains("3회"); + } + + @Test + @DisplayName("코멘트는 최대 4문장") + void narrative_cappedAtFour() { + LungeDepthAnalysisDto result = calculator.calculate(lungeSession, List.of( + frame(1, "left", 60.0), frame(2, "left", 118.0), frame(3, "left", 62.0), + frame(4, "left", 119.0), frame(5, "right", 95.0))); + + assertThat(result.getNarrative()).hasSizeLessThanOrEqualTo(4); + } +} diff --git a/backend/src/test/java/com/shadowfit/service/report/LungeStepLengthAnalysisCalculatorTest.java b/backend/src/test/java/com/shadowfit/service/report/LungeStepLengthAnalysisCalculatorTest.java new file mode 100644 index 00000000..59945bc7 --- /dev/null +++ b/backend/src/test/java/com/shadowfit/service/report/LungeStepLengthAnalysisCalculatorTest.java @@ -0,0 +1,191 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.LungeStepLengthAnalysisDto; +import com.shadowfit.model.exercise.Category; +import com.shadowfit.model.exercise.Exercise; +import com.shadowfit.model.exercise.Session; +import com.shadowfit.model.exercise.Status; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * LungeStepLengthAnalysisCalculator 단위 테스트 (2026-09-28). + * + *

회귀 대상은 다른 계산기들과 같은 세 가지 — ① 채점 공식의 경계값, ② 등급 5단계 경계, + * ③ 코멘트 우선순위 — 에 더해, rep의 대표값이 "그 rep에서 무릎이 가장 깊게 굽혀진 프레임"의 + * staggerRatio임을 고정하는 축 하나가 추가된다(LungeDepthAnalysisCalculator와 같은 대표 + * 프레임 선택 재사용). + */ +@DisplayName("LungeStepLengthAnalysisCalculator 테스트") +class LungeStepLengthAnalysisCalculatorTest { + + private LungeStepLengthAnalysisCalculator calculator; + private Session lungeSession; + private long nextPoseDataId; + + @BeforeEach + void setUp() { + calculator = new LungeStepLengthAnalysisCalculator(); + nextPoseDataId = 1L; + lungeSession = session(2L); + } + + private Session session(long exerciseId) { + Category category = Category.builder().id(1L).name("LOWER").build(); + Exercise exercise = Exercise.builder() + .id(exerciseId).name(exerciseId == 1L ? "스쿼트" : "전방 런지").category(category) + .expectedDurationMinutes(15) + .syncThresholdBeginner(new BigDecimal("60.00")).syncThresholdAdvanced(new BigDecimal("85.00")) + .build(); + return Session.builder() + .id(1L).exercise(exercise).startTime(LocalDateTime.now()) + .status(Status.COMPLETED) + .build(); + } + + private PoseFrameProjection frame(int repNumber, double staggerRatio) { + return new PoseFrameProjection(nextPoseDataId++, (double) repNumber, null, repNumber, 90.0, "left", null, staggerRatio); + } + + // ── 가드 ──────────────────────────────────────────────────────────── + + @Test + @DisplayName("런지가 아니면(exercise_id != 2) null") + void nonLungeExercise_returnsNull() { + Session squatSession = session(1L); + assertThat(calculator.calculate(squatSession, List.of(frame(1, 1.0)))).isNull(); + } + + @Test + @DisplayName("프레임이 없으면 null") + void emptyFrames_returnsNull() { + assertThat(calculator.calculate(lungeSession, List.of())).isNull(); + } + + @Test + @DisplayName("유효한 보폭(non-null staggerRatio) 데이터가 있는 rep이 하나도 없으면 null") + void noValidStagger_returnsNull() { + List frames = List.of( + new PoseFrameProjection(1L, 1.0, null, 1, 90.0, "left", null, null)); + + assertThat(calculator.calculate(lungeSession, frames)).isNull(); + } + + // ── 채점 경계값 ──────────────────────────────────────────────────── + + @Test + @DisplayName("stagger 1.0 이상은 만점") + void atOrAboveAdequate_scoresMax() { + LungeStepLengthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, 1.2))); + assertThat(result.getRepStepLengths().get(0).getStepScore()).isEqualTo(100); + } + + @Test + @DisplayName("stagger 0.6(짧은 보폭 진입 경계)은 60점") + void atShortEntry_scores60() { + LungeStepLengthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, 0.6))); + assertThat(result.getRepStepLengths().get(0).getStepScore()).isEqualTo(60); + } + + @Test + @DisplayName("stagger 0.8(0.6~1.0 중간)은 80점") + void atMidpoint_scores80() { + LungeStepLengthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, 0.8))); + assertThat(result.getRepStepLengths().get(0).getStepScore()).isEqualTo(80); + } + + @Test + @DisplayName("rep 대표값은 그 rep에서 무릎이 가장 깊게 굽혀진 프레임의 staggerRatio다") + void repRepresentative_isDeepestKneeFrame() { + // 같은 rep 안에 무릎 120도(얕음, stagger 1.2)와 90도(깊음, stagger 0.7) 프레임이 섞이면 + // 더 깊은(90도) 프레임의 stagger인 0.7을 대표로 써야 한다. + List frames = List.of( + new PoseFrameProjection(1L, 1.0, null, 1, 120.0, "left", null, 1.2), + new PoseFrameProjection(2L, 1.0, null, 1, 90.0, "left", null, 0.7)); + + LungeStepLengthAnalysisDto result = calculator.calculate(lungeSession, frames); + + assertThat(result.getRepStepLengths().get(0).getStaggerRatio()).isEqualTo(0.7); + } + + // ── 등급 5단계 ────────────────────────────────────────────────────── + + @Test + @DisplayName("등급: 세션 평균 점수에 따라 EXCELLENT~POOR 5단계") + void grade_fiveTiers() { + assertThat(gradeFor(95)).isEqualTo("EXCELLENT"); + assertThat(gradeFor(80)).isEqualTo("GOOD"); + assertThat(gradeFor(65)).isEqualTo("FAIR"); + assertThat(gradeFor(45)).isEqualTo("NEEDS_WORK"); + assertThat(gradeFor(20)).isEqualTo("POOR"); + } + + private String gradeFor(int targetScore) { + double stagger = targetScore >= 60 + ? 1.0 - (100 - targetScore) / 40.0 * 0.4 + : 0.6 - (60 - targetScore) / 100.0; + LungeStepLengthAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, stagger))); + return result.getStepGrade(); + } + + // ── 세션 평균 ─────────────────────────────────────────────────────── + + @Test + @DisplayName("세션 점수는 회차별 점수의 평균(반올림)") + void sessionScore_isAverageOfRepScores() { + // rep1: stagger=1.2 -> 100점, rep2: stagger=0.6 -> 60점 => 평균 80 + LungeStepLengthAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, 1.2), frame(2, 0.6))); + assertThat(result.getStepScore()).isEqualTo(80); + } + + // ── 회차별 코멘트 우선순위 ─────────────────────────────────────────── + + @Test + @DisplayName("코멘트 ①: 앞 회차 넉넉하고 바로 다음 회차가 크게 짧아지면 그 두 회차를 지목한다") + void narrative_adjacentDrop_mentionsBothReps() { + // rep1: stagger=1.2(100점) -> rep2: stagger=0.5(30점, 낙차 70) -> 트리거 + LungeStepLengthAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, 1.2), frame(2, 0.5))); + + assertThat(result.getNarrative()).anySatisfy(line -> + assertThat(line).contains("1회차").contains("2회차")); + } + + @Test + @DisplayName("코멘트 ②: 세션 전체 등급이 FAIR 미만이면 전반적 경고 코멘트를 낸다") + void narrative_lowOverallGrade_addsGeneralComment() { + LungeStepLengthAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, 0.4), frame(2, 0.4), frame(3, 0.4))); + + assertThat(result.getStepScore()).isLessThan(60); + assertThat(result.getNarrative()).anySatisfy(line -> assertThat(line).contains("앞발")); + } + + @Test + @DisplayName("코멘트 ③: 모든 회차가 고르게 양호하면 회차 언급 없는 한 줄로 폴백한다") + void narrative_allGood_fallsBackToSingleLine() { + LungeStepLengthAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, 1.1), frame(2, 1.2), frame(3, 1.15))); + + assertThat(result.getNarrative()).hasSize(1); + assertThat(result.getNarrative().get(0)).contains("3회"); + } + + @Test + @DisplayName("코멘트는 최대 4문장") + void narrative_cappedAtFour() { + LungeStepLengthAnalysisDto result = calculator.calculate(lungeSession, List.of( + frame(1, 1.2), frame(2, 0.4), frame(3, 1.2), frame(4, 0.4), frame(5, 0.4))); + + assertThat(result.getNarrative()).hasSizeLessThanOrEqualTo(4); + } +} diff --git a/backend/src/test/java/com/shadowfit/service/report/LungeTrunkLeanAnalysisCalculatorTest.java b/backend/src/test/java/com/shadowfit/service/report/LungeTrunkLeanAnalysisCalculatorTest.java new file mode 100644 index 00000000..dce2cf5d --- /dev/null +++ b/backend/src/test/java/com/shadowfit/service/report/LungeTrunkLeanAnalysisCalculatorTest.java @@ -0,0 +1,176 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.TrunkLeanAnalysisDto; +import com.shadowfit.model.exercise.Category; +import com.shadowfit.model.exercise.Exercise; +import com.shadowfit.model.exercise.Session; +import com.shadowfit.model.exercise.Status; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * LungeTrunkLeanAnalysisCalculator 단위 테스트 (2026-09-28). + * + *

SquatTrunkLeanAnalysisCalculatorTest와 같은 축을 검증하되, 임계값이 스쿼트(20/35)보다 + * 훨씬 관대한 런지 전용 밴드(35/55)로 채점되는지를 고정한다 — 런지의 의도적 전방 기울임은 + * 정상 기법이라(계산기 클래스 javadoc 참고) 스쿼트와 같은 경계를 쓰면 과잉 감점된다. + */ +@DisplayName("LungeTrunkLeanAnalysisCalculator 테스트") +class LungeTrunkLeanAnalysisCalculatorTest { + + private LungeTrunkLeanAnalysisCalculator calculator; + private Session lungeSession; + private long nextPoseDataId; + + @BeforeEach + void setUp() { + calculator = new LungeTrunkLeanAnalysisCalculator(); + nextPoseDataId = 1L; + lungeSession = session(2L); + } + + private Session session(long exerciseId) { + Category category = Category.builder().id(1L).name("LOWER").build(); + Exercise exercise = Exercise.builder() + .id(exerciseId).name(exerciseId == 1L ? "스쿼트" : "전방 런지").category(category) + .expectedDurationMinutes(15) + .syncThresholdBeginner(new BigDecimal("60.00")).syncThresholdAdvanced(new BigDecimal("85.00")) + .build(); + return Session.builder() + .id(1L).exercise(exercise).startTime(LocalDateTime.now()) + .status(Status.COMPLETED) + .build(); + } + + private PoseFrameProjection frame(int repNumber, double torsoTiltDeg) { + return new PoseFrameProjection(nextPoseDataId++, (double) repNumber, null, repNumber, 90.0, "left", torsoTiltDeg, null); + } + + // ── 가드 ──────────────────────────────────────────────────────────── + + @Test + @DisplayName("런지가 아니면(exercise_id != 2) null") + void nonLungeExercise_returnsNull() { + Session squatSession = session(1L); + assertThat(calculator.calculate(squatSession, List.of(frame(1, 10.0)))).isNull(); + } + + @Test + @DisplayName("프레임이 없으면 null") + void emptyFrames_returnsNull() { + assertThat(calculator.calculate(lungeSession, List.of())).isNull(); + } + + @Test + @DisplayName("유효한 체간 기울기(non-null) 데이터가 있는 rep이 하나도 없으면 null") + void noValidTilt_returnsNull() { + List frames = List.of( + new PoseFrameProjection(1L, 1.0, null, 1, 90.0, "left", null, null)); + + assertThat(calculator.calculate(lungeSession, frames)).isNull(); + } + + // ── 채점 경계값 (스쿼트보다 관대한 밴드) ──────────────────────────── + + @Test + @DisplayName("체간 기울기 35도 이하는 만점 — 스쿼트라면 60점일 값") + void atNaturalLimit_scoresMax() { + TrunkLeanAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, 35.0))); + assertThat(result.getRepTrunkLeans().get(0).getTiltScore()).isEqualTo(100); + } + + @Test + @DisplayName("체간 기울기 55도(과도 경계)는 60점") + void atExcessiveThreshold_scores60() { + TrunkLeanAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, 55.0))); + assertThat(result.getRepTrunkLeans().get(0).getTiltScore()).isEqualTo(60); + } + + @Test + @DisplayName("체간 기울기 45도(35~55 중간)는 80점") + void atMidpoint_scores80() { + TrunkLeanAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, 45.0))); + assertThat(result.getRepTrunkLeans().get(0).getTiltScore()).isEqualTo(80); + } + + // ── 등급 5단계 ────────────────────────────────────────────────────── + + @Test + @DisplayName("등급: 세션 평균 점수에 따라 EXCELLENT~POOR 5단계") + void grade_fiveTiers() { + assertThat(gradeFor(95)).isEqualTo("EXCELLENT"); + assertThat(gradeFor(80)).isEqualTo("GOOD"); + assertThat(gradeFor(65)).isEqualTo("FAIR"); + assertThat(gradeFor(45)).isEqualTo("NEEDS_WORK"); + assertThat(gradeFor(20)).isEqualTo("POOR"); + } + + private String gradeFor(int targetScore) { + double tilt = targetScore >= 60 + ? 35 + (100 - targetScore) / 40.0 * 20 + : 55 + (60 - targetScore) / 3.0; + TrunkLeanAnalysisDto result = calculator.calculate(lungeSession, List.of(frame(1, tilt))); + return result.getTiltGrade(); + } + + // ── 세션 평균 ─────────────────────────────────────────────────────── + + @Test + @DisplayName("세션 점수는 회차별 점수의 평균(반올림)") + void sessionScore_isAverageOfRepScores() { + // rep1: tilt=35 -> 100점, rep2: tilt=55 -> 60점 => 평균 80 + TrunkLeanAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, 35.0), frame(2, 55.0))); + assertThat(result.getTiltScore()).isEqualTo(80); + } + + // ── 회차별 코멘트 우선순위 ─────────────────────────────────────────── + + @Test + @DisplayName("코멘트 ①: 앞 회차 좋고 바로 다음 회차가 크게 나빠지면 그 두 회차를 지목한다") + void narrative_adjacentDrop_mentionsBothReps() { + // rep1: tilt=35(100점) -> rep2: tilt=65(30점, 낙차 70) -> 트리거 + TrunkLeanAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, 35.0), frame(2, 65.0))); + + assertThat(result.getNarrative()).anySatisfy(line -> + assertThat(line).contains("1회차").contains("2회차")); + } + + @Test + @DisplayName("코멘트 ②: 세션 전체 등급이 FAIR 미만이면 전반적 경고 코멘트를 낸다") + void narrative_lowOverallGrade_addsGeneralComment() { + TrunkLeanAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, 70.0), frame(2, 70.0), frame(3, 70.0))); + + assertThat(result.getTiltScore()).isLessThan(60); + assertThat(result.getNarrative()).anySatisfy(line -> assertThat(line).contains("코어")); + } + + @Test + @DisplayName("코멘트 ③: 모든 회차가 고르게 양호하면 회차 언급 없는 한 줄로 폴백한다") + void narrative_allGood_fallsBackToSingleLine() { + TrunkLeanAnalysisDto result = calculator.calculate( + lungeSession, List.of(frame(1, 20.0), frame(2, 25.0), frame(3, 22.0))); + + assertThat(result.getNarrative()).hasSize(1); + assertThat(result.getNarrative().get(0)).contains("3회"); + } + + @Test + @DisplayName("코멘트는 최대 4문장") + void narrative_cappedAtFour() { + TrunkLeanAnalysisDto result = calculator.calculate(lungeSession, List.of( + frame(1, 35.0), frame(2, 65.0), frame(3, 36.0), frame(4, 66.0), frame(5, 70.0))); + + assertThat(result.getNarrative()).hasSizeLessThanOrEqualTo(4); + } +} diff --git a/backend/src/test/java/com/shadowfit/service/report/ReportServiceTest.java b/backend/src/test/java/com/shadowfit/service/report/ReportServiceTest.java index 4972ce3c..7992eb90 100644 --- a/backend/src/test/java/com/shadowfit/service/report/ReportServiceTest.java +++ b/backend/src/test/java/com/shadowfit/service/report/ReportServiceTest.java @@ -50,6 +50,11 @@ class ReportServiceTest { @Mock private SessionRepository sessionRepository; @Mock private PoseDataRepository poseDataRepository; @Mock private SessionAnalysisCalculator sessionAnalysisCalculator; + @Mock private SquatDepthAnalysisCalculator squatDepthAnalysisCalculator; + @Mock private LungeDepthAnalysisCalculator lungeDepthAnalysisCalculator; + @Mock private SquatTrunkLeanAnalysisCalculator squatTrunkLeanAnalysisCalculator; + @Mock private LungeTrunkLeanAnalysisCalculator lungeTrunkLeanAnalysisCalculator; + @Mock private LungeStepLengthAnalysisCalculator lungeStepLengthAnalysisCalculator; private ReportService reportService; @@ -63,7 +68,9 @@ void setUp() { MockitoAnnotations.openMocks(this); // 실제 JSON 직렬화/역직렬화 동작이 검증 대상이라 ObjectMapper는 모킹하지 않고 실사용 reportService = new ReportService(reportRepository, sessionRepository, poseDataRepository, - sessionAnalysisCalculator, new ObjectMapper()); + sessionAnalysisCalculator, squatDepthAnalysisCalculator, lungeDepthAnalysisCalculator, + squatTrunkLeanAnalysisCalculator, lungeTrunkLeanAnalysisCalculator, + lungeStepLengthAnalysisCalculator, new ObjectMapper()); Member member = Member.builder().id(MEMBER_ID).email("t@t.com").username("u").password("p").build(); Category category = Category.builder().id(1L).name("LOWER").build(); @@ -127,7 +134,7 @@ void precomputedAnalysis_skipsPoseDataRecompute() throws Exception { SessionDetailedAnalysis stored = new SessionDetailedAnalysis(precomputed, List.of( new RepSyncRateDto(1, 80.0, "00:12"), new RepSyncRateDto(2, 75.0, "01:15") - )); + ), null, null, null, null, null); report.setDetailedAnalysis(new ObjectMapper().writeValueAsString(stored)); when(reportRepository.findBySessionId(SESSION_ID)).thenReturn(Optional.of(report)); @@ -156,7 +163,7 @@ void legacyAnalysisFormat_fallsBackToRecompute() throws Exception { report.setDetailedAnalysis(new ObjectMapper().writeValueAsString(legacy)); when(reportRepository.findBySessionId(SESSION_ID)).thenReturn(Optional.of(report)); - List frames = List.of(new PoseFrameProjection(1L, 0.0, 50.0, 1, 100.0)); + List frames = List.of(new PoseFrameProjection(1L, 0.0, 50.0, 1, 100.0, null, null, null)); when(poseDataRepository.findFramesBySessionId(eq(SESSION_ID), any())).thenReturn(frames); WorstSectionDto recomputed = new WorstSectionDto(); recomputed.setReason("재계산됨"); @@ -176,7 +183,7 @@ void legacyAnalysisFormat_fallsBackToRecompute() throws Exception { void blankAnalysis_fallsBackToPoseDataRecompute() { report.setDetailedAnalysis(null); // 시드 데이터처럼 precompute 이전 상태 when(reportRepository.findBySessionId(SESSION_ID)).thenReturn(Optional.of(report)); - List frames = List.of(new PoseFrameProjection(1L, 0.0, 50.0, 1, 100.0)); + List frames = List.of(new PoseFrameProjection(1L, 0.0, 50.0, 1, 100.0, null, null, null)); when(poseDataRepository.findFramesBySessionId(eq(SESSION_ID), any())).thenReturn(frames); WorstSectionDto recomputed = new WorstSectionDto(); recomputed.setReason("재계산됨"); @@ -193,7 +200,7 @@ void blankAnalysis_fallsBackToPoseDataRecompute() { void malformedAnalysis_fallsBackGracefully() { report.setDetailedAnalysis("{이건 JSON이 아님"); when(reportRepository.findBySessionId(SESSION_ID)).thenReturn(Optional.of(report)); - List frames = List.of(new PoseFrameProjection(1L, 0.0, 50.0, 1, 100.0)); + List frames = List.of(new PoseFrameProjection(1L, 0.0, 50.0, 1, 100.0, null, null, null)); when(poseDataRepository.findFramesBySessionId(eq(SESSION_ID), any())).thenReturn(frames); WorstSectionDto recomputed = new WorstSectionDto(); recomputed.setReason("재계산됨"); diff --git a/backend/src/test/java/com/shadowfit/service/report/SessionAnalysisCalculatorTest.java b/backend/src/test/java/com/shadowfit/service/report/SessionAnalysisCalculatorTest.java index 3c8bbea9..7c3db53c 100644 --- a/backend/src/test/java/com/shadowfit/service/report/SessionAnalysisCalculatorTest.java +++ b/backend/src/test/java/com/shadowfit/service/report/SessionAnalysisCalculatorTest.java @@ -74,7 +74,7 @@ private PoseFrameProjection frame(int repNumber, double timestampSec, Double syn /** 무릎각을 명시한 프레임. 작을수록 깊게 앉은 것이다(0 = 미상). */ private PoseFrameProjection frame( int repNumber, double timestampSec, Double syncRate, Double smoothedKneeAngle) { - return new PoseFrameProjection(nextPoseDataId++, timestampSec, syncRate, repNumber, smoothedKneeAngle); + return new PoseFrameProjection(nextPoseDataId++, timestampSec, syncRate, repNumber, smoothedKneeAngle, null, null, null); } @Test diff --git a/backend/src/test/java/com/shadowfit/service/report/SquatDepthAnalysisCalculatorTest.java b/backend/src/test/java/com/shadowfit/service/report/SquatDepthAnalysisCalculatorTest.java new file mode 100644 index 00000000..70b28526 --- /dev/null +++ b/backend/src/test/java/com/shadowfit/service/report/SquatDepthAnalysisCalculatorTest.java @@ -0,0 +1,214 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.SquatDepthAnalysisDto; +import com.shadowfit.model.exercise.Category; +import com.shadowfit.model.exercise.Exercise; +import com.shadowfit.model.exercise.Session; +import com.shadowfit.model.exercise.SquatDepthMode; +import com.shadowfit.model.exercise.Status; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * SquatDepthAnalysisCalculator 단위 테스트 (2026-09-21). + * + *

회귀 대상은 세 가지다 — ① 채점 공식의 경계값이 formula와 정확히 일치하는가, + * ② 등급 5단계 경계, ③ 코멘트 생성기가 트리거 우선순위대로 정확히 하나를 고르는가(문구 자체가 + * 아니라 "어떤 회차를 지목했는가"를 본다 — 문구는 잠정이라 SessionAnalysisCalculator의 worst + * reason과 같은 이유로 파싱하지 않는다). + */ +@DisplayName("SquatDepthAnalysisCalculator 테스트") +class SquatDepthAnalysisCalculatorTest { + + private SquatDepthAnalysisCalculator calculator; + private Session squatSession; + private long nextPoseDataId; + + @BeforeEach + void setUp() { + calculator = new SquatDepthAnalysisCalculator(); + nextPoseDataId = 1L; + squatSession = session(1L, SquatDepthMode.FULL); + } + + private Session session(long exerciseId, SquatDepthMode mode) { + Category category = Category.builder().id(1L).name("LOWER").build(); + Exercise exercise = Exercise.builder() + .id(exerciseId).name(exerciseId == 1L ? "스쿼트" : "전방 런지").category(category) + .expectedDurationMinutes(15) + .syncThresholdBeginner(new BigDecimal("60.00")).syncThresholdAdvanced(new BigDecimal("85.00")) + .build(); + return Session.builder() + .id(1L).exercise(exercise).startTime(LocalDateTime.now()) + .status(Status.COMPLETED).squatDepthMode(mode) + .build(); + } + + private PoseFrameProjection frame(int repNumber, double minKneeAngle) { + return new PoseFrameProjection(nextPoseDataId++, (double) repNumber, 80.0, repNumber, minKneeAngle, null, null, null); + } + + // ── 가드 ──────────────────────────────────────────────────────────── + + @Test + @DisplayName("스쿼트가 아니면(exercise_id != 1) null") + void nonSquatExercise_returnsNull() { + Session lungeSession = session(2L, SquatDepthMode.FULL); + List frames = List.of(frame(1, 90.0)); + + assertThat(calculator.calculate(lungeSession, frames)).isNull(); + } + + @Test + @DisplayName("프레임이 없으면 null") + void emptyFrames_returnsNull() { + assertThat(calculator.calculate(squatSession, List.of())).isNull(); + } + + @Test + @DisplayName("유효한 무릎각(>0)이 있는 rep이 하나도 없으면 null") + void noValidKneeAngle_returnsNull() { + List frames = List.of( + new PoseFrameProjection(1L, 1.0, 80.0, 1, 0.0, null, null, null), + new PoseFrameProjection(2L, 1.0, 80.0, 1, null, null, null, null)); + + assertThat(calculator.calculate(squatSession, frames)).isNull(); + } + + // ── FULL 모드 채점 경계값 ──────────────────────────────────────────── + + @Test + @DisplayName("FULL: 무릎 100도 이하는 만점") + void full_atOrBelowTarget_scoresMax() { + SquatDepthAnalysisDto result = calculator.calculate(squatSession, List.of(frame(1, 90.0))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(100); + } + + @Test + @DisplayName("FULL: 무릎 115도(실질 진입 경계)는 60점") + void full_atEntryBoundary_scores60() { + SquatDepthAnalysisDto result = calculator.calculate(squatSession, List.of(frame(1, 115.0))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(60); + } + + @Test + @DisplayName("FULL: 무릎 107.5도(100~115 중간)는 80점") + void full_atMidpoint_scores80() { + SquatDepthAnalysisDto result = calculator.calculate(squatSession, List.of(frame(1, 107.5))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(80); + } + + // ── HALF 모드 채점 경계값 ──────────────────────────────────────────── + + @Test + @DisplayName("HALF: 무릎 127.5도(밴드 중심)는 만점") + void half_atCenter_scoresMax() { + Session halfSession = session(1L, SquatDepthMode.HALF); + SquatDepthAnalysisDto result = calculator.calculate(halfSession, List.of(frame(1, 127.5))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(100); + } + + @Test + @DisplayName("HALF: 무릎 115도(밴드 얕은 쪽 경계)는 70점") + void half_atShallowEdge_scores70() { + Session halfSession = session(1L, SquatDepthMode.HALF); + SquatDepthAnalysisDto result = calculator.calculate(halfSession, List.of(frame(1, 115.0))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(70); + } + + @Test + @DisplayName("HALF: 무릎 140도(밴드 깊은 쪽 경계)도 70점 — 대칭") + void half_atDeepEdge_scores70() { + Session halfSession = session(1L, SquatDepthMode.HALF); + SquatDepthAnalysisDto result = calculator.calculate(halfSession, List.of(frame(1, 140.0))); + assertThat(result.getRepDepths().get(0).getDepthScore()).isEqualTo(70); + } + + // ── 등급 5단계 ────────────────────────────────────────────────────── + + @Test + @DisplayName("등급: 세션 평균 점수에 따라 EXCELLENT~POOR 5단계") + void grade_fiveTiers() { + assertThat(gradeFor(95)).isEqualTo("EXCELLENT"); + assertThat(gradeFor(80)).isEqualTo("GOOD"); + assertThat(gradeFor(65)).isEqualTo("FAIR"); + assertThat(gradeFor(45)).isEqualTo("NEEDS_WORK"); + assertThat(gradeFor(20)).isEqualTo("POOR"); + } + + /** + * 단일 rep의 무릎각을 역산해 원하는 점수를 만들고 등급만 본다(FULL 모드). + * scoreFull의 두 구간을 역산 대상 점수에 따라 나눠 쓴다 — + * 60~100점: knee∈[100,115] 선형 구간, 60점 미만: knee>115 방어 구간(기울기 -2). + */ + private String gradeFor(int targetScore) { + double knee = targetScore >= 60 + ? 100 + (100 - targetScore) / 40.0 * 15 // score = 100 - (knee-100)/15*40 + : 115 + (60 - targetScore) / 2.0; // score = 60 - (knee-115)*2 + SquatDepthAnalysisDto result = calculator.calculate(squatSession, List.of(frame(1, knee))); + return result.getDepthGrade(); + } + + // ── 세션 평균 ─────────────────────────────────────────────────────── + + @Test + @DisplayName("세션 점수는 회차별 점수의 평균(반올림)") + void sessionScore_isAverageOfRepScores() { + // rep1: knee=90 -> 100점, rep2: knee=115 -> 60점 => 평균 80 + SquatDepthAnalysisDto result = calculator.calculate( + squatSession, List.of(frame(1, 90.0), frame(2, 115.0))); + assertThat(result.getDepthScore()).isEqualTo(80); + } + + // ── 회차별 코멘트 우선순위 ─────────────────────────────────────────── + + @Test + @DisplayName("코멘트 ①: 앞 회차 좋고 바로 다음 회차가 크게 떨어지면 그 두 회차를 지목한다") + void narrative_adjacentDrop_mentionsBothReps() { + // rep1: knee=90(100점) -> rep2: knee=118(54점, 낙차 46) -> 트리거 + SquatDepthAnalysisDto result = calculator.calculate( + squatSession, List.of(frame(1, 90.0), frame(2, 118.0))); + + assertThat(result.getNarrative()).hasSize(1); + assertThat(result.getNarrative().get(0)).contains("1회차").contains("2회차"); + } + + @Test + @DisplayName("코멘트 ②: HALF 모드에서 풀 스쿼트급으로 깊이 앉은 회차를 지목한다") + void narrative_halfModeTooDeep_mentionsRep() { + Session halfSession = session(1L, SquatDepthMode.HALF); + // rep1,2 는 밴드 중심으로 안정적, rep3 만 무릎 105(풀 스쿼트급)로 깊게 앉음 + SquatDepthAnalysisDto result = calculator.calculate(halfSession, + List.of(frame(1, 127.5), frame(2, 127.5), frame(3, 105.0))); + + assertThat(result.getNarrative()).anySatisfy(line -> assertThat(line).contains("3회차")); + } + + @Test + @DisplayName("코멘트 ⑤: 모든 회차가 고르게 양호하면 회차 언급 없는 한 줄로 폴백한다") + void narrative_allGood_fallsBackToSingleLine() { + SquatDepthAnalysisDto result = calculator.calculate( + squatSession, List.of(frame(1, 95.0), frame(2, 92.0), frame(3, 90.0))); + + assertThat(result.getNarrative()).hasSize(1); + assertThat(result.getNarrative().get(0)).contains("3회"); + } + + @Test + @DisplayName("코멘트는 최대 4문장") + void narrative_cappedAtFour() { + // 편차가 크게 나도록 회차마다 깊이를 들쭉날쭉하게 구성 — 여러 트리거가 동시에 걸려도 4개 이하. + SquatDepthAnalysisDto result = calculator.calculate(squatSession, List.of( + frame(1, 90.0), frame(2, 118.0), frame(3, 92.0), frame(4, 119.0), frame(5, 91.0))); + + assertThat(result.getNarrative()).hasSizeLessThanOrEqualTo(4); + } +} diff --git a/backend/src/test/java/com/shadowfit/service/report/SquatTrunkLeanAnalysisCalculatorTest.java b/backend/src/test/java/com/shadowfit/service/report/SquatTrunkLeanAnalysisCalculatorTest.java new file mode 100644 index 00000000..b090bced --- /dev/null +++ b/backend/src/test/java/com/shadowfit/service/report/SquatTrunkLeanAnalysisCalculatorTest.java @@ -0,0 +1,191 @@ +package com.shadowfit.service.report; + +import com.shadowfit.dto.report.PoseFrameProjection; +import com.shadowfit.dto.report.detailreport.TrunkLeanAnalysisDto; +import com.shadowfit.model.exercise.Category; +import com.shadowfit.model.exercise.Exercise; +import com.shadowfit.model.exercise.Session; +import com.shadowfit.model.exercise.SquatDepthMode; +import com.shadowfit.model.exercise.Status; +import org.junit.jupiter.api.BeforeEach; +import org.junit.jupiter.api.DisplayName; +import org.junit.jupiter.api.Test; + +import java.math.BigDecimal; +import java.time.LocalDateTime; +import java.util.List; + +import static org.assertj.core.api.Assertions.assertThat; + +/** + * SquatTrunkLeanAnalysisCalculator 단위 테스트 (2026-09-28). + * + *

회귀 대상은 SquatDepthAnalysisCalculatorTest와 같은 세 가지 — ① 채점 공식의 경계값, + * ② 등급 5단계 경계, ③ 코멘트 우선순위 — 에 더해, rep 점수가 "최솟값"이 아니라 "그 rep에 + * 속한 프레임들의 평균"임을 고정하는 축 하나가 추가된다(깊이 계산기와의 핵심 차이). + */ +@DisplayName("SquatTrunkLeanAnalysisCalculator 테스트") +class SquatTrunkLeanAnalysisCalculatorTest { + + private SquatTrunkLeanAnalysisCalculator calculator; + private Session squatSession; + private long nextPoseDataId; + + @BeforeEach + void setUp() { + calculator = new SquatTrunkLeanAnalysisCalculator(); + nextPoseDataId = 1L; + squatSession = session(1L); + } + + private Session session(long exerciseId) { + Category category = Category.builder().id(1L).name("LOWER").build(); + Exercise exercise = Exercise.builder() + .id(exerciseId).name(exerciseId == 1L ? "스쿼트" : "전방 런지").category(category) + .expectedDurationMinutes(15) + .syncThresholdBeginner(new BigDecimal("60.00")).syncThresholdAdvanced(new BigDecimal("85.00")) + .build(); + return Session.builder() + .id(1L).exercise(exercise).startTime(LocalDateTime.now()) + .status(Status.COMPLETED).squatDepthMode(SquatDepthMode.FULL) + .build(); + } + + private PoseFrameProjection frame(int repNumber, double torsoTiltDeg) { + return new PoseFrameProjection(nextPoseDataId++, (double) repNumber, 80.0, repNumber, 90.0, null, torsoTiltDeg, null); + } + + // ── 가드 ──────────────────────────────────────────────────────────── + + @Test + @DisplayName("스쿼트가 아니면(exercise_id != 1) null") + void nonSquatExercise_returnsNull() { + Session lungeSession = session(2L); + assertThat(calculator.calculate(lungeSession, List.of(frame(1, 10.0)))).isNull(); + } + + @Test + @DisplayName("프레임이 없으면 null") + void emptyFrames_returnsNull() { + assertThat(calculator.calculate(squatSession, List.of())).isNull(); + } + + @Test + @DisplayName("유효한 체간 기울기(non-null) 데이터가 있는 rep이 하나도 없으면 null") + void noValidTilt_returnsNull() { + List frames = List.of( + new PoseFrameProjection(1L, 1.0, 80.0, 1, 90.0, null, null, null)); + + assertThat(calculator.calculate(squatSession, frames)).isNull(); + } + + // ── 채점 경계값 ──────────────────────────────────────────────────── + + @Test + @DisplayName("체간 기울기 35도 이하는 만점(정상 스쿼트 실측 약 30도)") + void atOrBelowNaturalLimit_scoresMax() { + TrunkLeanAnalysisDto result = calculator.calculate(squatSession, List.of(frame(1, 30.0))); + assertThat(result.getRepTrunkLeans().get(0).getTiltScore()).isEqualTo(100); + } + + @Test + @DisplayName("체간 기울기 45도(명백한 과도 경계)는 60점") + void atExcessiveThreshold_scores60() { + TrunkLeanAnalysisDto result = calculator.calculate(squatSession, List.of(frame(1, 45.0))); + assertThat(result.getRepTrunkLeans().get(0).getTiltScore()).isEqualTo(60); + } + + @Test + @DisplayName("체간 기울기 40도(35~45 중간)는 80점") + void atMidpoint_scores80() { + TrunkLeanAnalysisDto result = calculator.calculate(squatSession, List.of(frame(1, 40.0))); + assertThat(result.getRepTrunkLeans().get(0).getTiltScore()).isEqualTo(80); + } + + @Test + @DisplayName("rep 점수는 그 rep에 속한 프레임들의 체간 기울기 '평균'이다 — 최솟값이 아니다") + void repScore_isAverageOfFramesInRep_notMinimum() { + // 같은 rep 안에 20도와 50도 프레임이 섞이면 평균 35도로 채점돼야 한다(만점 경계). + List frames = List.of( + new PoseFrameProjection(1L, 1.0, 80.0, 1, 90.0, null, 20.0, null), + new PoseFrameProjection(2L, 1.0, 80.0, 1, 90.0, null, 50.0, null)); + + TrunkLeanAnalysisDto result = calculator.calculate(squatSession, frames); + + assertThat(result.getRepTrunkLeans().get(0).getAvgTiltDeg()).isEqualTo(35.0); + assertThat(result.getRepTrunkLeans().get(0).getTiltScore()).isEqualTo(100); + } + + // ── 등급 5단계 ────────────────────────────────────────────────────── + + @Test + @DisplayName("등급: 세션 평균 점수에 따라 EXCELLENT~POOR 5단계") + void grade_fiveTiers() { + assertThat(gradeFor(95)).isEqualTo("EXCELLENT"); + assertThat(gradeFor(80)).isEqualTo("GOOD"); + assertThat(gradeFor(65)).isEqualTo("FAIR"); + assertThat(gradeFor(45)).isEqualTo("NEEDS_WORK"); + assertThat(gradeFor(20)).isEqualTo("POOR"); + } + + private String gradeFor(int targetScore) { + double tilt = targetScore >= 60 + ? 35 + (100 - targetScore) / 40.0 * 10 + : 45 + (60 - targetScore) / 3.0; + TrunkLeanAnalysisDto result = calculator.calculate(squatSession, List.of(frame(1, tilt))); + return result.getTiltGrade(); + } + + // ── 세션 평균 ─────────────────────────────────────────────────────── + + @Test + @DisplayName("세션 점수는 회차별 점수의 평균(반올림)") + void sessionScore_isAverageOfRepScores() { + // rep1: tilt=30 -> 100점, rep2: tilt=45 -> 60점 => 평균 80 + TrunkLeanAnalysisDto result = calculator.calculate( + squatSession, List.of(frame(1, 30.0), frame(2, 45.0))); + assertThat(result.getTiltScore()).isEqualTo(80); + } + + // ── 회차별 코멘트 우선순위 ─────────────────────────────────────────── + + @Test + @DisplayName("코멘트 ①: 앞 회차 좋고 바로 다음 회차가 크게 나빠지면 그 두 회차를 지목한다") + void narrative_adjacentDrop_mentionsBothReps() { + // rep1: tilt=30(100점) -> rep2: tilt=55(30점, 낙차 70) -> 트리거 + TrunkLeanAnalysisDto result = calculator.calculate( + squatSession, List.of(frame(1, 30.0), frame(2, 55.0))); + + assertThat(result.getNarrative()).anySatisfy(line -> + assertThat(line).contains("1회차").contains("2회차")); + } + + @Test + @DisplayName("코멘트 ②: 세션 전체 등급이 FAIR 미만이면 전반적 경고 코멘트를 낸다") + void narrative_lowOverallGrade_addsGeneralComment() { + TrunkLeanAnalysisDto result = calculator.calculate( + squatSession, List.of(frame(1, 60.0), frame(2, 60.0), frame(3, 60.0))); + + assertThat(result.getTiltScore()).isLessThan(60); + assertThat(result.getNarrative()).anySatisfy(line -> assertThat(line).contains("전반적으로")); + } + + @Test + @DisplayName("코멘트 ③: 모든 회차가 고르게 양호하면 회차 언급 없는 한 줄로 폴백한다") + void narrative_allGood_fallsBackToSingleLine() { + TrunkLeanAnalysisDto result = calculator.calculate( + squatSession, List.of(frame(1, 30.0), frame(2, 32.0), frame(3, 28.0))); + + assertThat(result.getNarrative()).hasSize(1); + assertThat(result.getNarrative().get(0)).contains("3회"); + } + + @Test + @DisplayName("코멘트는 최대 4문장") + void narrative_cappedAtFour() { + TrunkLeanAnalysisDto result = calculator.calculate(squatSession, List.of( + frame(1, 30.0), frame(2, 55.0), frame(3, 32.0), frame(4, 56.0), frame(5, 60.0))); + + assertThat(result.getNarrative()).hasSizeLessThanOrEqualTo(4); + } +} diff --git a/demo-up.bat b/demo-up.bat new file mode 100644 index 00000000..a0e7b0b4 --- /dev/null +++ b/demo-up.bat @@ -0,0 +1,17 @@ +@echo off +REM 시연용 원클릭 기동 — Docker Desktop 이 켜져 있어야 한다. +REM 1) 격리 스택(mysql + backend:18080 + ai:18000) 기동 2) 프론트(Expo) 기동 +REM 브라우저 시연: http://localhost:8081 / 폰 시연: Expo Go 로 터미널 QR 스캔 +cd /d "%~dp0" +docker info >nul 2>&1 +if errorlevel 1 ( + echo [!] Docker Desktop 이 꺼져 있습니다. 먼저 Docker Desktop 을 켜고 다시 실행하세요. + pause + exit /b 1 +) +docker compose -p shadowfit-iso -f docker-compose.yml -f docker-compose.iso.yml up -d mysql shadowfit-backend shadowfit-ai ai-nginx +echo. +echo 백엔드가 뜰 때까지 약 30초 걸립니다. http://localhost:18080/swagger-ui/index.html 이 열리면 준비 완료. +echo. +cd frontend +call npx expo start diff --git a/docker-compose.iso.yml b/docker-compose.iso.yml index 412b5410..f5104c47 100644 --- a/docker-compose.iso.yml +++ b/docker-compose.iso.yml @@ -2,9 +2,8 @@ # 따로 띄운다. 사용법: # docker compose -p shadowfit-iso -f docker-compose.yml -f docker-compose.iso.yml up -d mysql shadowfit-backend # -# AI(shadowfit-ai)는 일부러 안 띄운다 — 여기 목적은 swagger·API 확인이고, backend 는 -# mysql 에만 depends_on 이 걸려 있어(#598 조사에서 확인) AI 없이도 기동한다. gRPC 콜이 실제로 -# 필요해지면 그때 shadowfit-ai 도 이 오버라이드에 추가할 것. +# mysql + backend 만 띄우면 swagger·API 확인에 쓸 수 있다. 스쿼트의 +# 앱→AI→Spring 전체 경로를 확인할 때는 shadowfit-ai 와 ai-nginx 도 함께 띄운다. # # 🔴 ports 는 `!override` 로 덮어써야 한다 — compose 는 리스트 필드(ports 등)를 기본적으로 # "병합"이 아니라 "이어붙이기"한다. 그냥 ports: 를 새로 적으면 베이스 파일의 8080/6565/ @@ -31,3 +30,11 @@ services: - "127.0.0.1:${ISO_ACTUATOR_PORT:-19090}:9090" environment: DB_HOST: mysql + + shadowfit-ai: + container_name: shadowfit-iso-ai + + ai-nginx: + container_name: shadowfit-iso-ai-nginx + ports: !override + - "${ISO_AI_PORT:-18000}:8000" diff --git a/docs/architecture/ai-backend-changelog.md b/docs/architecture/ai-backend-changelog.md index 7cc5565e..c04a1d0b 100644 --- a/docs/architecture/ai-backend-changelog.md +++ b/docs/architecture/ai-backend-changelog.md @@ -1,6 +1,18 @@ # Spring ↔ FastAPI 결합 변경 이력 -마지막 업데이트: **2026-08-08** (이전 2026-05-23 — 그 사이 2.5개월치를 §4 로 채웠다) +## 2026-09-17 — 스쿼트 횟수 판정 통일 (작업 브랜치) + +AI의 실시간·영상 분석·기준 영상 분할이 같은 완료 이벤트를 사용한다. 스쿼트 반복은 +각도와 초 단위 상태로 판정하며 기존 gRPC rep 콜백·proto는 유지한다. 업로드 영상의 +검증되지 않은 `quality_score`는 `null`이다. [근거와 한계](../decisions/squat-repetition-counting.md). + +## 2026-09-17 — 전방 런지 추가 (작업 브랜치) + +종목 2의 횟수 분석·기준 좌표 없는 시작/재부착을 추가했다. 기존 protobuf를 유지하며 +Spring은 V22의 `repetition_only` 플래그로 런지 점수를 NULL 처리한다. HTTP에는 단계·좌우 횟수를 +추가하고, 점수 미측정을 명시한다. [근거와 한계](../decisions/lunge-repetition-counting.md). + +마지막 업데이트: **2026-09-17** (스쿼트 판정 통일·전방 런지 작업분 추가) 범위: `ai-server/`(FastAPI)와 `backend/`(Spring Boot) 사이의 결합 방식·통신 프로토콜·인증·데이터 흐름 변경에 직접 영향을 준 커밋들. UI/문서/단순 버그 수정은 제외. > ⚠️ **범위 주의**: *"결합에 영향을 준"* 은 **파일 위치가 아니라 계약**으로 판정한다. 아웃박스(`cb26e4a`·`993dfa1`)는 **Spring 파일만** 건드렸지만 `StopAnalysis` 의 전달 의미론을 바꿨으므로 §4 에 들어간다 — `proto`·`ai-server` 경로만 훑으면 놓친다. 실제로 이 문서가 2.5개월 밀린 동안 **가장 큰 결합 변경이 그 커밋들이었다.** diff --git a/docs/architecture/ai-backend-commit-details.md b/docs/architecture/ai-backend-commit-details.md index e38dcb9c..0349010c 100644 --- a/docs/architecture/ai-backend-commit-details.md +++ b/docs/architecture/ai-backend-commit-details.md @@ -1,6 +1,24 @@ # Spring ↔ FastAPI 결합 — 커밋별 구체 변경 -마지막 업데이트: **2026-08-08** (이전 2026-05-23 — 그룹 9 와 부록 3개를 갱신했다) +## 2026-09-17 작업분 — 스쿼트 횟수 판정 통일 (아직 미커밋) + +- **proto·Spring·DB**: 변경 없음. 기존 완료 이벤트와 점수 저장 계약 유지. +- **AI**: `SquatCounter`를 실시간·업로드 영상에 공용 적용. 기준 영상도 동일한 완료 횟수로 분할. + HTTP는 촬영 시각·화면 비율을 전달하고 추적 소실 시 진행 중인 횟수를 초기화한다. +- **영상 응답**: 검증되지 않은 `quality_score`는 `null`로 반환. 기존 실시간 DTW 점수는 유지하되 연구 검증 점수로 해석하지 않는다. +- **근거·한계**: [스쿼트 반복 판정 문서](../decisions/squat-repetition-counting.md). + +## 2026-09-17 작업분 — 전방 런지 (아직 미커밋) + +- **proto**: 스키마 변경 없음. 런지 점수의 숫자 기본값은 측정값이 아니다. +- **AI**: 종목 2 등록, 발 이동·양 무릎 단계·원위치 복귀 판정, 시간 기반 필터, + 기준 좌표 없는 재부착, HTTP 좌우 횟수와 단계 응답. +- **Spring**: 횟수 전용 종목은 기준 URL 없이 시작. 포즈/세션 점수는 NULL 저장. + 상세 리포트 `scoreAvailable`, 트레이너 SSE nullable 점수. +- **DB**: V22에서 런지 활성화·`repetition_only` 열·포즈 점수 NULL 허용. +- **검증·근거**: [전방 런지 구현 문서](../decisions/lunge-repetition-counting.md). + +마지막 업데이트: **2026-09-17** (스쿼트 판정 통일·전방 런지 작업분 추가) 범위: 각 커밋이 Spring(`backend/`)·FastAPI(`ai-server/`)·`proto`·`docker-compose.yml` 어디를 어떻게 바꿨는지 기능 단위로 정리. > 🔴 **이 문서의 네 칸 분류에는 함정이 있다** (2026-08-08 추가). *"proto 는 항상 결합 인터페이스의 변경이라 가장 위"* 라는 읽기 규칙이 **proto 가 안 바뀌면 결합 변경이 아니다** 로 오해되기 쉽다. 실제로 이 프로젝트 최대의 결합 변경(아웃박스, `993dfa1`)은 **proto 0줄·AI 0줄**이면서 `StopAnalysis` 의 전달 의미론을 바꿨다. **계약은 시그니처만이 아니다** — 전달 보장, 멱등 요구, proto 밖 메타데이터(`x-request-id`)도 계약이다. diff --git a/docs/architecture/ai-backend-integration.md b/docs/architecture/ai-backend-integration.md index c85a5854..21515b26 100644 --- a/docs/architecture/ai-backend-integration.md +++ b/docs/architecture/ai-backend-integration.md @@ -1,6 +1,23 @@ # AI ↔ Backend 결합 현황 -마지막 업데이트: **2026-09-06** (§3-2 RPC별 stub 종류 정정 추가 — 이전 대규모 반영은 2026-08-08, §0 참조) +## 2026-09-17 추가: 스쿼트 반복 판정 통일 + +스쿼트(`exercise_id=1`)는 논문에서 제시한 무릎·고관절 단계와 초 단위 확인을 결합한 +`SquatCounter`로 실시간·업로드 영상 횟수를 함께 판단한다. 완료 시 기존 rep 배치와 +종료 콜백이 실행되며 nonce·proto·Spring 저장 구조는 유지된다. 업로드 영상 +`quality_score`는 `null`이고 기존 실시간 `sync_rate`는 참고용 DTW 유사도다. +[근거·검증 한계](../decisions/squat-repetition-counting.md). + +## 2026-09-17 추가: 전방 런지 횟수 측정 + +`exercise_id=2`는 전방 런지 분석기로 연결한다. 기준 좌표 없이 시작·재부착할 수 있으며, +기존 rep 배치와 종료 콜백으로 총 횟수를 저장한다. nonce·워커·proto 필드는 유지한다. +런지 HTTP 점수는 null이고, gRPC 기본 숫자 0은 Spring의 `repetition_only` 종목 판정으로 +DB NULL로 변환한다(V22). SSE 점수는 nullable, 상세 리포트는 `scoreAvailable`로 구분한다. +좌우 횟수는 살아 있는 AI 세션에서 유지되며 프로세스 재시작 이전 기록은 좌우 미상으로 표시한다. +근거·단계·배포 순서는 [전방 런지 구현 문서](../decisions/lunge-repetition-counting.md)를 참조한다. + +마지막 업데이트: **2026-09-17** (스쿼트 판정 통일·전방 런지 추가. 이전 대규모 반영은 §0 참조) 범위: `ai-server/` (Python, FastAPI + gRPC) ↔ `backend/` (Spring Boot, Java/Kotlin) 목적: 현재 어떻게 결합돼 있는지 사실만 정리한 스냅샷. 트레이드오프·대안 비교는 [`docs/decisions/ai-backend-coupling.md`](../decisions/ai-backend-coupling.md) 참조. diff --git a/docs/architecture/ai-backend-monthly-log.md b/docs/architecture/ai-backend-monthly-log.md index 610fe116..5bcd25bd 100644 --- a/docs/architecture/ai-backend-monthly-log.md +++ b/docs/architecture/ai-backend-monthly-log.md @@ -1,6 +1,21 @@ # Spring ↔ FastAPI 결합 — 월별 작업 로그 -마지막 업데이트: **2026-08-08** (이전 2026-05-24 — 그 사이 2026-06·07·08 을 뒤늦게 채웠다) +## 2026-09-17 — 스쿼트 반복 판정 통일 + +- **Spring 측**: 변경 없음. 기존 rep 이벤트와 세션 집계 계약 사용. +- **FastAPI 측**: 실시간·업로드 영상 공통 스쿼트 상태 판정, 기준 영상 분할 연동, + 촬영 시각·화면 비율 반영, 검증되지 않은 영상 품질 점수 제거. +- **공통**: proto 변경 없음. [논문 적용 범위와 실제 영상 평가 한계](../decisions/squat-repetition-counting.md). + +## 2026-09-17 — 전방 런지 구현 + +- **Spring 측**: 횟수 전용 종목 지원, 기준 URL 의존 제거, 미측정 점수 NULL 저장·집계 제외. +- **FastAPI 측**: 전방 런지 상태 판정, 좌우 횟수, 가림·끊김 시 미완성 동작 초기화, + 기준 좌표 없이 시작·복구, 기존 인증과 워커 라우팅 유지. +- **공통**: V22가 런지 종목을 활성화한다. AI를 먼저 배포해야 한다. protobuf 변경 없음. + [논문 근거·평가 방법·좌우 복구 한계](../decisions/lunge-repetition-counting.md). + +마지막 업데이트: **2026-09-17** (스쿼트 판정 통일·전방 런지 작업분 추가) > ⚠️ **06~08 절의 수록 기준은 앞 절들과 다르다.** 03~05 는 거의 전 커밋을 담았지만, 이 3개월은 커밋이 332건이라 **결합 계약(RPC·메시지·인증·메타데이터)이나 전달 의미론에 영향을 준 것만** 담았다. 나머지(DB·부하테스트·관리자 API·CI 등 Spring 단독 작업)는 [`../tasks/28-remaining-work-plan.md`](../tasks/28-remaining-work-plan.md)·[`../handoff/`](../handoff/) 와 git log 를 볼 것. > diff --git a/docs/decisions/lunge-repetition-counting.md b/docs/decisions/lunge-repetition-counting.md new file mode 100644 index 00000000..743006e6 --- /dev/null +++ b/docs/decisions/lunge-repetition-counting.md @@ -0,0 +1,240 @@ +# 전방 런지 반복 횟수 측정 + +작성: 2026-09-17. 사용자 요청에 따라 전방 런지를 구현했다. +2026-09-22 재설계: 아래 "2026-09-22 재설계" 절 참고 — 판정 축 자체를 발 이동 거리에서 +무릎 각도 사이클로 바꿨고, 지원 범위를 **완전 측면 촬영**으로 좁혔다. + +범위는 **완전 측면에서 촬영한 런지의 횟수**다. 학습 모델 신규 훈련, 자세 점수, +부상 위험 판정은 포함하지 않는다. 전방/후방/워킹 런지는 총 횟수 판정에서는 더 이상 +구분하지 않지만(아래 참고), **좌우(왼발/오른발) 구분은 완전 측면 촬영에서만 신뢰할 수 +있다.** + +## 1. 참고 근거와 적용 범위 + +| 근거 | 적용한 내용 | 그대로 재현하지 않은 부분 | +|---|---|---| +| Sousa et al., *A Movement Description Language for Functional Training Exercise Analysis*, JFMK 11(2):162, 2026, [DOI](https://doi.org/10.3390/jfmk11020162), §2 운동별 상태 설명·Figure 3 | 무릎 100° 이하를 바닥 경계로 사용 | 논문의 MDL 파서나 전체 시스템을 구현한 것은 아니다. 각도는 영상 기반 대리 지표이며 조절 가능한 기본값이다. | +| [MediaPipe Pose Classification — Repetition Counting](https://chuoling.github.io/mediapipe/solutions/pose_classification.html#repetition-counting) | 진입·복귀 경계를 다르게 두고 평활화를 사용해 경계 부근 중복 카운트를 줄이는 원칙 | kNN 자세 분류기의 확률을 사용하지 않는다. 좌표에서 계산한 무릎 각도에 시간 기반 EMA를 적용한다. | +| Hsu et al., *Viewpoint-invariant exercise repetition counting*, [DOI](https://doi.org/10.1007/s13755-023-00258-3) | 촬영 방향을 달리하고 수동 정답과 횟수를 비교하는 평가의 필요성 | 논문의 주기·스펙트럼 기반 알고리즘이나 시점 불변성을 구현·보장하지 않는다 — 오히려 2026-09-22 검증으로 시점 불변이 아니라는 것을 확인하고 완전 측면으로 범위를 좁혔다. | + +논문에 보고된 정확도는 ShadowFit의 정확도가 아니다. 2026-09-22 이전에는 합성 좌표와 +서비스 계약 테스트로만 검증했고, 실제 사람의 촬영본 정확도는 측정하지 않았다. 아래 +"2026-09-22 재설계" 절이 그 실촬영 검증과 그 결과로 바뀐 설계를 기록한다. + +## 2. 무엇을 1회로 세는가 (2026-09-22 이후) + +1. 두 발이 앞뒤로 벌어진 스탠스(런지 자세)가 보이면, 별도의 "준비 자세 확인" 없이 + 바로 인식한다 — 스트림이 이미 런지 바닥 자세로 시작해도 그 뒤로 다시 펴는 동작을 + 1회로 센다. +2. 두 무릎 중 더 굽은 쪽이 100° 이하까지 굽혀지면 "바닥"이다. +3. 그 뒤 두 무릎 중 어느 쪽이든 130° 이상으로 다시 펴지면(완전히 편 160°까지는 + 요구하지 않는다) 1회로 확정한다. +4. 어느 다리로 기록할지(왼발/오른발)는 **바닥 판정과 분리된 별도 신호**(발목-골반중심 + 거리)로 정한다 — 완전 측면 촬영에서만 신뢰할 수 있다(§3·§6 참고). + +```mermaid +stateDiagram-v2 + [*] --> ready + ready --> returning: 스탠스가 벌어진 채 한쪽 무릎이 100도 이하로 굽음(바닥) + returning --> ready: 어느 무릎이든 130도 이상으로 폄 + 0.6초 이상 경과 / 1회 + ready --> ready: 스탠스가 안 벌어짐(스쿼트 등) / 안 셈 +``` + +가림·영상 끊김·저가시성이면 진행 중 판정을 버리고 다시 준비한다. 일시 중단 뒤 +미완성 동작을 이어서 세어 가짜 1회를 만들지 않기 위해서다. + +### 2026-09-17 초판과 달라진 점 + +초판은 "두 발 모으고 서 있다가 한쪽 발이 정해진 거리(어깨-골반 길이의 0.65배)만큼 +앞으로 이동"하는 것으로 1회를 판정했다(발 이동 거리 기준, `forward_step` 임계값). +아래 2026-09-22 검증에서 이 전제 자체가 실촬영과 안 맞는 것으로 드러나 두 단계에 +걸쳐 재설계했다. + +## 3. 2026-09-22 재설계 — 실촬영 검증과 그 결과 + +### 3-1. 1차 검증: 발 이동 거리 판정이 실촬영에서 전부 0회 + +사용자가 실제 촬영한 4개 영상(`samples/validation/lunge_normal_01.mp4`· +`lunge_sallow_01.mp4`·`lunge_walking_01.mp4`·`lunge_45degree_01.mp4`)을 초판 +코드로 재생한 결과, **calibration(두 발 모으고 서 있기) 단계조차 통과한 프레임이 +0개**였다. 원인은 두 가지가 겹쳤다: + +- `initial_stance`(두 발 간격 허용치)가 실제 준비 자세(어깨너비 정도)보다 훨씬 + 빡빡했다 — 실측 발 간격이 허용치의 1.5~2.5배였다. +- calibration의 발 기준점(anchor) 흔들림 판정이 유예 없이 즉시 리셋됐다 — 사람이 + 가만히 서 있어도 체중을 살짝 옮기거나 발끝 방향이 한 프레임 흔들리면 0.4초짜리 + 안정 확인이 바로 처음부터 다시 시작됐다. + +먼저 이 두 문제(스쿼트의 `ankle_outlier_grace_sec`와 같은 유예 장치 추가, 발 간격 +허용치를 0.75로 완화)만 고쳤지만, calibration을 통과해도 **반복 판정 자체가 여전히 +0회**였다. 무릎 각도·발목 이동 거리를 직접 추적해보니, 4개 영상 전부 "이미 벌어진 +스탠스에서 제자리로 무릎만 굽혔다 폈다" 하는 동작이었다 — 발이 거의 안 움직여 +`forward_step`(0.65) 문턱을 넘지 못했다. 즉 **발 이동 거리로 1회를 정의하는 것 +자체가 실제 촬영된 동작과 안 맞았다.** + +### 3-2. 판정 축 변경: 무릎 각도 사이클 (스쿼트와 같은 방식) + +사용자 확인 후, 발 이동 거리 대신 스쿼트(`squat_counter.py`)와 같은 **무릎 각도 +사이클**로 바꿨다. 스탠스가 벌어져 있고(두 발목 거리/몸통길이 ≥ 0.55) 한쪽 무릎이 +100° 이하까지 굽혀졌다 펴지면 1회다. 스쿼트(양발 나란히)와는 이 스탠스 벌어짐 +정도로만 구분한다. + +트레이드오프: 발 이동 **방향**을 더 이상 추적하지 않으므로 전방/후방/워킹 런지를 +구분하지 못한다 — 사용자가 명시적으로 "워킹 런지까지 다 세자"를 선택해 받아들인 +트레이드오프다. + +### 3-3. calibration 단계 제거 + +무릎 각도 사이클로 바꾼 뒤에도 여전히 심하게 과소 카운트됐다. 원인: "완전히 편 +자세(160°)로 서야 다음 반복을 받을 준비가 된다"는 calibration 전제가, 실촬영에서 +반복 사이 최고점이 130~170°로 들쭉날쭉하고 자주 160°를 못 넘는 바람에 **여러 반복을 +하나로 뭉개버렸다** — `lunge_normal_01`에서 8초 동안 이어진 펄스 4~5개가 1회로 +합쳐진 사례를 확인했다. + +사용자가 "런지가 보이면 바로 세자"를 선택해, calibration(준비 자세 대기) 단계를 +아예 없앴다. 스트림이 이미 런지 바닥 자세로 시작해도 그 뒤로 다시 펴면 1회로 센다. +"바닥→다시 폄" 판정 기준도 완전한 직립(160°) 대신 `recovered_angle`(130°)로 낮췄다 +— 반복 사이 최고점이 130° 밑으로는 거의 안 내려간다는 실촬영 관찰에 근거한 구현값 +이다. + +### 3-4. 표본 간격보다 짧은 확인창 — 스쿼트에서 이미 겪은 버그가 그대로 있었다 + +calibration을 없앤 뒤 재검증하니 `lunge_sallow_01`이 여전히 0회였다. 원인은 +`squat_counter.py`의 standing-confirm 버그와 정확히 같은 종류였다: 바닥 확인창 +(`bottom_confirm_sec`=0.12초)이 3fps 표본 간격(≈0.33초)보다 짧은데, "표본 2개로 +확인"을 요구해서 **표본 1개짜리 진짜 바닥 접촉이 매번 다음 표본에서 리셋**됐다. +스쿼트와 같은 보정(표본 간격이 이미 확인창보다 크면 그 표본 하나가 최대 해상도의 +증거로 충분하다)을 바닥 확인·회복 확인 양쪽에 적용했다. + +### 3-5. 바닥 검출과 좌우 라벨을 분리 + +`lunge_walking_01`(왼발·오른발을 번갈아 진행)에서, "발목이 골반 중심에서 더 멀리 +떨어진 다리"를 곧바로 "바닥 판정에 쓸 다리"로 묶었더니 일부 프레임에서 실제로 더 +깊이 굽은 반대쪽 다리를 놓쳤다 — 몸 전체가 전진하는 워킹 런지 특성상 뒷다리가 아직 +이전 자세에서 덜 펴진 채로 남아 있는 순간이 있었다. **"바닥에 닿았는가"는 두 무릎 중 +더 굽은 쪽으로 판단**하고, **좌우 라벨은 별도로** 발목-골반중심 거리로 정하도록 +분리했다. + +### 3-6. 좌우 라벨은 완전 측면에서만 신뢰할 수 있다 → 지원 범위를 좁힘 + +3-5의 분리 이후 4개 영상 전부 총 횟수는 합리적인 수준이 됐다(아래 §3-7 표). 그런데 +`lunge_45degree_01`(45도 각도로 촬영)만 좌우 라벨이 크게 틀렸다 — 총 10회 중 9회를 +"왼쪽"으로 잘못 붙였는데, 실제로는 후반 5회가 전부 오른쪽 다리 동작이었다(무릎 각도로 +직접 확인). 완전 측면 3개(정상·얕음·워킹)는 좌우 라벨이 실제와 맞았다. + +원인은 발목-골반중심 거리 신호 자체다 — 완전 측면(90°)에서는 "발목이 골반 중심에서 +더 멀리 떨어진 쪽"이 곧 "앞다리"이지만, 45도처럼 비스듬한 각도에서는 원근 때문에 이 +매핑이 깨진다. 이 신호를 45도에서도 통하게 보정하는 대신, **사용자 확인 후 런지의 +지원 카메라 각도를 완전 측면으로 한정**했다 — 45도·정면 등 비스듬한 촬영은 지원 +범위 밖이며, 총 횟수가 맞더라도 좌우 구분은 보장하지 않는다. 촬영 가이드(§7)에도 +반영했다. + +### 3-7. 최종 검증 결과 (2026-09-22) + +`ai-server/scripts/evaluate_lunge.py`로 3fps에서 재생한 결과: + +| 영상 | 촬영 각도 | 총 횟수 | 좌/우 | 비고 | +|---|---|---:|---|---| +| `lunge_normal_01.mp4` | 완전 측면 | 10 | 5/5 | | +| `lunge_sallow_01.mp4` | 완전 측면 | 5 | 2/3 | "얕은 런지"라는 파일명과 달리 실제로는 바닥(100°) 문턱을 여러 차례 넘었다 — 사람이 직접 센 정답과 아직 대조하지 않음 | +| `lunge_walking_01.mp4` | 완전 측면 | 10 | 5/5 | 왼발·오른발을 번갈아 진행했다는 촬영자 설명과 좌/우 분포가 일치 | +| `lunge_45degree_01.mp4` | 45도 | 10 | 9/1 (틀림, 실제로는 약 5/5 추정) | §3-6에 따라 **지원 범위 밖** — 총 횟수 참고용, 좌우는 신뢰 불가 | + +⚠️ **위 총 횟수도 사람이 프레임 단위로 정밀하게 센 정답과 대조된 것은 아직 아니다** — +스쿼트 2026-09-21 검증(`docs/verification/`)과 같은 수준의 사람 판정 대조가 필요하다. +현재 결과는 "알고리즘이 합리적으로 작동하기 시작했다"는 근거이지 "실사용 정확도"의 +근거가 아니다. + +자동 테스트(`tests/test_lunge_analyzer.py`·`test_lunge_integration.py`)는 이번 +재설계에 맞춰 전부 갱신했다. 특히 예전에는 "세면 안 됨"으로 잠가뒀던 워킹·후방 +런지 스타일(발이 원위치로 안 돌아옴)은 이제 "세야 함"으로 기대치를 바꿨다 +(`test_stance_based_cycles_now_count`) — 3-2의 트레이드오프를 그대로 테스트로 +고정한 것이다. + +## 4. 좌표·설정 + +`ai-server/app/core/lunge_analyzer.py`의 `LungeThresholds`가 설정의 출처다. +좌표는 `(x × 영상 너비/높이, y)`로 변환해 세로·가로 영상에서 같은 이미지 평면 각도를 +얻는다. MediaPipe 정규화 `z`는 섞지 않는다. 스탠스 벌어짐(`stagger_min`)은 두 발목 +사이 거리를 준비 자세의 어깨 중심↔골반 중심 거리로 나눠 정규화한다. + +| 설정 | 기본값 | 근거 | +|---|---:|---| +| 바닥 | 100° | MDL 논문 초기값 채택 | +| 다시 폄(회복) | 130° | 2026-09-22 실촬영 관찰(반복 사이 최고점이 대체로 130° 이상) — 논문 검증치 아님 | +| 가시성 | 모든 필수 관절 0.6 이상 | 구현 기본값 | +| 바닥 확인 | 0.12초 | 구현 기본값. 표본 간격이 이 값보다 크면 표본 1개로 대체(§3-4) | +| 회복 확인 | 0.12초 | 위와 동일 | +| 최소 동작 시간 | 0.6초 | 구현 기본값 | +| 영상 공백 | 1.2초 초과 시 초기화 | 구현 기본값 | +| EMA 시간 상수 | 0.06초 | 구현 기본값 | +| 스탠스 벌어짐(런지 vs 스쿼트 구분) | 0.55(몸통 길이 배수) | 2026-09-22 실촬영 4개: 무릎이 굽혀진 순간 비율 0.74~1.70, 가만히 선 자세는 0~0.45. 스쿼트 실촬영으로는 아직 재검증 안 함(§3-6 유사 위험 — 발이 나란해도 몸통이 기울면 이 비율이 올라갈 수 있음) | + +각도 외 수치는 논문에서 검증된 값으로 주장하지 않는다. 프레임 개수가 아닌 서버의 +단조 증가 시계로 시간을 잰다. 라이브 경로의 기존 300ms 유입 제한은 유지한다. + +## 5. 서비스 연결 + +- AI 등록: `exercise_id=2 → lunge`. 플랭크 등 미지원 운동은 계속 거절한다. +- `StartAnalysis`, `ReattachAnalysis`: 런지는 기준 자세 좌표가 없어도 시작·복구한다. +- `/pose`: 총 횟수에 더해 `lunge`에 `phase`, `lead_leg`, `left_reps`, `right_reps`, + `unassigned_reps`, `guidance`, `score_available=false`를 반환한다. `sync_rate=null`. + `phase`는 `"ready"`/`"returning"`만 실제로 나온다 — `"calibrating"`/`"descending"`은 + 스키마 호환을 위해 남아 있는 미사용 값이다(2026-09-22, §3-3). +- 총 횟수는 기존 rep 배치·완료 콜백으로 저장된다. 인증 nonce·워커 라우팅·세션 잠금은 유지한다. +- 런지에는 스쿼트의 BACK_BENT 피드백을 적용하지 않는다. +- protobuf 숫자 필드는 그대로 둔다. 런지 콜백의 `sync_rate=0`은 전송 형식상 기본값이다. + Spring은 `exercises.repetition_only=true` 종목에 대해 **DB에 NULL로 저장**하고 세션 + 점수 통계도 NULL로 둔다. SSE 점수는 nullable, 상세 리포트에는 `scoreAvailable`을 추가했다. +- Flyway V22는 점수 NULL 허용, `repetition_only` 열 추가, 런지 분석 활성화를 수행한다. +- 앱: 스쿼트/전방 런지 선택, 촬영·단계 안내, 좌우 카운터, 종료 요약을 제공한다. + 런지는 기존 예시 데이터 리포트 화면으로 보내지 않는다. 카메라 실패 시 가짜 이미지를 전송하지 않는다. + +**좌우 기록의 현재 한계:** 총 횟수는 DB에서 복원하지만 좌우 분류는 AI 세션 메모리에만 있다. +동일 워커의 살아 있는 세션에 재부착하면 유지된다. AI 프로세스가 재시작되면 기존 총 횟수를 +`unassigned_reps`로 표시하고 새 동작부터 좌우를 구분한다. 기존 총 횟수를 임의로 반씩 나누지 않는다. +**추가로(2026-09-22) 좌우 분류 자체가 완전 측면 촬영에서만 신뢰할 수 있다(§3-6) — 45도 등 +비스듬한 각도에서는 총 횟수는 맞아도 좌우가 뒤섞일 수 있다.** + +## 6. 실행 및 확인 + +배포 순서: **새 AI → 새 백엔드(V22 적용·재시작) → 새 프런트**. +구 AI가 남아 있는 동안 런지 시작을 활성화하지 않는다. 로컬 변경만으로 운영 DB에 적용되지는 않는다. +실행에는 기존 백엔드·AI 연결과 `EXPO_PUBLIC_AI_PUBLIC_TOKEN` 등 정상 설정이 필요하다. + +```powershell +# ai-server 디렉터리, 의존성이 설치된 Python 환경 +$env:DEBUG='false' +python -m pytest tests --ignore=tests/test_camera.py -p no:cacheprovider -q +python scripts/evaluate_lunge.py ./clips/forward-lunge.mp4 --expected-left 5 --expected-right 5 --trace ./lunge-trace.csv +``` + +평가 스크립트는 로컬 고정 FPS 영상을 3fps로 분석하며 총/좌/우 횟수 오차와 설정을 출력한다. +`--sample-fps`로 다른 처리 속도도 비교할 수 있다. 프레임 누락·추론 실패는 CSV에서 확인한다. +동일 분석기를 사용하지만, 카메라 촬영·전송 지연까지 재현하는 통합 성능 측정은 아니다. + +## 7. 촬영 가이드 (2026-09-22) + +**완전 측면(90°)에서만 촬영한다.** 45도 등 비스듬한 각도는 총 횟수는 맞을 수 있어도 +좌우 구분을 보장하지 않는다(§3-6) — 지원 범위 밖으로 취급한다. + +- 카메라를 사람의 진행 방향과 직각(완전 측면)으로 고정한다. 정면·45도는 사용하지 않는다. +- 전신, 특히 양쪽 무릎·발목·발끝이 화면 안에 들어오게 한다. +- 두 발이 앞뒤로 벌어진 자세(런지)가 보이면 바로 인식하므로, 특별한 준비 자세 없이 + 바로 동작을 시작해도 된다. +- 무릎을 완전히 펴지 않고 반복(펄싱)해도 되지만, 반복 사이에 어느 정도(130° 이상)는 + 다시 펴야 한다 — 계속 깊이 굽힌 채로만 있으면 하나의 긴 동작으로 묶일 수 있다. +- 워킹 런지(발이 원위치로 안 돌아오고 계속 전진)도 이제 세어진다. 다만 좌우 구분은 + 완전 측면 촬영에서만 신뢰할 수 있다. + +실제 평가에서는 여러 사람의 좌/우 각 5~10회 촬영본을 확보하고 정상·얕은 동작·워킹· +가림·화면 이탈을 별도로 기록한다. 클립별 수동 총/좌/우 횟수와 비교해 절대 오차(MAE), +정확히 일치한 클립 비율, 좌우 라벨 정확도를 따로 보고한다 — §3-7이 그 대조를 아직 +하지 않은 1차 결과다. + +### 개발 환경 확인 (2026-09-22) + +- AI: 206 tests + 61 subtests 통과 (`test_camera.py` 제외). +- 실촬영 4개(완전 측면 3개 + 45도 1개) 재생 결과는 §3-7 참고. +- 백엔드·프런트·전체 통합 실행은 2026-09-17 이후 재검증하지 않았다 — 이번 재설계는 + AI 판정 로직에 한정된다. diff --git a/docs/decisions/squat-repetition-counting.md b/docs/decisions/squat-repetition-counting.md new file mode 100644 index 00000000..16becaf0 --- /dev/null +++ b/docs/decisions/squat-repetition-counting.md @@ -0,0 +1,83 @@ +# 스쿼트 반복 판정 근거와 검증 범위 + +작성: 2026-09-17. 범위는 스쿼트 **반복 횟수**다. 자세 점수와 부상 위험 예측의 임상적 타당성을 주장하지 않는다. + +## 참고 논문 + +| 자료 | 코드에 반영한 부분 | 구분해야 할 부분 | +|---|---|---| +| Sousa et al., *A Movement Description Language for Functional Training Exercise Analysis*, JFMK 11(2):162 (2026), [DOI](https://doi.org/10.3390/jfmk11020162), Listing 1 | 시작 무릎·고관절 각도 160° 초과, 깊은 자세 무릎 100° 미만·고관절 150° 미만, 다시 서는 한 주기. Listing의 조정 가능한 기본값을 경계값으로 사용 | 본문 설명에는 서기 150° 등 다른 예시값도 있다. 여기서는 명시적인 Listing 1을 택했다. 논문의 MDL 도구 전체를 재현한 것은 아니다. | +| Postlmayr et al., *PersonalPT: One-shot approach for skeletal-based repetitive action counting for physical therapy*, Smart Health 34:100516 (2024), [DOI](https://doi.org/10.1016/j.smhl.2024.100516), [저자 공개본](https://escholarship.org/content/qt68z8p1x8/qt68z8p1x8_noSplash_75dede52134ade45f41ed08a3f784ca1.pdf) | 쉼→활동→쉼 주기와 밀리초 단위 유효 동작 확인이라는 설계 관점. 프레임 개수 대신 실제 경과 시간을 사용 | 논문의 400ms는 **학습된 활동 상태 A의 지속 시간**이다. 우리 코드의 `min_active_sec=0.4`는 하강 시작부터 복귀까지의 시간이며 같은 측정값이 아니다. 논문의 GMM·PCA·개인화 학습·성능 수치는 구현하지 않았다. | + +## 구현된 판정 + +`ai-server/app/core/squat_counter.py`의 `SquatCounter`를 실시간 `StreamingSquatAnalyzer`와 업로드 영상 `analyze_squat_frames`가 함께 사용한다. 이미지 가로세로비를 반영한 2D 좌표로 어깨·고관절·무릎·발목을 계산한다. MediaPipe의 정규화된 `z`를 실제 깊이로 취급하지 않는다. 측면에서 먼쪽 다리가 가려질 수 있어 한쪽의 어깨·고관절·무릎·발목이 모두 추적되면 계산을 이어간다. 양쪽이 보일 때는 기존 좌우 평균을 유지한다. 이 가시성 처리 역시 논문의 성능 검증을 받은 방법은 아니다. + +1. 양쪽이 보이면 좌우 무릎·고관절 각도의 평균, 한쪽만 보이면 해당 다리의 각도로 충분히 선 자세를 확인한 뒤 시작한다. 영상이 앉은 자세에서 시작해도 그것만으로 1회를 만들지 않는다. +2. 같은 각도가 깊이 조건을 만족한 것을 확인한다. 얕은 굽힘은 세지 않는다. 좌우 평균과 한쪽 다리 대체는 논문의 단일 `knee_angle`·`hip_angle` 입력을 2D MediaPipe에 대응한 구현 선택이며, 논문이 이 결합 방식을 검증했다는 뜻은 아니다. +3. 다시 충분히 서면 1회를 추가한다. 이때만 기존 저장·리포트용 완료 이벤트를 낸다. +4. 양쪽 다리 모두 관절이 가려지거나 추적이 끊기면 진행 중인 주기만 버린다. 한쪽만 보이는 프레임에서도 이전부터 계속 추적된 다리가 있어야 하며, 동작 중 추적 대상 다리가 완전히 바뀌면 주기를 버린다. 준비 자세에서 선 채로 발 위치를 조정할 때는 발 기준점을 갱신한다. 하강이 시작된 뒤 발 좌표가 한두 프레임 튀면 그 프레임을 건너뛰고, 0.7초 이상 계속 벗어나면 진행 중인 주기를 취소한다. 완료된 횟수는 유지한다. + +기본 경계는 코드의 `SquatThresholds`에 모았다. 160°/100°/150° 각도는 Sousa의 Listing 1에서 가져왔다. 실제 2D 관절 추정의 잡음을 고려해 **서기 무릎 152° 이상, 바닥 무릎 115° 이하**의 허용 구간을 두고, 바닥 판정에는 **준비 자세 대비 골반 하강이 몸통 길이의 0.25배 이상**인지도 확인한다. 이는 저자들이 검증한 숫자가 아니라 기존 촬영본에 맞춰 정한 구현 값이다. **서기 확인 0.2초, 바닥 확인 0.12초, EMA 0.12초, 추적 공백 1.2초, 가시성 0.55, 발 위치 허용폭**도 3fps 서비스와 잡음에 맞춘 구현 값으로, 논문 검증값으로 표현하지 않는다. 오래 앉아 쉬는 동작을 스쿼트로 세지 않으려고 깊은 자세가 **연속 8초를 넘으면** 주기를 취소한다. 이는 제품 규칙이며, 8초 이상 유지하는 스쿼트는 빠질 수 있다. 각도만으로 의자에 앉기와 긴 홀드 스쿼트를 완전히 구분할 수 없다. + +### 2026-09-21: 서기 확인 지연이 3fps 표본 간격보다 짧아 연속된 두 반복을 하나로 합치던 문제 + +새로 촬영한 6개 영상(`docs/verification/2026-09-21-verification-report.md` 참고)을 사람이 직접 눈으로 검증하고 `--trace`의 원본 무릎·고관절 각도와 대조한 결과, `squat_normal_01.mp4`·`squat_normal_02.mp4`에서 반복 사이의 짧은 기립(1개 표본에서만 무릎이 편 상태로 관측되고 다음 표본에서 바로 재하강)이 완료로 확인되지 않고 **다음 반복과 합쳐져 1회로 과소 계상**되는 것을 확인했다. `update()`는 3fps로 샘플링된 프레임에서만 호출되므로 표본 간격(약 0.33~0.4초)이 이미 `standing_confirm_sec`(0.2초)보다 길다 — 즉 두 번째 표본이 오기 전에는 어떤 지속 시간도 이보다 더 잘게 관측할 수 없다. 기존 로직은 "서 있음"이 처음 관측된 표본에서는 확정하지 않고 **다음 표본에서도 여전히 서 있어야만** 확정했는데, 사용자가 정점에서 오래 멈추지 않는 빠른 템포에서는 그 다음 표본이 이미 재하강 중이라 영원히 확정되지 못했다. + +수정: 표본 간격(`dt`)이 이미 확인 지연 시간 이상이면, 그 자체가 우리가 관측할 수 있는 최소 지속 시간이므로 **첫 표본만으로도 확정**한다(`ai-server/app/core/squat_counter.py`의 `stage == "bottom"`일 때의 기립 확인 분기). 카메라·실시간 스트리밍처럼 `dt`가 확인 지연보다 훨씬 짧을 때는 기존처럼 여러 표본에 걸친 실제 체류를 요구하는 동작이 그대로 유지된다 — 즉 이 수정은 높은 프레임레이트 입력에서는 사실상 아무 영향이 없다. + +바닥 확인(`bottom_confirm_sec`)에도 같은 논리를 처음 적용했으나, 단일 표본만으로 바닥을 확정하면 `tests/test_squat_counter.py::test_reference_segments_follow_completed_repetitions`가 검증하는 "하강 단계가 최소 한 프레임은 기록된다"는 `reference_builder._segment_reps`의 전제가 깨지고, `squat_shallow_01.mp4`에서 단 1개 표본만 바닥 구간에 걸친 애매한 반복까지 완료로 계상해 버렸다. 이 변경은 되돌렸다 — **바닥 확인은 기존과 동일하게 최소 2개 연속 표본을 요구**하며, 기립 확인만 표본 간격을 고려하도록 바꿨다. + +수정 전후로 기존 `samples/raw/`의 라벨된 영상을 다시 돌려 회귀를 확인했다: 45도 정면(2/2)·45도 후면(2/2)·정면(3/3)은 그대로였고, ROI 영상(`sqaut_roi_0509.mp4`)은 같은 합침 문제로 5회였던 것이 6회로 개선되며 사람이 센 7회에 더 가까워졌다(여전히 촬영 규약 미충족이라 100% 일치를 주장하지 않음). `ai-server/tests/`는 카메라 하드웨어 테스트를 제외하고 200 passed·61 subtests passed로 동일하다. + +이 수정으로도 해결되지 않는, 별개의 한계가 하나 더 확인됐다: `squat_front_01.mp4`(정면 촬영, 빠른 템포)에서는 5회 중 3회가 바닥 구간에 **어떤 표본도 걸치지 않아** 아예 감지되지 못했다. 이는 확인 지연 문제가 아니라 3fps 표본 자체가 실제 최저점을 놓치는 나이퀴스트(표본화) 한계이며, 임계값을 더 낮추는 방식으로 고치면 다른 영상에서 얕은 동작을 진짜 반복으로 오인할 위험이 커진다. 현재는 이 한계를 임계값 조정으로 덮지 않고 문서화만 한다. + +기존 무릎 100°/150°와 4·15프레임 중심의 실시간 판정, 업로드 영상의 별도 판정, 기준 영상 분할의 별도 155° 규칙을 한 완료 이벤트로 통일했다. `reference_builder.py`도 새 완료 횟수와 주기 상태를 사용한다. 프레임 수가 바뀌어도 시간 기준은 유지되며, 너무 낮은 촬영 FPS로 바닥 구간이 한 장도 잡히지 않으면 감지할 수 없다. + +업로드 영상의 `quality_score`는 검증되지 않은 단일 점수를 생성하지 않고 `null`이다. 기존 실시간 `sync_rate`는 기준 영상과의 DTW 유사도이며, 표시 문구와 BACK_BENT 35° 규칙도 기존 휴리스틱이다. **논문 기반 반복 판정이 자세 점수 또는 안전 판정의 연구 검증을 뜻하지 않는다.** + +## 확인 방법과 현재 한계 + +합성 궤적 테스트는 시작부터 앉아 있는 장면, 얕은 스쿼트, 느린 상승, 5초 홀드, 10~90초 앉아서 쉬기, 3·10·30fps, 관절 소실, 한쪽 다리 가림·추적 대상 교체, 발 이동, 영상·기준 영상 분할 및 실시간 저장 이벤트를 검증한다. 이는 실제 사람 촬영 정확도의 근거가 아니다. + +저장된 `ai-server/scripts/demo_videos/demo_squat.mp4`를 업로드 경로로 재생한 결과, 308프레임 중 분석 가능한 자세 프레임이 **0개**였다. 한쪽 다리 허용 이후에도 3fps 표본 31프레임 중 0개였다. 따라서 이 영상의 `0회`를 정답과 일치한다고 해석하지 않는다. 실제 측면 촬영본에서 머리부터 발목까지 나오게 찍고 사람이 센 횟수와 아래 명령으로 비교해야 한다. + +과거 `ai-server/analysis_data/`의 추출 좌표도 보조 확인했다. 이 추출 좌표에는 원본 영상의 화면 비율이 없고, 당시에는 사람 기준 횟수도 없었다. 이후 사용자가 원본 정면 영상은 3회, 45도 정면 영상은 2회라고 라벨링했다. 2026-09-18 수정 후 MediaPipe 전체 경로로 다시 재생하면 각각 2회와 2회가 검출된다. 추출 좌표의 과거 검출값이 정답과 같았어도 개별 주기 시각이 맞는지는 확인되지 않았다. **실영상 누락은 여전히 남아 있으며**, 같은 영상에 맞춰 조정한 결과를 일반 사용자 정확도로 취급하지 않는다. + +```powershell +cd ai-server +python scripts/evaluate_squat.py .\clips\squat.mp4 --expected 5 --trace .\squat-trace.csv +``` + +결과의 `evaluation_valid=false`이면 추적·시작 자세 확인 실패이므로 `absolute_error=null`이다. 정면 촬영, 가림, 사람마다 다른 가동 범위, 의자에 앉기/긴 홀드의 혼동은 촬영본을 따로 모아 평가해야 한다. + +## 2026-09-21: 풀 스쿼트 / 하프 스쿼트 깊이 모드 + +사용자가 운동 시작 전(종목 선택과 같은 화면)에 "풀 스쿼트"/"하프 스쿼트" 중 하나를 고르면, 그 모드의 목표 깊이에 맞춰 반복을 인정하고 세션 종료 후 리포트에 깊이 정확도 점수·등급·회차별 코멘트를 보여준다. + +### 임계값 + +`ai-server/app/core/squat_counter.py`에 `HALF_SQUAT_THRESHOLDS`(`DEPTH_MODE_THRESHOLDS` 딕셔너리로 `"FULL"`/`"HALF"` 선택)를 추가했다. 풀 스쿼트 기준(160°/100°/150°, `bottom_knee_margin=15`)은 전혀 건드리지 않았다. + +- **`bottom_knee=125.0`**(+margin 15 = 실질 진입 140°) — 사용자가 확정한 하프 스쿼트 목표 밴드(무릎 115~140도)의 얕은 쪽 경계에 맞춘 값. 이 숫자 자체는 사용자 지정이라 실측 여부와 무관하다. +- **`bottom_hip=154.0`, `min_hip_drop=0.15`(VALIDATE)** — 🔴 **실촬영 하프 스쿼트 영상이 없어 실측값이 아니다.** 풀 스쿼트의 무릎:고관절 굴곡 비율(서기 160°→바닥 100°까지 60°, 같은 구간 고관절은 160°→150°까지 10°, 비율 10/60)을 하프 스쿼트의 무릎 굴곡(160°→125°까지 35°)에 그대로 적용해 `35 × (10/60) ≈ 5.8° → bottom_hip ≈ 154°`로, `min_hip_drop`도 같은 비율로 `0.25 × (35/60) ≈ 0.15`로 비례 추정했다. 2026-09-21 검증에서 확립한 원칙("실측 없이 임계값을 믿지 않는다")을 그대로 적용해, **이 두 값은 하프 스쿼트 실촬영 영상으로 검증되기 전까지 잠정값으로 취급한다.** 검증 절차는 아래 참고. + +`SquatCounter` 자체는 기존과 동일한 FSM을 쓴다 — 모드가 다른 것은 "바닥"으로 인정하는 각도 범위뿐이다. + +### 배선: 세션별 상태로 흘려야 하는 이유 + +`StreamingSquatAnalyzer`는 `app/core/analyzer_registry.py`가 프로세스 기동 시 **딱 하나만 만들어 모든 세션이 공유하는 stateless 싱글턴**이다("stateless 클래스라 공유 가능" 주석). 그래서 분석기 자신의 `self.thresholds`를 세션마다 바꾸는 방식은 쓸 수 없다 — 동시에 실행 중인 풀/하프 세션이 서로의 임계값을 덮어쓰게 된다. 대신 `persona`가 이미 쓰고 있는 세션별 상태 경로(`SessionState.persona` → `SessionStateRegistry.create`/`create_if_absent`)를 그대로 따라 `depth_mode`를 흘리고, `SquatCounter`가 지연 생성되는 시점(`squat_analyzer.py`의 `process_frame`)에만 `state.depth_mode`로 임계값을 고른다. 재부착에서는 `persona`와 동일하게 기존 값을 덮어쓰지 않는다. + +전달 경로: 프론트(종목 선택 화면) → `VideoRequestDto.depthMode` → `Session.squatDepthMode`(DB, `V23__add_squat_depth_mode.sql`) → `AnalyzeRequest.depth_mode`(gRPC, persona와 나란히) → `SessionState.depth_mode` → `SquatCounter` 생성 시 `DEPTH_MODE_THRESHOLDS` 조회. + +### 깊이 정확도 점수와 회차별 코멘트 + +카운팅(반복 인정 여부)과 별개로, **채점은 backend에서** `pose_data.smoothed_knee_angle`(이미 저장되는 값, `SessionAnalysisCalculator`가 worst rep 판정에 쓰는 것과 같은 데이터)만으로 계산한다(`SquatDepthAnalysisCalculator`). 회차별 최소 무릎각을 모드별 목표(풀: 100도 이하 만점·115도까지 선형 감점, 하프: 115~140도 밴드 중심 만점·경계에서 70점)로 채점해 평균을 세션 점수로 낸다. 회차별 코멘트는 우선순위(인접 회차 낙차 → 하프 모드에서 풀 스쿼트급으로 깊어짐 → 얕은 회차 → 편차 큼 → 전부 양호)로 최대 4문장까지 생성한다. + +**AI 임계값(반복 인정)과 backend 채점(점수)은 서로 다른 숫자를 쓰지만 개념적으로 연결돼 있다** — 하프 스쿼트 밴드(115~140도)가 바뀌면 `HALF_SQUAT_THRESHOLDS`와 `SquatDepthAnalysisCalculator`의 상수를 함께 재검토해야 한다. + +실시간 중에는 기존 토스트(횟수·"깊이 확인/미확인")만 그대로 노출한다 — 깊이 점수·회차별 코멘트는 **운동 종료 후 리포트 화면에만** 나타난다. 실시간 음성 안내는 이 저장소에 아직 구현되어 있지 않다(`frontend/app/(tabs)/exercise.tsx`에 "TTS 보류" 주석만 있음). + +### 검증 필요 + +이 기능은 **하프 스쿼트 실촬영 영상으로 아직 검증되지 않았다.** 2026-09-21 검증 보고서와 같은 절차 — 촬영 규약(45도, 전신, 시작·종료 2초 정지, 무릎이 115~140도 안에서 멈추는 깨끗한 5회) 준수 영상을 확보해 `evaluate_squat.py --depth-mode HALF --trace`로 사람 판정과 대조하고, `e1_walkthrough.py --depth-mode half`로 API 경로 전체를 확인한 뒤, `docs/verification/`에 별도 리포트로 남긴다. **그 전까지는 하프 스쿼트 모드의 정확도를 사용자에게 확정적으로 주장하지 않는다.** diff --git a/docs/presentation/algorithm-detail.pptx b/docs/presentation/algorithm-detail.pptx new file mode 100644 index 00000000..542ed60e Binary files /dev/null and b/docs/presentation/algorithm-detail.pptx differ diff --git a/docs/presentation/joint-extraction-slide.svg b/docs/presentation/joint-extraction-slide.svg new file mode 100644 index 00000000..8357c3dd --- /dev/null +++ b/docs/presentation/joint-extraction-slide.svg @@ -0,0 +1,151 @@ + + +Appendix  2-1 관절 추출 +HO-PT + +MediaPipe 관절 사용 현황 +33개 관절 중 스쿼트 8개, 런지 12개만 사용합니다 +스쿼트 · 8개 +런지 · 12개 + + + + + + + + + + + + + + + + + + + + + + + + +13 +14 +15 +16 + +11 + +12 + +23 + +24 + +25 + +26 + +27 + +28 + + + + + + + + + + + + + + + + + + + + + + + + + + + + +13 +14 +15 +16 + +11 + +12 + +23 + +24 + +25 + +26 + +27 + +28 + +29 + +30 + +31 + +32 + +스쿼트에서 쓰는 관절 8개 + +11 · 12 +어깨 +엉덩이각, 체간 기울기 + +23 · 24 +엉덩이 +무릎각·엉덩이각, 체간 기울기 + +25 · 26 +무릎 +무릎각 → 깊이·횟수 판정 + +27 · 28 +발목 +무릎각, 발 위치(준비 자세) + +런지에서 쓰는 관절 12개 + +11 · 12 +어깨 +체간 기울기 + +23 · 24 +엉덩이 +무릎각, 체간 기울기 + +25 · 26 +무릎 +앞무릎각 → 깊이·횟수 판정 + +27 · 28 +발목 +무릎각, 보폭 (발목 간격) + +29 ~ 32 +발뒤꿈치·발끝 +전신 확인용 (계산엔 미사용) +미사용: 얼굴 0~10 · 팔·손 13~22 (스쿼트는 발 29~32도 미사용) + \ No newline at end of file diff --git a/docs/verification/2026-09-21-verification-report.md b/docs/verification/2026-09-21-verification-report.md new file mode 100644 index 00000000..1da85f17 --- /dev/null +++ b/docs/verification/2026-09-21-verification-report.md @@ -0,0 +1,188 @@ +# 2026-09-21 신규 촬영 스쿼트 영상 검증 보고서 + +작성: 2026-09-21. 대상: `ai-server/sample/`에 새로 촬영된 6개 영상. 목표는 [고정 촬영 조건 스쿼트 피드백 시연 기준](constrained-squat-feedback-demo.md)이 정한 조건에서의 동작·피드백 일치이며, 모든 환경에서의 100% 정확도를 뜻하지 않는다. + +## 0. 방법과 중요한 방법론적 교훈 + +각 영상을 **사람이 먼저** 눈으로 확인했다. `cv2`로 0.13~0.4초 간격(애매한 구간은 0.06~0.2초)으로 프레임을 잘라 라벨을 붙인 대조표 이미지를 만들고, 파일명이나 AI 출력에 의존하지 않고 직접 셌다. 정답은 [`samples/validation/2026-09-21/ground-truth.json`](../../samples/validation/2026-09-21/ground-truth.json)에 남겼다. + +**1차 눈 검증 중 실수를 발견하고 정정했다.** `squat_side_01.mp4`에서 상체가 계속 앞으로 숙여져 있어 처음에는 "반복 아님, 7.5초짜리 애매한 동작"으로 판정했다. 그런데 `evaluate_squat.py --trace`가 뽑은 원본 무릎 각도를 보니 무릎은 매 주기 55~100도(바닥)와 150~178도(거의 편 상태) 사이를 정확히 1.8초 간격으로 오가고 있었다 — 상체 숙임 때문에 실루엣만으로는 무릎이 펴졌는지 알아보기 어려웠을 뿐, 실제로는 5회의 진짜 반복이었다. `squat_normal_01.mp4`·`squat_normal_02.mp4`도 같은 이유로 각각 4회·3회로 과소 판정했다가 5회로 정정했다. **이후로는 깊이 판정에서 실루엣(상체 각도)보다 원본 무릎·고관절 각도 수치를 우선했다.** 자세한 정정 과정은 ground-truth.json의 `methodology_note`에 남겼다. + +## 1. 영상별 사람 판정과 촬영 조건 + +| 영상 | 촬영 각도 | 전신 노출 | 가림 | 시작 2초 정지 | 종료 2초 정지 | 사람 판정 정상 횟수 | 사람 판정 얕은 횟수 | +|---|---|---|---|---|---|---:|---:| +| squat_normal_01.mp4 | ~45도(측면 근접) | O | 없음 | ~2.0초(경계) | ~0.7초(미달) | **5** | 0 | +| squat_normal_02.mp4 | ~45도(측면 근접) | O | 없음 | ~1.7초(미달) | ~1.0초(미달) | **5** | 0 | +| squat_shallow_01.mp4 | ~45도(측면 근접) | O | 없음(왼다리는 시야 밖) | 없음(즉시 동작 시작) | 없음 | 0 | **5(시각), 단 2회는 원본 각도상 경계선 접촉** | +| squat_negative_01.mp4 | ~45도(측면 근접) | O | 없음 | 사실상 전체(22.26초) | 사실상 전체 | 0 | 0 | +| squat_front_01.mp4 | **정면(0도)** — 협의된 45도 아님 | O | 없음 | ~1.5초(미달) | ~0.6초(미달) | **5** | 0 | +| squat_side_01.mp4 | **완전 측면(~90도)** — 협의된 45도 아님 | O | 없음(먼 다리는 시야 밖, 예상됨) | ~0.4초(미달) | 확인 불가 | **5** | 0 | + +`squat_normal_03.mp4`는 계획에는 있었지만 실제로 촬영되지 않았다(확인 완료, 폴더에 없음). + +## 2. Baseline(수정 전) vs 수정 후 AI 결과 + +3fps, `ai-server/scripts/evaluate_squat.py --sample-fps 3`. 전체 원본 JSON은 [baseline/](2026-09-21/baseline/), 수정 후는 [final/](2026-09-21/final/)에, 프레임별 trace CSV는 각 폴더의 `traces/`에 있다. + +| 영상 | 사람 판정 | Baseline AI | 수정 후 AI | 절대오차(수정 후) | 사용 가능 포즈 프레임 | calibration | +|---|---:|---:|---:|---:|---:|---| +| squat_normal_01.mp4 | 5 | 4 | **5** | **0** | 37/37 (100%) | 성공 | +| squat_normal_02.mp4 | 5 | 4 | **5** | **0** | 41/41 (100%) | 성공 | +| squat_shallow_01.mp4 | 0(정상 깊이 기준) | 0 | 0 | 0 | 21/21 (100%) | 늦게 성공(4.02초, 3회는 그 전에 발생) | +| squat_negative_01.mp4 | 0 | 0 | **0** | **0** | 61/61 (100%) | 성공 | +| squat_front_01.mp4 | 5 | 1 | 1 | 4 (샘플링 한계, 아래 §3 참고) | 33/33 (100%) | 성공 | +| squat_side_01.mp4 | 5 | 5 | 5 | 0 | 34/34 (100%) | 성공 | + +**통과**: `squat_normal_01`, `squat_normal_02`, `squat_negative_01`, `squat_side_01` — 수정 후 AI 횟수가 사람 판정과 정확히 일치. +**실패(원인 규명됨, 미해결)**: `squat_front_01` — 5회 중 1회만 검출. 원인은 §3. +**해석 필요**: `squat_shallow_01` — 촬영 규약 미충족으로 사람 판정 자체가 불완전(§4). + +기존 저장소 라벨 영상(`samples/raw/`)에 대한 회귀 확인은 §5에 있다. + +## 3. 실패 원인 분석 (요청된 순서대로) + +1. **MediaPipe 관절 visibility** — 6개 영상 모두 사용 가능 포즈 프레임 비율 100%. 원인 아님. +2. **선 자세 calibration** — `negative_01`·`normal_01`·`normal_02`·`front_01`·`side_01`은 정상 성공. `shallow_01`만 늦게(4.02초) 성공했고, 그 전에 일어난 3회는 계산 자체가 시작되지 않아 평가 대상에서 빠졌다(§4). +3. **무릎·고관절 각도** — `front_01`의 놓친 3~4회는 각도 임계값(무릎 ≤115도) 자체가 틀려서가 아니라, 3fps 표본이 실제 최저점을 포착하지 못해 발생했다(아래 4번 참고). 임계값을 낮추는 방식으로는 고치지 않았다 — 다른 영상에서 얕은 동작을 정상으로 오인할 위험이 커지기 때문이다. +4. **골반 수직 이동량** — 관련 없음. 모든 반복에서 `hip_drop`은 이미 최소 기준을 충분히 넘었다(§3 `front_01` 추적표의 `attempt_max_hip_drop` 참고). +5. **하강·하단·상승·기립 상태 전이** — **여기가 핵심 원인이었다.** `normal_01`·`normal_02`에서 반복 사이 정점 체류가 짧을 때(무릎이 편 상태로 관측된 표본이 1개뿐이고 바로 다음 표본에 재하강), 기존 코드는 이를 완료로 확인하지 못하고 **다음 반복과 합쳐서 1회로 과소 계상**했다. +6. **최소 상태 유지 시간** — 근본 원인. `standing_confirm_sec=0.2초`가 3fps 표본 간격(약 0.33~0.4초)보다 짧다. `update()`는 표본이 들어올 때만 호출되므로, 두 번째 표본이 오기 전에는 어떤 지속시간도 0.2초보다 더 잘게 관측할 방법이 없다. 기존 코드는 "처음 서 있는 것으로 관측된 표본"에서는 절대 확정하지 않고 반드시 **다음 표본에서도 여전히 서 있어야** 확정했는데, 템포가 빠르면 그 다음 표본이 이미 재하강 중이라 영원히 확정되지 않았다. +7. **시간 기준 프레임 샘플링** — `front_01`에서 남은, 이번에 고치지 않은 원인. 3fps는 초당 최대 3개 지점만 관측한다. `front_01`의 반복 3~4~5는 실제로는 무릎이 108~130도까지 내려갔지만(육안상 명백히 깊은 스쿼트, [증거 이미지](screenshots/2026-09-21/squat_front_01_missed_depth_evidence.jpg)), 그 순간이 두 표본 사이에 있어 **어떤 표본도 바닥 조건(무릎 ≤115도)을 만족하는 순간을 포착하지 못했다**. 이는 확인 지연 문제가 아니라 표본화 해상도 자체의 한계(나이퀴스트류 문제)이며, 6번 항목의 수정과는 무관하다. +8. **좌우 관절 선택** — `shallow_01`·`side_01`은 한쪽 다리만 시야에 들어와 한쪽 다리 대체 로직을 썼다. 코드는 이를 정상적으로 처리했고 문제를 일으키지 않았다(`ai-server/tests/test_squat_counter.py`의 한쪽 다리 테스트들이 이미 이 경로를 검증한다). +9. **정면·45도·측면 촬영 차이** — `front_01`(정면)과 `side_01`(완전 측면)은 협의된 45도 촬영 조건을 벗어난다. 각도 계산 자체는 두 경우 모두 정상 동작했으나(각각 5회 관측 가능, `side_01`은 실제로 5회 모두 검출), `front_01`의 표본화 문제는 정면 촬영에서 이 사람의 템포가 상대적으로 빨랐던 것과 겹쳐 더 두드러졌을 가능성이 있다. +10. **영상 시작·종료의 동작 절단** — `shallow_01`은 시작 2초 정지가 전혀 없어 0~3.65초 동안 계산이 "waiting_for_standing" 상태에 머물렀고, 그 사이 일어난 3회의 얕은 시도는 평가 대상에서 완전히 빠졌다(§4). 나머지 영상은 시작·종료 정지가 2초에 못 미치더라도(1.5~2.0초 근처) calibration과 마지막 반복 완료에는 지장이 없었다. + +## 4. `squat_shallow_01.mp4`를 "통과"로 읽으면 안 되는 이유 + +촬영 규약(시작 2초 정지 자세)을 지키지 않아 사람이 육안으로 본 5회의 얕은 시도 중 **3회(0.23~0.47초, 1.63~1.86초, 2.79~3.26초)는 calibration이 끝나기 전에 일어나 AI가 아예 평가하지 못했다.** 나머지 2회(4.19~4.65초, 5.81~6.05초)는 baseline 코드 기준으로 "깊이 미확인" 피드백이 발생해 얼핏 보면 의도(전부 얕게)와 맞아떨어지는 것처럼 보이지만, 원본 각도 추적표를 보면 이 두 번은 **단일 3fps 표본에서 무릎 101~115도·고관절 102~107도로 앱의 바닥 조건 경계에 실제로 닿아 있었다.** 앱은 단일 표본만으로는 바닥 단계를 확정하지 않도록 의도적으로 보수적으로 유지했으므로(§3-6, §3-7 구분 참고) 이 2회를 "깊이 미확인"으로 처리한 것은 **정확도 버그가 아니라 방어적으로 올바른 판단**이다. 다만 이 영상은 "일관되게 얕은 동작" 시연으로 쓰기에는 본인의 실제 수행 깊이가 일관되지 않았고, 촬영 규약도 지키지 않았다. **깨끗한 얕은 동작 기각 시연을 위해서는 시작 2초 정지를 포함하고 처음부터 끝까지 일관되게 무릎이 얕게만 굽혀지는 영상을 다시 촬영해야 한다.** + +## 5. 코드 수정 + +`ai-server/app/core/squat_counter.py`의 `SquatCounter.update()`, `stage == "bottom"`일 때의 기립 확인 분기 한 곳만 고쳤다: + +```python +if standing: + if self.standing_since is None: + self.standing_since = now + if ((now - self.standing_since >= t.standing_confirm_sec + or dt >= t.standing_confirm_sec) + and now - self.started_at >= t.min_active_sec): + self.rep_count += 1 + ... +``` + +`dt`(이번 호출과 직전 호출 사이의 실제 경과 시간)가 이미 확인 지연 시간 이상이면, 그 자체가 우리가 관측할 수 있는 최소 지속 시간이므로 **첫 표본만으로도 확정**한다. 카메라·실시간 스트리밍처럼 `dt`가 확인 지연보다 훨씬 짧을 때(고fps)는 기존처럼 여러 표본에 걸친 실제 체류를 요구하는 동작이 그대로 유지된다 — 즉 이 수정은 3fps처럼 표본 간격이 넓은 입력에서만 효과가 있고, 실시간 카메라 스트리밍(보통 수십 fps)에서는 사실상 아무 영향이 없다. + +**바닥 확인(`bottom_confirm_sec`)에는 같은 수정을 적용하지 않고 되돌렸다.** 처음에는 대칭적으로 같은 수정을 시도했으나 두 가지 문제가 있었다: +- `tests/test_squat_counter.py::test_reference_segments_follow_completed_repetitions`가 검증하는 "하강 단계가 최소 한 프레임은 `descending`으로 기록된다"는 `reference_builder._segment_reps`의 전제가 깨져 기준 영상 구간 분할이 실패했다. +- `squat_shallow_01.mp4`에서 단 1개 표본만 바닥 경계에 걸친 애매한 반복까지 완료로 계상해, §4에서 설명한 "깊이 미확인"의 보수적 판정이 사라졌다. + +따라서 최종적으로는 **기립 확인만** 표본 간격을 고려하도록 바꾸고, 바닥 확인은 기존과 동일하게 최소 2개 연속 표본을 요구하도록 유지했다. 특정 영상 하나만 맞추기 위해 임계값을 낮추지 않았다는 원칙을 지켰다 — 각도 임계값은 전혀 건드리지 않았고, 시간 확인 로직만 표본화 현실에 맞게 고쳤다. + +## 6. 회귀 테스트 + +| 항목 | 결과 | +|---|---| +| AI 스쿼트·런지 pytest (`-k "squat or lunge"`, 카메라 제외) | **57 passed** | +| AI 전체 pytest (카메라 하드웨어 테스트 제외) | **200 passed, 61 subtests passed** — 기존 문서 기준과 동일 | +| Backend 전체 Gradle 테스트 (Docker `gradle:jdk21`) | **857 tests, 0 failures, 17 skipped, 100% 성공** — 기존 문서 기준과 동일(§7-1) | +| Frontend `npx tsc --noEmit` | **통과** (오류 없음) | +| Expo web export | **통과** (20개 정적 라우트 모두 생성) | +| `git diff --check` | **통과** (기존 CRLF 정규화 경고만 있고 실제 공백 오류 없음) | +| 기존 라벨 영상 회귀(`samples/raw/`, `samples/validation/labels.csv`) | 아래 표 참고 | + +`test_squat_counter.py::test_reference_segments_follow_completed_repetitions`는 수정으로 인해 완료 시점이 한 표본 앞당겨지는 것이 의도된 동작이므로 `end_frame_index` 기댓값을 8→7로 갱신했고(이유를 주석으로 남김), 다른 기존 테스트의 기댓값은 손대지 않았다. + +### 기존 라벨 영상 회귀 확인 (`samples/raw/`, 3fps) + +| 영상 | 사람 라벨 | 수정 전 문서 기록 | 수정 후 실측 | +|---|---:|---:|---:| +| kkw_45-degree_frontview_squat.mp4 | 2 | 2 | 2 (변화 없음) | +| kkw_front_squat.mp4 | 3 | 3 | 3 (변화 없음) | +| kkw_45-degree_backview_squat.mp4 | 2 | 2 | 2 (변화 없음) | +| sqaut_roi_0509.mp4 | 7(촬영 규약 미충족) | 5 | **6** (같은 합침 문제가 완화되어 사람 라벨에 더 근접; 여전히 규약 미충족으로 100% 주장 안 함) | +| 60kg_squat.mp4 | 15(랙이 무릎 가림) | 문서 미기재 | 6 (valid_ratio 0.768, 가림으로 인한 기존 한계, 무관) | +| squat.mp4 | 9(랙이 무릎 가림) | 문서 미기재 | valid_ratio 0.611 → evaluation_valid=False(기존 한계, 무관) | + +퇴행 없음. `sqaut_roi_0509.mp4`가 오히려 개선되었다. + +## 7. Backend 테스트 / 통합(E2E) 검증 + +### 7-1. Backend Gradle 전체 테스트 + +Docker `gradle:jdk21` 컨테이너(호스트 `.gradle` 캐시와 Docker 소켓을 마운트해 Testcontainers가 중첩 MySQL 컨테이너를 띄울 수 있게 함)에서 실행(`BUILD SUCCESSFUL in 22m 3s`, 실행 시간 21m0.27s). 결과: **857 tests, 0 failures, 17 skipped, 100% successful** — 기존 문서 기준(857 tests, 0 failures, 0 errors, 17 skipped)과 정확히 동일하다. 이번 변경은 `ai-server/`에만 있고 backend 소스는 건드리지 않았으므로 예상대로 퇴행이 없었다. + +### 7-2. 실제 API 경로 통합 검증 (격리된 `shadowfit-iso-*` Docker 스택) + +이미 떠 있던 `shadowfit-iso` 스택(mysql/backend/ai/ai-nginx, `docker-compose.iso.yml`) 중 `shadowfit-ai` 이미지만 이번 수정을 반영해 재빌드·재기동했다(`docker compose -p shadowfit-iso -f docker-compose.yml -f docker-compose.iso.yml build shadowfit-ai && ... up -d shadowfit-ai`). Backend는 이번 변경(ai-server만 수정)과 무관해 재빌드하지 않았다. + +`ai-server/scripts/e1_walkthrough.py`(회원가입→로그인→온보딩→세션 시작→프레임 전송→세션 종료→리포트 확인까지 실제 HTTP/gRPC 경로를 그대로 타는 기존 스크립트, 이슈 #196)를 세 영상에 대해 실행했다. + +| 영상 | 전송 fps | 결과 | +|---|---:|---| +| squat_normal_01.mp4 | 3.0 | rep **4**/5, `RATE_LIMITED` 스킵 1건 발생(§7-3) | +| squat_normal_01.mp4 (재현) | 3.0 | rep **4**/5, `RATE_LIMITED` 스킵 1건(동일 재현) | +| squat_normal_01.mp4 | **2.5** | rep **5/5** 일치, 완료 안내 5건, 리포트 `totalReps=5`·`avgSyncRate=80`, **E1 통과** | +| squat_negative_01.mp4 | 2.5 | rep 0, 완료·깊이미확인 0건, 리포트 `totalReps=0` (기대와 일치; 스크립트의 판정 기준 자체가 "1회 이상 완료"를 전제로 하므로 스크립트 출력은 미통과로 표시되지만 실제 값은 사람 판정과 일치) | +| squat_shallow_01.mp4 | 2.5 | rep 0, 깊이 미확인 2건 — 오프라인 `evaluate_squat.py` 결과와 정확히 동일 | + +핵심 확인 사항: +- 이번 코드 수정(§5)은 오프라인 배치 평가 스크립트뿐 아니라 **실제 회원가입→세션→프레임 전송→gRPC 콜백→Backend 리포트 저장까지의 전체 경로**에서도 사람이 센 5회와 정확히 일치했다(2.5fps 전송 시). +- `message`·`rep_completed` 필드는 [frontend/app/(tabs)/exercise.tsx:338-339](../../frontend/app/(tabs)/exercise.tsx)에서 그대로 `coachingNotice` 상태로 옮겨져 토스트로 렌더링된다(465~470행) — 코드 상으로 AI 응답과 화면 토스트 사이의 배선은 끊어진 곳이 없다. 실제 화면에서 육안으로 보이는지는 §10 체크리스트로 남긴다. + +### 7-3. 새로 발견한, 이번 수정과 무관한 별개 이슈: 정확히 3fps로 보낼 때의 레이트리밋 여유가 매우 좁다 + +`squat_normal_01.mp4`를 정확히 3fps(간격 333ms)로 두 번 보냈을 때 **매번** 프레임 1개가 `RATE_LIMITED`로 스킵되어 rep이 5가 아니라 4로 나왔다(§5의 기립 확인 수정과 무관 — 스킵된 프레임 자체가 판정에 들어가지 못했다). 원인을 좁혀보니: + +- 서버의 유입 속도 상한은 `ai-server/app/grpc/session_state.py`의 `MIN_FRAME_INTERVAL_SEC = 0.300`(300ms)이다. +- 같은 파일 주석은 앱의 실제 전송 간격을 `exercise.tsx intervalMs=330`(330ms)이라고 적어 두었다 — **서버 하한(300ms)과 앱의 의도된 간격(330ms) 사이의 여유가 30ms뿐이다.** +- 전송 간격을 2.5fps(400ms)로 늘리자 같은 영상에서 스킵이 0건으로 사라지고 5/5가 정확히 일치했다. + +즉 정확히 3fps로 보내도록 설계된 현재 여유폭은, 로컬 Docker 환경의 극히 미세한 타이밍 지터(내 테스트 스크립트의 `time.sleep` 오차 수준)만으로도 프레임을 하나씩 잃을 수 있을 만큼 빠듯하다. 이는 이번에 수정한 `squat_counter.py`의 문제가 아니라 **레이트리미터(`MIN_FRAME_INTERVAL_SEC`)와 클라이언트 전송 간격(`intervalMs`) 사이의 여유 설계**에 관한, 별개의 기존 이슈다. 이번 작업 범위 밖이라 고치지 않았지만, 실기기(휴대폰 카메라, 네트워크 지연이 로컬보다 더 크고 변동성도 큼)에서는 이 margin이 로컬 Docker 테스트보다 훨씬 더 자주 소진될 수 있으므로 별도로 검토가 필요하다. + +## 8. 현재 주장할 수 있는 성능과 한계 + +**주장 가능**: 고정 촬영 조건(45도 근접, 전신 노출, 가림 없음, 충분한 조명)에서 촬영한 새 영상 2개(`normal_01`, `normal_02`)와 기존 라벨 영상들에서, 수정된 코드는 사람이 눈으로 확인한 정상 깊이 반복 횟수와 정확히 일치했다(각 5/5). `negative_01`(스쿼트 없음 22초)에서도 오검출 0건이었다. 이 일치는 오프라인 배치 평가뿐 아니라 **회원가입부터 리포트 저장까지의 실제 API 경로**(§7-2)에서도 재현됐다 — 즉 카운팅 로직 수정이 배관 전체를 통과해 실제로 반영된다는 것까지 확인했다. + +**주장할 수 없는 것**: +- **최종 홀드아웃 부재**: `normal_01`·`normal_02`는 이번 수정을 진단하는 데 직접 사용한 영상이라 최종 증거로 다시 쓰면 검증 유출이다. `negative_01`만 이번 수정과 무관한 독립 홀드아웃으로 인정한다. **정상 스쿼트에 대한 독립적인 최종 합격 주장은 아직 할 수 없다.** +- **얕은 동작 기각의 깨끗한 증거 없음**: `shallow_01`은 촬영 규약 미충족(시작 정지 없음)과 본인 수행의 깊이 비일관성 때문에 깨끗한 시연이 아니다. +- **3fps 표본화의 실제 한계 확인됨**: 빠른 템포로 수행하면(특히 `front_01`처럼) 실제 깊은 반복이 3fps 표본 사이로 빠져나가 놓칠 수 있다. 이는 이번 수정으로 고치지 않았고, 사용자에게 코칭 문구(바닥에서 짧게라도 멈추기)나 표본 속도 조정 등 별도 논의가 필요하다. +- **정확히 3fps로 보낼 때의 레이트리밋 여유가 좁다(§7-3, 신규 발견)**: 서버 상한(300ms)과 앱의 의도된 전송 간격(330ms) 사이 여유가 30ms뿐이라, 로컬 Docker 환경의 미세한 타이밍 지터만으로도 정상 반복이 누락되는 것을 실측했다(2.5fps로 늘리면 사라짐). 실기기·실네트워크에서는 더 자주 발생할 수 있다. 이번 작업 범위 밖이라 고치지 않았다. +- **45도 협의 각도에서 촬영된 영상이 실질적으로 없음**: `normal_01`·`normal_02`는 45도에 가깝지만 정확히 협의된 각도인지 확인할 기준점이 없고, `front_01`(정면)·`side_01`(완전 측면)은 명백히 협의 각도를 벗어난다. +- 어떤 조건에서도 **일반 사용자 환경 정확도 100%를 주장하지 않는다.** + +## 9. 사용자가 추가로 촬영·확인해야 할 사항 + +1. **새 정상 스쿼트 영상 1개 이상** — 45도, 시작·종료 2초 정지 포함, 5회. 이번 디버깅에 쓰지 않은 새 영상이어야 독립적인 최종 합격 주장이 가능하다. +2. **새 얕은 스쿼트 영상 1개** — 시작 2초 정지를 반드시 포함하고, 처음부터 끝까지 무릎이 일관되게 얕게(무릎 각도가 115도 밑으로 내려가지 않게)만 굽혀지도록 수행. +3. (선택) **`front_01`과 같은 빠른 템포 정면 영상을 하나 더** — 바닥에서 아주 짧게(0.3~0.5초)라도 멈추는 버전으로 촬영해, 표본화 한계가 실제로 "멈춤 없는 빠른 템포"에서만 발생하는지 "정면 각도" 자체의 문제는 아닌지 구분. +4. `squat_normal_03.mp4`는 계획에는 있었지만 폴더에 없다 — 필요하면 추가 촬영. +5. 휴대폰 카메라로 직접 실행하는 §10 체크리스트(아래) — API 경로는 이번에 직접 확인했지만, 실기기 화면에 토스트가 실제로 보이는지와 §7-3의 레이트리밋 여유 문제가 실네트워크에서 얼마나 자주 발생하는지는 사용자 확인이 필요하다. + +## 10. 통합 검증(§8 요청) 체크리스트 + +`shadowfit-iso` Docker 스택(`docker-compose.iso.yml`)이 이미 떠 있어 `shadowfit-ai` 이미지를 이번 수정으로 재빌드·재기동하고(§7-2), `ai-server/scripts/e1_walkthrough.py`로 회원가입→로그인→온보딩→세션 시작→프레임 전송→세션 종료→리포트 확인까지 실제 API 경로를 직접 실행해 아래 항목 대부분을 코드/API 레벨에서 확인했다. 휴대폰 카메라 자체는 조작할 수 없어 화면 표시 확인만 사용자 체크리스트로 남긴다. + +- [x] 로그인 또는 테스트 계정 생성 — API로 직접 확인(§7-2) +- [x] 스쿼트 운동 세션 생성 — API로 직접 확인 +- [x] 실제 영상 프레임 전송(신규 촬영 영상 재생) — `squat_normal_01`·`squat_negative_01`·`squat_shallow_01` 3개로 확인 +- [x] AI 횟수 및 `스쿼트 깊이를 확인하고 1회 기록했어요.` / `이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.` 메시지가 API 응답에 정확히 담기는지 확인 — 화면 토스트 배선(`frontend/app/(tabs)/exercise.tsx:338-339, 465-470`)도 코드로 확인 +- [x] 세션 정상 종료 — API로 직접 확인 +- [x] Backend 리포트에 동일한 횟수가 저장되는지 확인 — `totalReps` 일치 확인(§7-2) +- [ ] **실기기 화면에 토스트가 실제로 보이는지** — 카메라를 직접 조작할 수 없어 사용자 확인 필요 +- [ ] 특히 `normal_01`·`normal_02`처럼 반복 사이 정점 체류가 짧은 템포에서, 이번 수정 이후 반복이 합쳐지지 않고 따로 카운트되는지 실기기에서 재확인 +- [ ] §7-3의 레이트리밋 여유(30ms) 문제가 실기기·실네트워크에서 얼마나 자주 발생하는지 확인 — 로컬 Docker에서는 정확히 3fps로 보낼 때 매번 재현됐다 + +## 변경된 파일 + +- `ai-server/app/core/squat_counter.py` — 기립 확인 로직 수정(§5) +- `ai-server/tests/test_squat_counter.py` — 수정된 동작에 맞춰 기존 테스트 기댓값 1건 갱신(§5) +- `docs/decisions/squat-repetition-counting.md` — 원인·수정 내역 추가 +- `docs/verification/constrained-squat-feedback-demo.md` — 2026-09-21 결과 절 추가 +- `docs/verification/2026-09-21-verification-report.md` — 본 문서(신규) +- `docs/verification/2026-09-21/` — manifest, baseline/final 평가 JSON, trace CSV(신규) +- `docs/verification/screenshots/2026-09-21/` — 검증용 대조표·증거 이미지(신규) +- `samples/validation/2026-09-21/` — 검증용 영상 사본과 ground-truth.json(신규, 원본은 `ai-server/sample/`에 그대로 보존) +- `samples/validation/.gitignore` — 기존 패턴이 최상위 파일만 가리고 날짜별 하위 폴더(`2026-09-21/` 등)의 영상은 걸러내지 못하던 것을 발견해 재귀 패턴 추가(영상 원본이 실수로 커밋되는 것을 방지) diff --git a/docs/verification/2026-09-21/baseline/squat_front_01.json b/docs/verification/2026-09-21/baseline/squat_front_01.json new file mode 100644 index 00000000..474612b7 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_front_01.json @@ -0,0 +1,60 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_front_01.mp4", + "source_fps": 30.105160091526397, + "sample_fps": 3.0, + "sampled_frames": 33, + "usable_frames": 33, + "calibrated_frames": 33, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 1, + "coaching_events": [ + { + "time_sec": 2.923, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 0 + }, + { + "time_sec": 5.481, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 1 + }, + { + "time_sec": 7.673, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 1 + }, + { + "time_sec": 9.5, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 1 + }, + { + "time_sec": 11.327, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 1 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/baseline/squat_front_01.stderr.log b/docs/verification/2026-09-21/baseline/squat_front_01.stderr.log new file mode 100644 index 00000000..b65f725a --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_front_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789927698.358817 19668 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927698.388121 19668 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927698.408576 28756 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/baseline/squat_negative_01.json b/docs/verification/2026-09-21/baseline/squat_negative_01.json new file mode 100644 index 00000000..226f202e --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_negative_01.json @@ -0,0 +1,34 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_negative_01.mp4", + "source_fps": 30.105293939552702, + "sample_fps": 3.0, + "sampled_frames": 61, + "usable_frames": 61, + "calibrated_frames": 61, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 0, + "coaching_events": [], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/baseline/squat_negative_01.stderr.log b/docs/verification/2026-09-21/baseline/squat_negative_01.stderr.log new file mode 100644 index 00000000..15fa02ae --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_negative_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789927691.315348 21980 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927691.345029 26680 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927691.365194 1420 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/baseline/squat_normal_01.json b/docs/verification/2026-09-21/baseline/squat_normal_01.json new file mode 100644 index 00000000..7fd1fb06 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_normal_01.json @@ -0,0 +1,55 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_normal_01.mp4", + "source_fps": 30.10519356736308, + "sample_fps": 3.0, + "sampled_frames": 37, + "usable_frames": 37, + "calibrated_frames": 37, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 4, + "coaching_events": [ + { + "time_sec": 6.577, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 1 + }, + { + "time_sec": 8.404, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 2 + }, + { + "time_sec": 10.231, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 3 + }, + { + "time_sec": 12.423, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 4 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/baseline/squat_normal_01.stderr.log b/docs/verification/2026-09-21/baseline/squat_normal_01.stderr.log new file mode 100644 index 00000000..6bd14617 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_normal_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789927677.592945 27400 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927677.626312 28916 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927677.647678 23452 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/baseline/squat_normal_02.json b/docs/verification/2026-09-21/baseline/squat_normal_02.json new file mode 100644 index 00000000..c6910bb5 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_normal_02.json @@ -0,0 +1,55 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_normal_02.mp4", + "source_fps": 30.105212994381937, + "sample_fps": 3.0, + "sampled_frames": 41, + "usable_frames": 41, + "calibrated_frames": 41, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 4, + "coaching_events": [ + { + "time_sec": 7.673, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 1 + }, + { + "time_sec": 9.5, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 2 + }, + { + "time_sec": 11.327, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 3 + }, + { + "time_sec": 13.885, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 4 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/baseline/squat_normal_02.stderr.log b/docs/verification/2026-09-21/baseline/squat_normal_02.stderr.log new file mode 100644 index 00000000..b3efd7e1 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_normal_02.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789927682.560266 14076 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927682.591090 8748 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927682.610876 3224 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/baseline/squat_shallow_01.json b/docs/verification/2026-09-21/baseline/squat_shallow_01.json new file mode 100644 index 00000000..d897db2b --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_shallow_01.json @@ -0,0 +1,45 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_shallow_01.mp4", + "source_fps": 30.104989463253688, + "sample_fps": 3.0, + "sampled_frames": 21, + "usable_frames": 21, + "calibrated_frames": 10, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 0, + "coaching_events": [ + { + "time_sec": 5.115, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 0 + }, + { + "time_sec": 6.577, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 0 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/baseline/squat_shallow_01.stderr.log b/docs/verification/2026-09-21/baseline/squat_shallow_01.stderr.log new file mode 100644 index 00000000..6c13d5bb --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_shallow_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789927687.832647 18776 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927687.869232 18776 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927687.888035 30576 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/baseline/squat_side_01.json b/docs/verification/2026-09-21/baseline/squat_side_01.json new file mode 100644 index 00000000..3d1c6733 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_side_01.json @@ -0,0 +1,60 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_side_01.mp4", + "source_fps": 30.105150876158596, + "sample_fps": 3.0, + "sampled_frames": 34, + "usable_frames": 34, + "calibrated_frames": 34, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 5, + "coaching_events": [ + { + "time_sec": 2.192, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 1 + }, + { + "time_sec": 4.019, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 2 + }, + { + "time_sec": 5.846, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 3 + }, + { + "time_sec": 7.673, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 4 + }, + { + "time_sec": 11.692, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 5 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/baseline/squat_side_01.stderr.log b/docs/verification/2026-09-21/baseline/squat_side_01.stderr.log new file mode 100644 index 00000000..fb703c77 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/squat_side_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789927702.874869 25788 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927702.907604 15072 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789927702.933277 29356 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/baseline/traces/squat_front_01.csv b/docs/verification/2026-09-21/baseline/traces/squat_front_01.csv new file mode 100644 index 00000000..b1a3a992 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/traces/squat_front_01.csv @@ -0,0 +1,34 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,179.93,178.57,165.12,164.13,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,ready,standing,179.92,178.76,165.06,164.08,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.731,ready,standing,179.69,178.86,165.0,164.08,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.096,ready,standing,179.71,178.98,165.1,164.06,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.462,ready,standing,176.28,176.47,163.0,162.3,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.827,descending,descending,154.06,149.89,149.76,146.26,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.192,descending,descending,125.22,115.58,119.65,109.8,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.558,descending,ascending,139.77,126.45,139.3,128.92,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.923,ready,standing,164.87,143.58,158.56,148.47,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +3.288,ready,standing,175.93,170.01,163.9,160.94,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +3.654,ready,standing,163.01,161.67,157.19,155.52,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +4.019,descending,bottom,116.37,110.75,118.8,111.63,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.385,bottom,bottom,117.21,108.53,121.76,111.72,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.75,bottom,ascending,139.99,139.85,147.06,143.01,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.115,bottom,standing,171.34,171.87,160.79,160.33,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.481,ready,standing,178.78,177.83,162.79,162.02,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +5.846,ready,standing,175.95,178.62,164.92,162.06,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +6.212,ready,standing,179.3,179.55,162.98,163.73,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +6.577,ready,standing,162.11,170.34,154.77,155.84,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +6.942,descending,descending,134.53,132.53,121.08,120.48,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +7.308,descending,transition,132.31,129.71,124.16,127.93,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +7.673,ready,standing,158.49,155.7,149.73,154.55,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +8.038,ready,standing,173.91,176.31,158.99,165.24,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +8.404,ready,standing,161.77,166.12,153.89,159.39,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +8.769,descending,descending,118.95,118.9,114.47,119.41,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +9.135,descending,ascending,128.24,122.9,128.08,128.19,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +9.5,ready,standing,160.71,157.43,153.04,153.83,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +9.865,ready,standing,176.04,175.58,160.9,164.15,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +10.231,ready,standing,149.8,154.88,147.47,152.67,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +10.596,descending,bottom,115.09,108.66,112.22,107.89,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.962,descending,ascending,128.7,123.38,133.51,127.98,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +11.327,ready,standing,168.88,168.74,159.28,157.54,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +11.692,ready,standing,178.86,178.8,164.18,163.99,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., diff --git a/docs/verification/2026-09-21/baseline/traces/squat_negative_01.csv b/docs/verification/2026-09-21/baseline/traces/squat_negative_01.csv new file mode 100644 index 00000000..6810b05a --- /dev/null +++ b/docs/verification/2026-09-21/baseline/traces/squat_negative_01.csv @@ -0,0 +1,62 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,175.49,179.64,170.03,168.09,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,ready,standing,177.39,177.85,172.58,165.88,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.731,ready,standing,178.33,177.97,174.18,164.97,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.096,ready,standing,177.25,178.4,174.67,164.37,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.462,ready,standing,176.44,179.28,173.83,165.04,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.827,ready,standing,175.99,178.87,173.25,164.86,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.192,ready,standing,176.19,179.25,173.2,165.44,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.558,ready,standing,176.33,171.79,173.77,172.21,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.923,ready,standing,176.9,167.75,179.03,179.24,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +3.288,ready,standing,176.32,177.83,172.16,174.11,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +3.654,ready,standing,173.26,179.63,173.18,172.61,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.019,ready,standing,173.91,179.93,171.58,169.55,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.385,ready,standing,177.63,178.57,171.85,171.32,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.75,ready,standing,174.14,173.44,176.8,174.5,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +5.115,ready,standing,176.66,175.83,175.98,172.37,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +5.481,ready,standing,177.61,176.61,179.27,168.68,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +5.846,ready,standing,178.81,177.8,177.19,168.06,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +6.212,ready,standing,179.26,179.12,175.65,169.63,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +6.577,ready,standing,178.71,170.55,176.6,170.22,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +6.942,ready,standing,178.49,179.34,178.17,170.11,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +7.308,ready,standing,175.76,176.82,175.16,171.59,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +7.673,ready,standing,177.44,176.16,173.78,172.82,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +8.038,ready,standing,177.36,176.61,177.74,173.28,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +8.404,ready,standing,170.06,177.7,175.26,176.78,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +8.769,ready,standing,179.34,179.1,164.7,173.93,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +9.135,ready,standing,177.18,169.19,166.44,177.49,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +9.5,ready,standing,178.75,168.03,169.16,178.76,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +9.865,ready,standing,178.6,170.45,170.23,179.7,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +10.231,ready,standing,178.6,176.64,171.68,178.71,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +10.596,ready,standing,176.68,177.16,168.03,177.98,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +10.962,ready,standing,175.49,175.98,168.52,179.71,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +11.327,ready,standing,177.14,174.72,167.27,173.68,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +11.692,ready,standing,177.77,175.43,167.28,168.75,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +12.058,ready,standing,175.12,177.41,167.56,169.2,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +12.423,ready,standing,167.15,175.97,162.11,162.3,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +12.788,ready,standing,172.66,177.36,166.47,162.47,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +13.154,ready,standing,175.92,179.41,167.31,165.66,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +13.519,ready,standing,177.64,170.21,163.48,163.19,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +13.885,ready,standing,179.16,173.11,162.84,168.96,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +14.25,ready,standing,179.9,173.18,162.48,171.4,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +14.615,ready,standing,179.74,173.39,163.17,171.13,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +14.981,ready,standing,178.89,178.17,162.74,170.26,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +15.346,ready,standing,177.56,179.22,166.09,168.58,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +15.712,ready,standing,178.63,178.53,170.37,166.95,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +16.077,ready,standing,179.26,179.23,168.41,168.58,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +16.442,ready,standing,177.31,173.91,169.17,164.79,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +16.808,ready,standing,179.53,174.25,165.49,165.93,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +17.173,ready,standing,176.47,179.67,167.72,163.82,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +17.538,ready,standing,178.19,176.22,169.17,161.93,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +17.904,ready,standing,172.48,175.55,178.4,166.3,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +18.269,ready,standing,176.98,177.76,179.51,169.89,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +18.635,ready,standing,178.31,170.64,177.29,179.1,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +19.0,ready,standing,178.62,165.37,178.16,174.19,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +19.365,ready,standing,179.05,167.17,176.76,175.77,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +19.731,ready,standing,175.7,176.93,178.53,172.66,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +20.096,ready,standing,171.96,179.69,169.09,166.13,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +20.462,ready,standing,176.92,179.9,164.55,165.68,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +20.827,ready,standing,178.7,174.89,168.94,161.29,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +21.192,ready,standing,169.87,174.98,160.08,175.86,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +21.558,ready,standing,176.19,179.75,165.67,178.66,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +21.923,ready,standing,179.55,179.91,169.0,179.48,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., diff --git a/docs/verification/2026-09-21/baseline/traces/squat_normal_01.csv b/docs/verification/2026-09-21/baseline/traces/squat_normal_01.csv new file mode 100644 index 00000000..542a5cfc --- /dev/null +++ b/docs/verification/2026-09-21/baseline/traces/squat_normal_01.csv @@ -0,0 +1,38 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,179.66,175.31,164.87,174.11,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,ready,standing,179.42,175.69,165.09,174.48,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.731,ready,standing,179.18,175.8,165.31,174.55,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.096,ready,standing,179.0,175.89,165.57,174.53,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.462,ready,standing,178.87,175.91,165.62,174.52,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.827,ready,standing,178.69,175.89,165.61,174.55,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.192,ready,standing,176.71,178.44,169.25,178.53,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.558,descending,descending,156.11,143.6,159.89,149.42,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.923,descending,bottom,127.99,59.7,131.58,66.55,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +3.288,bottom,bottom,74.13,29.55,72.27,31.82,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +3.654,bottom,bottom,108.19,40.53,109.1,48.95,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.019,bottom,ascending,148.22,148.11,148.88,140.97,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.385,bottom,standing,161.53,160.76,165.23,155.73,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.75,bottom,descending,143.31,120.93,144.07,123.72,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.115,bottom,bottom,95.0,50.68,87.1,45.26,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.481,bottom,bottom,103.05,65.11,93.46,58.35,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.846,bottom,ascending,144.73,120.57,135.87,113.16,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.212,bottom,standing,170.5,170.55,164.09,150.84,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.577,ready,standing,162.17,143.7,158.05,136.59,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +6.942,descending,bottom,119.83,79.32,108.86,76.17,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +7.308,bottom,bottom,102.25,53.66,84.54,46.76,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +7.673,bottom,ascending,137.14,103.61,124.07,95.66,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +8.038,bottom,standing,167.85,174.42,159.23,150.49,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +8.404,ready,standing,169.9,161.86,166.44,149.88,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +8.769,descending,descending,140.97,101.43,128.91,97.38,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +9.135,descending,bottom,96.31,49.45,68.06,40.88,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +9.5,bottom,bottom,97.06,56.08,82.36,54.37,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +9.865,bottom,standing,164.43,154.08,147.9,130.63,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +10.231,ready,standing,169.35,159.92,161.53,142.4,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +10.596,descending,descending,145.73,114.82,135.59,109.46,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.962,descending,bottom,89.6,50.74,61.11,39.92,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +11.327,bottom,bottom,97.34,46.88,70.89,38.7,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +11.692,bottom,ascending,138.14,102.7,120.67,96.87,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +12.058,bottom,standing,171.39,164.83,157.52,141.2,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +12.423,ready,standing,176.22,168.19,172.5,156.24,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +12.788,ready,standing,179.05,176.81,178.48,164.28,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +13.154,ready,standing,179.24,179.45,171.36,173.46,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., diff --git a/docs/verification/2026-09-21/baseline/traces/squat_normal_02.csv b/docs/verification/2026-09-21/baseline/traces/squat_normal_02.csv new file mode 100644 index 00000000..623bdd3e --- /dev/null +++ b/docs/verification/2026-09-21/baseline/traces/squat_normal_02.csv @@ -0,0 +1,42 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,,177.15,,173.01,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,ready,standing,,177.09,,173.66,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.731,ready,standing,,176.95,,174.06,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.096,ready,standing,,173.75,,177.96,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.462,ready,standing,,175.77,,162.53,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.827,ready,standing,176.8,173.26,177.7,161.05,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.192,ready,standing,173.99,179.61,178.55,162.75,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.558,ready,standing,170.41,179.37,175.67,161.65,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.923,ready,standing,169.86,177.58,175.15,160.73,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +3.288,ready,standing,163.6,170.26,162.06,177.63,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +3.654,descending,descending,116.1,155.55,116.89,156.36,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.019,descending,bottom,69.18,156.81,67.57,145.92,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.385,bottom,bottom,59.03,129.91,55.62,115.64,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.75,bottom,bottom,87.33,141.46,84.51,131.78,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.115,bottom,ascending,135.47,160.37,128.3,156.13,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.481,bottom,standing,158.91,167.14,148.08,167.56,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.846,bottom,descending,122.92,157.74,120.95,154.43,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.212,bottom,bottom,70.89,134.33,62.77,117.42,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.577,bottom,bottom,54.66,117.91,46.33,96.68,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.942,bottom,ascending,97.54,148.88,93.07,139.0,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +7.308,bottom,standing,167.4,168.74,139.11,157.45,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +7.673,ready,standing,156.06,168.16,133.78,157.85,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +8.038,descending,descending,105.7,147.14,90.23,130.94,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +8.404,descending,bottom,56.47,109.06,41.12,83.38,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +8.769,bottom,bottom,59.08,121.47,52.01,107.26,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +9.135,bottom,standing,154.63,160.57,127.66,147.63,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +9.5,ready,standing,159.98,164.57,135.34,153.75,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +9.865,descending,descending,108.21,141.6,95.6,134.23,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.231,descending,bottom,57.16,102.12,42.35,78.62,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.596,bottom,bottom,71.18,120.05,59.33,99.9,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +10.962,bottom,standing,160.32,158.18,125.93,140.52,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +11.327,ready,standing,166.29,165.44,133.12,150.2,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +11.692,descending,descending,114.67,149.38,94.6,133.03,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +12.058,descending,bottom,60.31,112.39,41.13,83.1,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +12.423,bottom,bottom,67.47,119.6,49.26,92.49,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +12.788,bottom,bottom,72.33,125.46,53.96,108.17,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +13.154,bottom,ascending,120.62,147.03,108.59,140.21,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +13.519,bottom,standing,173.42,163.84,156.13,166.18,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +13.885,ready,standing,179.63,171.16,164.73,178.59,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +14.25,ready,standing,176.29,175.41,173.68,170.76,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +14.615,ready,standing,175.74,178.61,178.41,165.28,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., diff --git a/docs/verification/2026-09-21/baseline/traces/squat_shallow_01.csv b/docs/verification/2026-09-21/baseline/traces/squat_shallow_01.csv new file mode 100644 index 00000000..26dc202f --- /dev/null +++ b/docs/verification/2026-09-21/baseline/traces/squat_shallow_01.csv @@ -0,0 +1,22 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,waiting_for_standing,transition,,142.95,,140.68,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +0.365,waiting_for_standing,descending,,94.68,,95.6,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +0.731,waiting_for_standing,ascending,,107.62,,102.22,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +1.096,waiting_for_standing,ascending,,172.34,,147.05,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +1.462,waiting_for_standing,descending,,156.05,,134.57,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +1.827,waiting_for_standing,descending,,90.0,,82.85,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +2.192,waiting_for_standing,ascending,,112.3,,93.91,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +2.558,waiting_for_standing,ascending,,173.91,,142.83,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +2.923,waiting_for_standing,descending,,146.89,,130.77,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +3.288,waiting_for_standing,descending,,103.78,,97.96,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +3.654,waiting_for_standing,ascending,,155.1,,135.98,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +4.019,ready,standing,,171.04,,156.71,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.385,descending,descending,,133.55,,132.81,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.75,descending,bottom,,101.49,,101.69,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +5.115,ready,standing,,166.25,,144.93,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +5.481,ready,standing,,173.18,,152.47,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +5.846,descending,bottom,,111.18,,106.8,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +6.212,descending,transition,,115.02,,103.65,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +6.577,ready,standing,,175.3,,149.2,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +6.942,ready,standing,,178.86,,164.33,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +7.308,ready,standing,,178.53,,171.71,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., diff --git a/docs/verification/2026-09-21/baseline/traces/squat_side_01.csv b/docs/verification/2026-09-21/baseline/traces/squat_side_01.csv new file mode 100644 index 00000000..501eacb7 --- /dev/null +++ b/docs/verification/2026-09-21/baseline/traces/squat_side_01.csv @@ -0,0 +1,35 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,,178.16,,175.43,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,descending,descending,,147.62,,150.22,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +0.731,descending,bottom,,99.67,,94.25,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +1.096,bottom,bottom,,60.86,,57.58,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +1.462,bottom,bottom,,94.28,,85.96,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +1.827,bottom,standing,,155.64,,134.7,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +2.192,ready,standing,,153.39,,138.5,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +2.558,descending,bottom,,103.31,,94.16,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.923,bottom,bottom,,65.07,,53.31,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +3.288,bottom,bottom,,91.04,,78.46,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +3.654,bottom,standing,,172.54,,132.75,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.019,ready,standing,,166.54,,127.84,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +4.385,descending,bottom,,102.06,,78.68,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.75,bottom,bottom,,57.97,,37.91,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.115,bottom,bottom,,79.25,,60.68,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.481,bottom,standing,,161.84,,118.33,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.846,ready,standing,,158.86,,117.82,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +6.212,descending,bottom,,103.56,,78.59,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +6.577,bottom,bottom,,62.59,,44.12,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.942,bottom,bottom,,79.79,,60.15,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +7.308,bottom,standing,,168.1,,123.23,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +7.673,ready,standing,,176.1,,137.18,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +8.038,ready,standing,,178.39,,147.64,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +8.404,ready,standing,,177.48,,164.17,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +8.769,ready,standing,,179.43,,177.68,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +9.135,ready,standing,,177.92,,174.9,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +9.5,ready,standing,,178.85,,170.98,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +9.865,descending,descending,,132.62,,144.03,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.231,descending,bottom,,77.32,,87.48,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.596,bottom,bottom,,75.5,,81.89,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +10.962,bottom,ascending,,119.98,,117.71,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +11.327,bottom,standing,,175.25,,155.62,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +11.692,ready,standing,,176.81,,167.09,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +12.058,ready,standing,,176.34,,173.82,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., diff --git a/docs/verification/2026-09-21/constrained-result.json b/docs/verification/2026-09-21/constrained-result.json new file mode 100644 index 00000000..49b86ce9 --- /dev/null +++ b/docs/verification/2026-09-21/constrained-result.json @@ -0,0 +1,42 @@ +{ + "passed": true, + "sample_fps": 3.0, + "clips": [ + { + "name": "normal-01", + "video": "samples\\validation\\2026-09-21\\squat_normal_01.mp4", + "passed": true, + "expected_reps": 5, + "actual_reps": 5, + "expected_complete_events": 5, + "actual_complete_events": 5, + "expected_partial_events": 0, + "actual_partial_events": 0, + "mismatches": [] + }, + { + "name": "normal-02", + "video": "samples\\validation\\2026-09-21\\squat_normal_02.mp4", + "passed": true, + "expected_reps": 5, + "actual_reps": 5, + "expected_complete_events": 5, + "actual_complete_events": 5, + "expected_partial_events": 0, + "actual_partial_events": 0, + "mismatches": [] + }, + { + "name": "negative-01", + "video": "samples\\validation\\2026-09-21\\squat_negative_01.mp4", + "passed": true, + "expected_reps": 0, + "actual_reps": 0, + "expected_complete_events": 0, + "actual_complete_events": 0, + "expected_partial_events": 0, + "actual_partial_events": 0, + "mismatches": [] + } + ] +} diff --git a/docs/verification/2026-09-21/final/squat_front_01.json b/docs/verification/2026-09-21/final/squat_front_01.json new file mode 100644 index 00000000..57b00f37 --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_front_01.json @@ -0,0 +1,60 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_front_01.mp4", + "source_fps": 30.105160091526397, + "sample_fps": 3.0, + "sampled_frames": 33, + "usable_frames": 33, + "calibrated_frames": 33, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 1, + "coaching_events": [ + { + "time_sec": 2.923, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 0 + }, + { + "time_sec": 5.115, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 1 + }, + { + "time_sec": 7.673, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 1 + }, + { + "time_sec": 9.5, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 1 + }, + { + "time_sec": 11.327, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 1 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/final/squat_front_01.stderr.log b/docs/verification/2026-09-21/final/squat_front_01.stderr.log new file mode 100644 index 00000000..5ccfe368 --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_front_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789928360.059571 21352 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928360.086527 21352 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928360.107339 15516 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/final/squat_negative_01.json b/docs/verification/2026-09-21/final/squat_negative_01.json new file mode 100644 index 00000000..226f202e --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_negative_01.json @@ -0,0 +1,34 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_negative_01.mp4", + "source_fps": 30.105293939552702, + "sample_fps": 3.0, + "sampled_frames": 61, + "usable_frames": 61, + "calibrated_frames": 61, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 0, + "coaching_events": [], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/final/squat_negative_01.stderr.log b/docs/verification/2026-09-21/final/squat_negative_01.stderr.log new file mode 100644 index 00000000..9d24e01e --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_negative_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789928353.984353 2188 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928354.012926 2188 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928354.033544 960 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/final/squat_normal_01.json b/docs/verification/2026-09-21/final/squat_normal_01.json new file mode 100644 index 00000000..28b77c83 --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_normal_01.json @@ -0,0 +1,60 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_normal_01.mp4", + "source_fps": 30.10519356736308, + "sample_fps": 3.0, + "sampled_frames": 37, + "usable_frames": 37, + "calibrated_frames": 37, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 5, + "coaching_events": [ + { + "time_sec": 4.385, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 1 + }, + { + "time_sec": 6.212, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 2 + }, + { + "time_sec": 8.038, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 3 + }, + { + "time_sec": 9.865, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 4 + }, + { + "time_sec": 12.058, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 5 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/final/squat_normal_01.stderr.log b/docs/verification/2026-09-21/final/squat_normal_01.stderr.log new file mode 100644 index 00000000..8fc777db --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_normal_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789928341.301061 16920 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928341.346429 16920 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928341.367921 18524 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/final/squat_normal_02.json b/docs/verification/2026-09-21/final/squat_normal_02.json new file mode 100644 index 00000000..16234a93 --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_normal_02.json @@ -0,0 +1,60 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_normal_02.mp4", + "source_fps": 30.105212994381937, + "sample_fps": 3.0, + "sampled_frames": 41, + "usable_frames": 41, + "calibrated_frames": 41, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 5, + "coaching_events": [ + { + "time_sec": 5.481, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 1 + }, + { + "time_sec": 7.308, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 2 + }, + { + "time_sec": 9.135, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 3 + }, + { + "time_sec": 10.962, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 4 + }, + { + "time_sec": 13.519, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 5 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/final/squat_normal_02.stderr.log b/docs/verification/2026-09-21/final/squat_normal_02.stderr.log new file mode 100644 index 00000000..ec4f6716 --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_normal_02.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789928346.068412 22200 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928346.098381 27368 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928346.119810 23028 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/final/squat_shallow_01.json b/docs/verification/2026-09-21/final/squat_shallow_01.json new file mode 100644 index 00000000..d897db2b --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_shallow_01.json @@ -0,0 +1,45 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_shallow_01.mp4", + "source_fps": 30.104989463253688, + "sample_fps": 3.0, + "sampled_frames": 21, + "usable_frames": 21, + "calibrated_frames": 10, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 0, + "coaching_events": [ + { + "time_sec": 5.115, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 0 + }, + { + "time_sec": 6.577, + "message": "이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.", + "rep_count": 0 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/final/squat_shallow_01.stderr.log b/docs/verification/2026-09-21/final/squat_shallow_01.stderr.log new file mode 100644 index 00000000..ee73a645 --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_shallow_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789928350.997416 11064 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928351.026306 11064 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928351.046024 13684 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/final/squat_side_01.json b/docs/verification/2026-09-21/final/squat_side_01.json new file mode 100644 index 00000000..10a05be0 --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_side_01.json @@ -0,0 +1,60 @@ +{ + "video": "samples\\validation\\2026-09-21\\squat_side_01.mp4", + "source_fps": 30.105150876158596, + "sample_fps": 3.0, + "sampled_frames": 34, + "usable_frames": 34, + "calibrated_frames": 34, + "valid_frame_ratio": 1.0, + "evaluation_valid": true, + "reps": 5, + "coaching_events": [ + { + "time_sec": 1.827, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 1 + }, + { + "time_sec": 3.654, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 2 + }, + { + "time_sec": 5.481, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 3 + }, + { + "time_sec": 7.308, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 4 + }, + { + "time_sec": 11.327, + "message": "스쿼트 깊이를 확인하고 1회 기록했어요.", + "rep_count": 5 + } + ], + "thresholds": { + "standing_knee": 160.0, + "standing_hip": 160.0, + "bottom_knee": 100.0, + "bottom_hip": 150.0, + "standing_knee_margin": 8.0, + "initial_hip_margin": 10.0, + "bottom_knee_margin": 15.0, + "bottom_dwell_margin": 5.0, + "min_hip_drop": 0.25, + "hip_return_tolerance": 0.3, + "ankle_outlier_grace_sec": 0.7, + "min_active_sec": 0.4, + "standing_confirm_sec": 0.2, + "bottom_confirm_sec": 0.12, + "max_bottom_sec": 8.0, + "max_gap_sec": 1.2, + "smoothing_sec": 0.12, + "visibility": 0.55, + "ankle_tolerance": 0.35, + "phase_velocity": 12.0 + } +} diff --git a/docs/verification/2026-09-21/final/squat_side_01.stderr.log b/docs/verification/2026-09-21/final/squat_side_01.stderr.log new file mode 100644 index 00000000..3552698a --- /dev/null +++ b/docs/verification/2026-09-21/final/squat_side_01.stderr.log @@ -0,0 +1,5 @@ +INFO: Created TensorFlow Lite XNNPACK delegate for CPU. +WARNING: All log messages before absl::InitializeLog() is called are written to STDERR +W0000 00:00:1789928364.234623 24104 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928364.262721 24104 inference_feedback_manager.cc:114] Feedback manager requires a model with a single signature inference. Disabling support for feedback tensors. +W0000 00:00:1789928364.283422 23732 landmark_projection_calculator.cc:186] Using NORM_RECT without IMAGE_DIMENSIONS is only supported for the square ROI. Provide IMAGE_DIMENSIONS or use PROJECTION_MATRIX. diff --git a/docs/verification/2026-09-21/final/traces/squat_front_01.csv b/docs/verification/2026-09-21/final/traces/squat_front_01.csv new file mode 100644 index 00000000..21803c3b --- /dev/null +++ b/docs/verification/2026-09-21/final/traces/squat_front_01.csv @@ -0,0 +1,34 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,179.93,178.57,165.12,164.13,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,ready,standing,179.92,178.76,165.06,164.08,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.731,ready,standing,179.69,178.86,165.0,164.08,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.096,ready,standing,179.71,178.98,165.1,164.06,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.462,ready,standing,176.28,176.47,163.0,162.3,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.827,descending,descending,154.06,149.89,149.76,146.26,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.192,descending,descending,125.22,115.58,119.65,109.8,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.558,descending,ascending,139.77,126.45,139.3,128.92,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.923,ready,standing,164.87,143.58,158.56,148.47,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +3.288,ready,standing,175.93,170.01,163.9,160.94,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +3.654,ready,standing,163.01,161.67,157.19,155.52,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +4.019,descending,bottom,116.37,110.75,118.8,111.63,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.385,bottom,bottom,117.21,108.53,121.76,111.72,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.75,bottom,ascending,139.99,139.85,147.06,143.01,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.115,ready,standing,171.34,171.87,160.79,160.33,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +5.481,ready,standing,178.78,177.83,162.79,162.02,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +5.846,ready,standing,175.95,178.62,164.92,162.06,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +6.212,ready,standing,179.3,179.55,162.98,163.73,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +6.577,ready,standing,162.11,170.34,154.77,155.84,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +6.942,descending,descending,134.53,132.53,121.08,120.48,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +7.308,descending,transition,132.31,129.71,124.16,127.93,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +7.673,ready,standing,158.49,155.7,149.73,154.55,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +8.038,ready,standing,173.91,176.31,158.99,165.24,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +8.404,ready,standing,161.77,166.12,153.89,159.39,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +8.769,descending,descending,118.95,118.9,114.47,119.41,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +9.135,descending,ascending,128.24,122.9,128.08,128.19,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +9.5,ready,standing,160.71,157.43,153.04,153.83,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +9.865,ready,standing,176.04,175.58,160.9,164.15,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +10.231,ready,standing,149.8,154.88,147.47,152.67,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +10.596,descending,bottom,115.09,108.66,112.22,107.89,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.962,descending,ascending,128.7,123.38,133.51,127.98,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +11.327,ready,standing,168.88,168.74,159.28,157.54,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +11.692,ready,standing,178.86,178.8,164.18,163.99,1,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., diff --git a/docs/verification/2026-09-21/final/traces/squat_negative_01.csv b/docs/verification/2026-09-21/final/traces/squat_negative_01.csv new file mode 100644 index 00000000..6810b05a --- /dev/null +++ b/docs/verification/2026-09-21/final/traces/squat_negative_01.csv @@ -0,0 +1,62 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,175.49,179.64,170.03,168.09,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,ready,standing,177.39,177.85,172.58,165.88,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.731,ready,standing,178.33,177.97,174.18,164.97,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.096,ready,standing,177.25,178.4,174.67,164.37,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.462,ready,standing,176.44,179.28,173.83,165.04,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.827,ready,standing,175.99,178.87,173.25,164.86,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.192,ready,standing,176.19,179.25,173.2,165.44,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.558,ready,standing,176.33,171.79,173.77,172.21,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.923,ready,standing,176.9,167.75,179.03,179.24,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +3.288,ready,standing,176.32,177.83,172.16,174.11,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +3.654,ready,standing,173.26,179.63,173.18,172.61,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.019,ready,standing,173.91,179.93,171.58,169.55,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.385,ready,standing,177.63,178.57,171.85,171.32,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.75,ready,standing,174.14,173.44,176.8,174.5,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +5.115,ready,standing,176.66,175.83,175.98,172.37,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +5.481,ready,standing,177.61,176.61,179.27,168.68,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +5.846,ready,standing,178.81,177.8,177.19,168.06,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +6.212,ready,standing,179.26,179.12,175.65,169.63,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +6.577,ready,standing,178.71,170.55,176.6,170.22,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +6.942,ready,standing,178.49,179.34,178.17,170.11,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +7.308,ready,standing,175.76,176.82,175.16,171.59,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +7.673,ready,standing,177.44,176.16,173.78,172.82,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +8.038,ready,standing,177.36,176.61,177.74,173.28,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +8.404,ready,standing,170.06,177.7,175.26,176.78,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +8.769,ready,standing,179.34,179.1,164.7,173.93,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +9.135,ready,standing,177.18,169.19,166.44,177.49,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +9.5,ready,standing,178.75,168.03,169.16,178.76,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +9.865,ready,standing,178.6,170.45,170.23,179.7,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +10.231,ready,standing,178.6,176.64,171.68,178.71,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +10.596,ready,standing,176.68,177.16,168.03,177.98,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +10.962,ready,standing,175.49,175.98,168.52,179.71,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +11.327,ready,standing,177.14,174.72,167.27,173.68,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +11.692,ready,standing,177.77,175.43,167.28,168.75,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +12.058,ready,standing,175.12,177.41,167.56,169.2,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +12.423,ready,standing,167.15,175.97,162.11,162.3,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +12.788,ready,standing,172.66,177.36,166.47,162.47,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +13.154,ready,standing,175.92,179.41,167.31,165.66,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +13.519,ready,standing,177.64,170.21,163.48,163.19,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +13.885,ready,standing,179.16,173.11,162.84,168.96,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +14.25,ready,standing,179.9,173.18,162.48,171.4,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +14.615,ready,standing,179.74,173.39,163.17,171.13,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +14.981,ready,standing,178.89,178.17,162.74,170.26,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +15.346,ready,standing,177.56,179.22,166.09,168.58,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +15.712,ready,standing,178.63,178.53,170.37,166.95,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +16.077,ready,standing,179.26,179.23,168.41,168.58,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +16.442,ready,standing,177.31,173.91,169.17,164.79,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +16.808,ready,standing,179.53,174.25,165.49,165.93,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +17.173,ready,standing,176.47,179.67,167.72,163.82,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +17.538,ready,standing,178.19,176.22,169.17,161.93,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +17.904,ready,standing,172.48,175.55,178.4,166.3,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +18.269,ready,standing,176.98,177.76,179.51,169.89,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +18.635,ready,standing,178.31,170.64,177.29,179.1,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +19.0,ready,standing,178.62,165.37,178.16,174.19,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +19.365,ready,standing,179.05,167.17,176.76,175.77,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +19.731,ready,standing,175.7,176.93,178.53,172.66,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +20.096,ready,standing,171.96,179.69,169.09,166.13,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +20.462,ready,standing,176.92,179.9,164.55,165.68,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +20.827,ready,standing,178.7,174.89,168.94,161.29,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +21.192,ready,standing,169.87,174.98,160.08,175.86,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +21.558,ready,standing,176.19,179.75,165.67,178.66,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +21.923,ready,standing,179.55,179.91,169.0,179.48,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., diff --git a/docs/verification/2026-09-21/final/traces/squat_normal_01.csv b/docs/verification/2026-09-21/final/traces/squat_normal_01.csv new file mode 100644 index 00000000..52bb51c3 --- /dev/null +++ b/docs/verification/2026-09-21/final/traces/squat_normal_01.csv @@ -0,0 +1,38 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,179.66,175.31,164.87,174.11,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,ready,standing,179.42,175.69,165.09,174.48,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.731,ready,standing,179.18,175.8,165.31,174.55,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.096,ready,standing,179.0,175.89,165.57,174.53,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.462,ready,standing,178.87,175.91,165.62,174.52,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.827,ready,standing,178.69,175.89,165.61,174.55,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.192,ready,standing,176.71,178.44,169.25,178.53,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.558,descending,descending,156.11,143.6,159.89,149.42,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.923,descending,bottom,127.99,59.7,131.58,66.55,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +3.288,bottom,bottom,74.13,29.55,72.27,31.82,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +3.654,bottom,bottom,108.19,40.53,109.1,48.95,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.019,bottom,ascending,148.22,148.11,148.88,140.97,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.385,ready,standing,161.53,160.76,165.23,155.73,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +4.75,descending,descending,143.31,120.93,144.07,123.72,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +5.115,descending,bottom,95.0,50.68,87.1,45.26,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +5.481,bottom,bottom,103.05,65.11,93.46,58.35,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.846,bottom,ascending,144.73,120.57,135.87,113.16,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.212,ready,standing,170.5,170.55,164.09,150.84,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +6.577,ready,standing,162.17,143.7,158.05,136.59,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +6.942,descending,bottom,119.83,79.32,108.86,76.17,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +7.308,bottom,bottom,102.25,53.66,84.54,46.76,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +7.673,bottom,ascending,137.14,103.61,124.07,95.66,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +8.038,ready,standing,167.85,174.42,159.23,150.49,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +8.404,ready,standing,169.9,161.86,166.44,149.88,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +8.769,descending,descending,140.97,101.43,128.91,97.38,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +9.135,descending,bottom,96.31,49.45,68.06,40.88,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +9.5,bottom,bottom,97.06,56.08,82.36,54.37,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +9.865,ready,standing,164.43,154.08,147.9,130.63,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +10.231,ready,standing,169.35,159.92,161.53,142.4,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +10.596,descending,descending,145.73,114.82,135.59,109.46,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.962,descending,bottom,89.6,50.74,61.11,39.92,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +11.327,bottom,bottom,97.34,46.88,70.89,38.7,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +11.692,bottom,ascending,138.14,102.7,120.67,96.87,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +12.058,ready,standing,171.39,164.83,157.52,141.2,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +12.423,ready,standing,176.22,168.19,172.5,156.24,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +12.788,ready,standing,179.05,176.81,178.48,164.28,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +13.154,ready,standing,179.24,179.45,171.36,173.46,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., diff --git a/docs/verification/2026-09-21/final/traces/squat_normal_02.csv b/docs/verification/2026-09-21/final/traces/squat_normal_02.csv new file mode 100644 index 00000000..2daaa9da --- /dev/null +++ b/docs/verification/2026-09-21/final/traces/squat_normal_02.csv @@ -0,0 +1,42 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,,177.15,,173.01,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,ready,standing,,177.09,,173.66,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.731,ready,standing,,176.95,,174.06,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.096,ready,standing,,173.75,,177.96,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.462,ready,standing,,175.77,,162.53,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +1.827,ready,standing,176.8,173.26,177.7,161.05,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.192,ready,standing,173.99,179.61,178.55,162.75,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.558,ready,standing,170.41,179.37,175.67,161.65,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +2.923,ready,standing,169.86,177.58,175.15,160.73,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +3.288,ready,standing,163.6,170.26,162.06,177.63,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +3.654,descending,descending,116.1,155.55,116.89,156.36,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.019,descending,bottom,69.18,156.81,67.57,145.92,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.385,bottom,bottom,59.03,129.91,55.62,115.64,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +4.75,bottom,bottom,87.33,141.46,84.51,131.78,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.115,bottom,ascending,135.47,160.37,128.3,156.13,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.481,ready,standing,158.91,167.14,148.08,167.56,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +5.846,descending,descending,122.92,157.74,120.95,154.43,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +6.212,descending,bottom,70.89,134.33,62.77,117.42,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +6.577,bottom,bottom,54.66,117.91,46.33,96.68,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.942,bottom,ascending,97.54,148.88,93.07,139.0,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +7.308,ready,standing,167.4,168.74,139.11,157.45,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +7.673,ready,standing,156.06,168.16,133.78,157.85,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +8.038,descending,descending,105.7,147.14,90.23,130.94,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +8.404,descending,bottom,56.47,109.06,41.12,83.38,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +8.769,bottom,bottom,59.08,121.47,52.01,107.26,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +9.135,ready,standing,154.63,160.57,127.66,147.63,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +9.5,ready,standing,159.98,164.57,135.34,153.75,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +9.865,descending,descending,108.21,141.6,95.6,134.23,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.231,descending,bottom,57.16,102.12,42.35,78.62,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.596,bottom,bottom,71.18,120.05,59.33,99.9,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +10.962,ready,standing,160.32,158.18,125.93,140.52,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +11.327,ready,standing,166.29,165.44,133.12,150.2,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +11.692,descending,descending,114.67,149.38,94.6,133.03,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +12.058,descending,bottom,60.31,112.39,41.13,83.1,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +12.423,bottom,bottom,67.47,119.6,49.26,92.49,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +12.788,bottom,bottom,72.33,125.46,53.96,108.17,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +13.154,bottom,ascending,120.62,147.03,108.59,140.21,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +13.519,ready,standing,173.42,163.84,156.13,166.18,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +13.885,ready,standing,179.63,171.16,164.73,178.59,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +14.25,ready,standing,176.29,175.41,173.68,170.76,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +14.615,ready,standing,175.74,178.61,178.41,165.28,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., diff --git a/docs/verification/2026-09-21/final/traces/squat_shallow_01.csv b/docs/verification/2026-09-21/final/traces/squat_shallow_01.csv new file mode 100644 index 00000000..26dc202f --- /dev/null +++ b/docs/verification/2026-09-21/final/traces/squat_shallow_01.csv @@ -0,0 +1,22 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,waiting_for_standing,transition,,142.95,,140.68,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +0.365,waiting_for_standing,descending,,94.68,,95.6,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +0.731,waiting_for_standing,ascending,,107.62,,102.22,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +1.096,waiting_for_standing,ascending,,172.34,,147.05,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +1.462,waiting_for_standing,descending,,156.05,,134.57,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +1.827,waiting_for_standing,descending,,90.0,,82.85,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +2.192,waiting_for_standing,ascending,,112.3,,93.91,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +2.558,waiting_for_standing,ascending,,173.91,,142.83,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +2.923,waiting_for_standing,descending,,146.89,,130.77,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +3.288,waiting_for_standing,descending,,103.78,,97.96,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +3.654,waiting_for_standing,ascending,,155.1,,135.98,0,정면 기준 45도에서 머리부터 발목까지 보이도록 똑바로 서주세요., +4.019,ready,standing,,171.04,,156.71,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.385,descending,descending,,133.55,,132.81,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.75,descending,bottom,,101.49,,101.69,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +5.115,ready,standing,,166.25,,144.93,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +5.481,ready,standing,,173.18,,152.47,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +5.846,descending,bottom,,111.18,,106.8,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +6.212,descending,transition,,115.02,,103.65,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +6.577,ready,standing,,175.3,,149.2,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요.,이번 동작에서 충분히 내려간 장면을 확인하지 못했어요. +6.942,ready,standing,,178.86,,164.33,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., +7.308,ready,standing,,178.53,,171.71,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요., diff --git a/docs/verification/2026-09-21/final/traces/squat_side_01.csv b/docs/verification/2026-09-21/final/traces/squat_side_01.csv new file mode 100644 index 00000000..0e58e47a --- /dev/null +++ b/docs/verification/2026-09-21/final/traces/squat_side_01.csv @@ -0,0 +1,35 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,ready,standing,,178.16,,175.43,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +0.365,descending,descending,,147.62,,150.22,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +0.731,descending,bottom,,99.67,,94.25,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +1.096,bottom,bottom,,60.86,,57.58,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +1.462,bottom,bottom,,94.28,,85.96,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +1.827,ready,standing,,155.64,,134.7,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +2.192,ready,standing,,153.39,,138.5,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +2.558,descending,descending,,103.31,,94.16,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +2.923,descending,bottom,,65.07,,53.31,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +3.288,bottom,bottom,,91.04,,78.46,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +3.654,ready,standing,,172.54,,132.75,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +4.019,ready,standing,,166.54,,127.84,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +4.385,descending,bottom,,102.06,,78.68,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.75,bottom,bottom,,57.97,,37.91,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.115,bottom,bottom,,79.25,,60.68,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.481,ready,standing,,161.84,,118.33,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +5.846,ready,standing,,158.86,,117.82,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +6.212,descending,bottom,,103.56,,78.59,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +6.577,bottom,bottom,,62.59,,44.12,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.942,bottom,bottom,,79.79,,60.15,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +7.308,ready,standing,,168.1,,123.23,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +7.673,ready,standing,,176.1,,137.18,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +8.038,ready,standing,,178.39,,147.64,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +8.404,ready,standing,,177.48,,164.17,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +8.769,ready,standing,,179.43,,177.68,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +9.135,ready,standing,,177.92,,174.9,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +9.5,ready,standing,,178.85,,170.98,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +9.865,descending,descending,,132.62,,144.03,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.231,descending,bottom,,77.32,,87.48,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.596,bottom,bottom,,75.5,,81.89,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +10.962,bottom,ascending,,119.98,,117.71,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +11.327,ready,standing,,175.25,,155.62,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +11.692,ready,standing,,176.81,,167.09,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +12.058,ready,standing,,176.34,,173.82,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., diff --git a/docs/verification/2026-09-21/manifest.json b/docs/verification/2026-09-21/manifest.json new file mode 100644 index 00000000..b13bf131 --- /dev/null +++ b/docs/verification/2026-09-21/manifest.json @@ -0,0 +1,26 @@ +{ + "sample_fps": 3.0, + "clips": [ + { + "name": "normal-01", + "video": "samples/validation/2026-09-21/squat_normal_01.mp4", + "expected_reps": 5, + "expected_complete_events": 5, + "expected_partial_events": 0 + }, + { + "name": "normal-02", + "video": "samples/validation/2026-09-21/squat_normal_02.mp4", + "expected_reps": 5, + "expected_complete_events": 5, + "expected_partial_events": 0 + }, + { + "name": "negative-01", + "video": "samples/validation/2026-09-21/squat_negative_01.mp4", + "expected_reps": 0, + "expected_complete_events": 0, + "expected_partial_events": 0 + } + ] +} diff --git a/docs/verification/aihub-crossfit-squat-2026-09-18.md b/docs/verification/aihub-crossfit-squat-2026-09-18.md new file mode 100644 index 00000000..e187f65b --- /dev/null +++ b/docs/verification/aihub-crossfit-squat-2026-09-18.md @@ -0,0 +1,78 @@ +# AI Hub 크로스핏 에어 스쿼트 검증 (2026-09-18) + +## 자료와 판정 범위 + +사용자가 내려받은 `Downloads/Sample`에는 **고관절 오류 에어 스쿼트 한 동작을 같은 시각에 찍은 8개 카메라 영상**과 카메라별 2D 관절 CSV·동작 구간 JSON이 있다. 영상은 각각 214프레임, 1920×1080, 30fps다. JSON에는 카메라마다 동일한 동작 구간 1개(53~201프레임, 약 1.77~6.70초)가 있다. 시작·하단·끝 영상 프레임과 관절 좌표 변화로 이 샘플의 앉았다 일어나는 **1주기**를 확인했다. 카메라 8개는 독립적인 8명이나 8회 동작이 아니다. + +`Downloads/213.크로스핏 동작 데이터/.../TL.zip`은 학습용 **라벨만** 들어 있다. 에어 스쿼트 카테고리의 카메라별 관절 CSV·JSON 2,888쌍은 촬영 361건의 8시점이다. 각 JSON에 동작 구간은 1개다. ZIP에는 대응 원천 영상이 없어 전체 361건에 대한 MediaPipe 인식은 검증할 수 없다. 콘솔 인코딩에 따라 한국어 카테고리명이 깨져 보일 수 있으므로, 분류 시에는 JSON의 원래 Unicode 문자열을 사용한다. + +현재 제품 기본값인 **3fps**, 관절 가시성 **0.55**와 `SquatCounter`를 사용했다. 샘플 영상은 `diagnose_squat_tracking.py`로 MediaPipe → 카운터 전체 경로를 재생했다. 별도로 AI Hub 2D CSV의 좌표를 MediaPipe 관절 번호에 맞춰 카운터에 직접 넣어 탐지기와 카운터 문제를 분리했다. 후자는 가시성 정보가 없어 모든 입력 관절의 가시성을 1로 두므로 실제 영상 경로와 동등하지 않다. + +## 샘플 영상 8시점 + +| 카메라 | 영상의 사용 가능 프레임 | 영상 품질 기준 | 영상 검출 횟수 | 라벨 좌표 직접 입력 횟수 | +|---|---:|---|---:|---:| +| 0 | 22/22 | 통과 | 1 | 1 | +| 1 | 22/22 | 통과 | 0 | 0 | +| 2 | 22/22 | 통과 | 1 | 1 | +| 3 | 0/22 | 미달 | 0 | 0 | +| 4 | 22/22 | 통과 | 1 | 1 | +| 5 | 8/22 | 미달 | 0 | 1 | +| 6 | 19/22 | 통과 | 0 | 1 | +| 7 | 0/22 | 미달 | 0 | 0 | + +한 동작의 **8시점 중 5시점이 추적 품질 기준을 통과했고 3시점에서 1회가 검출**됐다. 라벨 좌표만 직접 넣어도 5시점만 1회를 냈다. 카메라 3·7은 측면에서 가려진 한쪽 무릎 또는 발목의 가시성이 22프레임 모두 기준에 못 미쳤다. 카메라 5는 사람이 작게 보여 7프레임에서 자세를 아예 못 찾았고, 7프레임에서 관절 가시성이 부족했다. 카메라 6은 19프레임을 사용할 수 있었지만 동작 중 가시성 손실로 하단 상태가 초기화돼 0회가 됐다. 라벨 좌표로 재생한 카메라 1·3·7의 0회는 발 위치 변화 조건에 따른 상태 초기화가 포함된다. + +샘플에는 **고관절 오류** 라벨이 붙어 있다. 사람 눈으로 본 한 주기와 제품에서 세어야 할 유효 횟수가 같은지는 제품의 정의에 따라 달라질 수 있으므로, 위 표는 시점별 동작 감지와 누락 원인 분석으로 해석한다. + +따라서 기존 저장소 영상의 `1/7`은 데이터 전체의 성능이 아니라 특정 촬영 영상과 품질 조건의 결과였다. 새 스튜디오 샘플에서도 각도에 따라 추적률과 카운트가 크게 달라진다. + +## 전체 학습 라벨의 카운터 단독 검사 + +`scripts/evaluate_aihub_keypoints.py`로 ZIP을 풀지 않고 에어 스쿼트 CSV 2,888개를 모두 3fps로 재생했다. 누락·읽기 오류는 없었다. + +| 결과 | 카메라 시점 수 | +|---|---:| +| 1회 출력 | 2,012 / 2,888 (69.7%) | +| 0회 출력 | 876 / 2,888 (30.3%) | + +촬영 건을 기준으로 보면 361건 중 **92건은 8시점 모두 1회**, **27건은 8시점 모두 0회**였다. 카메라별 1회 출력은 `camera1` 105/361(29.1%)부터 `camera7` 307/361(85.0%)까지 차이가 났다. 이는 각도와 촬영 조건에 현재 카운터가 민감하다는 근거다. + +**69.7%는 정확도나 재현율이 아니다.** JSON은 동작 구간의 시작·끝과 자세 오류 종류를 표시하지만, 모든 영상의 사람 기준 반복 횟수를 별도 필드로 보증하지 않는다. 더욱이 이 자료는 `Training` 라벨이고, 영상·앱 카메라·MediaPipe 가시성 손실을 거치지 않았다. 성능 평가에 쓰려면 촬영 건 단위로 독립적인 검증/시험 자료를 분리하고, 실제 반복 횟수를 확인해야 한다. + +## 다음 검증 조건 + +### 한쪽 다리 가시성 개선 후 재검사 + +측면 영상의 먼쪽 다리가 가려지는 문제를 줄이려고 `SquatCounter`가 **어깨·골반·무릎·발목이 연결된 한쪽 다리**만 보여도 해당 다리 각도로 분석하도록 바꿨다. 양쪽이 보일 때는 기존 평균을 사용하고, 진행 중 추적 대상 다리가 완전히 바뀌면 그 주기를 버린다. 각도·시간·가시성 임계값과 발 이동 기준은 그대로 뒀다. + +같은 샘플 AVI를 3fps에서 MediaPipe부터 다시 재생한 결과는 아래와 같다. 8시점은 한 촬영을 동시에 본 것이므로 독립 표본 8개가 아니다. + +| 카메라 | 수정 전 사용 가능 프레임 / 검출 | 수정 후 사용 가능 프레임 / 검출 | +|---|---:|---:| +| 0 | 22/22 · 1회 | 22/22 · 1회 | +| 1 | 22/22 · 0회 | 22/22 · 0회 | +| 2 | 22/22 · 1회 | 22/22 · 1회 | +| 3 | 0/22 · 0회 | 22/22 · 1회 | +| 4 | 22/22 · 1회 | 22/22 · 1회 | +| 5 | 8/22 · 0회 | 10/22 · 0회 | +| 6 | 19/22 · 0회 | 22/22 · 1회 | +| 7 | 0/22 · 0회 | 22/22 · 1회 | + +샘플은 **3/8시점에서 6/8시점으로** 1회 검출이 늘었다. 샘플 원본에 고관절 오류 라벨이 붙어 있고 시점도 서로 종속되어 있으므로 이 비율을 정확도나 정상 자세 승인률로 해석하지 않는다. 카메라 1은 여전히 0회이며, 5는 인물 검출 자체가 불안정하다. + +학습 라벨 2,888쌍을 같은 조건으로 다시 재생했을 때는 **2,012쌍에서 1회**로 수정 전과 동일했다. 이 CSV에는 관절 가시성 정보가 없어 이번 변경을 평가할 수 없다. + +1. 스쿼트는 사람 기준 완료 횟수가 확정된 영상을 받아 실제 앱 입력 조건에서 다시 평가한다. 특히 발 위치 변화 조건과 양쪽 평균 각도의 누락·오검출을 분리 비교한다. +2. AI Hub 샘플의 한 동작만으로 기준값을 조정하지 않는다. 정상·오류·다른 촬영자를 분리한 영상과 정답을 확보한 뒤 수정 전후 누락·오검출을 비교한다. +3. 이번 자료에는 전방 런지가 없어 런지 실영상 검증에는 사용할 수 없다. + +원본 영상·CSV·JSON은 다운로드 폴더에서 읽기 전용으로 사용했고 저장소에는 복사하지 않았다. 데이터 구조는 [AI Hub 크로스핏 동작 데이터](https://www.aihub.or.kr/aihubdata/data/view.do?dataSetSn=71422)에 공개되어 있다. + +## 횟수 판정 보정 후 재검사 + +위의 6/8과 2,012/2,888은 한쪽 다리 가시성 개선 단계의 기록이다. 서기 각도에 여유를 두고 골반 하강을 추가로 확인하며, 준비 자세에서 발 기준점을 갱신하도록 보정한 현재 카운터는 샘플 8시점 중 `camera0`, `camera1`, `camera2`, `camera3`, `camera4`, `camera6`, `camera7`에서 1회, `camera5`에서 0회를 검출한다. 따라서 **7/8시점**이 1회를 출력한다. 모두 같은 한 동작을 본 시점이며, `camera5`는 관절 추적 자체가 불안정하다. + +에어 스쿼트 학습용 2D 좌표 2,888시점의 재생 결과는 **1회 출력 2,398개, 0회 출력 490개**다. 촬영 361건 중 157건은 8시점 모두 1회를, 14건은 8시점 모두 0회를 출력했다. 이 결과는 동작 구간 라벨을 이용한 카운터 동작 확인일 뿐, 사람 기준 반복 횟수 정확도가 아니다. 이 좌표에는 MediaPipe 가시성 점수도 없다. + +다른 종목의 같은 형식 2D 좌표를 넣으면 스쿼트가 아닌 동작도 세는 현상이 있다. 선택 순서상 첫 `camera0` 정상 데드리프트 30건은 모두 2회를 출력했다. 2D 골반·무릎 궤적만으로 운동 종목을 구분하지 못하므로, 실제 제품에서 다른 동작이 얼마나 오검출되는지는 별도 영상과 정답으로 검증해야 한다. 현재 값을 종목 분류 정확도나 실사용 횟수 정확도로 표현하지 않는다. diff --git a/docs/verification/constrained-squat-feedback-demo.md b/docs/verification/constrained-squat-feedback-demo.md new file mode 100644 index 00000000..e6659c7c --- /dev/null +++ b/docs/verification/constrained-squat-feedback-demo.md @@ -0,0 +1,77 @@ +# 고정 촬영 조건 스쿼트 피드백 시연 기준 + +작성: 2026-09-18. 목표는 **고정된 촬영 조건과 미리 정한 시험 영상**에서의 동작·피드백 일치다. 모든 장소와 사람에 대한 자세 판정 정확도를 뜻하지 않는다. + +## 촬영 조건 + +- 한 사람, 한 카메라 위치, 45도 정면 방향. 카메라를 고정하고 머리부터 발목까지 여백을 두고 담는다. +- 조명이 충분하고 무릎·골반·발목을 가리는 랙이나 기구가 없다. 영상 중 카메라와 발 위치를 옮기지 않는다. +- 매 영상의 앞뒤에 서 있는 자세를 2초 이상 담는다. 화면 속 몸 방향과 카메라 위치를 영상마다 같게 유지한다. +- 앱 기본 분석 속도인 3fps로 평가한다. 이 조건을 못 채운 프레임은 횟수·자세의 정답으로 취급하지 않고 촬영 안내를 표시한다. + +## 현재 구현한 화면 안내 + +- 깊은 자세까지 추적한 뒤 다시 서면 `스쿼트 깊이를 확인하고 1회 기록했어요.`를 한 번 보낸다. +- 골반은 내려갔지만 카운터가 하단 자세를 확인하지 못한 채 다시 서면 횟수를 늘리지 않고 `이번 동작에서 충분히 내려간 장면을 확인하지 못했어요.`를 한 번 보낸다. 이 문장은 **관찰 결과**이며, 운동자가 실제로 얕게 했다고 단정하지 않는다. +- 관절이 가려지면 기존 `LOW_VISIBILITY` 촬영 안내를 사용한다. 상체 기울기를 `등 굽음`이나 부상 위험으로 해석하는 피드백은 이번 시연의 성공 조건에 포함하지 않는다. + +이 피드백은 논문의 각도 기반 주기 판정에서 출발하지만, 골반 하강 여유값과 문구는 구현 선택이다. 임상적으로 검증된 자세 평가나 운동 종목 자동 분류가 아니다. + +## 100% 합격의 뜻 + +촬영 전에 시험 영상 5개를 정한다: 정상 스쿼트 5회씩 3개, 일부러 깊이만 줄인 동작 5회 1개, 서 있거나 가볍게 자세만 바꾸는 20초 영상 1개. 각 동작의 **완료 또는 되돌아온 시각**과 `정상/깊이 미확인`을 사람이 기록한다. 첫 두 영상으로 촬영 조건만 점검한 뒤, 남은 영상으로 최종 평가한다. 판정값을 최종 영상에 맞춰 바꾸면 그 영상을 다시 독립 검증 자료라고 부르지 않는다. + +합격은 분석 가능한 최종 영상에서 사람 라벨과 카운트·피드백 종류·발생 시각이 모두 일치하고, 추가 횟수나 추가 피드백이 0개이며, 앱 화면에 안내가 실제로 나타나는 경우다. `scripts/evaluate_squat.py --trace`의 `coaching_event` 열과 JSON의 `coaching_events`에서 이벤트 시각을 확인할 수 있다. 한 건이라도 다르면 100%라고 보고하지 않고 어떤 시점에서 누락 또는 오검출됐는지 기록한다. + +현재 저장소 영상에서는 45도 정면·후면의 수동 횟수 2회씩은 모두 검출했지만, ROI 영상은 사용자가 센 7회 중 완결된 5회만 검출했다. ROI 영상은 첫 프레임부터 이미 앉는 중이고 마지막 기립 직후 끝나므로, 이 문서가 정한 앞뒤 2초 선 자세 조건을 충족하지 않는다. 따라서 **현재는 새 시험 영상에서의 100% 합격을 주장하지 않는다.** 촬영 조건이 정해진 새 영상이 필요하다. + +## 현재 확인 결과 + +2026-09-18에 원본 영상에서 MediaPipe부터 다시 처리했다. 45도 정면은 22/22 프레임 사용 가능·2회·완료 안내 2건, 45도 후면은 23/25 프레임 사용 가능·2회·완료 안내 2건, ROI는 54/54 프레임 사용 가능·5회·완료 안내 5건이었다. 얕은 동작 안내 1건과 정상 동작 완료 안내 1건의 단발성은 합성 궤적 및 HTTP 응답 테스트로 확인했다. + +2026-09-19에는 별도 MySQL·Spring·AI Docker 스택에서 회원가입부터 리포트까지 실제 API 경로를 실행했다. + +| 영상 | 사람 라벨 | API 횟수 | 완료 안내 | 리포트 저장 | 결과 | +|---|---:|---:|---:|---:|---| +| 45도 정면 | 2 | 2 | 2 | 2 | 통과 | +| 45도 후면 | 2 | 2 | 2 | 2 | 통과 | +| ROI | 7 | 5 | 5 | 5 | 촬영 규약 미충족 | + +ROI 추적표를 보면 0초의 무릎 각도가 약 120도로 이미 동작 중이고, 마지막에는 선 자세 표본이 한 장뿐이라 0.2초 복귀 확인을 할 수 없다. [첫 프레임](screenshots/roi-first-frame.jpg), [마지막 프레임](screenshots/roi-last-frame.jpg), [54개 표본 추적표](roi-squat-trace.csv)를 근거로 남겼다. 가운데 완결된 5회는 API와 리포트가 모두 5회로 일치했다. 이 결과는 촬영 앞뒤의 선 자세가 단순 권장사항이 아니라 판정 가능한 동작 경계를 만드는 조건임을 보여준다. + +검사 프로그램이 중간 실패해도 세션 종료를 재시도하도록 고쳤고, 실패 세션 3개를 연속으로 만든 뒤 같은 AI 작업자에서 정상 영상 2회를 다시 처리해 통과했다. AI 검출기 풀이 찼을 때도 시작 성공처럼 남지 않고 백엔드가 실패 상태로 전환되는 것을 4개 동시 세션으로 확인했다. AI 테스트는 `test_camera.py` 제외 **200 passed, 61 subtests passed**, 백엔드는 Docker JDK 21에서 **857 tests, 0 failures, 0 errors, 17 skipped**, 프런트 TypeScript 검사와 Expo 웹 export는 통과했다. 실제 휴대전화 카메라 화면의 토스트와 새 시험 영상 5개는 아직 확인이 필요하다. + +## 2026-09-21 갱신: 새 시험 영상 검증과 기립 확인 지연 수정 + +`squat_normal_01.mp4`·`squat_normal_02.mp4`·`squat_shallow_01.mp4`·`squat_negative_01.mp4`·`squat_front_01.mp4`·`squat_side_01.mp4` 6개를 받아 사람이 먼저 눈으로 확인(프레임 단위 캡처, 파일명이나 AI 결과에 의존하지 않음)한 뒤 `evaluate_squat.py`로 평가했다. 상세 방법·영상별 사람 판정·실패 원인·수정 내역은 [2026-09-21 검증 보고서](2026-09-21-verification-report.md)에 있다. 요약: + +- `squat_normal_01.mp4`·`squat_normal_02.mp4`는 실제로 각 5회씩 정상 깊이 반복이었지만(눈으로만 본 1차 확인은 각각 4회·3회로 과소 판정 — 원본 각도 추적표로 정정), 정점에서 짧게만 서는 반복이 있어 기존 코드는 4회로 과소 계상했다. 원인은 기립 확인 지연(0.2초)이 3fps 표본 간격(약 0.33~0.4초)보다 짧아, 두 번째 표본이 오기 전에 확정할 방법이 없었기 때문이다. `squat_counter.py`의 기립 확인 로직을 표본 간격을 고려하도록 고친 뒤 두 영상 모두 5회로 정확히 일치했다 (근거: [수정 전](../2026-09-21/baseline/) / [수정 후](../2026-09-21/final/) trace). +- `squat_negative_01.mp4`는 22.26초 내내 스쿼트 없음을 확인했고 AI도 0회·오검출 0건으로 일치했다. +- `squat_shallow_01.mp4`는 촬영 규약(시작 2초 정지 자세)을 지키지 않아 사람이 본 5회 중 3회가 준비 자세 계산 완료 전에 일어나 AI가 아예 평가하지 못했고, 나머지 2회는 원본 각도상 경계선에 걸쳐 있어 완료로 계상하지 않는 것이 보수적으로 맞다고 판단했다. 깨끗한 얕은 동작 기각 시연을 위해서는 재촬영이 필요하다. +- `squat_front_01.mp4`(순수 정면, 협의된 45도 아님)는 사람이 5회 모두 확인했지만 3fps 표본이 실제 최저점을 자주 놓쳐 AI는 1회만 확정했다 — 확인 지연이 아니라 표본화 자체의 한계로, 이번에는 임계값을 낮추지 않고 한계로만 기록했다. +- `squat_side_01.mp4`(순수 측면, 협의된 45도 아님)는 1차 눈 검증에서 상체가 계속 앞으로 숙여져 있어 "반복 아님"으로 오판했으나, 원본 무릎 각도 추적표를 보면 무릎은 매 주기 55~178도 사이를 오가는 진짜 5회 반복이었다. 상체 숙임이 심한 자세 자체는 코칭 품질 관점에서 별도로 기록해 둔다. + +수정 후 `normal_01`·`normal_02`는 이번 수정을 진단하는 데 쓴 영상이라 최종 홀드아웃으로 다시 쓰지 않는다(검증 유출). `negative_01`만 독립적인 최종 홀드아웃으로 인정한다. 45도 각도의 새 정상/얕은 영상 재촬영이 더 필요하다. + +## 촬영자가 가져올 자료 + +아래 파일명으로 찍으면 결과를 바로 대조할 수 있다. + +1. `squat_normal_01.mp4` — 정상 깊이 5회 +2. `squat_normal_02.mp4` — 정상 깊이 5회 +3. `squat_normal_03.mp4` — 정상 깊이 5회 +4. `squat_shallow_01.mp4` — 의도적으로 깊이를 줄인 동작 5회 +5. `squat_negative_01.mp4` — 20초간 서 있기와 가벼운 자세 변경, 스쿼트 0회 + +각 파일과 함께 실제 횟수, 얕게 수행한 동작의 완료 시각만 적는다. 프레임 번호는 나중에 자동으로 계산할 수 있으므로 사용자가 직접 매길 필요가 없다. 최종 세 영상은 임계값을 고친 뒤 재사용하지 않고 그대로 합격/불합격을 판정한다. + +영상 파일을 `samples/validation`에 둔 뒤 [검증 명세 예시](constrained-squat-manifest.example.json)의 파일명과 기대값을 확인하고 아래 명령을 실행한다. + +```powershell +$env:PYTHONPATH=(Resolve-Path 'ai-server').Path +ai-server/.venv/Scripts/python.exe ai-server/scripts/evaluate_constrained_squat_set.py ` + docs/verification/constrained-squat-manifest.example.json ` + --output docs/verification/constrained-squat-result.json +``` + +이 명령은 각 영상의 횟수, 완료 안내 수, 깊이 미확인 안내 수를 한꺼번에 비교하고 하나라도 다르면 종료 코드 1을 반환한다. 현재 저장소의 완결된 주기만 넣은 연기 시험 결과는 [3/3 통과](existing-squat-smoke-result.json)다. 최종 합격 때는 이 자동 결과와 프레임별 이벤트 시각을 함께 확인한다. diff --git a/docs/verification/constrained-squat-manifest.example.json b/docs/verification/constrained-squat-manifest.example.json new file mode 100644 index 00000000..e40c3c76 --- /dev/null +++ b/docs/verification/constrained-squat-manifest.example.json @@ -0,0 +1,40 @@ +{ + "sample_fps": 3.0, + "clips": [ + { + "name": "normal-01", + "video": "samples/validation/squat_normal_01.mp4", + "expected_reps": 5, + "expected_complete_events": 5, + "expected_partial_events": 0 + }, + { + "name": "normal-02", + "video": "samples/validation/squat_normal_02.mp4", + "expected_reps": 5, + "expected_complete_events": 5, + "expected_partial_events": 0 + }, + { + "name": "normal-03", + "video": "samples/validation/squat_normal_03.mp4", + "expected_reps": 5, + "expected_complete_events": 5, + "expected_partial_events": 0 + }, + { + "name": "shallow-01", + "video": "samples/validation/squat_shallow_01.mp4", + "expected_reps": 0, + "expected_complete_events": 0, + "expected_partial_events": 5 + }, + { + "name": "negative-01", + "video": "samples/validation/squat_negative_01.mp4", + "expected_reps": 0, + "expected_complete_events": 0, + "expected_partial_events": 0 + } + ] +} diff --git a/docs/verification/existing-squat-smoke-result.json b/docs/verification/existing-squat-smoke-result.json new file mode 100644 index 00000000..e8b9a1e4 --- /dev/null +++ b/docs/verification/existing-squat-smoke-result.json @@ -0,0 +1,42 @@ +{ + "passed": true, + "sample_fps": 3.0, + "clips": [ + { + "name": "front", + "video": "samples\\raw\\kkw_45-degree_frontview_squat.mp4", + "passed": true, + "expected_reps": 2, + "actual_reps": 2, + "expected_complete_events": 2, + "actual_complete_events": 2, + "expected_partial_events": 0, + "actual_partial_events": 0, + "mismatches": [] + }, + { + "name": "back", + "video": "samples\\raw\\kkw_45-degree_backview_squat.mp4", + "passed": true, + "expected_reps": 2, + "actual_reps": 2, + "expected_complete_events": 2, + "actual_complete_events": 2, + "expected_partial_events": 0, + "actual_partial_events": 0, + "mismatches": [] + }, + { + "name": "roi-complete-cycles", + "video": "samples\\raw\\sqaut_roi_0509.mp4", + "passed": true, + "expected_reps": 5, + "actual_reps": 5, + "expected_complete_events": 5, + "actual_complete_events": 5, + "expected_partial_events": 0, + "actual_partial_events": 0, + "mismatches": [] + } + ] +} diff --git a/docs/verification/roi-squat-trace.csv b/docs/verification/roi-squat-trace.csv new file mode 100644 index 00000000..9070c693 --- /dev/null +++ b/docs/verification/roi-squat-trace.csv @@ -0,0 +1,55 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance,coaching_event +0.0,waiting_for_standing,transition,119.85,,110.17,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +0.366,waiting_for_standing,descending,86.21,,73.53,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +0.732,waiting_for_standing,descending,58.98,,47.91,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +1.099,waiting_for_standing,transition,57.85,,45.66,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +1.465,waiting_for_standing,transition,59.58,,44.76,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +1.831,waiting_for_standing,transition,55.78,,38.71,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +2.197,waiting_for_standing,transition,52.05,,35.83,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +2.564,waiting_for_standing,ascending,61.82,,47.99,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +2.93,waiting_for_standing,ascending,102.83,,94.37,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +3.296,waiting_for_standing,ascending,162.39,,148.14,,0,측면에서 몸 전체와 한쪽 다리가 보이도록 똑바로 서주세요., +3.662,ready,standing,173.08,,161.43,,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.029,ready,standing,156.74,,149.2,,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요., +4.395,descending,descending,124.07,,129.26,,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +4.761,descending,bottom,85.48,,87.03,,0,편안한 범위에서 무릎과 고관절을 굽혀주세요., +5.127,bottom,bottom,65.17,,62.87,,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.493,bottom,bottom,68.64,,63.25,,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +5.86,bottom,bottom,77.22,,71.5,,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.226,bottom,ascending,120.19,,119.25,,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.592,bottom,standing,167.2,,158.26,,0,굽힘을 확인했습니다. 다시 똑바로 서주세요., +6.958,ready,standing,161.84,,156.34,,1,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +7.325,descending,descending,127.82,,132.1,,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +7.691,descending,bottom,82.95,,82.76,,1,편안한 범위에서 무릎과 고관절을 굽혀주세요., +8.057,bottom,bottom,54.94,,50.07,,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +8.423,bottom,bottom,57.51,,52.48,,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +8.789,bottom,bottom,86.54,,82.84,,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +9.156,bottom,ascending,129.43,,122.16,,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +9.522,bottom,standing,167.32,,156.73,,1,굽힘을 확인했습니다. 다시 똑바로 서주세요., +9.888,ready,standing,153.98,,148.68,,2,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +10.254,descending,bottom,108.57,,111.25,,2,편안한 범위에서 무릎과 고관절을 굽혀주세요., +10.621,bottom,bottom,69.1,,63.72,,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +10.987,bottom,bottom,55.37,,48.39,,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +11.353,bottom,bottom,65.15,,61.02,,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +11.719,bottom,ascending,123.51,,120.09,,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +12.086,bottom,standing,162.7,,154.03,,2,굽힘을 확인했습니다. 다시 똑바로 서주세요., +12.452,ready,standing,155.63,,146.04,,3,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +12.818,descending,bottom,100.32,,98.96,,3,편안한 범위에서 무릎과 고관절을 굽혀주세요., +13.184,bottom,bottom,63.13,,57.14,,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +13.55,bottom,bottom,72.19,,64.93,,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +13.917,bottom,ascending,105.27,,99.35,,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +14.283,bottom,standing,156.07,,140.73,,3,굽힘을 확인했습니다. 다시 똑바로 서주세요., +14.649,ready,standing,172.62,,166.42,,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +15.015,ready,standing,176.18,,165.61,,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +15.382,ready,standing,170.89,,153.17,,4,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +15.748,descending,descending,133.1,,113.08,,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +16.114,descending,bottom,66.71,,49.51,,4,편안한 범위에서 무릎과 고관절을 굽혀주세요., +16.48,bottom,bottom,56.1,,34.27,,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +16.846,bottom,bottom,92.57,,63.87,,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +17.213,bottom,standing,155.34,,118.07,,4,굽힘을 확인했습니다. 다시 똑바로 서주세요., +17.579,ready,standing,173.48,,136.17,,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요.,스쿼트 깊이를 확인하고 1회 기록했어요. +17.945,ready,standing,159.86,,123.69,,5,서 있는 자세로 복귀했습니다. 다음 동작을 시작하세요., +18.311,descending,bottom,110.79,,72.75,,5,편안한 범위에서 무릎과 고관절을 굽혀주세요., +18.678,bottom,bottom,78.89,,38.02,,5,굽힘을 확인했습니다. 다시 똑바로 서주세요., +19.044,bottom,bottom,110.15,,63.22,,5,굽힘을 확인했습니다. 다시 똑바로 서주세요., +19.41,bottom,standing,164.91,,127.35,,5,굽힘을 확인했습니다. 다시 똑바로 서주세요., diff --git a/docs/verification/screenshots/2026-09-21/squat_front_01_missed_depth_evidence.jpg b/docs/verification/screenshots/2026-09-21/squat_front_01_missed_depth_evidence.jpg new file mode 100644 index 00000000..58f7f17d Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_front_01_missed_depth_evidence.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_front_01_overview1.jpg b/docs/verification/screenshots/2026-09-21/squat_front_01_overview1.jpg new file mode 100644 index 00000000..626ad833 Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_front_01_overview1.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_front_01_overview2.jpg b/docs/verification/screenshots/2026-09-21/squat_front_01_overview2.jpg new file mode 100644 index 00000000..b1e85dfb Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_front_01_overview2.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_negative_01_overview.jpg b/docs/verification/screenshots/2026-09-21/squat_negative_01_overview.jpg new file mode 100644 index 00000000..6c3303ae Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_negative_01_overview.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_normal_01_bounce_890-1080.jpg b/docs/verification/screenshots/2026-09-21/squat_normal_01_bounce_890-1080.jpg new file mode 100644 index 00000000..40744f82 Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_normal_01_bounce_890-1080.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_normal_01_overview.jpg b/docs/verification/screenshots/2026-09-21/squat_normal_01_overview.jpg new file mode 100644 index 00000000..a0afe943 Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_normal_01_overview.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_normal_02_bounce_731-957.jpg b/docs/verification/screenshots/2026-09-21/squat_normal_02_bounce_731-957.jpg new file mode 100644 index 00000000..5529ed96 Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_normal_02_bounce_731-957.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_normal_02_overview.jpg b/docs/verification/screenshots/2026-09-21/squat_normal_02_overview.jpg new file mode 100644 index 00000000..f8f7253a Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_normal_02_overview.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_shallow_01_overview1.jpg b/docs/verification/screenshots/2026-09-21/squat_shallow_01_overview1.jpg new file mode 100644 index 00000000..58a830e2 Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_shallow_01_overview1.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_shallow_01_overview2.jpg b/docs/verification/screenshots/2026-09-21/squat_shallow_01_overview2.jpg new file mode 100644 index 00000000..689c927a Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_shallow_01_overview2.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_side_01_overview1.jpg b/docs/verification/screenshots/2026-09-21/squat_side_01_overview1.jpg new file mode 100644 index 00000000..c096e364 Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_side_01_overview1.jpg differ diff --git a/docs/verification/screenshots/2026-09-21/squat_side_01_overview2.jpg b/docs/verification/screenshots/2026-09-21/squat_side_01_overview2.jpg new file mode 100644 index 00000000..56514979 Binary files /dev/null and b/docs/verification/screenshots/2026-09-21/squat_side_01_overview2.jpg differ diff --git a/docs/verification/screenshots/roi-first-frame.jpg b/docs/verification/screenshots/roi-first-frame.jpg new file mode 100644 index 00000000..4fb2b21d Binary files /dev/null and b/docs/verification/screenshots/roi-first-frame.jpg differ diff --git a/docs/verification/screenshots/roi-last-frame.jpg b/docs/verification/screenshots/roi-last-frame.jpg new file mode 100644 index 00000000..a0cc4436 Binary files /dev/null and b/docs/verification/screenshots/roi-last-frame.jpg differ diff --git a/docs/verification/squat-45-front-trace-12fps.csv b/docs/verification/squat-45-front-trace-12fps.csv new file mode 100644 index 00000000..6fc88a51 --- /dev/null +++ b/docs/verification/squat-45-front-trace-12fps.csv @@ -0,0 +1,80 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance +0.0,waiting_for_standing,transition,170.34,148.4,176.39,148.93,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.1,waiting_for_standing,standing,171.17,149.21,176.63,149.29,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.199,waiting_for_standing,transition,171.14,147.86,175.57,147.47,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.299,waiting_for_standing,descending,170.07,143.03,172.55,142.61,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.398,waiting_for_standing,descending,169.34,136.36,170.04,136.89,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.498,waiting_for_standing,descending,168.7,132.93,168.39,133.12,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.597,waiting_for_standing,descending,167.82,127.83,166.9,129.07,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.697,waiting_for_standing,descending,163.75,122.73,162.83,123.57,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.796,waiting_for_standing,descending,158.19,116.79,157.85,117.38,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.896,waiting_for_standing,descending,153.87,115.08,153.39,114.79,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.995,waiting_for_standing,descending,148.97,111.03,148.1,110.44,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.095,waiting_for_standing,descending,143.88,104.48,143.07,104.95,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.195,waiting_for_standing,descending,141.55,101.06,140.73,102.55,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.294,waiting_for_standing,descending,137.86,97.99,137.39,100.9,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.394,waiting_for_standing,descending,135.99,94.87,135.94,99.16,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.493,waiting_for_standing,descending,135.1,91.6,135.25,97.19,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.593,waiting_for_standing,descending,133.85,89.27,134.41,95.52,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.692,waiting_for_standing,descending,131.49,86.39,132.27,93.13,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.792,waiting_for_standing,descending,129.29,83.98,130.16,91.55,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.891,waiting_for_standing,transition,128.92,82.89,129.55,90.6,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.991,waiting_for_standing,transition,130.46,81.56,130.34,89.55,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.09,waiting_for_standing,transition,131.39,80.62,130.77,88.55,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.19,waiting_for_standing,transition,132.28,80.34,131.37,87.87,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.289,waiting_for_standing,transition,132.81,80.47,131.73,87.69,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.389,waiting_for_standing,transition,133.61,80.98,132.61,88.03,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.489,waiting_for_standing,ascending,136.39,82.9,134.9,89.35,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.588,waiting_for_standing,ascending,140.85,86.54,139.7,92.77,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.688,waiting_for_standing,ascending,147.03,93.34,146.44,100.34,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.787,waiting_for_standing,ascending,153.78,101.46,154.25,107.71,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.887,waiting_for_standing,ascending,160.08,112.55,162.36,118.38,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.986,waiting_for_standing,ascending,166.22,131.28,168.91,131.48,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +3.086,waiting_for_standing,ascending,172.6,146.24,174.65,143.36,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +3.185,waiting_for_standing,standing,176.69,158.62,175.48,153.07,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +3.285,waiting_for_standing,standing,178.16,169.48,174.65,161.21,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +3.384,waiting_for_standing,standing,178.34,173.3,173.1,167.98,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +3.484,ready,standing,178.56,175.57,171.92,171.29,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +3.584,ready,standing,178.57,177.54,170.83,172.5,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +3.683,ready,standing,178.54,178.83,170.17,172.81,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +3.783,ready,standing,178.35,179.47,169.53,173.19,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +3.882,ready,standing,178.16,179.6,169.14,173.68,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +3.982,ready,standing,178.2,179.43,169.11,173.82,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.081,ready,standing,178.16,179.08,169.28,173.54,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.181,ready,standing,177.93,179.4,169.14,173.11,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.28,ready,standing,178.26,178.23,169.64,171.69,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.38,ready,standing,179.06,175.77,170.34,169.86,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.479,ready,standing,178.7,170.12,171.49,166.27,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.579,ready,standing,177.38,163.76,173.1,162.36,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.678,ready,standing,175.15,154.06,176.23,155.44,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.778,descending,descending,172.43,145.6,176.66,148.24,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +4.878,descending,descending,169.48,139.16,174.7,142.55,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +4.977,descending,descending,166.93,131.93,171.98,136.96,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.077,descending,descending,163.76,124.95,168.77,131.61,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.176,descending,descending,160.98,116.84,165.92,125.58,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.276,descending,descending,157.68,112.94,162.86,122.02,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.375,descending,descending,152.17,108.04,157.31,115.95,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.475,descending,descending,147.85,103.83,152.62,111.24,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.574,descending,descending,144.67,100.25,148.66,107.3,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.674,descending,descending,140.86,94.27,144.32,101.54,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.773,descending,descending,137.39,89.71,140.4,97.06,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.873,descending,descending,135.79,88.41,139.14,96.02,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.973,descending,descending,133.34,86.07,136.9,94.4,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.072,descending,descending,131.85,84.13,135.14,93.23,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.172,descending,transition,132.07,82.24,134.97,92.31,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.271,descending,transition,133.65,81.5,136.68,91.95,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.371,descending,transition,133.93,80.33,137.07,91.29,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.47,descending,transition,134.19,79.86,137.4,90.72,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.57,descending,transition,135.09,80.62,138.32,90.84,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.669,descending,transition,135.32,81.56,138.39,91.35,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.769,descending,ascending,137.05,83.12,139.88,92.16,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.868,descending,ascending,141.11,89.76,144.09,97.35,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.968,descending,ascending,146.89,101.03,150.39,107.26,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +7.068,descending,ascending,153.53,110.38,158.6,116.59,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +7.167,descending,ascending,162.44,126.28,168.0,129.29,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +7.267,descending,ascending,169.78,142.82,173.83,142.47,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +7.366,ready,standing,173.97,153.59,174.93,151.42,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요. +7.466,ready,standing,176.44,162.64,174.18,159.6,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요. +7.565,ready,standing,178.13,171.34,172.69,166.55,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요. +7.665,ready,standing,178.98,176.16,171.5,170.42,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요. +7.764,ready,standing,179.36,177.34,170.32,173.26,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요. diff --git a/docs/verification/squat-45-front-trace.csv b/docs/verification/squat-45-front-trace.csv new file mode 100644 index 00000000..a96972e9 --- /dev/null +++ b/docs/verification/squat-45-front-trace.csv @@ -0,0 +1,23 @@ +time_sec,stage,phase,left_knee,right_knee,left_hip,right_hip,reps,guidance +0.0,waiting_for_standing,transition,170.34,148.4,176.39,148.93,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.365,waiting_for_standing,transition,167.61,142.44,169.34,140.79,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +0.73,waiting_for_standing,descending,161.92,123.43,162.4,122.54,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.095,waiting_for_standing,descending,151.31,105.55,151.8,107.66,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.46,waiting_for_standing,descending,139.22,90.81,140.91,95.84,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +1.825,waiting_for_standing,descending,130.26,80.44,131.07,86.84,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.19,waiting_for_standing,transition,127.8,82.29,128.03,89.81,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.555,waiting_for_standing,ascending,137.88,88.83,137.62,97.26,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +2.92,waiting_for_standing,ascending,163.94,121.21,166.5,126.31,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +3.285,waiting_for_standing,standing,173.76,165.77,178.78,156.45,0,측면에서 양쪽 어깨·골반·무릎·발목이 보이도록 똑바로 서주세요. +3.65,ready,standing,179.43,178.51,174.24,167.5,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.015,ready,standing,179.66,174.81,173.03,172.84,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.38,ready,standing,179.54,173.38,172.81,166.62,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +4.745,ready,standing,176.62,152.79,177.82,150.83,0,준비됐습니다. 제자리에서 스쿼트를 시작하세요. +5.11,descending,descending,168.9,129.11,172.64,134.15,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.475,descending,descending,148.95,101.18,155.57,109.97,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +5.84,descending,descending,135.34,81.59,140.95,92.62,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.205,descending,bottom,123.18,76.36,129.81,86.53,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.57,descending,ascending,127.1,81.2,132.59,92.19,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +6.935,descending,ascending,144.7,100.44,149.8,111.75,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +7.3,descending,ascending,167.63,145.91,174.95,145.47,0,편안한 범위에서 무릎과 고관절을 굽혀주세요. +7.665,ready,standing,176.81,178.05,175.69,166.97,0,이번 동작은 세지 않았습니다. 준비 자세에서 다시 시작하세요. diff --git a/docs/verification/squat-lunge-2026-09-18.md b/docs/verification/squat-lunge-2026-09-18.md new file mode 100644 index 00000000..0fae2a5c --- /dev/null +++ b/docs/verification/squat-lunge-2026-09-18.md @@ -0,0 +1,130 @@ +# 스쿼트·전방 런지 검증 기록 (2026-09-18) + +## 결론 + +반복 횟수 판정과 런지 세션 저장의 자동 테스트는 통과했다. 저장소의 스쿼트 영상 7개 중 최초 구현에서 추적 품질 검사를 통과한 것은 1개였고, 첫 실영상 수동 대조에서는 6개 스쿼트 영상 모두 불일치하며 평균 절대 오차가 5.83회였다. 추가 보정 후 같은 6개 영상에서는 **2개가 정확히 일치하고 평균 절대 오차가 3.33회**다. 다만 랙 가림과 다른 종목의 오검출이 남아 있어 **실제 사용자 촬영 정확도 또는 앱 전체 동작을 합격 처리할 수 없다.** 아래 앞부분은 변경 단계별 기록이며, 최신 결과는 문서 끝의 '스쿼트 횟수 판정 추가 수정'에 있다. 결과는 모두 현재 작업 트리의 미커밋 코드 기준이다. + +## 자동 검사 + +| 검사 | 결과 | 의미 | +|---|---|---| +| AI 스쿼트·런지 핵심 테스트 | 통과 (아래 전체 테스트에 포함) | 합성 좌표의 상태 전이와 HTTP 런지 연결 | +| AI 전체 테스트 (`test_camera.py` 제외) | 199 passed, 61 subtests passed | 한쪽 다리 가림·추적 대상 교체·준비 자세에서 발 위치 조정·깊이 안내 테스트를 포함한 AI 회귀 검사 | +| Spring `LungeSessionTest` | 1 passed, 0 skipped | H2에서 런지 시작, 횟수 저장·재부착, 점수 NULL 처리 | +| Spring `FlywayMigrationValidationTest` (Testcontainers/MySQL) | 2 passed, 0 skipped | V22를 포함한 마이그레이션 22개 적용 및 JPA 스키마 검증 | +| 프런트 `npx tsc --noEmit` | passed | 타입·화면 연결 정적 검사 | +| Chrome 가상 카메라 화면 확인 | passed | 스쿼트·전방 런지 선택, 횟수 표시, 비디오 요소 렌더링; 카메라 오류 없음 | +| `git diff --check` | passed | 변경 파일의 공백 오류 검사 | + +AI 테스트는 `ai-server/.venv`에 `requirements-dev.txt`를 설치하고 `DEBUG=false`로 실행했다. 셸에 이미 있던 `DEBUG=release`는 boolean 설정으로 읽을 수 없어 테스트 수집이 실패했으므로, 실행 명령에서만 덮어썼다. Spring 테스트는 JDK 21과 Gradle `--offline`으로 실행했다. Chrome 검사는 가상 카메라의 미리보기와 화면 렌더링만 확인했으며, AI 서버로 실제 동작을 전송하지 않았다. + +## 저장소 영상 평가 + +`scripts/evaluate_squat.py`로 MediaPipe 자세 추출과 스쿼트 반복 판정을 **3fps**에서 재생했다. `사용 가능 프레임`은 필수 관절의 추적·가시성 조건을 통과한 프레임이다. 아래는 사용자 수동 라벨을 받기 전 최초 결과다. 당시에는 정답 횟수가 없어 오차를 계산하지 않았다. + +| 영상 | 사용 가능 / 표본 프레임 | 평가 유효 | 검출 횟수 | +|---|---:|---|---:| +| `samples/raw/kkw_45-degree_frontview_squat.mp4` | 22 / 22 | 예 | 0 | +| `samples/raw/kkw_front_squat.mp4` | 29 / 45 | 아니오 | 1 | +| `samples/raw/squat.mp4` | 0 / 72 | 아니오 | 0 | +| `samples/raw/kkw_45-degree_backview_squat.mp4` | 0 / 25 | 아니오 | 0 | +| `samples/raw/sqaut_roi_0509.mp4` | 0 / 54 | 아니오 | 0 | +| `samples/raw/60kg_squat.mp4` | 18 / 185 | 아니오 | 0 | +| `ai-server/scripts/demo_videos/demo_squat.mp4` | 0 / 31 | 아니오 | 0 | + +45도 정면 영상은 자세 추출 자체는 됐지만 첫 동작이 선 자세 보정 전에 시작됐다. 두 번째 동작은 3fps에서 양쪽 무릎의 평균 각도가 하단 기준 100도 이하인 프레임이 1개뿐이어서 `bottom_confirm_sec`를 충족하지 못했다. 12fps로 재생해도 무릎 평균 각도 최솟값이 약 106도로 하단 판정에 진입하지 않았다. 0회는 이 코드의 완료 조건에서 나온 결과이며, 사람 기준 정답 여부는 미확인이다. 나머지 6개는 추적 품질 기준을 통과하지 못했다. + +### 추가 원인 분석 + +`scripts/diagnose_squat_tracking.py`로 동일한 3fps·관절 가시성 0.55 조건에서 각 프레임의 탈락 이유를 분리했다. 품질 통과는 추적 가능한 프레임이 70% 이상이고 선 자세 보정이 한 번 끝났다는 운영상 기준이다. **횟수 정확도 합격을 뜻하지 않는다.** + +| 영상 | 자세 자체 미검출 | 관절 가시성 미달 | 주된 원인 | +|---|---:|---:|---| +| `kkw_45-degree_frontview_squat.mp4` | 0 / 22 | 0 / 22 | 추적은 안정적이나 하단 자세 확정 실패 | +| `kkw_front_squat.mp4` | 0 / 45 | 16 / 45 | 오른쪽 무릎 16프레임 미달; 29/45=64.4%로 품질 기준 미달 | +| `squat.mp4` | 4 / 72 | 68 / 72 | 오른쪽 발목 68프레임 미달; 랙이 다리를 가림 | +| `kkw_45-degree_backview_squat.mp4` | 0 / 25 | 25 / 25 | 오른쪽 무릎 25프레임 미달 | +| `sqaut_roi_0509.mp4` | 0 / 54 | 54 / 54 | 오른쪽 무릎 54프레임 미달 | +| `60kg_squat.mp4` | 11 / 185 | 156 / 185 | 오른쪽 무릎·발목 156프레임 미달; 랙과 원판이 몸을 가림 | +| `demo_squat.mp4` | 1 / 31 | 30 / 31 | 상반신 근접 촬영으로 골반·무릎·발목이 보이지 않음 | + +민감도 확인용으로 관절 가시성 기준만 0.55에서 0.35로 낮추자 `kkw_front_squat.mp4`는 45/45프레임·2회, `kkw_45-degree_backview_squat.mp4`는 25/25프레임·1회, `sqaut_roi_0509.mp4`는 45/54프레임·0회가 됐다. 이는 기준값에 결과가 크게 좌우된다는 뜻이지, 0.35가 올바른 기준이라는 증거는 아니다. 특히 `sqaut_roi_0509.mp4`는 품질 기준은 통과해도 선 자세 보정 후 프레임이 4개뿐이라 횟수 검증에 적절하지 않다. 정답 횟수 없이 기준을 낮추면 오검출 여부를 알 수 없으므로 제품 기본값은 변경하지 않았다. + +45도 정면 영상의 [3fps 추적표](squat-45-front-trace.csv)와 [12fps 추적표](squat-45-front-trace-12fps.csv)를 보관했다. 프레임을 더 자주 처리해도 하단 자세가 확정되지 않아 0회였다. 현재 양쪽 무릎 각도를 평균내는 방식은 측면·45도 촬영에서 한쪽 다리의 추정 오차에 민감하다. + +이 최초 평가에서는 카메라 안내가 측면 촬영을 권장하면서도 카운터는 양쪽 어깨·골반·무릎·발목을 모두 가시성 0.55 이상으로 요구했다. 측면에서 먼쪽 다리가 가려지는 영상과 이 조건이 충돌했다. 아래의 한쪽 다리 가시성 개선은 이 문제를 대상으로 한다. + +추가로 사용자가 내려받은 AI Hub 크로스핏 샘플 영상 8시점과 에어 스쿼트 학습 라벨 2,888개를 검사했다. 같은 동작의 8시점 중 영상 전체 경로에서는 3시점만 1회를 검출했다. 상세 결과와 독립 표본이 아니라는 한계는 [AI Hub 검증 기록](aihub-crossfit-squat-2026-09-18.md)에 정리했다. + +### 한쪽 다리 가시성 개선 후 재검사 + +양쪽이 보이면 기존 좌우 각도 평균을 사용하고, 측면에서 한쪽 다리만 보이면 그쪽의 어깨·골반·무릎·발목 각도로 분석하도록 변경했다. 동작 중 추적 대상 다리가 완전히 바뀌거나 발이 크게 이동하면 주기를 취소한다. 같은 3fps·가시성 0.55 설정에서 MediaPipe부터 기존 영상을 다시 재생했다. + +| 영상 | 수정 전 사용 가능 / 표본 · 검출 | 수정 후 사용 가능 / 표본 · 검출 | 수정 후 품질 기준 | +|---|---:|---:|---| +| `kkw_45-degree_frontview_squat.mp4` | 22/22 · 0회 | 22/22 · 0회 | 통과 | +| `kkw_front_squat.mp4` | 29/45 · 1회 | 45/45 · 2회 | 통과 | +| `squat.mp4` | 0/72 · 0회 | 61/72 · 0회 | 통과 | +| `kkw_45-degree_backview_squat.mp4` | 0/25 · 0회 | 25/25 · 1회 | 통과 | +| `sqaut_roi_0509.mp4` | 0/54 · 0회 | 54/54 · 0회 | 통과 | +| `60kg_squat.mp4` | 18/185 · 0회 | 171/185 · 0회 | 통과 | +| `demo_squat.mp4` | 0/31 · 0회 | 0/31 · 0회 | 미달 | + +추적 품질 기준을 통과한 영상은 **1/7개에서 6/7개**로 늘었다. 이는 가려진 다리 때문에 버리던 프레임을 분석할 수 있게 된 결과다. 새로 사용 가능해진 영상 중에도 0회가 있으며, 6/7은 횟수 정확도가 아니다. AI Hub 샘플 8시점은 3시점에서 6시점으로 검출이 늘었고, 전체 학습 라벨 2,888쌍의 카운터 단독 결과는 변화가 없었다. 자세한 시점별 결과는 [AI Hub 검증 기록](aihub-crossfit-squat-2026-09-18.md)에 있다. + +### 사용자 수동 횟수와 대조 + +사용자가 같은 영상 7개에 완료 횟수를 붙였다. `samples/validation/labels.csv`에 로컬 라벨을 기록하고 `scripts/evaluate_dataset.py`로 앱 기본값인 3fps에서 재평가했다. `labels.csv`와 `results.csv`는 로컬 평가 파일로 Git에서 제외된다. `평가 유효`는 관절 사용 가능 프레임이 70% 이상이고 한 번이라도 선 자세를 확인한 운영상 조건일 뿐, 정확한 포즈나 충분한 주기 추적을 보증하지 않는다. + +| 영상 | 수동 횟수 | 검출 횟수 | 절대 오차 | 선 자세 보정 상태 프레임 / 표본 | +|---|---:|---:|---:|---:| +| 45도 정면 | 2 | 0 | 2 | 12/22 | +| 정면 (랙이 무릎 가림) | 3 | 2 | 1 | 44/45 | +| `squat.mp4` (랙이 무릎 가림) | 9 | 0 | 9 | 1/72 | +| 45도 후면 | 2 | 1 | 1 | 13/25 | +| ROI | 7 | 0 | 7 | 13/54 | +| 60kg (랙이 무릎 가림) | 15 | 0 | 15 | 65/185 | +| 데모 (스쿼트 없음) | 0 | 0 | 평가 제외 | 0/31 | + +스쿼트가 있는 6개 영상의 **수동 총합 38회 대비 검출 총합 3회**, 영상별 **정확히 일치 0/6개**, **평균 절대 오차 35/6=5.83회**다. 총횟수 라벨만 있으므로 3개 검출이 실제 동작과 시간상 일치하는지 확인하지 못했다. 따라서 3/38을 재현율로 표현하지 않는다. 데모 영상은 0회를 출력했지만 자세 추적 가능한 프레임이 0개여서 오검출 방지의 성공 사례로 계산하지 않는다. + +상태 전이로 확인한 누락 원인은 다르다. 45도 정면은 첫 회를 선 자세 보정 전부터 시작했고 두 번째 회는 2D 무릎 각도가 하단 경계를 넘지 못했다. 정면은 세 번째 하단을 잡았지만 영상 끝까지 다시 선 상태를 확인하지 못했다. `squat.mp4`와 ROI는 대부분의 프레임에서 선 자세 조건을 확인하지 못했다. 45도 후면은 두 번째 주기 시작 시 발 좌표 변화로 초기화됐다. 60kg은 몇 차례 하단까지 잡았지만 랙에 가린 프레임에서 발 좌표가 기준 몸통 길이의 약 0.4~1.0배까지 튀어 주기를 반복 초기화했다. 실제 발 이동인지 포즈 추정 오류인지는 가림 때문에 확정할 수 없다. 가시성만으로 `평가 유효`를 판단하는 현재 기준은 이 문제를 걸러내지 못한다. + +이 7개만 보고 논문 각도 경계나 발 이동 허용폭을 일괄 완화하면 오검출이 늘 수 있다. 특히 랙에 가린 영상은 2D 관절 좌표 자체가 불안정하다. 독립적인 가림 없는 휴대폰 촬영본과 동작별 완료 시각, 움직임이 비슷한 비스쿼트 동작을 확보해 수정 전후 누락과 오검출을 함께 확인해야 한다. + +저장소에 **전방 런지 촬영 영상은 없다.** 따라서 런지에 대해서는 합성 좌표와 서비스 계약까지만 검증했다. 좌우 실제 인식률은 측정하지 못했다. + +## 실사용 검증 전 남은 조건 + +1. 기존 스쿼트 7개 영상의 수동 총횟수 대조는 완료했다. 다음에는 측면에서 머리부터 발끝까지 보이는 사용자 휴대폰 스쿼트·전방 런지 촬영본과 사람이 센 총횟수·런지 좌우 횟수로 앱 촬영 조건에서 독립 검증한다. 완료 시각도 적으면 어떤 주기를 놓치거나 잘못 센 것인지 판별할 수 있다. 영상 끝에 선 자세를 잠시 유지해야 완료 판정을 확인할 수 있다. +2. 같은 촬영 조건으로 앱 카메라 → AI `/pose` → Spring 세션 저장 → 홈 기록까지 한 번 연결한다. 현재 `ai-server/.env`의 `AI_PUBLIC_TOKEN`과 `frontend/.env.local`의 `EXPO_PUBLIC_AI_PUBLIC_TOKEN`이 모두 비어 있다. Docker Desktop에서 기존 `shadowfit-backend` 컨테이너도 DB 호스트 `shadowfit-mysql`을 찾지 못해 재시작 중이므로, 앱 전체 경로는 아직 검증하지 못했다. + +실영상 정확도를 판단할 때는 촬영본별 수동 정답과 검출 횟수를 비교하고, 정상 동작뿐 아니라 얕은 동작·가림·정면·워킹/후방 런지의 오검출도 따로 기록한다. 영상이 분석 조건을 충족하지 못하면 0회를 정확한 판정으로 취급하지 않는다. + +## 영상 도착 전 준비 (2026-09-18) + +`samples/validation/labels.template.csv`와 촬영·정답 작성 안내를 만들고, `ai-server/scripts/evaluate_dataset.py`로 여러 영상을 같은 3fps 조건에서 일괄 평가하도록 준비했다. 기존 스쿼트 영상 두 개로 결과 CSV를 생성하고, **정답이 없는 영상과 추적 실패 영상이 MAE에 들어가지 않는 동작**을 확인했다. 이 확인에 사용한 임시 0회 표기는 실제 사람이 센 정답이 아니다. 런지 실영상은 여전히 없어 런지 배치 결과는 아직 없다. + +Docker Desktop 실행 후 격리된 MySQL 8.0 Testcontainers에서 `FlywayMigrationValidationTest`를 재실행해 2개 테스트가 모두 통과했다. 로그에서 V22를 포함한 마이그레이션 22개가 적용됐고 Spring 컨텍스트가 JPA 스키마 검증을 통과한 것을 확인했다. 첫 실행은 gRPC 임시 포트 충돌로 실패했으며, 재실행 명령에서만 `GRPC_SERVER_PORT=-1`로 gRPC 서버를 꺼서 해결했다. 사용자 DB는 사용하지 않았다. + +## 스쿼트 횟수 판정 추가 수정 (2026-09-18) + +위의 표는 당시 구현의 기록이다. 이후 실제 영상에서 선 자세 판정이 너무 엄격하고, 운동 전에 발을 옮긴 것을 동작 중 발 이동으로 오인하는 문제를 확인했다. 서기 각도에 2D 추정 오차 여유를 두고, 각도와 함께 몸통 길이로 정규화한 골반 하강을 확인하도록 바꿨다. 준비 자세에서는 발 기준점을 갱신하고, 하강 중 한두 프레임의 발 좌표 오류는 건너뛰되 지속적인 발 이동은 주기를 취소한다. 이 여유값은 **기존 영상에 맞춰 정한 구현 값**이며 논문에서 검증한 성능 수치가 아니다. + +MediaPipe를 포함한 `scripts/evaluate_dataset.py` 3fps 재실행 결과다. 데모 영상은 포즈 프레임이 0개라 정답 0회여도 정확도에서 제외한다. + +| 영상 | 수동 횟수 | 이전 검출 | 현재 검출 | 현재 평가 유효 | +|---|---:|---:|---:|---| +| 45도 정면 | 2 | 0 | 2 | 예 | +| 정면, 랙 가림 | 3 | 2 | 2 | 예 | +| `squat.mp4`, 랙 가림 | 9 | 0 | 2 | 아니오 (44/72 사용 가능 프레임) | +| 45도 후면 | 2 | 1 | 2 | 예 | +| ROI | 7 | 0 | 5 | 예 | +| 60kg, 랙 가림 | 15 | 0 | 5 | 예 | +| 데모, 전신이 보이지 않음 | 0 | 0 | 0 | 아니오 (0/31 사용 가능 프레임) | + +사람이 센 횟수가 있는 스쿼트 영상 6개 중 **정확히 일치한 영상은 2개**다. 같은 6개를 모두 비교한 절대 오차 평균은 5.83회에서 **3.33회**로 감소했다. 운영상 포즈 품질을 통과한 현재 영상 5개만 계산하면 평균 절대 오차는 **2.6회**다. 가림이 없다고 알려진 세 영상에서는 2/3개가 일치하고 평균 절대 오차가 0.67회다. 그러나 이 영상들을 보면서 판정값을 정했으므로 어느 수치도 독립 검증 정확도가 아니다. ROI는 시작부터 앉은 자세라 첫 동작을 확인할 수 없고, 짧은 선 자세를 놓친 주기도 있다. 랙이 무릎을 가린 영상은 여전히 크게 누락된다. + +AI Hub 에어 스쿼트 샘플의 같은 동작 8시점에서는 1회 검출이 6/8에서 **7/8**로 늘었다. 학습용 2D 관절 좌표의 에어 스쿼트 361개 기록·2,888개 시점에서는 1회 출력 시점이 2,012개에서 **2,398개**로 늘었다. 이 자료에는 확인된 회차별 정답과 MediaPipe 가시성 점수가 없어 **정확도나 재현율로 해석하지 않는다**. 같은 AI Hub 좌표를 다른 종목에 넣으면 스쿼트가 아닌 동작도 세는 사례가 있다. 예를 들어 선택 순서상 첫 30개의 `camera0` 정상 데드리프트 좌표 모두에서 스쿼트 카운터가 2회를 출력했다. 현 판정기는 운동 종목 자체를 구분하지 못한다. + +AI 테스트는 `test_camera.py`를 제외하고 **199 passed, 61 subtests passed**다. 실제 촬영본에서 독립적으로 확인해야 할 것은 스쿼트 완료 시각, 런지 좌우 횟수, 장애물이 없는 카메라 시점별 누락, 비스쿼트 동작의 오검출이다. 현재 결과로 제품 수준 성능이나 AI 모델 학습 완료를 주장하지 않는다. diff --git a/frontend/.env.example b/frontend/.env.example index 5e5f0e06..08426a60 100644 --- a/frontend/.env.example +++ b/frontend/.env.example @@ -50,6 +50,9 @@ EXPO_PUBLIC_AI_PUBLIC_TOKEN=REPLACE_WITH_SAME_VALUE_AS_ROOT_AI_PUBLIC_TOKEN # cleartext 정책상 http 주소로는 연결 자체가 거부됩니다) # # EXPO_PUBLIC_AI_BASE_URL=http://192.168.0.10:8000/api/v1 +# Isolated Docker demo (docker-compose.iso.yml): +# EXPO_PUBLIC_BACKEND_PORT=18080 +# EXPO_PUBLIC_AI_PORT=18000 # # 🔴 릴리스 빌드에서는 **이 값이 필수이고 https 여야 한다** (이슈 #148). # 개발에서는 비워 두면 Metro 호스트로 자동 해석되지만, 릴리스에는 Metro 가 없다. @@ -58,4 +61,4 @@ EXPO_PUBLIC_AI_PUBLIC_TOKEN=REPLACE_WITH_SAME_VALUE_AS_ROOT_AI_PUBLIC_TOKEN # 지금은 앱이 시작 시점에 «AI 서버 설정 오류» 로 말한다. # # ⚠️ 아직 프로덕션 주소가 없다 — 배포 호스트도 도메인도 미정이다 -# (docs/decisions/reverse-proxy-and-tls.md §8). \ No newline at end of file +# (docs/decisions/reverse-proxy-and-tls.md §8). diff --git a/frontend/app/(tabs)/activity.tsx b/frontend/app/(tabs)/activity.tsx index 58f7c360..c27d4998 100644 --- a/frontend/app/(tabs)/activity.tsx +++ b/frontend/app/(tabs)/activity.tsx @@ -1,4 +1,4 @@ -import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ActivityIndicator } from 'react-native'; +import { View, Text, StyleSheet, ScrollView, TouchableOpacity, ActivityIndicator, Alert } from 'react-native'; import { SafeAreaView } from 'react-native-safe-area-context'; import { useRouter, useFocusEffect } from 'expo-router'; import { useCallback, useState } from 'react'; @@ -46,7 +46,7 @@ export default function ActivityScreen() { {/* 헤더 */} - Activity + 운동 기록 {/* 주간 네비게이션 (현재 주만 표시 - 추후 이전/다음 주 기능 확장) */} @@ -68,9 +68,9 @@ export default function ActivityScreen() { <> {/* 주간 통계 */} - - - + + + {/* 운동일지 */} @@ -79,7 +79,7 @@ export default function ActivityScreen() { - {data?.totalWorkouts ?? 0} Workouts {data?.totalMinutes ?? 0} Min {data?.totalCalories ?? 0} Kcal + {data?.totalWorkouts ?? 0}회 완료 · {data?.totalMinutes ?? 0}분 운동 @@ -126,17 +126,17 @@ export default function ActivityScreen() { key={ex.sessionId} style={styles.exerciseCard} activeOpacity={0.7} - onPress={() => router.push(`/report/${ex.sessionId}` as any)} + onPress={() => ex.scoreAvailable === false + ? Alert.alert(ex.exerciseName, `${ex.setSummary}\n자세 점수는 측정하지 않았습니다.`) + : router.push(`/report/${ex.sessionId}` as any)} > {ex.exerciseName} {ex.setSummary} - - - {Math.round(ex.syncRate)}% - - 싱크로율 + + {ex.scoreAvailable === false ? '횟수 기록' : '기록 보기'} + )) @@ -161,13 +161,6 @@ function WeeklyStat({ Icon, value, label }: { Icon: LucideIcon; value: string; l ); } -// 싱크로율 색상 구간: 80%+ 정석 / 60~80% 교정 필요 / <60% 부상 위험 -function getSyncColor(rate: number) { - if (rate >= 80) return COLORS.primary; - if (rate >= 60) return COLORS.warning; - return COLORS.error; -} - const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: COLORS.background }, header: { paddingHorizontal: SPACING.xxl, paddingTop: SPACING.md }, @@ -246,9 +239,8 @@ const styles = StyleSheet.create({ exerciseInfo: { flex: 1 }, exerciseName: { fontSize: FONT_SIZE.md, fontWeight: '700', color: COLORS.text }, exerciseSets: { fontSize: FONT_SIZE.sm, color: COLORS.textSecondary, marginTop: 2 }, - syncBadge: { alignItems: 'flex-end' }, - syncValue: { fontSize: FONT_SIZE.xl, fontWeight: '800' }, - syncLabel: { fontSize: FONT_SIZE.xs, color: COLORS.textSecondary }, + detailBadge: { flexDirection: 'row', alignItems: 'center', gap: SPACING.sm }, + detailText: { fontSize: FONT_SIZE.sm, fontWeight: '700', color: COLORS.textSecondary }, loadingBox: { paddingVertical: SPACING.xxxl, diff --git a/frontend/app/(tabs)/exercise.tsx b/frontend/app/(tabs)/exercise.tsx index 9cfe7383..5cac122b 100644 --- a/frontend/app/(tabs)/exercise.tsx +++ b/frontend/app/(tabs)/exercise.tsx @@ -1,13 +1,14 @@ import { useState, useEffect, useRef, useCallback } from 'react'; -import { View, Text, StyleSheet, TouchableOpacity, Animated, Alert, AppState, type AppStateStatus } from 'react-native'; +import { View, Text, StyleSheet, TouchableOpacity, Alert, AppState, Platform, type AppStateStatus } from 'react-native'; import { CameraView, useCameraPermissions } from 'expo-camera'; -import { LinearGradient } from 'expo-linear-gradient'; import { useLocalSearchParams, useFocusEffect } from 'expo-router'; import { exercisesService } from '@/services/exercisesService'; import { aiService, aiConfigError } from '@/services/aiService'; import type { FeedbackTemplate } from '@/types/feedback'; import { FEEDBACK_TYPE_LABEL } from '@/types/feedback'; -import type { AiFeedbackType } from '@/types/pose'; +import type { AiFeedbackType, LungeProgress, PoseSkipReason, SquatProgress } from '@/types/pose'; +import ReadinessBanner, { deriveReadiness } from '@/components/exercise/ReadinessBanner'; +import MannequinDemo from '@/components/exercise/MannequinDemo'; import { Camera as CameraIcon, ChevronLeft, @@ -16,34 +17,17 @@ import { Zap, ChevronUp, ChevronDown, - Play, - FlaskConical, + Box, + X, } from 'lucide-react-native'; import { useRouter } from 'expo-router'; -import * as Haptics from 'expo-haptics'; import { COLORS, FONT_SIZE, SPACING, RADIUS } from '@/constants/Colors'; import Button from '@/components/ui/Button'; -/** 색상을 rgba 문자열로 변환 (hex만 지원) */ -function hexToRgba(hex: string, alpha: number) { - const clean = hex.replace('#', ''); - const r = parseInt(clean.slice(0, 2), 16); - const g = parseInt(clean.slice(2, 4), 16); - const b = parseInt(clean.slice(4, 6), 16); - return `rgba(${r}, ${g}, ${b}, ${alpha})`; -} - -/** 싱크로율 → 색상 (80%+ 정석 / 60~80% 교정 필요 / <60% 부상 위험) */ -function getSyncColor(rate: number) { - if (rate >= 80) return COLORS.syncHigh; // 라임 그린 — 정석 - if (rate >= 60) return COLORS.syncMid; // 주황 — 교정 필요 - return COLORS.syncLow; // 빨강 — 부상 위험 -} - /** 백엔드 exerciseId → AI exercise_type 매핑 */ function exerciseTypeOf(exerciseId: number): string { // 백엔드 시드: 1=스쿼트, 2=런지, 3=플랭크 - // AI 측은 squat/deadlift/pullup 분석기만 있음. 매핑 부족분은 squat 폴백. + // 선택 가능한 종목은 스쿼트와 전방 런지다. switch (exerciseId) { case 1: return 'squat'; case 2: return 'lunge'; @@ -52,21 +36,34 @@ function exerciseTypeOf(exerciseId: number): string { } } -/** 임시 mock base64 1×1 px JPEG. 카메라 frame capture 도입 시 교체. - * 실제 분석은 mediapipe 라 0byte 페이로드는 거부될 수 있으나, 폴링 흐름 검증용. */ -const MOCK_FRAME_B64 = - '/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/2wBDAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQEBAQH/wAARCAABAAEDASIAAhEBAxEB/8QAFQABAQAAAAAAAAAAAAAAAAAAAAj/xAAUEAEAAAAAAAAAAAAAAAAAAAAA/8QAFAEBAAAAAAAAAAAAAAAAAAAAAP/EABQRAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhEDEQA/AL+AB//Z'; - export default function ExerciseScreen() { const router = useRouter(); const params = useLocalSearchParams<{ exerciseId?: string }>(); // 운동 종목 — 라우트 param 우선, 기본 1(스쿼트). 추후 종목 선택 UI 추가 시 정리. - const exerciseId = params.exerciseId ? Number(params.exerciseId) : 1; + const [exerciseId, setExerciseId] = useState(params.exerciseId === '2' ? 2 : 1); + const isLunge = exerciseId === 2; + const [lunge, setLunge] = useState(null); + // 운동 시작 전/중 «지금 뭘 해야 하는지» 배너용 상태 (ReadinessBanner) + const [squat, setSquat] = useState(null); + const [lastSkip, setLastSkip] = useState(null); + const [gotResponse, setGotResponse] = useState(false); + const [aiError, setAiError] = useState(false); + // 횟수가 올라간 순간 화면 중앙에 잠깐 띄우는 «✓ N회» + const [repFlash, setRepFlash] = useState(null); + const [captureMessage, setCaptureMessage] = useState(null); + const [cameraError, setCameraError] = useState(null); + const [cameraRetryKey, setCameraRetryKey] = useState(0); + // 분석용 촬영 해상도(안드로이드). 지정하지 않으면 폰이 12MP(4000x3000) 원본을 찍는다 — + // 2026-10-06 실기기에서 프레임 간격이 1.3~2초(≈0.5fps)로 늘어져 횟수를 못 셌다. 같은 사진을 + // 960px 로 줄여도 MediaPipe 관절 가시성은 유지(오히려 12MP 에서 검출 실패하던 프레임도 검출됨)된다. + const [pictureSize, setPictureSize] = useState(undefined); const [permission, requestPermission] = useCameraPermissions(); const [isRecording, setIsRecording] = useState(false); const [syncRate, setSyncRate] = useState(0); const [guideOpen, setGuideOpen] = useState(false); + // 3D 목각인형 시범 패널. 카메라와 같이 돌면 폰이 버벅일 수 있어 운동 중에는 띄우지 않는다. + const [demoOpen, setDemoOpen] = useState(false); // 백엔드 세션 (POST /exercises/sessions → PATCH /sessions/{id}/end) const [sessionId, setSessionId] = useState(null); @@ -80,15 +77,53 @@ export default function ExerciseScreen() { // 워커로 고정 전달한다. 안 실으면 커널이 무작위 분산시켜 세션 상태가 없는 워커로 갈 수 있다. const [aiWorkerIndex, setAiWorkerIndex] = useState(null); const [busy, setBusy] = useState(false); + const lastRouteExercise = useRef(params.exerciseId); + useEffect(() => { + if (lastRouteExercise.current === params.exerciseId) return; + lastRouteExercise.current = params.exerciseId; + if (!isRecording && !busy && sessionId == null) { + setExerciseId(params.exerciseId === '2' ? 2 : 1); + setLunge(null); + } + }, [params.exerciseId, isRecording, busy, sessionId]); // 페르소나 멘트 프리로드 (TTS 보류 — 일단 받아서 보관만) const [, setFeedbackTemplates] = useState([]); // AI 응답 — 최근 자세 결함 라벨 (시각 표시용) const [lastFeedback, setLastFeedback] = useState(null); + const [coachingNotice, setCoachingNotice] = useState<{ message: string; success: boolean } | null>(null); // AI 응답 — 누적 횟수 const [repCount, setRepCount] = useState(0); // 카메라 ref (takePictureAsync 호출용) const cameraRef = useRef(null); + // 카메라가 준비되면 분석에 충분한 가장 작은 4:3 촬영 크기를 고른다(긴 변 1024px 이상). + // 비율을 맞추는 이유: pictureSize 를 주면 ratio 설정이 무시돼, 미리보기와 다른 비율을 고르면 + // 사진이 미리보기와 다른 영역으로 잘린다. getAvailablePictureSizesAsync 는 안드로이드 전용이라 + // iOS 는 건드리지 않는다(기존 동작 유지). 실패해도 운동은 기존처럼 원본 해상도로 진행한다. + const handleCameraReady = async () => { + if (Platform.OS !== 'android') return; + try { + const sizes = (await cameraRef.current?.getAvailablePictureSizesAsync()) ?? []; + const candidates = sizes + .map((label) => { + const [w, h] = label.split('x').map(Number); + return { label, w, h }; + }) + .filter((s) => s.w > 0 && s.h > 0 && Math.abs(s.w / s.h - 4 / 3) < 0.02 && Math.max(s.w, s.h) >= 1024) + .sort((a, b) => a.w * a.h - b.w * b.h); + if (__DEV__) { + // eslint-disable-next-line no-console + console.log('[camera] pictureSize 선택:', candidates[0]?.label ?? '없음(원본 유지)', '/ 후보:', sizes.join(',')); + } + if (candidates[0]) setPictureSize(candidates[0].label); + } catch (e) { + if (__DEV__) { + // eslint-disable-next-line no-console + console.warn('[camera] pictureSize 조회 실패 — 원본 해상도 유지:', (e as Error).message); + } + } + }; + // 앱 포그라운드 여부 — 백그라운드에서는 폴링만 멈춘다. 세션은 끝내지 않는다(재개로 이어간다). const [isForeground, setIsForeground] = useState(true); // 이 화면이 포커스돼 있는지 — 다른 탭으로 이동해도 화면은 마운트된 채 남으므로 @@ -112,6 +147,7 @@ export default function ExerciseScreen() { try { const re = await exercisesService.reattachSession(active.data.sessionId); const r = re.data; + setExerciseId(active.data.exerciseId); setSessionId(r.sessionId); setSessionNonce(r.sessionNonce); setAiWorkerIndex(r.aiWorkerIndex ?? null); @@ -170,15 +206,23 @@ export default function ExerciseScreen() { // 예전에는 릴리스 빌드가 조용히 http://localhost:8000 을 만들었고, ATS·cleartext 정책이 // 그걸 막아 «세션은 시작됐는데 카운트가 안 오르는» 상태가 됐다. 원인이 주소라는 단서가 // 어디에도 없었다. 세션을 만들기 전에 걸러야 DB 에 못 쓸 세션이 안 남는다. - if (aiConfigError) { + if (!isRecording && aiConfigError) { Alert.alert('AI 서버 설정 오류', aiConfigError); return; } + if (!isRecording && !process.env.EXPO_PUBLIC_AI_PUBLIC_TOKEN) { + Alert.alert('AI 서버 설정 오류', 'AI 연결 설정이 없어 운동을 분석할 수 없습니다.'); + return; + } + setBusy(true); try { if (!isRecording) { + setLunge(null); + setCaptureMessage(null); // ── 시작: 백엔드에 세션 생성 + 멘트 프리로드 ───────── + // 하프 스쿼트는 시연 범위에서 뺐다(2026-10-06) — depthMode 를 생략하면 백엔드가 FULL 로 취급. const res = await exercisesService.startSession({ exerciseId }); setSessionId(res.data.sessionId); setSessionNonce(res.data.sessionNonce); @@ -192,15 +236,15 @@ export default function ExerciseScreen() { } else { // ── 종료: 백엔드 종료 통보 + 리포트로 이동 ────────── const id = sessionId; + if (id != null) await exercisesService.endSession(id); setIsRecording(false); // 비밀값은 세션과 함께 버린다 (#187). 리포트 화면으로 넘어가면 어차피 언마운트되지만, // «끝난 세션의 자격증명이 메모리에 남아 있다» 를 화면 전환 타이밍에 기대지 않는다. setSessionNonce(null); setAiWorkerIndex(null); - if (id != null) { - await exercisesService.endSession(id); - router.replace(`/report/${id}` as any); - } + setSessionId(null); + // 스쿼트·런지 모두 리포트로 이동한다 — 런지도 깊이·체간·보폭 점수가 리포트에 나온다. + if (id != null) router.replace(`/report/${id}` as any); } } catch (e: any) { console.error('[exercise session] status=', e?.response?.status, 'data=', e?.response?.data); @@ -208,25 +252,44 @@ export default function ExerciseScreen() { '운동 세션 오류', e?.response?.data?.message ?? '세션 처리 중 오류가 발생했습니다', ); - // 시작 실패면 녹화 상태 유지 안 함 / 종료 실패면 일단 화면은 종료 처리됨 + // 시작 실패면 운동 상태 유지 안 함 / 종료 실패면 일단 화면은 종료 처리됨 if (!isRecording) setIsRecording(false); } finally { setBusy(false); } }; - // 테두리 점멸 애니메이션 - const borderOpacity = useRef(new Animated.Value(0)).current; - - // 녹화 정지 시 싱크로율 0 + 결함 라벨 + rep 초기화 + // 운동 종료 시 참고 유사도, 알림, 횟수 초기화 useEffect(() => { if (!isRecording) { setSyncRate(0); setLastFeedback(null); + setCoachingNotice(null); setRepCount(0); + setLunge(null); + setCaptureMessage(null); + setSquat(null); + setLastSkip(null); + setGotResponse(false); + setAiError(false); + setRepFlash(null); } }, [isRecording]); + // 횟수가 올라가면 «✓ N회» 를 1.2초 띄운다 — 폰 화면만 봐도 방금 인식된 걸 알 수 있게. + const previousRepCount = useRef(0); + useEffect(() => { + if (repCount > previousRepCount.current) { + setRepFlash(repCount); + const timer = setTimeout(() => setRepFlash(null), 1200); + previousRepCount.current = repCount; + return () => clearTimeout(timer); + } + previousRepCount.current = repCount; + }, [repCount]); + + const readiness = deriveReadiness({ isRecording, isLunge, gotResponse, aiError, lastSkip, squat, lunge }); + // 자세 결함 토스트 — 4초 후 자동 사라짐 useEffect(() => { if (!lastFeedback) return; @@ -234,6 +297,12 @@ export default function ExerciseScreen() { return () => clearTimeout(t); }, [lastFeedback]); + useEffect(() => { + if (!coachingNotice) return; + const t = setTimeout(() => setCoachingNotice(null), 4000); + return () => clearTimeout(t); + }, [coachingNotice]); + // ── AI 폴링 (분기 H2) ──────────────────────────────────── // takePictureAsync 는 셔터·인코딩 비용이 크므로 10fps 는 비현실적. // ~3fps (330ms) 로 시작, 실제 디바이스에서 부담되면 더 줄여도 됨. @@ -244,7 +313,7 @@ export default function ExerciseScreen() { // 프레임을 쏘면서 «세션 없음» 을 반복해 받느니 아예 시작을 안 하는 편이 낫다. // 화면이 포커스를 잃었거나 앱이 백그라운드면 폴링 자체를 안 돈다(§2) — 세션은 끝내지 // 않고 그대로 두며, 돌아오면 이 effect 가 재실행돼 이어서 폴링한다. - if (!isRecording || sessionId == null || sessionNonce == null || !isForeground || !isScreenFocused) return; + if (busy || !isRecording || sessionId == null || sessionNonce == null || !isForeground || !isScreenFocused) return; const token = process.env.EXPO_PUBLIC_AI_PUBLIC_TOKEN; if (!token) return; @@ -255,22 +324,30 @@ export default function ExerciseScreen() { let inFlight = false; const exerciseType = exerciseTypeOf(exerciseId); const intervalMs = 330; // ~3fps — takePictureAsync 부담 고려 + // 2026-10-06 실기기(안드로이드) 첫 시험에서 프레임 간격이 1.3~2초(≈0.6fps)였다 — 카운팅 상수가 + // 3fps 기준이라 이 속도면 횟수를 못 센다. 원인 후보는 takePictureAsync 의 후처리(skipProcessing=false). + // 끄면 EXIF 방향만 달린 사진이 올라오는데, 서버(cv2.imdecode)가 EXIF 방향을 반영하고 EXIF 가 없어도 + // MediaPipe 검출은 유지됨을 실험으로 확인했다. 기기 검증 전이라 기본은 기존대로 두고 환경변수로 켠다. + const fastCapture = process.env.EXPO_PUBLIC_FAST_CAPTURE === '1'; + let frameNo = 0; const tick = async () => { if (cancelled || inFlight) return; inFlight = true; try { - let image = MOCK_FRAME_B64; - // 실제 카메라 프레임 (가능하면). 카메라가 아직 마운트 안 됐을 때만 mock 사용. + let image: string | undefined; + const captureStartedAt = Date.now(); + let captureMs = 0; try { const cam = cameraRef.current; if (cam) { const snap = await cam.takePictureAsync({ base64: true, quality: 0.4, // 분석엔 충분, 페이로드 줄임 - skipProcessing: true, // 회전·EXIF 처리 스킵 → 지연 단축 + skipProcessing: fastCapture, // false: 분석 좌표계가 기기 회전과 일치하도록 처리(기본) shutterSound: false, }); + captureMs = Date.now() - captureStartedAt; if (snap?.base64) image = snap.base64; } } catch (e) { @@ -281,10 +358,15 @@ export default function ExerciseScreen() { } if (cancelled) return; + if (!image) { + setCaptureMessage('카메라 영상을 가져오지 못했습니다. 카메라 상태를 확인해주세요.'); + return; + } try { // timestamp_sec 은 더 보내지 않는다 (이슈 #156). 여기서 보내던 Date.now()/1000 은 // epoch 라 «세션 시작 기준 경과 초» 가 아니었고, 변환하는 곳이 한 군데도 없어 그대로 // 리포트까지 흘러 시각 표시가 무의미해졌다. 이제 서버가 도착 시각으로 만든다. + const aiStartedAt = Date.now(); const res = await aiService.detectPose( { image, @@ -296,7 +378,25 @@ export default function ExerciseScreen() { ); if (cancelled) return; const r = res.data; + if (__DEV__ && ++frameNo % 5 === 1) { + // 실기기 시험용 — 5프레임마다 캡처/AI 소요(ms)와 판정 결과를 Metro 터미널에 남긴다. + // eslint-disable-next-line no-console + console.log( + `[frame ${frameNo}] capture=${captureMs}ms ai=${Date.now() - aiStartedAt}ms ` + + `size=${Math.round(image.length / 1024)}KB fast=${fastCapture} ` + + `success=${r.success} skip=${r.skip_reason ?? '-'} reps=${r.rep_count ?? '-'}`, + ); + } + setGotResponse(true); + setAiError(false); + if (r.lunge) setLunge(r.lunge); + if (r.squat) setSquat(r.squat); if (r.success === false) { + if (r.skip_reason !== 'RATE_LIMITED') { + setCaptureMessage(r.lunge?.guidance ?? r.message ?? '전신이 보이도록 위치를 조정해주세요.'); + // RATE_LIMITED 는 건강한 세션에서도 나는 서버의 의도적 스킵이라 «안 보임» 으로 읽지 않는다. + setLastSkip(r.skip_reason ?? null); + } // success 는 «판정에 들어갔는가» 다(#267) — RATE_LIMITED·NO_POSE·LOW_VISIBILITY 는 // 정상 동작 중에도 나는 스킵이라 폴링을 유지한다. 세션·순서 문제만 치명적이다. const fatal = @@ -312,10 +412,22 @@ export default function ExerciseScreen() { } return; } + setCaptureMessage(null); + setLastSkip(null); if (r.sync_rate != null) setSyncRate(Math.round(r.sync_rate)); - if (r.feedback_type) setLastFeedback(r.feedback_type); + if (r.message) { + setCoachingNotice({ message: r.message, success: r.rep_completed === true }); + setLastFeedback(null); + } else if (r.feedback_type) { + setLastFeedback(r.feedback_type); + setCoachingNotice(null); + } if (r.rep_count != null) setRepCount(r.rep_count); } catch (e: any) { + if (!cancelled) { + setCaptureMessage('AI 연결을 확인하고 있습니다. 잠시 원위치에서 기다려주세요.'); + setAiError(true); + } if (__DEV__) { // eslint-disable-next-line no-console console.warn('[ai pose] status=', e?.response?.status, e?.message); @@ -331,51 +443,7 @@ export default function ExerciseScreen() { cancelled = true; clearInterval(id); }; - }, [isRecording, sessionId, sessionNonce, exerciseId, aiWorkerIndex, isForeground, isScreenFocused]); - - // 싱크로율 낮을 때 진동 피드백 - const prevSyncRef = useRef(syncRate); - useEffect(() => { - if (!isRecording) return; - const prev = prevSyncRef.current; - prevSyncRef.current = syncRate; - - // 부상 위험 구간 (<60%) 진입/유지 시 진동 알림 - if (syncRate < 60 && prev >= 60) { - Haptics.notificationAsync(Haptics.NotificationFeedbackType.Warning); - } else if (syncRate < 60) { - Haptics.impactAsync(Haptics.ImpactFeedbackStyle.Light); - } - }, [syncRate, isRecording]); - - // 싱크로율에 따른 비네트 페이드 애니메이션 - useEffect(() => { - if (!isRecording) { - borderOpacity.setValue(0); - return; - } - - if (syncRate < 60) { - // 부상 위험 구간(<60%): 빨강이 부드럽게 페이드 in/out - const pulse = Animated.loop( - Animated.sequence([ - Animated.timing(borderOpacity, { toValue: 0.9, duration: 800, useNativeDriver: false }), - Animated.timing(borderOpacity, { toValue: 0.4, duration: 800, useNativeDriver: false }), - ]), - ); - pulse.start(); - return () => pulse.stop(); - } - - // 60% 이상: 은은하게 고정 (정석 80%+ 는 더 옅게) - Animated.timing(borderOpacity, { - toValue: syncRate >= 80 ? 0.5 : 0.6, - duration: 400, - useNativeDriver: false, - }).start(); - }, [syncRate, isRecording]); - - const syncColor = getSyncColor(syncRate); + }, [busy, isRecording, sessionId, sessionNonce, exerciseId, aiWorkerIndex, isForeground, isScreenFocused]); // 카메라 권한 없을 때 if (!permission) { @@ -405,19 +473,19 @@ export default function ExerciseScreen() { return ( - {/* 싱크로율 기반 비네트 그라데이션 (4방향) */} - - - - {/* 카메라 뷰 */} - + setCameraError(error.message || '카메라 연결에 실패했습니다.')} + > {/* 상단 UI 오버레이 */} router.back()} style={styles.iconBtn}> @@ -433,38 +501,71 @@ export default function ExerciseScreen() { - {/* 싱크로율 게이지 */} - - - 싱크로율 - - + + 카메라를 열 수 없습니다 + + {Platform.OS === 'web' + ? '브라우저의 카메라 권한과 연결된 카메라를 확인해주세요.' + : '기기의 카메라 권한과 연결 상태를 확인해주세요.'} + + {__DEV__ && {cameraError}} +