Storage: {_html_escape(usage_storage_note())} Event log: {_html_escape(USAGE_EVENTS_PATH)} Summary: {_html_escape(USAGE_SUMMARY_PATH)} Last event: {_html_escape(summary.get("last_event_at") or "No events yet")}
"""
JOINT_DISPLAY_NAMES = {
"nose": "鼻子",
"left_eye": "左眼",
"right_eye": "右眼",
"left_ear": "左耳",
"right_ear": "右耳",
"left_shoulder": "左肩",
"right_shoulder": "右肩",
"shoulder": "肩部",
"left_elbow": "左肘",
"right_elbow": "右肘",
"elbow": "肘部",
"left_wrist": "左腕",
"right_wrist": "右腕",
"wrist": "手腕",
"left_hip": "左髋",
"right_hip": "右髋",
"hip": "髋部",
"left_knee": "左膝",
"right_knee": "右膝",
"knee": "膝盖",
"left_ankle": "左踝",
"right_ankle": "右踝",
"ankle": "脚踝",
}
ROWING_ERROR_CATALOG = [
{
"error_id": "early_body_open",
"error_name": "过早打开身体",
"phase": "拉桨前期",
"description": "Drive前20%身体提前后倒,影响蹬腿发力效率",
"severity_levels": {
"normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
},
},
{
"error_id": "early_elbow_bend",
"error_name": "曲臂过早",
"phase": "拉桨前期",
"description": "Drive前20%手肘提前弯曲,导致手臂先发力而非腿部",
"severity_levels": {
"normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
},
},
{
"error_id": "shooting_slide",
"error_name": "跑座板",
"phase": "拉桨中期",
"description": "Drive前40%座板速度明显快于手柄,导致力量浪费",
"severity_levels": {
"normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
},
},
{
"error_id": "leg_recovery_issue",
"error_name": "腿部回收异常",
"phase": "回桨阶段",
"description": "Recovery阶段膝盖回收动作异常(收腿过早/过晚/角度不对)",
"severity_levels": {
"normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
},
},
{
"error_id": "excessive_layback",
"error_name": "后仰过多",
"phase": "出水阶段",
"description": "Finish阶段躯干后倒角度过大,可能导致腰部压力",
"severity_levels": {
"normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
},
},
{
"error_id": "knee_not_extended",
"error_name": "膝盖未伸直",
"phase": "出水阶段",
"description": "Finish阶段膝盖未完全伸直,影响力量传递",
"severity_levels": {
"normal": {"threshold": 160, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 150, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 140, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("-inf"), "color": "#FF6B6B", "text": "重度"},
"is_angle": True,
},
},
{
"error_id": "wavy_handle_path",
"error_name": "手柄轨迹异常",
"phase": "全程",
"description": "手柄轨迹偏离直线,影响划桨效率",
"severity_levels": {
"normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
},
},
{
"error_id": "catch_technique_issue",
"error_name": "抓水技术问题",
"phase": "抓水阶段",
"description": "Catch阶段动作与标准模式偏差较大",
"severity_levels": {
"normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
},
},
{
"error_id": "wrist_flexion",
"error_name": "手腕折腕",
"phase": "出水阶段",
"description": "Finish阶段手腕过度伸展,影响握桨稳定性",
"severity_levels": {
"normal": {"threshold": 1.2, "color": "#6BCB77", "text": "正常"},
"low": {"threshold": 1.5, "color": "#FFD93D", "text": "轻度"},
"medium": {"threshold": 2.0, "color": "#FF9F43", "text": "中度"},
"high": {"threshold": float("inf"), "color": "#FF6B6B", "text": "重度"},
},
},
]
ERROR_LOCALIZATION = {
"early_body_open": {
"zh": {
"name": "过早打开身体",
"phase": "拉桨前期",
"description": "Drive 前 20% 身体提前后倒,影响蹬腿发力效率。",
"suggestion": "保持手臂放松伸直,先用腿推动脚踏,再让躯干逐步打开。",
},
"en": {
"name": "Early Body Opening",
"phase": "Early Drive",
"description": "The trunk opens too early in the first 20% of the drive, reducing leg-drive efficiency.",
"suggestion": "Keep the arms relaxed and long. Push with the legs first, then open the trunk progressively.",
},
},
"early_elbow_bend": {
"zh": {
"name": "曲臂过早",
"phase": "拉桨前期",
"description": "Drive 前 20% 手肘提前弯曲,导致手臂先发力而非腿部主导。",
"suggestion": "在蹬腿阶段保持手臂伸直,把手臂拉桨延后到身体打开之后。",
},
"en": {
"name": "Early Elbow Bend",
"phase": "Early Drive",
"description": "The elbows bend too early in the first 20% of the drive, shifting load from legs to arms.",
"suggestion": "Keep the arms straight during leg drive and delay the arm pull until after trunk opening.",
},
},
"shooting_slide": {
"zh": {
"name": "跑座板",
"phase": "拉桨中期",
"description": "Drive 前 40% 座板速度明显快于手柄,导致力量传递效率下降。",
"suggestion": "让手柄和座板同步移动,想象脚踏、髋部和手柄处在同一条发力链上。",
},
"en": {
"name": "Shooting Slide",
"phase": "Mid Drive",
"description": "The seat moves faster than the handle in the first 40% of the drive, reducing force transfer.",
"suggestion": "Synchronize seat and handle movement, keeping footplate, hips, and handle on one connected power chain.",
},
},
"leg_recovery_issue": {
"zh": {
"name": "腿部回收异常",
"phase": "回桨阶段",
"description": "Recovery 阶段膝盖回收节奏或角度异常。",
"suggestion": "按照手臂、身体、腿的顺序回桨,先让手柄越过膝盖,再逐步收腿。",
},
"en": {
"name": "Leg Recovery Issue",
"phase": "Recovery",
"description": "The knee recovery timing or angle deviates from the expected recovery pattern.",
"suggestion": "Recover in the arms-body-legs order. Let the handle pass the knees before gradually bending the legs.",
},
},
"excessive_layback": {
"zh": {
"name": "后仰过多",
"phase": "出水阶段",
"description": "Finish 阶段躯干后倒角度过大,可能增加腰部压力。",
"suggestion": "控制出水位置,保持核心稳定,躯干后仰以可控的小角度结束。",
},
"en": {
"name": "Excessive Layback",
"phase": "Finish",
"description": "The trunk leans back excessively at the finish, which may increase lower-back stress.",
"suggestion": "Control the finish position, keep the core stable, and finish with a smaller, controlled layback angle.",
},
},
"knee_not_extended": {
"zh": {
"name": "膝盖未伸直",
"phase": "出水阶段",
"description": "Finish 阶段膝盖未充分伸展,影响力量传递。",
"suggestion": "在身体明显打开和手臂发力前,优先完成腿部蹬伸。",
},
"en": {
"name": "Incomplete Knee Extension",
"phase": "Finish",
"description": "The knees are not fully extended at the finish, limiting force transfer.",
"suggestion": "Prioritize completing leg extension before the trunk opens strongly and the arms finish the stroke.",
},
},
"wavy_handle_path": {
"zh": {
"name": "手柄轨迹异常",
"phase": "全程",
"description": "手柄轨迹偏离稳定路径,影响划桨效率。",
"suggestion": "保持手柄路径平稳,出水和回桨时避免明显上下波动。",
},
"en": {
"name": "Irregular Handle Path",
"phase": "Full Stroke",
"description": "The handle path deviates from a stable trajectory, reducing rowing efficiency.",
"suggestion": "Keep the handle path smooth and avoid unnecessary vertical movement during finish and recovery.",
},
},
"catch_technique_issue": {
"zh": {
"name": "抓水技术问题",
"phase": "抓水阶段",
"description": "Catch 阶段动作与参考模式偏差较大。",
"suggestion": "在前端保持身体稳定、手臂自然伸展,先建立身体张力再启动蹬腿。",
},
"en": {
"name": "Catch Technique Issue",
"phase": "Catch",
"description": "The catch position deviates from the learned reference movement pattern.",
"suggestion": "Stay stable at the front end, keep the arms naturally extended, build body tension, then initiate leg drive.",
},
},
"wrist_flexion": {
"zh": {
"name": "手腕折腕",
"phase": "出水阶段",
"description": "Finish 阶段手腕过度伸展或弯折,影响握桨稳定性。",
"suggestion": "保持手腕中立,手柄由肘部和背部完成拉入,不要用手腕补动作。",
},
"en": {
"name": "Wrist Flexion",
"phase": "Finish",
"description": "The wrist bends excessively at the finish, reducing handle stability.",
"suggestion": "Keep the wrists neutral. Finish the handle draw with elbows and back rather than compensating with the wrists.",
},
},
}
SEVERITY_LOCALIZATION = {
"zh": {"normal": "正常", "low": "轻度", "medium": "中度", "high": "重度"},
"en": {"normal": "Normal", "low": "Low", "medium": "Medium", "high": "High"},
}
class LSTMAutoEncoder(nn.Module):
def __init__(
self,
input_dim: int,
hidden_dim: int,
latent_dim: int,
num_layers: int,
dropout: float = 0.0,
) -> None:
super().__init__()
lstm_dropout = dropout if num_layers > 1 else 0.0
self.encoder_lstm = nn.LSTM(
input_dim,
hidden_dim,
num_layers,
batch_first=True,
dropout=lstm_dropout,
)
self.encoder_fc = nn.Linear(hidden_dim, latent_dim)
self.decoder_fc = nn.Linear(latent_dim, hidden_dim)
self.decoder_lstm = nn.LSTM(
hidden_dim,
hidden_dim,
num_layers,
batch_first=True,
dropout=lstm_dropout,
)
self.output_layer = nn.Linear(hidden_dim, input_dim)
def forward(self, x: torch.Tensor) -> tuple[torch.Tensor, torch.Tensor]:
_, (hidden, _) = self.encoder_lstm(x)
z = self.encoder_fc(hidden[-1])
z_rep = z.unsqueeze(1).repeat(1, x.size(1), 1)
decoded = self.decoder_fc(z_rep)
decoded, _ = self.decoder_lstm(decoded)
recon = self.output_layer(decoded)
return recon, z
def choose_device() -> torch.device:
if torch.backends.mps.is_available():
return torch.device("mps")
if torch.cuda.is_available():
return torch.device("cuda")
return torch.device("cpu")
def choose_ae_device() -> torch.device:
# The autoencoder is lightweight; keep it on CPU in Spaces to reduce memory use.
force_cpu_default = bool(os.getenv("SPACE_ID"))
if env_flag("ROWING_AE_FORCE_CPU", force_cpu_default):
return torch.device("cpu")
return choose_device()
def get_yolo_device() -> str:
"""YOLO 设备字符串: 'mps' / '0' (cuda) / 'cpu'"""
if torch.backends.mps.is_available():
return "mps"
if torch.cuda.is_available():
return "0"
return "cpu"
def env_flag(name: str, default: bool) -> bool:
raw = os.getenv(name)
if raw is None:
return default
return raw.strip().lower() in {"1", "true", "yes", "on"}
def env_int(name: str, default: int, minimum: int | None = None) -> int:
try:
value = int(os.getenv(name, str(default)))
except (TypeError, ValueError):
value = default
if minimum is not None:
value = max(minimum, value)
return value
def cpu_fast_mode_enabled() -> bool:
default = bool(os.getenv("SPACE_ID")) or get_yolo_device() == "cpu"
return env_flag("ROWING_CPU_FAST_MODE", default)
def configure_cpu_runtime() -> None:
torch_threads = env_int("ROWING_TORCH_THREADS", min(4, max(1, os.cpu_count() or 1)), 1)
try:
torch.set_num_threads(torch_threads)
except Exception as exc:
logger.warning("Could not set torch CPU threads: %s", exc)
try:
cv2.setNumThreads(0)
except Exception as exc:
logger.warning("Could not set OpenCV CPU threads: %s", exc)
def package_version(package_name: str) -> str:
try:
return metadata.version(package_name)
except metadata.PackageNotFoundError:
return "not installed"
def log_runtime_versions() -> None:
logger.info(
"Runtime versions: gradio=%s torch=%s torchvision=%s ultralytics=%s opencv=%s numpy=%s scipy=%s matplotlib=%s",
package_version("gradio"),
package_version("torch"),
package_version("torchvision"),
package_version("ultralytics"),
cv2.__version__,
np.__version__,
package_version("scipy"),
package_version("matplotlib"),
)
logger.info(
"Runtime hardware: yolo_device=%s torch_threads=%s cpu_count=%s space_id=%s",
get_yolo_device(),
torch.get_num_threads(),
os.cpu_count(),
os.getenv("SPACE_ID", ""),
)
def first_existing_index(names: list[str], candidates: list[str]) -> int | None:
for candidate in candidates:
if candidate in names:
return names.index(candidate)
return None
@lru_cache(maxsize=1)
def load_yolo_model():
if not YOLO_MODEL_PATH.exists():
raise FileNotFoundError(f"Missing YOLO model: {YOLO_MODEL_PATH}")
from ultralytics import YOLO
return YOLO(str(YOLO_MODEL_PATH))
def load_ae_model(model_path: Path, threshold_path: Path):
device = choose_ae_device()
logger.info("Loading AE model %s on device=%s", model_path.name, device)
checkpoint = torch.load(str(model_path), map_location=device, weights_only=False)
raw_config = checkpoint.get("config") or {}
config = {
"input_dim": int(checkpoint.get("input_dim", raw_config.get("input_dim", 18))),
"hidden_dim": int(raw_config.get("hidden_dim", 96)),
"latent_dim": int(raw_config.get("latent_dim", 24)),
"num_layers": int(raw_config.get("num_layers", 2)),
"dropout": float(raw_config.get("dropout", 0.0)),
"target_len": int(raw_config.get("target_len", 100)),
"phase_filter": raw_config.get("phase_filter", "drive"),
}
model = LSTMAutoEncoder(
input_dim=config["input_dim"],
hidden_dim=config["hidden_dim"],
latent_dim=config["latent_dim"],
num_layers=config["num_layers"],
dropout=config["dropout"],
).to(device)
model.load_state_dict(checkpoint["model_state_dict"])
model.eval()
threshold = float(np.load(str(threshold_path)))
return model, config, threshold, device
def readable_seconds(seconds: float) -> str:
if seconds < 60:
return f"{seconds:.1f}s"
minutes = int(seconds // 60)
remain = seconds - minutes * 60
return f"{minutes}m {remain:.0f}s"
def progress_description(done: int, total: int | None, start_time: float) -> tuple[float, str]:
elapsed = max(0.0, time.time() - start_time)
if total and total > 0:
pct = min(1.0, float(done) / float(total))
if done > 0 and pct > 0:
estimated_total = elapsed / pct
remaining = max(0.0, estimated_total - elapsed)
eta_text = readable_seconds(remaining)
else:
eta_text = "calculating"
desc = (
f"Processing frame {done}/{total} - {pct * 100:.1f}% | "
f"elapsed {readable_seconds(elapsed)} | ETA {eta_text}"
)
return pct, desc
desc = f"Processing frame {done} | elapsed {readable_seconds(elapsed)}"
return 0.0, desc
def encode_browser_mp4(input_path: Path, output_path: Path, fps: float) -> Path:
ffmpeg = shutil.which("ffmpeg")
if ffmpeg is None:
print("FFmpeg not found; returning OpenCV mp4v output.", flush=True)
return input_path
cmd = [
ffmpeg,
"-y",
"-i",
str(input_path),
"-r",
f"{fps:.6f}",
"-c:v",
"libx264",
"-preset",
"veryfast",
"-pix_fmt",
"yuv420p",
"-movflags",
"+faststart",
str(output_path),
]
try:
subprocess.run(cmd, check=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
except subprocess.CalledProcessError as exc:
print(f"FFmpeg encode failed; returning OpenCV mp4v output. {exc.stderr[-800:]}", flush=True)
return input_path
return output_path if output_path.exists() and output_path.stat().st_size > 0 else input_path
@lru_cache(maxsize=8)
def ffmpeg_encoder_available(encoder_name: str) -> bool:
ffmpeg = shutil.which("ffmpeg")
if ffmpeg is None:
return False
try:
result = subprocess.run(
[ffmpeg, "-hide_banner", "-encoders"],
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=10,
)
except Exception:
return False
return encoder_name in result.stdout
def run_ffmpeg_command(cmd: list[str], label: str) -> subprocess.CompletedProcess:
logger.debug("%s command: %s", label, " ".join(cmd))
return subprocess.run(
cmd,
check=True,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=FFMPEG_TIMEOUT_SECONDS,
)
def ffmpeg_clip(input_path: Path, output_path: Path, start_sec: float, end_sec: float | None) -> Path:
ffmpeg = shutil.which("ffmpeg")
if ffmpeg is None:
logger.error("FFmpeg not found in system path")
raise gr.Error("FFmpeg is required to create a monitored clip.")
logger.info(f"Starting ffmpeg clip: input={input_path}, output={output_path}, start_sec={start_sec:.3f}, end_sec={end_sec}")
if not input_path.exists():
logger.error(f"Input file does not exist: {input_path}")
raise gr.Error(f"Input file not found: {input_path.name}")
if input_path.stat().st_size == 0:
logger.error(f"Input file is empty: {input_path}")
raise gr.Error(f"Input file is empty: {input_path.name}")
base_cmd = [ffmpeg, "-y", "-ss", f"{max(0.0, start_sec):.3f}", "-i", str(input_path)]
if end_sec is not None and end_sec > start_sec:
duration = end_sec - start_sec
logger.info(f"Clipping with duration: {duration:.3f}s")
else:
duration = None
logger.info("Clipping from start to end of video")
fast_cmd = [*base_cmd]
if duration is not None:
fast_cmd.extend(["-t", f"{duration:.3f}"])
fast_cmd.extend([
"-map",
"0:v:0",
"-an",
"-c:v",
"copy",
"-avoid_negative_ts",
"make_zero",
"-movflags",
"+faststart",
str(output_path),
])
try:
result = run_ffmpeg_command(fast_cmd, "FFmpeg fast clip")
logger.info(f"FFmpeg fast clip completed successfully. stdout={result.stdout[:500]}")
except (subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc:
if output_path.exists():
output_path.unlink(missing_ok=True)
stderr = getattr(exc, "stderr", "") or ""
logger.warning("FFmpeg fast clip failed; falling back to re-encode. %s", stderr[-800:])
encode_cmd = [*base_cmd]
if duration is not None:
encode_cmd.extend(["-t", f"{duration:.3f}"])
if platform.system() == "Darwin" and ffmpeg_encoder_available("h264_videotoolbox"):
encode_cmd.extend(["-an", "-c:v", "h264_videotoolbox", "-b:v", "5000k", "-pix_fmt", "yuv420p"])
else:
encode_cmd.extend(["-an", "-c:v", "libx264", "-preset", "ultrafast", "-pix_fmt", "yuv420p"])
encode_cmd.extend(["-movflags", "+faststart", str(output_path)])
try:
result = run_ffmpeg_command(encode_cmd, "FFmpeg re-encode clip")
logger.info(f"FFmpeg re-encode completed successfully. stdout={result.stdout[:500]}")
except subprocess.TimeoutExpired:
logger.error("FFmpeg clip timed out after %ss", FFMPEG_TIMEOUT_SECONDS)
raise gr.Error(
"Video clipping timed out. Try a shorter clip, reduce the video resolution, or install Homebrew FFmpeg."
)
except subprocess.CalledProcessError as reencode_exc:
logger.error(f"FFmpeg clip failed with exit code {reencode_exc.returncode}")
logger.error(f"FFmpeg stderr: {reencode_exc.stderr}")
raise gr.Error(f"Could not create the monitored clip. FFmpeg error: {reencode_exc.stderr[-500:]}")
if not output_path.exists():
logger.error(f"Output file was not created: {output_path}")
raise gr.Error("The monitored clip was not created. Please check the start/end time.")
if output_path.stat().st_size == 0:
logger.error(f"Output file is empty: {output_path}")
raise gr.Error("The monitored clip was empty. Please check the start/end time.")
logger.info(f"Clip created successfully: {output_path}, size={output_path.stat().st_size/1024:.2f} KB")
return output_path
def resolve_uploaded_video_path(video_input) -> Path | None:
logger.debug(f"resolve_uploaded_video_path called with type={type(video_input).__name__}, value={video_input}")
if video_input is None:
logger.debug("video_input is None, returning None")
return None
if isinstance(video_input, (str, Path)):
result = Path(video_input)
logger.debug(f"video_input is str/Path, returning: {result}")
return result
if isinstance(video_input, dict):
path = video_input.get("path") or video_input.get("name")
result = Path(path) if path else None
logger.debug(f"video_input is dict, keys={list(video_input.keys())}, path={path}, returning: {result}")
return result
if isinstance(video_input, (tuple, list)) and video_input:
logger.debug(f"video_input is tuple/list, recursing on first element")
return resolve_uploaded_video_path(video_input[0])
path = getattr(video_input, "path", None) or getattr(video_input, "name", None)
result = Path(path) if path else None
logger.debug(f"video_input is object, path attr={path}, returning: {result}")
return result
def smooth_keypoints(buffer: list[np.ndarray], keypoints: np.ndarray, window_size: int) -> np.ndarray:
if window_size <= 1:
return keypoints
buffer.append(keypoints.copy())
del buffer[:-window_size]
stacked = np.stack(buffer, axis=0)
smoothed = keypoints.copy()
smoothed[:, :2] = stacked[:, :, :2].mean(axis=0)
smoothed[:, 2] = stacked[:, :, 2].mean(axis=0)
return smoothed
def draw_person(
canvas: np.ndarray,
keypoints: np.ndarray,
point_conf: float,
line_width: int,
line_color=LINE_COLOR,
joint_color=JOINT_COLOR,
skeleton=None,
):
points = keypoints[:, :2]
confs = keypoints[:, 2]
for a, b in (skeleton or SKELETON):
if confs[a] < point_conf or confs[b] < point_conf:
continue
pa = tuple(np.round(points[a]).astype(int))
pb = tuple(np.round(points[b]).astype(int))
cv2.line(canvas, pa, pb, line_color, line_width, lineType=cv2.LINE_AA)
radius = max(3, line_width + 2)
for idx, (x, y) in enumerate(points):
if confs[idx] < point_conf:
continue
cv2.circle(canvas, (int(round(x)), int(round(y))), radius, joint_color, -1, lineType=cv2.LINE_AA)
def draw_overlay_people(
canvas: np.ndarray,
people_keypoints: list[np.ndarray],
point_conf: float,
line_width: int,
status_text: str,
) -> None:
for keypoints in people_keypoints:
draw_person(canvas, keypoints, point_conf, line_width + 4, (5, 8, 12), (5, 8, 12))
draw_person(canvas, keypoints, point_conf, line_width)
cv2.putText(canvas, status_text, (18, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.85, (5, 8, 12), 5, cv2.LINE_AA)
cv2.putText(canvas, status_text, (18, 34), cv2.FONT_HERSHEY_SIMPLEX, 0.85, TEXT_COLOR, 2, cv2.LINE_AA)
def normalize_cycle(cycle: np.ndarray, keypoint_names: list[str], target_len: int) -> np.ndarray:
xy = cycle[:, :, :2].astype(np.float32)
ankle = first_existing_index(keypoint_names, ["left_ankle", "right_ankle", "ankle"])
left_hip = first_existing_index(keypoint_names, ["left_hip", "hip"])
right_hip = first_existing_index(keypoint_names, ["right_hip"])
if ankle is not None:
origin = xy[:, ankle]
elif left_hip is not None and right_hip is not None:
origin = (xy[:, left_hip] + xy[:, right_hip]) / 2.0
elif left_hip is not None:
origin = xy[:, left_hip]
else:
origin = xy.mean(axis=1)
centered = xy - origin[:, None, :]
nose = first_existing_index(keypoint_names, ["nose", "head"])
shoulder = first_existing_index(keypoint_names, ["left_shoulder", "right_shoulder", "shoulder"])
hip = left_hip if left_hip is not None else right_hip
scale_values = None
if nose is not None and ankle is not None:
scale_values = np.linalg.norm(centered[:, nose] - centered[:, ankle], axis=1)
elif shoulder is not None and ankle is not None:
scale_values = np.linalg.norm(centered[:, shoulder] - centered[:, ankle], axis=1)
elif shoulder is not None and hip is not None:
scale_values = np.linalg.norm(centered[:, shoulder] - centered[:, hip], axis=1)
if scale_values is None:
scale_values = np.linalg.norm(centered, axis=2).max(axis=1)
scale = float(np.nanmedian(scale_values[scale_values > 1e-6])) if np.any(scale_values > 1e-6) else 1.0
normalized = centered / scale
t_orig = np.linspace(0, 1, normalized.shape[0])
t_new = np.linspace(0, 1, target_len)
interpolated = np.zeros((target_len, normalized.shape[1], 2), dtype=np.float32)
for joint_idx in range(normalized.shape[1]):
for axis in range(2):
interpolator = interp1d(t_orig, normalized[:, joint_idx, axis], kind="linear", fill_value="extrapolate")
interpolated[:, joint_idx, axis] = interpolator(t_new)
return interpolated.reshape(target_len, -1)
def compute_angle(a: np.ndarray, b: np.ndarray, c: np.ndarray) -> float:
ab = a - b
bc = c - b
cos_angle = np.dot(ab, bc) / (np.linalg.norm(ab) * np.linalg.norm(bc) + 1e-8)
cos_angle = np.clip(cos_angle, -1.0, 1.0)
return np.degrees(np.arccos(cos_angle))
def compute_torso_angle(shoulder: np.ndarray, hip: np.ndarray) -> float:
torso_vec = shoulder - hip
vertical_vec = np.array([0, -1])
cos_angle = np.dot(torso_vec, vertical_vec) / (np.linalg.norm(torso_vec) + 1e-8)
cos_angle = np.clip(cos_angle, -1.0, 1.0)
angle = np.degrees(np.arccos(cos_angle))
if torso_vec[0] > 0:
angle = -angle
return angle
def compute_knee_angle(hip: np.ndarray, knee: np.ndarray, ankle: np.ndarray) -> float:
return compute_angle(hip, knee, ankle)
def diagnose_rowing_technique(
pose: np.ndarray,
keypoint_names: list[str],
num_frames: int,
reconstruction: np.ndarray | None = None,
joint_frame_mse: np.ndarray | None = None,
cycle_mse: float | None = None,
mse_threshold: float | None = None,
score: float | None = None,
) -> list[dict]:
diagnoses = []
def get_joint_idx(name_keyword: str) -> int:
for idx, name in enumerate(keypoint_names):
if name_keyword in name.lower():
return idx
return -1
wrist_idx = get_joint_idx("wrist")
elbow_idx = get_joint_idx("elbow")
shoulder_idx = get_joint_idx("shoulder")
hip_idx = get_joint_idx("hip")
knee_idx = get_joint_idx("knee")
ankle_idx = get_joint_idx("ankle")
if wrist_idx < 0 or shoulder_idx < 0 or hip_idx < 0:
return diagnoses
torso_angles = np.array([
compute_torso_angle(pose[i, shoulder_idx], pose[i, hip_idx])
for i in range(num_frames)
])
joint_errors = None
avg_error = 0
if reconstruction is not None and joint_frame_mse is not None:
joint_errors = np.mean(joint_frame_mse, axis=0)
avg_error = np.mean(joint_errors) if len(joint_errors) > 0 else 0
score_value = float(score) if score is not None else None
mse_threshold_value = float(mse_threshold or 0.0)
recovery_start = int(0.75 * num_frames)
drive_end = int(0.40 * num_frames)
finish_start = int(0.85 * num_frames)
catch_end = int(0.10 * num_frames)
drive_early_end = int(0.20 * num_frames)
def determine_severity(error_ratio: float, catalog_item: dict) -> str:
levels = catalog_item["severity_levels"]
is_angle = levels.get("is_angle", False)
if is_angle:
angle_value = error_ratio
if angle_value >= levels["normal"]["threshold"]:
return "normal"
elif angle_value >= levels["low"]["threshold"]:
return "low"
elif angle_value >= levels["medium"]["threshold"]:
return "medium"
else:
return "high"
else:
if error_ratio < levels["normal"]["threshold"]:
return "normal"
elif error_ratio < levels["low"]["threshold"]:
return "low"
elif error_ratio < levels["medium"]["threshold"]:
return "medium"
else:
return "high"
def moderate_severity(raw_severity: str, local_abs_error: float) -> str:
if raw_severity in ("normal", "low"):
return raw_severity
joint_exceeds_threshold = mse_threshold_value > 0 and local_abs_error > mse_threshold_value
joint_strongly_exceeds = mse_threshold_value > 0 and local_abs_error > mse_threshold_value * 2.0
low_score = score_value is not None and score_value < 70.0
very_low_score = score_value is not None and score_value < 55.0
if raw_severity == "high":
if very_low_score or joint_strongly_exceeds:
return "high"
if low_score or joint_exceeds_threshold:
return "medium"
return "low"
if raw_severity == "medium":
if low_score or joint_exceeds_threshold:
return "medium"
return "low"
return raw_severity
for catalog_item in ROWING_ERROR_CATALOG:
error_id = catalog_item["error_id"]
error_name = catalog_item["error_name"]
phase = catalog_item["phase"]
description = catalog_item["description"]
error_ratio = 1.0
local_abs_error = 0.0
evidence = ""
try:
if error_id == "early_body_open":
if drive_early_end > 0 and joint_errors is not None:
early_error = np.mean(joint_frame_mse[:drive_early_end, [shoulder_idx, hip_idx]]) if hip_idx < len(joint_errors) else 0
local_abs_error = float(early_error)
error_ratio = early_error / (avg_error + 1e-8)
early_torso_angle = np.mean(torso_angles[:drive_early_end])
evidence = f"躯干角度{early_torso_angle:.1f}°,上半身误差比{error_ratio:.2f}倍"
elif error_id == "early_elbow_bend":
if joint_errors is not None and elbow_idx >= 0 and elbow_idx < len(joint_errors):
local_abs_error = float(joint_errors[elbow_idx])
error_ratio = joint_errors[elbow_idx] / (avg_error + 1e-8)
evidence = f"手肘误差比{error_ratio:.2f}倍"
elif error_id == "shooting_slide":
if joint_errors is not None and drive_end > 0 and wrist_idx < len(joint_errors):
wrist_vx = np.abs(np.gradient(pose[:drive_end, wrist_idx, 0]))
hip_vx = np.abs(np.gradient(pose[:drive_end, hip_idx, 0]))
valid_mask = (wrist_vx > 0.001) & (hip_vx > 0.001)
if np.any(valid_mask):
speed_ratio = np.mean(hip_vx[valid_mask] / wrist_vx[valid_mask])
local_abs_error = float(avg_error)
error_ratio = speed_ratio / 1.5
evidence = f"座板速度是手柄的{speed_ratio:.2f}倍"
else:
evidence = "速度数据不足"
elif error_id == "leg_recovery_issue":
if joint_errors is not None and knee_idx >= 0 and knee_idx < len(joint_errors) and recovery_start < num_frames:
knee_error = np.mean(joint_frame_mse[recovery_start:, knee_idx])
local_abs_error = float(knee_error)
error_ratio = knee_error / (avg_error + 1e-8)
evidence = f"膝盖误差比{error_ratio:.2f}倍"
elif error_id == "excessive_layback":
if finish_start < num_frames and joint_errors is not None:
finish_error = np.mean(joint_frame_mse[finish_start:, [shoulder_idx, hip_idx]]) if hip_idx < len(joint_errors) else 0
local_abs_error = float(finish_error)
error_ratio = finish_error / (avg_error + 1e-8)
finish_torso_angle = np.mean(torso_angles[finish_start:])
evidence = f"躯干后仰{finish_torso_angle:.1f}°,上半身误差比{error_ratio:.2f}倍"
elif error_id == "knee_not_extended":
if knee_idx >= 0 and ankle_idx >= 0 and finish_start < num_frames:
knee_angles = np.array([
compute_knee_angle(pose[i, hip_idx], pose[i, knee_idx], pose[i, ankle_idx])
for i in range(num_frames)
])
finish_knee_angle = np.mean(knee_angles[finish_start:])
if joint_frame_mse is not None and knee_idx < joint_frame_mse.shape[1]:
local_abs_error = float(np.mean(joint_frame_mse[finish_start:, knee_idx]))
error_ratio = finish_knee_angle
evidence = f"膝盖角度{finish_knee_angle:.1f}°"
elif error_id == "wavy_handle_path":
if joint_errors is not None and wrist_idx < len(joint_errors):
local_abs_error = float(joint_errors[wrist_idx])
error_ratio = joint_errors[wrist_idx] / (avg_error + 1e-8)
evidence = f"手腕误差比{error_ratio:.2f}倍"
elif error_id == "catch_technique_issue":
if catch_end > 0 and joint_frame_mse is not None:
catch_error = np.mean(joint_frame_mse[:catch_end])
local_abs_error = float(catch_error)
error_ratio = catch_error / (avg_error + 1e-8) if avg_error > 0 else 1.0
evidence = f"抓水误差比{error_ratio:.2f}倍"
elif error_id == "wrist_flexion":
if joint_errors is not None and wrist_idx < len(joint_errors) and finish_start < num_frames:
wrist_error = np.mean(joint_frame_mse[finish_start:, wrist_idx])
local_abs_error = float(wrist_error)
error_ratio = wrist_error / (avg_error + 1e-8)
evidence = f"手腕误差比{error_ratio:.2f}倍"
except Exception:
error_ratio = 1.0
local_abs_error = 0.0
evidence = "检测失败"
severity = moderate_severity(determine_severity(error_ratio, catalog_item), local_abs_error)
severity_info = catalog_item["severity_levels"][severity]
diagnoses.append({
"error_id": error_id,
"error_name": error_name,
"phase": phase,
"description": description,
"suggestion": ERROR_LOCALIZATION.get(error_id, {}).get("zh", {}).get("suggestion", ""),
"severity": severity,
"severity_text": severity_info["text"],
"severity_color": severity_info["color"],
"evidence": evidence,
"local_mse": float(local_abs_error),
"cycle_mse": float(cycle_mse or 0.0),
"threshold": float(mse_threshold_value),
})
return diagnoses
def detect_cycles(wrist_x: np.ndarray, fps: float = 30.0) -> list[tuple[int, int, str]]:
wrist_x = np.asarray(wrist_x, dtype=np.float32)
n = len(wrist_x)
if n < 8 or np.nanmax(wrist_x) - np.nanmin(wrist_x) < 1e-6:
return []
window_size = max(5, min(21, n // 12))
if window_size % 2 == 0:
window_size += 1
kernel = np.ones(window_size, dtype=np.float32) / window_size
smoothed = np.convolve(wrist_x, kernel, mode="same")
half = window_size // 2
smoothed[:half] = wrist_x[:half]
smoothed[-half:] = wrist_x[-half:]
amplitude = float(np.ptp(smoothed))
fps = max(1.0, float(fps or 30.0))
min_segment_frames = max(4, int(round(env_int("ROWING_MIN_PHASE_MS", 450, 100) / 1000.0 * fps)))
max_segment_frames = max(min_segment_frames + 2, int(round(env_int("ROWING_MAX_PHASE_MS", 2800, 600) / 1000.0 * fps)))
min_motion_ratio = float(os.getenv("ROWING_MIN_PHASE_MOTION_RATIO", "0.18"))
min_motion_px = max(float(os.getenv("ROWING_MIN_PHASE_MOTION_PX", "8")), amplitude * min_motion_ratio)
distance = max(3, min_segment_frames // 2)
prominence = max(amplitude * 0.055, min_motion_px * 0.25, 0.5)
max_peaks, _ = find_peaks(smoothed, distance=distance, prominence=prominence)
min_peaks, _ = find_peaks(-smoothed, distance=distance, prominence=prominence)
extrema = [(int(idx), "max") for idx in max_peaks] + [(int(idx), "min") for idx in min_peaks]
edge_span = max(3, min(distance, n // 8))
start_kind = "min" if smoothed[0] <= smoothed[edge_span] else "max"
end_kind = "min" if smoothed[-1] <= smoothed[-1 - edge_span] else "max"
extrema.extend([(0, start_kind), (n - 1, end_kind)])
extrema.sort(key=lambda item: item[0])
if len(extrema) < 2:
return []
filtered: list[tuple[int, str]] = []
for idx, kind in extrema:
if not filtered:
filtered.append((idx, kind))
continue
prev_idx, prev_kind = filtered[-1]
if kind != prev_kind:
if idx - prev_idx >= max(2, distance // 4) or idx in (0, n - 1) or prev_idx in (0, n - 1):
filtered.append((idx, kind))
continue
prev_val = smoothed[prev_idx]
cur_val = smoothed[idx]
keep_current = (kind == "max" and cur_val > prev_val) or (kind == "min" and cur_val < prev_val)
if keep_current:
filtered[-1] = (idx, kind)
def segment_motion(start: int, end: int) -> float:
if end <= start:
return 0.0
return float(abs(smoothed[end] - smoothed[start]))
def split_long_segment(start: int, end: int, start_kind: str, end_kind: str) -> list[tuple[int, int, str, str]]:
if end - start <= max_segment_frames:
return [(start, end, start_kind, end_kind)]
inner = [(idx, kind) for idx, kind in filtered if start < idx < end]
if not inner:
return []
points = [(start, start_kind)] + inner + [(end, end_kind)]
pieces = []
for (piece_start, piece_start_kind), (piece_end, piece_end_kind) in zip(points, points[1:]):
if piece_end - piece_start >= min_segment_frames:
pieces.append((piece_start, piece_end, piece_start_kind, piece_end_kind))
return pieces
candidates = []
for (start, start_kind), (end, end_kind) in zip(filtered, filtered[1:]):
candidates.extend(split_long_segment(int(start), int(end), start_kind, end_kind))
ranges = []
drive_count = 0
recovery_count = 0
rejected_short = 0
rejected_long = 0
rejected_motion = 0
for start, end, start_kind, end_kind in candidates:
length = end - start
motion = segment_motion(start, end)
if length < min_segment_frames:
rejected_short += 1
continue
if length > max_segment_frames:
rejected_long += 1
continue
if motion < min_motion_px:
rejected_motion += 1
continue
if start_kind == "min" and end_kind == "max":
drive_count += 1
ranges.append((int(start), int(end), f"cycle{drive_count}_drive"))
elif start_kind == "max" and end_kind == "min":
recovery_count += 1
ranges.append((int(start), int(end), f"cycle{recovery_count}_recovery"))
logger.info(
"Cycle detection: frames=%s fps=%.2f amplitude=%.2f min_len=%s max_len=%s min_motion=%.2f extrema=%s ranges=%s rejected_short=%s rejected_long=%s rejected_motion=%s",
n,
fps,
amplitude,
min_segment_frames,
max_segment_frames,
min_motion_px,
len(filtered),
len(ranges),
rejected_short,
rejected_long,
rejected_motion,
)
return ranges
def extract_model_keypoints(keypoints_17: np.ndarray) -> np.ndarray:
keypoints_17 = np.asarray(keypoints_17, dtype=np.float32)
if keypoints_17.shape[0] == len(MODEL_KEYPOINT_NAMES):
return keypoints_17.copy()
if keypoints_17.shape[0] < len(KEYPOINT_NAMES):
padded = np.zeros((len(KEYPOINT_NAMES), 3), dtype=np.float32)
padded[: keypoints_17.shape[0], : keypoints_17.shape[1]] = keypoints_17
keypoints_17 = padded
return keypoints_17[MODEL_KEYPOINT_INDICES].copy()
def prepare_wrist_signal(wrist_x_values: list[float]) -> np.ndarray:
wrist_x = np.asarray(wrist_x_values, dtype=np.float32)
valid = np.isfinite(wrist_x)
if np.any(valid):
valid_idx = np.flatnonzero(valid)
return np.interp(np.arange(len(wrist_x)), valid_idx, wrist_x[valid_idx]).astype(np.float32)
return np.zeros(len(wrist_x), dtype=np.float32)
def fallback_cycles(frame_numbers: list[int]) -> list[tuple[int, int, str]]:
if len(frame_numbers) < 2:
return []
mid = len(frame_numbers) // 2
if mid <= 0 or mid >= len(frame_numbers):
return [(int(frame_numbers[0]), int(frame_numbers[-1]), "cycle1_drive")]
return [
(int(frame_numbers[0]), int(frame_numbers[mid]), "cycle1_drive"),
(int(frame_numbers[mid]), int(frame_numbers[-1]), "cycle1_recovery"),
]
def fill_missing_keypoints(sequence: list[np.ndarray]) -> list[np.ndarray]:
filled = []
last_valid = None
zero_pose = np.zeros((len(KEYPOINT_NAMES), 3), dtype=np.float32)
for keypoints in sequence:
keypoints = np.asarray(keypoints, dtype=np.float32)
if keypoints.shape != zero_pose.shape:
keypoints = zero_pose.copy()
is_valid = bool(np.any(keypoints[:, 2] > 0.05))
if is_valid:
last_valid = keypoints.copy()
filled.append(keypoints.copy())
elif last_valid is not None:
filled.append(last_valid.copy())
else:
filled.append(zero_pose.copy())
return filled
def make_mse_plot(mse_state, frame_idx=0):
if not mse_state:
return None
matplotlib.use("Agg")
matplotlib.rcParams["font.sans-serif"] = [
"PingFang SC",
"Arial Unicode MS",
"Heiti TC",
"Noto Sans CJK SC",
"DejaVu Sans",
]
matplotlib.rcParams["axes.unicode_minus"] = False
from matplotlib.figure import Figure
frame_errors = np.asarray(mse_state.get("frame_errors", []), dtype=np.float32)
joint_frame_mse = np.asarray(mse_state.get("joint_frame_mse", []), dtype=np.float32)
keypoint_names = mse_state.get("keypoint_names", MODEL_KEYPOINT_NAMES)
threshold = float(mse_state.get("threshold", 0.0))
label = mse_state.get("label", "cycle")
if frame_errors.size == 0 or joint_frame_mse.size == 0:
return None
frame_idx = max(0, min(int(frame_idx or 0), len(frame_errors) - 1))
x = np.arange(len(frame_errors))
fig = Figure(figsize=(11, 5.8), dpi=140, constrained_layout=True)
ax = fig.subplots()
ax.plot(x, frame_errors, color="#111827", linewidth=2.4, label="Total MSE", zorder=4)
palette = ["#2563eb", "#059669", "#d97706", "#7c3aed", "#dc2626", "#0891b2", "#be123c", "#65a30d", "#9333ea"]
for idx, name in enumerate(keypoint_names):
label_name = name.replace("_", " ").title()
ax.plot(x, joint_frame_mse[:, idx], linewidth=1.2, alpha=0.78, color=palette[idx % len(palette)], label=label_name)
ax.scatter([frame_idx], [joint_frame_mse[frame_idx, idx]], s=16, color=palette[idx % len(palette)], zorder=5)
ax.scatter([frame_idx], [frame_errors[frame_idx]], s=38, color="#111827", zorder=6)
ax.axvline(frame_idx, color="#f59e0b", linestyle=":", linewidth=1.8, label=f"Selected frame {frame_idx + 1}")
ax.axhline(threshold, color="#ef4444", linestyle="--", linewidth=1.2, label="Threshold")
ax.set_title(f"{label} Frame and Joint MSE")
ax.set_xlabel("Normalized Frame")
ax.set_ylabel("MSE")
ax.grid(alpha=0.24)
ax.legend(loc="center left", bbox_to_anchor=(1.02, 0.5), fontsize=8, frameon=False)
return fig
def render_mse_canvas(mse_state, frame_idx=0) -> np.ndarray | None:
if not mse_state:
return None
frame_errors = np.asarray(mse_state.get("frame_errors", []), dtype=np.float32)
joint_frame_mse = np.asarray(mse_state.get("joint_frame_mse", []), dtype=np.float32)
keypoint_names = mse_state.get("keypoint_names", MODEL_KEYPOINT_NAMES)
threshold = float(mse_state.get("threshold", 0.0))
label = mse_state.get("label", "cycle")
if frame_errors.size == 0 or joint_frame_mse.size == 0:
return None
frame_idx = max(0, min(int(frame_idx or 0), len(frame_errors) - 1))
width, height = 1600, 760
left, right, top, bottom = 96, 330, 86, 92
plot_w = width - left - right
plot_h = height - top - bottom
canvas = np.full((height, width, 3), 255, dtype=np.uint8)
max_value = float(max(np.max(frame_errors), np.max(joint_frame_mse), threshold, 1e-6))
max_value *= 1.12
n = len(frame_errors)
def to_xy(i: int, value: float) -> tuple[int, int]:
x = left + int(round((i / max(1, n - 1)) * plot_w))
y = top + plot_h - int(round((float(value) / max_value) * plot_h))
return x, y
for frac in np.linspace(0, 1, 5):
y = top + int(round(plot_h * frac))
cv2.line(canvas, (left, y), (left + plot_w, y), (229, 233, 240), 2, cv2.LINE_AA)
for frac in np.linspace(0, 1, 6):
x = left + int(round(plot_w * frac))
cv2.line(canvas, (x, top), (x, top + plot_h), (241, 245, 249), 1, cv2.LINE_AA)
cv2.rectangle(canvas, (left, top), (left + plot_w, top + plot_h), (148, 163, 184), 2, cv2.LINE_AA)
palette = [(235, 99, 37), (105, 150, 5), (6, 126, 217), (237, 58, 124), (211, 38, 38), (178, 91, 124), (194, 145, 8), (13, 148, 136), (168, 85, 247)]
for idx in range(joint_frame_mse.shape[1]):
pts = np.array([to_xy(i, joint_frame_mse[i, idx]) for i in range(n)], dtype=np.int32)
cv2.polylines(canvas, [pts], False, palette[idx % len(palette)], 2, cv2.LINE_AA)
total_pts = np.array([to_xy(i, frame_errors[i]) for i in range(n)], dtype=np.int32)
cv2.polylines(canvas, [total_pts], False, (17, 24, 39), 5, cv2.LINE_AA)
if threshold > 0:
y_thr = to_xy(0, threshold)[1]
cv2.line(canvas, (left, y_thr), (left + plot_w, y_thr), (68, 68, 239), 2, cv2.LINE_AA)
cv2.putText(canvas, "Threshold", (left + plot_w + 18, y_thr + 6), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (68, 68, 239), 2, cv2.LINE_AA)
x_sel = to_xy(frame_idx, 0)[0]
cv2.line(canvas, (x_sel, top), (x_sel, top + plot_h), (11, 126, 245), 4, cv2.LINE_AA)
cv2.circle(canvas, to_xy(frame_idx, frame_errors[frame_idx]), 8, (17, 24, 39), -1, cv2.LINE_AA)
for idx in range(joint_frame_mse.shape[1]):
cv2.circle(canvas, to_xy(frame_idx, joint_frame_mse[frame_idx, idx]), 5, palette[idx % len(palette)], -1, cv2.LINE_AA)
title = f"{label} MSE | frame {frame_idx + 1}/{n}"
cv2.putText(canvas, title, (left, 50), cv2.FONT_HERSHEY_SIMPLEX, 1.05, (17, 24, 39), 3, cv2.LINE_AA)
cv2.putText(canvas, "Normalized Frame", (left + plot_w // 2 - 120, height - 32), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (71, 85, 105), 2, cv2.LINE_AA)
cv2.putText(canvas, "MSE", (24, top + plot_h // 2), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (71, 85, 105), 2, cv2.LINE_AA)
cv2.putText(canvas, f"Total {frame_errors[frame_idx]:.6f}", (left + plot_w + 18, top + 34), cv2.FONT_HERSHEY_SIMPLEX, 0.72, (17, 24, 39), 2, cv2.LINE_AA)
legend_y = top + 76
cv2.line(canvas, (left + plot_w + 18, legend_y), (left + plot_w + 62, legend_y), (17, 24, 39), 5, cv2.LINE_AA)
cv2.putText(canvas, "Total MSE", (left + plot_w + 74, legend_y + 8), cv2.FONT_HERSHEY_SIMPLEX, 0.62, (51, 65, 85), 2, cv2.LINE_AA)
for idx, name in enumerate(keypoint_names[: min(len(keypoint_names), joint_frame_mse.shape[1])]):
y = legend_y + 38 + idx * 32
color = palette[idx % len(palette)]
cv2.line(canvas, (left + plot_w + 18, y), (left + plot_w + 62, y), color, 3, cv2.LINE_AA)
cv2.putText(canvas, name.replace("_", " "), (left + plot_w + 74, y + 8), cv2.FONT_HERSHEY_SIMPLEX, 0.56, (51, 65, 85), 1, cv2.LINE_AA)
return canvas
def render_mse_frame(mse_state, frame_idx=0) -> str | None:
if mse_state and mse_state.get("frame_paths"):
paths = mse_state["frame_paths"]
frame_idx = max(0, min(int(frame_idx or 0), len(paths) - 1))
return paths[frame_idx]
canvas = render_mse_canvas(mse_state, frame_idx)
if canvas is None:
return None
label = mse_state.get("label", "cycle") if mse_state else "cycle"
out = Path(tempfile.mkdtemp(prefix="rowing_mse_")) / f"{label}_mse_{int(frame_idx or 0):03d}.png"
cv2.imwrite(str(out), canvas)
return str(out)
def build_mse_frame_paths(mse_state, output_dir: Path) -> list[str]:
frame_errors = np.asarray(mse_state.get("frame_errors", []), dtype=np.float32)
frame_paths = []
for frame_idx in range(len(frame_errors)):
canvas = render_mse_canvas(mse_state, frame_idx)
if canvas is None:
continue
frame_path = output_dir / f"{mse_state.get('label', 'cycle')}_mse_{frame_idx:03d}.png"
cv2.imwrite(str(frame_path), canvas)
frame_paths.append(str(frame_path))
return frame_paths
def gradio_file_url(path: str) -> str:
return f"/gradio_api/file={quote(str(path), safe='/')}"
def make_fast_frame_viewer_html(compare_state, mse_state, frame_idx=0) -> str:
compare_paths = (compare_state or {}).get("frame_paths") or []
mse_paths = (mse_state or {}).get("frame_paths") or []
if not compare_paths or not mse_paths:
return """
Validate an action cycle to enable the fast frame viewer.
"""
total = min(len(compare_paths), len(mse_paths))
frame_idx = max(0, min(int(frame_idx or 0), total - 1))
compare_urls = [gradio_file_url(path) for path in compare_paths[:total]]
mse_urls = [gradio_file_url(path) for path in mse_paths[:total]]
rows_by_frame = [make_frame_joint_mse_rows(mse_state, idx)[:6] for idx in range(total)]
viewer_id = f"rv_viewer_{uuid.uuid4().hex}"
payload = {
"compare": compare_urls,
"mse": mse_urls,
"rows": rows_by_frame,
"initial": frame_idx,
"total": total,
}
payload_b64 = base64.b64encode(json.dumps(payload, ensure_ascii=False).encode("utf-8")).decode("ascii")
return f"""
'
severity_counts = {"normal": 0, "low": 0, "medium": 0, "high": 0}
for d in diagnoses:
if isinstance(d, dict):
sev = d.get("severity", "normal")
severity_counts[sev] = severity_counts.get(sev, 0) + 1
total = len(diagnoses)
normal_pct = (severity_counts["normal"] / total * 100) if total > 0 else 0
low_pct = (severity_counts["low"] / total * 100) if total > 0 else 0
medium_pct = (severity_counts["medium"] / total * 100) if total > 0 else 0
high_pct = (severity_counts["high"] / total * 100) if total > 0 else 0
labels = SEVERITY_LOCALIZATION.get(lang, SEVERITY_LOCALIZATION["zh"])
return f"""