Spaces:
Sleeping
Sleeping
Download app.py from Koom759/rowing-validator: direct link, hf CLI and curl.
- Browser
- Download file 186 kB
-
https://huggingface.co/spaces/Koom759/rowing-validator/resolve/main/app.py
- Command line
-
hf download hf://spaces/Koom759/rowing-validator/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Koom759/rowing-validator/resolve/main/app.py
186 kB
from __future__ import annotations
import base64
import json
import logging
import math
import os
import platform
import shutil
import subprocess
import tempfile
import threading
import time
import uuid
from datetime import datetime, timezone
from functools import lru_cache
from importlib import metadata
from pathlib import Path
from urllib.parse import quote
import cv2
import gradio as gr
import matplotlib
import numpy as np
import torch
import torch.nn as nn
from scipy.interpolate import interp1d
from scipy.signal import find_peaks
SCRIPT_DIR = Path(__file__).parent.resolve()
def resolve_runtime_log_dir() -> Path:
configured_dir = os.getenv("USAGE_LOG_DIR") or os.getenv("LOG_DIR")
if configured_dir:
return Path(configured_dir).expanduser().resolve()
data_dir = Path("/data")
if data_dir.exists() and os.access(data_dir, os.W_OK):
return data_dir / "rowing_validator_logs"
return SCRIPT_DIR / "logs"
LOG_DIR = resolve_runtime_log_dir()
LOG_DIR.mkdir(parents=True, exist_ok=True)
USAGE_LOG_DIR = LOG_DIR / "usage"
USAGE_LOG_DIR.mkdir(parents=True, exist_ok=True)
USAGE_EVENTS_PATH = USAGE_LOG_DIR / "usage_events.jsonl"
USAGE_SUMMARY_PATH = USAGE_LOG_DIR / "usage_summary.json"
USAGE_LOG_LOCK = threading.Lock()
PROCESS_STOP_EVENT = threading.Event()
APP_STARTED_AT = datetime.now(timezone.utc).isoformat()
logging.basicConfig(
level=getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper(), logging.INFO),
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(LOG_DIR / "app.log", encoding="utf-8"),
logging.StreamHandler(),
],
)
logger = logging.getLogger(__name__)
FFMPEG_TIMEOUT_SECONDS = int(os.getenv("FFMPEG_TIMEOUT_SECONDS", "180"))
WEIGHT_DIR = SCRIPT_DIR / "Weight"
YOLO_MODEL_PATH = WEIGHT_DIR / "yolo11x-pose.pt"
DRIVE_MODEL_PATH = WEIGHT_DIR / "best_drive_ae_model.pt"
DRIVE_THRESHOLD_PATH = WEIGHT_DIR / "drive_threshold.npy"
RECOVERY_MODEL_PATH = WEIGHT_DIR / "best_recovery_ae_model.pt"
RECOVERY_THRESHOLD_PATH = WEIGHT_DIR / "recovery_threshold.npy"
KEYPOINT_NAMES = [
"nose",
"left_eye",
"right_eye",
"left_ear",
"right_ear",
"left_shoulder",
"right_shoulder",
"left_elbow",
"right_elbow",
"left_wrist",
"right_wrist",
"left_hip",
"right_hip",
"left_knee",
"right_knee",
"left_ankle",
"right_ankle",
]
MODEL_KEYPOINT_NAMES = [
"nose",
"left_eye",
"left_ear",
"left_shoulder",
"left_elbow",
"left_wrist",
"left_hip",
"left_knee",
"left_ankle",
]
MODEL_KEYPOINT_INDICES = [KEYPOINT_NAMES.index(name) for name in MODEL_KEYPOINT_NAMES]
MODEL_SKELETON = [
(0, 1),
(1, 2),
(2, 3),
(0, 3),
(3, 4),
(4, 5),
(3, 6),
(6, 7),
(7, 8),
]
SKELETON = [
(15, 13),
(13, 11),
(16, 14),
(14, 12),
(11, 12),
(5, 11),
(6, 12),
(5, 6),
(5, 7),
(7, 9),
(6, 8),
(8, 10),
(1, 2),
(0, 1),
(0, 2),
(1, 3),
(2, 4),
(3, 5),
(4, 6),
]
JOINT_COLOR = (255, 230, 120)
LINE_COLOR = (80, 220, 255)
TEXT_COLOR = (230, 240, 255)
MODEL_LINE_COLOR = (255, 100, 100)
MODEL_JOINT_COLOR = (255, 150, 150)
UPLOAD_WAIT_SECONDS = 60
USAGE_COUNTER_KEYS = {
"page_visit": "page_visits",
"video_upload": "video_uploads",
"clip_created": "clips_created",
"stickman_started": "stickman_runs_started",
"stickman_completed": "stickman_runs_completed",
"diagnosis_started": "diagnoses_started",
"diagnosis_completed": "diagnoses_completed",
"language_changed": "language_changes",
"usage_refreshed": "usage_refreshes",
"error": "errors",
}
def _default_usage_summary() -> dict:
return {
"app_started_at": APP_STARTED_AT,
"first_event_at": None,
"last_event_at": None,
"total_events": 0,
"page_visits": 0,
"video_uploads": 0,
"clips_created": 0,
"stickman_runs_started": 0,
"stickman_runs_completed": 0,
"diagnoses_started": 0,
"diagnoses_completed": 0,
"language_changes": 0,
"usage_refreshes": 0,
"errors": 0,
}
def read_usage_summary() -> dict:
if not USAGE_SUMMARY_PATH.exists():
return _default_usage_summary()
try:
with USAGE_SUMMARY_PATH.open("r", encoding="utf-8") as f:
stored = json.load(f)
summary = _default_usage_summary()
summary.update(stored)
return summary
except Exception as exc:
logger.warning("Could not read usage summary: %s", exc)
return _default_usage_summary()
def write_usage_summary(summary: dict) -> None:
tmp_path = USAGE_SUMMARY_PATH.with_suffix(".tmp")
with tmp_path.open("w", encoding="utf-8") as f:
json.dump(summary, f, ensure_ascii=False, indent=2)
tmp_path.replace(USAGE_SUMMARY_PATH)
def log_usage_event(event_name: str, session_id: str | None = None, details: dict | None = None) -> None:
timestamp = datetime.now(timezone.utc).isoformat()
event = {
"timestamp": timestamp,
"event": event_name,
"session_id": session_id,
"details": details or {},
}
try:
with USAGE_LOG_LOCK:
with USAGE_EVENTS_PATH.open("a", encoding="utf-8") as f:
f.write(json.dumps(event, ensure_ascii=False) + "\n")
summary = read_usage_summary()
summary["total_events"] = int(summary.get("total_events", 0)) + 1
summary["first_event_at"] = summary.get("first_event_at") or timestamp
summary["last_event_at"] = timestamp
counter_key = USAGE_COUNTER_KEYS.get(event_name)
if counter_key:
summary[counter_key] = int(summary.get(counter_key, 0)) + 1
write_usage_summary(summary)
except Exception as exc:
logger.warning("Could not write usage event '%s': %s", event_name, exc)
def _html_escape(value) -> str:
return (
str(value)
.replace("&", "&")
.replace("<", "<")
.replace(">", ">")
.replace('"', """)
)
def usage_storage_note() -> str:
env_dir = os.getenv("USAGE_LOG_DIR") or os.getenv("LOG_DIR")
if env_dir:
return f"Persistent if this configured directory is mounted: {LOG_DIR}"
if str(LOG_DIR).startswith("/data"):
return f"Persistent Hugging Face storage: {LOG_DIR}"
return f"Temporary runtime storage: {LOG_DIR}. Enable Space persistent storage or set USAGE_LOG_DIR for long-term retention."
def usage_summary_html() -> str:
summary = read_usage_summary()
metric_specs = [
("Visits", "page_visits"),
("Uploads", "video_uploads"),
("Clips", "clips_created"),
("Stickman Runs", "stickman_runs_completed"),
("Diagnoses", "diagnoses_completed"),
("Errors", "errors"),
]
cards = "".join(
f"""
<div class="usage-card">
<span>{label}</span>
<strong>{int(summary.get(key, 0))}</strong>
</div>
"""
for label, key in metric_specs
)
return f"""
<div class="usage-panel">
<div class="usage-grid">{cards}</div>
<div class="usage-note">
<strong>Storage</strong>: {_html_escape(usage_storage_note())}<br/>
<strong>Event log</strong>: {_html_escape(USAGE_EVENTS_PATH)}<br/>
<strong>Summary</strong>: {_html_escape(USAGE_SUMMARY_PATH)}<br/>
<strong>Last event</strong>: {_html_escape(summary.get("last_event_at") or "No events yet")}
</div>
</div>
"""
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 """
<div class="fast-frame-viewer-placeholder">
Validate an action cycle to enable the fast frame viewer.
</div>
"""
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"""
<div class="rv-fast-viewer" id="{viewer_id}" data-payload="{payload_b64}" onmouseenter="rvInitFrameViewer('{viewer_id}')" onclick="rvInitFrameViewer('{viewer_id}')">
<div class="rv-fast-toolbar">
<button type="button" class="rv-fast-btn" onclick="rvFramePrev('{viewer_id}')">◀</button>
<button type="button" class="rv-fast-btn rv-play-btn" onclick="rvFramePlay('{viewer_id}')">▶ Play</button>
<button type="button" class="rv-fast-btn" onclick="rvFrameNext('{viewer_id}')">▶</button>
<span class="rv-frame-label" id="{viewer_id}_label">Frame {frame_idx + 1}/{total}</span>
<span class="rv-load-label" id="{viewer_id}_load">Loading frames...</span>
</div>
<input
id="{viewer_id}_range"
class="rv-fast-range"
type="range"
min="0"
max="{total - 1}"
step="1"
value="{frame_idx}"
disabled
oninput="rvFrameUpdate('{viewer_id}', this.value)"
/>
<div class="rv-fast-grid">
<div class="rv-fast-panel">
<div class="rv-fast-title">Action Comparison</div>
<canvas id="{viewer_id}_compare" width="960" height="560"></canvas>
</div>
<div class="rv-fast-panel">
<div class="rv-fast-title">MSE Analysis</div>
<canvas id="{viewer_id}_mse" width="1600" height="760"></canvas>
</div>
</div>
<div class="rv-fast-joints" id="{viewer_id}_joints"></div>
</div>
"""
def make_frame_joint_mse_rows(mse_state, frame_idx=0) -> list[list[str]]:
if not mse_state:
return []
joint_frame_mse = np.asarray(mse_state.get("joint_frame_mse", []), dtype=np.float32)
keypoint_names = mse_state.get("keypoint_names", MODEL_KEYPOINT_NAMES)
if joint_frame_mse.size == 0:
return []
frame_idx = max(0, min(int(frame_idx or 0), joint_frame_mse.shape[0] - 1))
values = joint_frame_mse[frame_idx]
order = sorted(range(len(keypoint_names)), key=lambda idx: values[idx], reverse=True)
return [
[
JOINT_DISPLAY_NAMES.get(keypoint_names[idx], keypoint_names[idx]),
keypoint_names[idx],
f"{float(values[idx]):.6f}",
]
for idx in order
]
def compute_overlap_plot_params(normalized_pose: np.ndarray, recon_pose: np.ndarray) -> dict:
foot_idx = first_existing_index(MODEL_KEYPOINT_NAMES, ["left_ankle", "ankle"])
user = normalized_pose.copy()
model = recon_pose.copy()
if foot_idx is not None:
user -= user[:, foot_idx : foot_idx + 1, :]
model -= model[:, foot_idx : foot_idx + 1, :]
all_points = np.vstack([user.reshape(-1, 2), model.reshape(-1, 2)])
min_xy = all_points.min(axis=0)
max_xy = all_points.max(axis=0)
canvas_w, canvas_h = 960, 560
margin = 14
anchor = np.array([canvas_w * 0.13, canvas_h * 0.84], dtype=np.float32)
candidates = []
if max_xy[0] > 1e-6:
candidates.append((canvas_w - margin - anchor[0]) / max_xy[0])
if min_xy[0] < -1e-6:
candidates.append((anchor[0] - margin) / abs(min_xy[0]))
if max_xy[1] > 1e-6:
candidates.append((canvas_h - margin - anchor[1]) / max_xy[1])
if min_xy[1] < -1e-6:
candidates.append((anchor[1] - margin) / abs(min_xy[1]))
scale = float(max(1.0, min(candidates) * 0.998)) if candidates else 260.0
scale *= 1.8
return {
"canvas_w": canvas_w,
"canvas_h": canvas_h,
"anchor": anchor.tolist(),
"scale": scale,
"foot_idx": foot_idx,
}
def render_overlap_canvas(compare_state: dict, frame_idx=0) -> np.ndarray | None:
if not compare_state:
return None
normalized_pose = np.asarray(compare_state["normalized_pose"], dtype=np.float32)
recon_pose = np.asarray(compare_state["reconstruction_pose"], dtype=np.float32)
frame_errors = np.asarray(compare_state["frame_errors"], dtype=np.float32)
joint_frame_mse = np.asarray(compare_state.get("joint_frame_mse", []), dtype=np.float32)
threshold = float(compare_state["threshold"])
label = compare_state.get("label", "cycle")
phase = compare_state.get("phase_type", "unknown")
plot_params = compare_state.get("plot_params") or compute_overlap_plot_params(normalized_pose, recon_pose)
frame_idx = max(0, min(int(frame_idx or 0), len(normalized_pose) - 1))
user_pose = normalized_pose[frame_idx].copy()
model_pose = recon_pose[frame_idx].copy()
foot_idx = first_existing_index(MODEL_KEYPOINT_NAMES, ["left_ankle", "ankle"])
if foot_idx is not None:
user_pose -= user_pose[foot_idx]
model_pose -= model_pose[foot_idx]
canvas_w = int(plot_params["canvas_w"])
canvas_h = int(plot_params["canvas_h"])
scale = float(plot_params["scale"])
anchor = np.asarray(plot_params["anchor"], dtype=np.float32)
def to_canvas(points: np.ndarray) -> np.ndarray:
converted = points.copy()
converted[:, 0] = anchor[0] + converted[:, 0] * scale
converted[:, 1] = anchor[1] + converted[:, 1] * scale
return converted
canvas = np.full((canvas_h, canvas_w, 3), 248, dtype=np.uint8)
for y in range(70, canvas_h - 70, 80):
cv2.line(canvas, (70, y), (canvas_w - 70, y), (228, 232, 238), 1, cv2.LINE_AA)
for x in range(80, canvas_w - 70, 80):
cv2.line(canvas, (x, 90), (x, canvas_h - 80), (232, 236, 242), 1, cv2.LINE_AA)
user_kpts = np.column_stack((to_canvas(user_pose), np.ones(len(MODEL_KEYPOINT_NAMES), dtype=np.float32)))
model_kpts = np.column_stack((to_canvas(model_pose), np.ones(len(MODEL_KEYPOINT_NAMES), dtype=np.float32)))
draw_person(canvas, model_kpts, 0.1, 7, MODEL_LINE_COLOR, MODEL_JOINT_COLOR, MODEL_SKELETON)
draw_person(canvas, user_kpts, 0.1, 5, LINE_COLOR, JOINT_COLOR, MODEL_SKELETON)
foot = tuple(np.round(user_kpts[foot_idx, :2]).astype(int)) if foot_idx is not None else (int(anchor[0]), int(anchor[1]))
cv2.circle(canvas, foot, 10, (30, 30, 30), 2, cv2.LINE_AA)
cv2.putText(canvas, "foot overlap", (foot[0] + 12, foot[1] + 4), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (40, 40, 40), 1, cv2.LINE_AA)
title = f"{label} | {phase.upper()} model | frame {frame_idx + 1}/{len(normalized_pose)}"
cv2.putText(canvas, title, (28, 38), cv2.FONT_HERSHEY_SIMPLEX, 0.78, (22, 31, 45), 2, cv2.LINE_AA)
cv2.putText(canvas, f"MSE {frame_errors[frame_idx]:.6f} / threshold {threshold:.6f}", (28, 68), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (71, 85, 105), 1, cv2.LINE_AA)
if joint_frame_mse.size:
top_idx = int(np.argmax(joint_frame_mse[frame_idx]))
top_name = JOINT_DISPLAY_NAMES.get(MODEL_KEYPOINT_NAMES[top_idx], MODEL_KEYPOINT_NAMES[top_idx])
cv2.putText(canvas, f"Top joint: {top_name} {joint_frame_mse[frame_idx, top_idx]:.6f}", (28, 96), cv2.FONT_HERSHEY_SIMPLEX, 0.55, (71, 85, 105), 1, cv2.LINE_AA)
cv2.line(canvas, (28, canvas_h - 42), (70, canvas_h - 42), LINE_COLOR, 5, cv2.LINE_AA)
cv2.putText(canvas, "Actual pose", (82, canvas_h - 36), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (51, 65, 85), 1, cv2.LINE_AA)
cv2.line(canvas, (238, canvas_h - 42), (280, canvas_h - 42), MODEL_LINE_COLOR, 5, cv2.LINE_AA)
cv2.putText(canvas, "Model reconstruction", (292, canvas_h - 36), cv2.FONT_HERSHEY_SIMPLEX, 0.58, (51, 65, 85), 1, cv2.LINE_AA)
return canvas
def render_overlap_frame(compare_state: dict, frame_idx=0) -> str | None:
if compare_state and compare_state.get("frame_paths"):
paths = compare_state["frame_paths"]
frame_idx = max(0, min(int(frame_idx or 0), len(paths) - 1))
return paths[frame_idx]
canvas = render_overlap_canvas(compare_state, frame_idx)
if canvas is None:
return None
label = compare_state.get("label", "cycle")
out = Path(tempfile.mkdtemp(prefix="rowing_frame_")) / f"{label}_frame_{int(frame_idx or 0):03d}.png"
cv2.imwrite(str(out), canvas)
return str(out)
def create_monitored_clip(
video_path,
start_sec,
end_sec,
upload_guard,
progress: gr.Progress = gr.Progress(track_tqdm=False),
):
logger.info(f"create_monitored_clip called: video_path={video_path}, start_sec={start_sec}, end_sec={end_sec}, upload_guard={upload_guard}")
source = resolve_uploaded_video_path(video_path)
logger.info(f"Resolved source path: {source}")
if source is None:
logger.error("Failed to resolve video path, video_path type: %s, value: %s", type(video_path), video_path)
if upload_guard == "uploading":
for second in range(UPLOAD_WAIT_SECONDS):
progress(second / UPLOAD_WAIT_SECONDS, desc=f"Waiting for video upload... {second + 1}/{UPLOAD_WAIT_SECONDS}s")
time.sleep(1)
return None, None, "The video is still uploading. Please wait until the upload preview appears."
return None, None, "No video was uploaded. Please choose a video first."
if not source.exists():
logger.error(f"Video file does not exist: {source}")
return None, None, f"Video file not found: {source}"
if source.stat().st_size == 0:
logger.error(f"Video file is empty: {source}")
return None, None, f"Video file is empty: {source.name}"
try:
start_sec = max(0.0, float(start_sec or 0.0))
end_sec = float(end_sec or 0.0)
logger.info(f"Parsed time values: start_sec={start_sec}, end_sec={end_sec}")
except (ValueError, TypeError) as e:
logger.error(f"Failed to parse time values: {e}")
return None, None, f"Invalid time values: {e}"
end_value = end_sec if end_sec > start_sec else None
workdir = Path(tempfile.mkdtemp(prefix="rowing_clip_"))
clip_path = workdir / f"{source.stem}_monitored_clip.mp4"
logger.info(f"Created work directory: {workdir}, output clip path: {clip_path}")
try:
progress(0, desc="Creating monitored clip...")
clip_path = ffmpeg_clip(source, clip_path, start_sec, end_value)
except gr.Error as e:
logger.error(f"gr.Error during clip creation: {e}")
raise
except Exception as e:
logger.error(f"Unexpected error during clip creation: {e}", exc_info=True)
return None, None, f"Unexpected error: {str(e)}"
summary = f"Clip ready.\n- Source: {source.name}\n- Start: {start_sec:.2f}s\n- End: {'video end' if end_value is None else f'{end_value:.2f}s'}"
logger.info(f"Clip creation completed: {clip_path}")
return str(clip_path), str(clip_path), summary
def build_stickman_video(
video_path,
clip_path,
upload_guard,
progress: gr.Progress = gr.Progress(track_tqdm=False),
):
conf = 0.30
point_conf = 0.25
process_full_video = True
max_frames = 300
frame_stride = 1
smoothing_window = 5
line_width = 3
yolo_imgsz = env_int("ROWING_YOLO_IMGSZ", 640, 32)
yolo_imgsz = yolo_imgsz if yolo_imgsz > 0 else None
default_overlay_delay = max(0, int(round((smoothing_window - 1) / 2.0)))
overlay_delay_frames = env_int("ROWING_OVERLAY_DELAY_FRAMES", default_overlay_delay, 0)
PROCESS_STOP_EVENT.clear()
source = Path(clip_path) if clip_path else resolve_uploaded_video_path(video_path)
if source is None:
if upload_guard == "uploading":
for second in range(UPLOAD_WAIT_SECONDS):
progress(second / UPLOAD_WAIT_SECONDS, desc=f"Waiting for video upload... {second + 1}/{UPLOAD_WAIT_SECONDS}s")
time.sleep(1)
return None, None, None, []
return None, None, None, []
if not source.exists():
return None, None, None, []
model = load_yolo_model()
cap = cv2.VideoCapture(str(source))
if not cap.isOpened():
return None, None, None, []
fps = cap.get(cv2.CAP_PROP_FPS) or 30.0
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) or 1280
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) or 720
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT)) or 0
frame_stride = max(1, int(frame_stride))
smoothing_window = max(1, int(smoothing_window))
max_frames = int(max_frames)
if process_full_video or max_frames <= 0:
frame_limit = total_frames if total_frames > 0 else math.inf
else:
frame_limit = min(max_frames, total_frames) if total_frames > 0 else max_frames
progress_total = int(math.ceil(frame_limit / frame_stride)) if frame_limit != math.inf else None
output_fps = max(1.0, fps / frame_stride)
workdir = Path(tempfile.mkdtemp(prefix="rowing_space_"))
raw_output_path = workdir / f"{source.stem}_stickman_overlay_raw.mp4"
output_path = workdir / f"{source.stem}_stickman_overlay.mp4"
fourcc = cv2.VideoWriter_fourcc(*"mp4v")
writer = cv2.VideoWriter(str(raw_output_path), fourcc, output_fps, (width, height))
if not writer.isOpened():
cap.release()
return None, None, None, []
start_time = time.time()
read_count = 0
written_count = 0
detected_person_frames = 0
smoothing_buffers: list[list[np.ndarray]] = [[], [], []]
all_keypoints = []
wrist_x_values = []
last_valid_keypoints = None
progress(0, desc="Loading YOLO11x model and opening video...")
logger.info(
"START stickman source=%s size=%sx%s fps=%.2f total_frames=%s frame_limit=%s stride=%s yolo_imgsz=%s yolo_device=%s",
source.name,
width,
height,
fps,
total_frames,
progress_total or "unknown",
frame_stride,
yolo_imgsz or "default",
get_yolo_device(),
)
logger.info(
"Overlay delay compensation: smoothing_window=%s delay_processed_frames=%s delay_source_frames=%s delay_seconds=%.3f",
smoothing_window,
overlay_delay_frames,
overlay_delay_frames * frame_stride,
(overlay_delay_frames * frame_stride) / max(fps, 1e-6),
)
frame_buffer: list[tuple[int, np.ndarray]] = []
last_overlay_people: list[np.ndarray] = []
processed_count = 0
while read_count < frame_limit:
if PROCESS_STOP_EVENT.is_set():
logger.info("Stickman processing stopped by user at read_frame=%s output_frame=%s", read_count, written_count)
break
ok, frame = cap.read()
if not ok:
break
if read_count % frame_stride != 0:
read_count += 1
continue
predict_kwargs = {"conf": conf, "verbose": False, "device": get_yolo_device()}
if yolo_imgsz:
predict_kwargs["imgsz"] = yolo_imgsz
result = model.predict(frame, **predict_kwargs)[0]
person_count = 0
overlay_people: list[np.ndarray] = []
if result.keypoints is not None and len(result.keypoints) > 0:
kpts = result.keypoints.data.cpu().numpy()
boxes_conf = result.boxes.conf.cpu().numpy() if result.boxes is not None else np.ones(len(kpts))
order = np.argsort(boxes_conf)[::-1]
for rank, person_idx in enumerate(order[:3]):
smoothed_kpts = smooth_keypoints(smoothing_buffers[rank], kpts[person_idx], smoothing_window)
overlay_people.append(smoothed_kpts.copy())
person_count += 1
if rank == 0:
all_keypoints.append(smoothed_kpts.copy())
last_valid_keypoints = smoothed_kpts.copy()
wrist_idx = KEYPOINT_NAMES.index("left_wrist") if "left_wrist" in KEYPOINT_NAMES else 9
wrist_x_values.append(smoothed_kpts[wrist_idx, 0])
if person_count:
detected_person_frames += 1
for empty_rank in range(person_count, len(smoothing_buffers)):
smoothing_buffers[empty_rank].clear()
else:
for buffer in smoothing_buffers:
buffer.clear()
if last_valid_keypoints is not None:
all_keypoints.append(last_valid_keypoints.copy())
wrist_idx = KEYPOINT_NAMES.index("left_wrist") if "left_wrist" in KEYPOINT_NAMES else 9
wrist_x_values.append(last_valid_keypoints[wrist_idx, 0])
else:
all_keypoints.append(np.zeros((len(KEYPOINT_NAMES), 3), dtype=np.float32))
wrist_x_values.append(np.nan)
if overlay_people:
last_overlay_people = [person.copy() for person in overlay_people]
frame_buffer.append((read_count, frame.copy()))
if len(frame_buffer) > overlay_delay_frames:
display_frame_idx, canvas = frame_buffer.pop(0)
status_text = f"frame {display_frame_idx} | persons {person_count}"
draw_overlay_people(canvas, overlay_people, point_conf, line_width, status_text)
writer.write(canvas)
written_count += 1
processed_count += 1
read_count += 1
pct, desc = progress_description(processed_count, progress_total, start_time)
if processed_count > 0:
per_frame = (time.time() - start_time) / processed_count
desc = f"{desc} | {per_frame:.1f}s/frame"
progress(pct, desc=desc)
cap.release()
while frame_buffer:
display_frame_idx, canvas = frame_buffer.pop(0)
status_text = f"frame {display_frame_idx} | persons {len(last_overlay_people)}"
draw_overlay_people(canvas, last_overlay_people, point_conf, line_width, status_text)
writer.write(canvas)
written_count += 1
writer.release()
elapsed = time.time() - start_time
if written_count == 0:
return None, None, "No frames were processed. Try lowering frame stride.", []
final_output_path = encode_browser_mp4(raw_output_path, output_path, output_fps)
output_size_mb = final_output_path.stat().st_size / (1024 * 1024)
all_keypoints = fill_missing_keypoints(all_keypoints)
wrist_x = prepare_wrist_signal(wrist_x_values)
cycles = detect_cycles(wrist_x, output_fps)
used_cycle_fallback = False
if not cycles:
cycles = fallback_cycles(list(range(len(all_keypoints))))
used_cycle_fallback = bool(cycles)
logger.info("Cycle detection returned no extrema; using fallback segments: %s", cycles)
drive_count = len([c for c in cycles if "drive" in c[2]])
recovery_count = len([c for c in cycles if "recovery" in c[2]])
fallback_note = "\n- Note: cycle detector fallback split was used" if used_cycle_fallback else ""
summary = (
f"{'Stopped.' if PROCESS_STOP_EVENT.is_set() else 'Done.'}\n"
f"- Source: {source.name}\n"
f"- Resolution: {width}x{height}, FPS: {fps:.2f}\n"
f"- Read frames: {read_count}\n"
f"- Output frames: {written_count}\n"
f"- Detected persons: {detected_person_frames}\n"
f"- Elapsed: {readable_seconds(elapsed)}\n"
f"- Average: {elapsed / max(1, written_count):.1f}s/frame\n"
f"- YOLO image size: {yolo_imgsz or 'default'}\n"
f"- Output type: stickman overlay on source video\n"
f"- Overlay delay compensation: {overlay_delay_frames} processed frames "
f"({overlay_delay_frames * frame_stride} source frames, {(overlay_delay_frames * frame_stride) / max(fps, 1e-6):.3f}s)\n"
f"- Cycle constraints: phase length {env_int('ROWING_MIN_PHASE_MS', 450, 100)}-{env_int('ROWING_MAX_PHASE_MS', 2800, 600)} ms, "
f"motion ratio >= {float(os.getenv('ROWING_MIN_PHASE_MOTION_RATIO', '0.18')):.2f}\n"
f"- Output size: {output_size_mb:.1f} MB\n"
f"- Model: {YOLO_MODEL_PATH.name}\n"
f"- Detected segments: {len(cycles)} ({drive_count} Drive, {recovery_count} Recovery)"
f"{fallback_note}"
)
payload = {
"cycles": cycles,
"keypoints": [k.astype(np.float32).tolist() for k in all_keypoints],
"source_path": str(source),
"processed_video_path": str(final_output_path),
"fps": float(fps),
"output_fps": float(output_fps),
"width": int(width),
"height": int(height),
"frame_stride": int(frame_stride),
"written_count": int(written_count),
"stopped": bool(PROCESS_STOP_EVENT.is_set()),
"yolo_imgsz": int(yolo_imgsz) if yolo_imgsz else None,
"overlay_delay_frames": int(overlay_delay_frames),
}
return str(final_output_path), str(final_output_path), summary, payload
def validate_cycle_and_compare(
video_path,
clip_path,
cycle_payload,
cycle_index,
progress: gr.Progress = gr.Progress(track_tqdm=False),
):
cycles = cycle_payload.get("cycles", []) if isinstance(cycle_payload, dict) else cycle_payload
if cycles is None or len(cycles) == 0:
return (
None,
None,
"Error: No cycles detected. Please process a video first.",
"",
[],
None,
None,
gr.update(value=0, maximum=99, interactive=False),
None,
[],
"",
)
if cycle_index is None:
cycle_index = 0
cycle_index = int(cycle_index)
if cycle_index < 0 or cycle_index >= len(cycles):
cycle_index = 0
cycle_info = cycles[cycle_index]
start_frame, end_frame, label = cycle_info
phase_type = "drive" if "drive" in label else "recovery"
fps = float(cycle_payload.get("output_fps") or cycle_payload.get("fps") or 30.0) if isinstance(cycle_payload, dict) else 30.0
progress(0, desc="Preparing extracted keypoints for validation...")
if not isinstance(cycle_payload, dict) or not cycle_payload.get("keypoints"):
return (
None,
None,
"Error: Missing extracted keypoints. Please process the video again.",
"",
[],
None,
None,
gr.update(value=0, maximum=99, interactive=False),
None,
[],
"",
)
extracted_keypoints = [np.asarray(k, dtype=np.float32) for k in cycle_payload["keypoints"]]
start_frame = max(0, int(start_frame))
end_frame = min(len(extracted_keypoints) - 1, int(end_frame))
cycle_keypoints_17 = extracted_keypoints[start_frame : end_frame + 1]
cycle_keypoints = [extract_model_keypoints(k) for k in cycle_keypoints_17]
if len(cycle_keypoints) < 2:
return (
None,
None,
"Error: Not enough frames in cycle",
"",
[],
None,
None,
gr.update(value=0, maximum=99, interactive=False),
None,
[],
"",
)
try:
if phase_type == "drive":
ae_model, config, threshold, device = load_ae_model(DRIVE_MODEL_PATH, DRIVE_THRESHOLD_PATH)
else:
ae_model, config, threshold, device = load_ae_model(RECOVERY_MODEL_PATH, RECOVERY_THRESHOLD_PATH)
cycle_array = np.stack(cycle_keypoints, axis=0)
normalized = normalize_cycle(cycle_array, MODEL_KEYPOINT_NAMES, config["target_len"])
if normalized.shape[1] != config["input_dim"]:
raise ValueError(
f"输入维度不匹配: 模型需要 {config['input_dim']} 维,当前关键点归一化后为 {normalized.shape[1]} 维。"
)
x = torch.from_numpy(normalized[None, :, :]).float().to(device)
with torch.no_grad():
recon, z = ae_model(x)
err = torch.mean((recon - x) ** 2).item()
recon_np = recon.cpu().numpy()[0]
normalized_pose = normalized.reshape(config["target_len"], len(MODEL_KEYPOINT_NAMES), 2)
recon_pose = recon_np.reshape(config["target_len"], len(MODEL_KEYPOINT_NAMES), 2)
diff = recon_pose - normalized_pose
joint_frame_mse = np.mean(diff**2, axis=2)
joint_errors = joint_frame_mse.mean(axis=0)
frame_errors = joint_frame_mse.mean(axis=1)
is_abnormal = err > threshold
score = max(0.0, min(100.0, 100.0 * (1.0 - err / (threshold * 2.0))))
diagnoses = diagnose_rowing_technique(
normalized_pose,
MODEL_KEYPOINT_NAMES,
config["target_len"],
recon_pose,
joint_frame_mse,
err,
threshold,
score,
)
progress(0.7, desc="Generating comparison visualization...")
compare_state = {
"normalized_pose": normalized_pose.astype(float).tolist(),
"reconstruction_pose": recon_pose.astype(float).tolist(),
"frame_errors": frame_errors.astype(float).tolist(),
"joint_frame_mse": joint_frame_mse.astype(float).tolist(),
"threshold": float(threshold),
"label": label,
"phase_type": phase_type,
"plot_params": compute_overlap_plot_params(normalized_pose, recon_pose),
}
plot_params = compare_state["plot_params"]
comp_width = int(plot_params["canvas_w"])
comp_height = int(plot_params["canvas_h"])
comp_workdir = Path(tempfile.mkdtemp(prefix="rowing_comp_"))
comp_raw_path = comp_workdir / f"{label}_comparison_raw.mp4"
comp_output_path = comp_workdir / f"{label}_comparison.mp4"
comp_fps = max(1.0, fps / 2)
comp_writer = cv2.VideoWriter(str(comp_raw_path), cv2.VideoWriter_fourcc(*"mp4v"), comp_fps, (comp_width, comp_height))
frame_paths = []
for frame_idx in range(config["target_len"]):
canvas = render_overlap_canvas(compare_state, frame_idx)
comp_writer.write(canvas)
frame_path = comp_workdir / f"{label}_frame_{frame_idx:03d}.png"
cv2.imwrite(str(frame_path), canvas)
frame_paths.append(str(frame_path))
comp_writer.release()
compare_state["frame_paths"] = frame_paths
final_comp_path = encode_browser_mp4(comp_raw_path, comp_output_path, comp_fps)
report = (
f"=== 动作验证报告 ===\n"
f"片段: {label}\n"
f"阶段: {phase_type.capitalize()}\n"
f"帧数: {len(cycle_keypoints)} (原始) -> {config['target_len']} (归一化)\n"
f"MSE: {err:.6f}\n"
f"阈值: {threshold:.6f}\n"
f"判定: {'异常 ⚠️' if is_abnormal else '正常 ✓'}\n"
f"分数: {score:.1f}/100\n\n"
f"=== 错误检测结果 ===\n"
)
for diag in diagnoses:
color_map = {"normal": "🟢", "low": "🟡", "medium": "🟠", "high": "🔴"}
report += f"{color_map[diag['severity']]} {diag['phase']}: {diag['error_name']} - {diag['severity_text']}\n"
if diag["severity"] != "normal":
report += f" 描述: {diag['description']}\n"
report += f" 证据: {diag['evidence']}\n"
report += "\n"
mse_state = {
"frame_errors": frame_errors.astype(float).tolist(),
"joint_frame_mse": joint_frame_mse.astype(float).tolist(),
"keypoint_names": MODEL_KEYPOINT_NAMES,
"threshold": float(threshold),
"label": label,
}
mse_state["frame_paths"] = build_mse_frame_paths(mse_state, comp_workdir)
peak_frame = int(np.argmax(frame_errors))
comparison_frame = render_overlap_frame(compare_state, peak_frame)
fast_viewer_html = make_fast_frame_viewer_html(compare_state, mse_state, peak_frame)
return (
comparison_frame,
str(final_comp_path),
report,
f"{score:.1f}/100",
diagnoses,
mse_state,
compare_state,
gr.update(value=peak_frame, maximum=config["target_len"] - 1, interactive=True),
render_mse_frame(mse_state, peak_frame),
make_frame_joint_mse_rows(mse_state, peak_frame),
fast_viewer_html,
)
except Exception as e:
import traceback
traceback.print_exc()
return (
None,
None,
f"Validation error: {str(e)}",
"",
[],
None,
None,
gr.update(value=0, maximum=99, interactive=False),
None,
[],
"",
)
i18n = {
"zh": {
"app_title": "RowingValidator Beta",
"app_subtitle": "AI划船动作分析",
"for_coaches": "FOR COACHES & ATHLETES",
"hero_title": "先进的AI划船视频分析与虚拟教练平台",
"hero_subtitle": "安全高效地划船",
"start_free": "免费开始 →",
"feature_1_title": "提高速度",
"feature_1_desc": "通过技术优化,提升划行速度",
"feature_2_title": "提升效率",
"feature_2_desc": "提高能量转换效率,划得更省力",
"feature_3_title": "减少受伤",
"feature_3_desc": "纠正错误动作,减少运动损伤",
"why_title": "为什么选择我们",
"why_subtitle": "我们的AI技术帮助您深入分析划船动作,发现问题并提供专业指导",
"why_1_title": "AI精准分析",
"why_1_desc": "基于YOLO和自编码器模型,精准识别动作细节,提供专业反馈",
"why_2_title": "实时对比",
"why_2_desc": "将您的动作与标准动作进行实时对比,直观展示差异",
"why_3_title": "个性化建议",
"why_3_desc": "根据您的动作特点,提供针对性的改进建议和训练计划",
"demo_title": "观看使用演示",
"demo_subtitle": "了解如何使用我们的工具分析划船动作",
"cta_title": "准备好提升您的划船技术了吗?",
"cta_subtitle": "加入数千名使用我们的AI分析提升技术的运动员",
"footer": "© 2026 RowingValidator Beta. All rights reserved.",
"nav_features": "功能",
"nav_demo": "演示",
"back_home": "← 返回首页",
"tool_title": "视频上传与分析",
"tool_subtitle": "上传您的划船视频,让AI分析您的技术动作",
"tab_1": "📹 视频上传与YOLO处理",
"tab_2": "🔄 周期选择与动作对比",
"tab_3": "📋 验证报告",
"upload_label": "上传视频",
"clip_settings": "视频裁剪设置",
"start_time": "开始时间(秒)",
"end_time": "结束时间(0=视频末尾)",
"create_clip": "创建裁剪片段",
"clip_preview": "裁剪预览",
"clip_summary": "裁剪摘要",
"process_video": "提取火柴人并叠加原视频",
"stop_process": "停止处理",
"stickman_result": "🎬 火柴人叠加结果",
"stickman_video": "火柴人叠加视频",
"download_video": "下载叠加视频",
"process_summary": "处理摘要",
"cycle_select": "周期选择",
"select_cycle": "选择分析周期",
"validate_action": "验证动作并生成对比",
"cycle_info": "周期信息",
"cycle_detail": "周期详情",
"compare_title": "🆚 动作对比",
"compare_subtitle": "逐帧对比:实际动作 vs 模型重建",
"download_compare": "下载对比视频",
"action_score": "动作评分",
"score_label": "评分",
"mse_analysis": "MSE 逐帧分析",
"select_frame": "选择归一化帧",
"mse_plot": "总 MSE 与各关节 MSE",
"joint_mse": "各关节 MSE 详情",
"report_title": "技术诊断报告",
"error_list": "错误检测列表",
"error_details": "错误详情",
"error_stats": "错误分布统计",
"usage_tab": "📈 使用统计",
"usage_title": "使用统计",
"usage_refresh": "刷新使用统计",
},
"en": {
"app_title": "RowingValidator Beta",
"app_subtitle": "AI Rowing Analysis",
"for_coaches": "FOR COACHES & ATHLETES",
"hero_title": "ADVANCED AI ROWING VIDEO ANALYSIS AND VIRTUAL COACHING PLATFORM",
"hero_subtitle": "ROW SAFELY & EFFICIENTLY",
"start_free": "START FOR FREE",
"feature_1_title": "Increase Speed",
"feature_1_desc": "Improve rowing speed through technical optimization",
"feature_2_title": "Boost Efficiency",
"feature_2_desc": "Improve energy conversion efficiency, row with less effort",
"feature_3_title": "Reduce Injuries",
"feature_3_desc": "Correct improper form and reduce sports injuries",
"why_title": "Why Choose Us",
"why_subtitle": "Our AI technology helps you deeply analyze rowing technique, identify issues, and provide professional guidance",
"why_1_title": "AI-Powered Analysis",
"why_1_desc": "Based on YOLO and autoencoder models, precisely identify movement details and provide professional feedback",
"why_2_title": "Real-Time Comparison",
"why_2_desc": "Compare your movements with standard form in real-time with intuitive visual differences",
"why_3_title": "Personalized Advice",
"why_3_desc": "Provide targeted improvement suggestions and training plans based on your movement characteristics",
"demo_title": "Watch the Demo",
"demo_subtitle": "Learn how to use our tool to analyze your rowing technique",
"cta_title": "Ready to Improve Your Rowing Technique?",
"cta_subtitle": "Join thousands of athletes improving their technique with our AI analysis",
"footer": "© 2026 RowingValidator Beta. All rights reserved.",
"nav_features": "Features",
"nav_demo": "Demo",
"back_home": "← Back to Home",
"tool_title": "Video Upload & Analysis",
"tool_subtitle": "Upload your rowing video and let AI analyze your technique",
"tab_1": "📹 Video Upload & YOLO Processing",
"tab_2": "🔄 Cycle Selection & Comparison",
"tab_3": "📋 Validation Report",
"upload_label": "Upload Video",
"clip_settings": "Clip Settings",
"start_time": "Start Time (s)",
"end_time": "End Time (0=end)",
"create_clip": "Create Clip",
"clip_preview": "Clip Preview",
"clip_summary": "Clip Summary",
"process_video": "Extract Stickman & Overlay Video",
"stop_process": "Stop Processing",
"stickman_result": "🎬 Stickman Overlay Result",
"stickman_video": "Stickman Overlay Video",
"download_video": "Download Overlay Video",
"process_summary": "Processing Summary",
"cycle_select": "Cycle Selection",
"select_cycle": "Select Analysis Cycle",
"validate_action": "Validate & Compare",
"cycle_info": "Cycle Info",
"cycle_detail": "Cycle Details",
"compare_title": "🆚 Action Comparison",
"compare_subtitle": "Frame-by-frame: Actual vs Model Reconstruction",
"download_compare": "Download Comparison Video",
"action_score": "Action Score",
"score_label": "Score",
"mse_analysis": "MSE Frame Analysis",
"select_frame": "Select Normalized Frame",
"mse_plot": "Total MSE & Joint MSE",
"joint_mse": "Joint MSE Details",
"report_title": "Technical Diagnosis Report",
"error_list": "Error Detection List",
"error_details": "Error Details",
"error_stats": "Error Distribution Statistics",
"usage_tab": "📈 Usage",
"usage_title": "Usage Tracking",
"usage_refresh": "Refresh Usage Stats",
},
}
import base64
def read_static_image_base64(filename: str) -> str:
candidates = [
SCRIPT_DIR / filename,
SCRIPT_DIR / "assets" / filename,
SCRIPT_DIR.parent / filename,
Path.cwd() / filename,
]
for path in candidates:
if not path.exists():
continue
try:
return base64.b64encode(path.read_bytes()).decode()
except Exception as e:
logger.warning(f"Could not read {path}: {e}")
logger.warning(
"Could not find %s. Tried: %s",
filename,
", ".join(str(path) for path in candidates),
)
return ""
def static_file_url(filename: str) -> str:
path = SCRIPT_DIR / filename
if not path.exists():
return ""
return f"/gradio_api/file={quote(str(path), safe='/:')}"
def demo_video_html() -> str:
video_url = static_file_url("Video1.mp4")
if not video_url:
return """
<div class="demo-video-fallback">
Demo video is not available. Upload a rowing clip in the Tool tab to start analysis.
</div>
"""
return f"""
<video class="home-demo-video" autoplay muted loop playsinline controls>
<source src="{_html_escape(video_url)}" type="video/mp4">
</video>
"""
bg_base64 = ""
bg_why_base64 = ""
bg_cta_base64 = ""
bg_base64 = read_static_image_base64("background.png")
bg_why_base64 = read_static_image_base64("background_why.png")
bg_cta_base64 = read_static_image_base64("background_cta.png")
custom_css = """
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700;800&display=swap');
:root,
html,
body,
.gradio-container {
color-scheme: light !important;
}
* {
font-family: 'Inter', 'PingFang SC', 'Microsoft YaHei', sans-serif !important;
}
""" + (f""".hero-section {{
background: url(data:image/png;base64,{bg_base64});
background-size: cover;
background-position: center;
background-repeat: no-repeat;
background-attachment: fixed;
position: relative;
overflow: hidden;
min-height: 100vh;
height: 100vh;
width: 150%;
margin-left: -25%;
margin-right: -25%;
display: flex;
align-items: center;
justify-content: center;
}}
""" if bg_base64 else "") + (f""".why-section {{
background: url(data:image/png;base64,{bg_why_base64});
background-size: cover;
background-position: center;
background-repeat: no-repeat;
width: 150%;
margin-left: -25%;
margin-right: -25%;
padding: 160px 40px 200px;
}}
""" if bg_why_base64 else "") + (f""".cta-section {{
background: url(data:image/png;base64,{bg_cta_base64});
background-size: cover;
background-position: center;
background-repeat: no-repeat;
position: relative;
overflow: hidden;
padding: 200px 40px 320px;
width: 150%;
margin-left: -25%;
margin-right: -25%;
text-align: center;
}}
""" if bg_cta_base64 else "") + """
.gradio-container {
background: #ffffff !important;
color: #0f172a !important;
max-width: 100% !important;
overflow: visible !important;
}
.gradio-container * {
color: #0f172a !important;
}
html[data-theme="dark"],
body.dark,
.dark,
.dark .gradio-container {
background: #ffffff !important;
color: #0f172a !important;
}
.rv-fast-viewer {
width: 100%;
background: #ffffff;
border: 1px solid #dbe3ef;
border-radius: 8px;
padding: 14px;
margin: 8px 0 14px;
box-shadow: 0 2px 10px rgba(15, 23, 42, 0.06);
}
.rv-fast-toolbar {
display: flex;
align-items: center;
gap: 8px;
margin-bottom: 12px;
}
.rv-fast-btn {
border: 1px solid #cbd5e1;
background: #f8fafc;
color: #0f172a !important;
border-radius: 6px;
padding: 7px 12px;
font-weight: 700;
cursor: pointer;
}
.rv-fast-btn:hover {
background: #e8f1ff;
border-color: #93c5fd;
}
.rv-frame-label {
margin-left: auto;
font-weight: 800;
color: #1a365d !important;
}
.rv-load-label {
font-size: 12px;
font-weight: 700;
color: #64748b !important;
}
.rv-fast-grid {
display: grid;
grid-template-columns: minmax(0, 1fr);
gap: 18px;
align-items: start;
}
.rv-fast-panel {
min-width: 0;
border: 1px solid #e2e8f0;
border-radius: 8px;
overflow: hidden;
background: #f8fafc;
}
.rv-fast-title {
padding: 8px 10px;
font-weight: 800;
color: #334155 !important;
background: #eef4fb;
border-bottom: 1px solid #e2e8f0;
}
.rv-fast-panel canvas {
display: block;
width: 100%;
height: auto;
background: #ffffff;
}
.rv-fast-range {
width: 100%;
margin: 14px 0 10px;
accent-color: #f97316;
}
.rv-fast-range:disabled {
opacity: 0.42;
}
.rv-fast-joints {
display: grid;
grid-template-columns: repeat(2, minmax(0, 1fr));
gap: 6px 10px;
font-size: 13px;
color: #334155 !important;
}
.rv-fast-joint-row {
display: flex;
justify-content: space-between;
gap: 8px;
padding: 7px 9px;
background: #f8fafc;
border: 1px solid #e2e8f0;
border-radius: 6px;
}
.fast-frame-viewer-placeholder {
border: 1px dashed #cbd5e1;
border-radius: 8px;
padding: 18px;
color: #64748b !important;
background: #f8fafc;
}
@media (max-width: 900px) {
.rv-fast-grid,
.rv-fast-joints {
grid-template-columns: 1fr;
}
}
html[data-theme="dark"] input,
html[data-theme="dark"] textarea,
html[data-theme="dark"] select,
html[data-theme="dark"] label,
.dark input,
.dark textarea,
.dark select,
.dark label {
background: #ffffff !important;
color: #1a365d !important;
}
.gradio-container,
.gradio-container .contain,
.gradio-container .wrap,
.gradio-container .block,
.gradio-container .form,
.gradio-container .panel,
.gradio-container .tabs,
.gradio-container .tabitem,
.gradio-container .tab-nav,
.gradio-container .dataframe,
.gradio-container .table-wrap,
.gradio-container table,
.gradio-container thead,
.gradio-container tbody,
.gradio-container tr,
.gradio-container th,
.gradio-container td,
.gradio-container iframe,
.gradio-container .file-preview,
.gradio-container .empty,
.gradio-container .dropzone,
.gradio-container .upload-container,
.gradio-container [data-testid="block-info"],
.gradio-container [data-testid="component-wrapper"],
.gradio-container [data-testid="dataframe"],
.gradio-container [data-testid="video"],
.gradio-container [data-testid="image"] {
background-color: #ffffff !important;
color: #1a365d !important;
}
.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container table input,
.gradio-container table textarea {
background-color: #ffffff !important;
color: #1a365d !important;
-webkit-text-fill-color: #1a365d !important;
}
.gradio-container th {
background-color: #f1f5f9 !important;
color: #1a365d !important;
}
.gradio-container td {
background-color: #ffffff !important;
color: #1a365d !important;
border-color: #e2e8f0 !important;
}
#global-language-toggle,
.global-language-toggle {
position: fixed !important;
top: 14px !important;
right: 28px !important;
z-index: 1200 !important;
background: rgba(255, 255, 255, 0.96) !important;
border: 1px solid rgba(26, 54, 93, 0.18) !important;
border-radius: 9999px !important;
padding: 0 !important;
box-shadow: 0 8px 28px rgba(26, 54, 93, 0.12) !important;
}
#global-language-toggle,
#global-language-toggle *,
#global-language-toggle button,
.global-language-toggle,
.global-language-toggle *,
.global-language-toggle button {
color: #1a365d !important;
font-size: 13px !important;
background: transparent !important;
border: none !important;
box-shadow: none !important;
border-radius: 9999px !important;
min-width: 132px !important;
padding: 8px 14px !important;
font-weight: 650 !important;
}
.gradio-container .why-section h2,
.gradio-container .why-section p[data-i18n="why_subtitle"] {
color: white !important;
font-weight: 600 !important;
}
.gradio-container .cta-section * {
color: white !important;
}
.gradio-container .cta-section h2,
.gradio-container .cta-section p,
.gradio-container .cta-section button {
color: white !important;
text-shadow: 0 1px 3px rgba(0,0,0,0.5);
}
.gradio-container .home-content p[data-i18n="footer"] {
color: white !important;
font-weight: 600 !important;
font-size: 18px !important;
text-shadow: 0 1px 3px rgba(0,0,0,0.5);
}
.why-section {
position: relative !important;
z-index: 999 !important;
margin-top: 80px;
padding: 80px 40px 120px;
}
.why-section::before {
content: "";
position: absolute;
top: 0;
left: -25%;
width: 150%;
height: 100%;
z-index: -1;
}
.gr-box {
border: 1px solid #e2e8f0 !important;
border-radius: 16px !important;
background: #ffffff !important;
}
.gr-input {
border: 1px solid #e2e8f0 !important;
border-radius: 12px !important;
}
.gr-textbox textarea, .gr-textbox input {
border: 1px solid #e2e8f0 !important;
border-radius: 12px !important;
background: #ffffff !important;
color: #1a365d !important;
}
.gr-number input {
background: #ffffff !important;
color: #1a365d !important;
border: 1px solid #e2e8f0 !important;
border-radius: 12px !important;
}
.gr-input, .gr-box {
background: #ffffff !important;
color: #1a365d !important;
}
.gr-input *, .gr-box * {
color: #1a365d !important;
}
.gr-dropdown, .gr-dropdown * {
background: #ffffff !important;
color: #1a365d !important;
}
.gr-dropdown input {
color: #1a365d !important;
}
.gr-slider {
border: 1px solid #e2e8f0 !important;
border-radius: 16px !important;
background: #f8fafc !important;
padding: 16px !important;
}
.gr-video {
border: 2px solid #e2e8f0 !important;
border-radius: 20px !important;
overflow: hidden !important;
box-shadow: 0 4px 20px rgba(0, 0, 0, 0.05) !important;
background: #f1f5f9 !important;
}
.gr-image, .gr-plot {
border: 2px solid #e2e8f0 !important;
border-radius: 16px !important;
background: #f8fafc !important;
}
.gr-image img, .gr-plot svg {
border-radius: 12px !important;
}
.gr-image .label, .gr-video .label, .gr-plot .label {
color: #ffffff !important;
font-weight: 600 !important;
background: rgba(26, 54, 93, 0.8) !important;
padding: 8px 12px !important;
border-radius: 8px !important;
}
.gradio-container label,
.gradio-container input,
.gradio-container textarea,
.gradio-container select,
.gradio-container .wrap,
.gradio-container .wrap * {
color: #1a365d !important;
}
.gr-video .gr-button, .gr-image .gr-button, .gr-plot .gr-button {
color: #1a365d !important;
border-color: #1a365d !important;
}
.gr-video input, .gr-image input, .gr-plot input {
color: #1a365d !important;
}
.upload-zone,
.upload-zone *,
.gr-file,
.gr-file *,
.gr-video,
.gr-video * {
color: #1a365d !important;
}
.gr-video video,
.gr-image img {
background: #f8fafc !important;
}
.gr-video .label,
.gr-image .label,
.gr-plot .label {
color: #ffffff !important;
}
.comparison-frame,
.comparison-frame *,
.comparison-frame [data-testid="image"],
.comparison-frame .image-container {
background: #f8fafc !important;
}
.comparison-frame img {
object-fit: contain !important;
max-height: 780px !important;
}
.report-card {
border-radius: 16px;
border: 1px solid #e2e8f0;
background: #ffffff;
padding: 16px 18px;
margin: 12px 0;
box-shadow: 0 8px 24px rgba(26, 54, 93, 0.06);
}
.report-card.normal { border-left: 6px solid #22c55e; }
.report-card.low { border-left: 6px solid #facc15; background: #fffdf2; }
.report-card.medium { border-left: 6px solid #fb923c; background: #fff7ed; }
.report-card.high { border-left: 6px solid #ef4444; background: #fff5f5; }
.report-head {
display: flex;
align-items: center;
gap: 10px;
font-weight: 800;
color: #1a365d;
margin-bottom: 8px;
}
.severity-pill {
display: inline-flex;
align-items: center;
gap: 6px;
border-radius: 999px;
padding: 4px 10px;
font-size: 12px;
font-weight: 800;
}
.severity-pill.normal { background: #dcfce7; color: #166534 !important; }
.severity-pill.low { background: #fef9c3; color: #854d0e !important; }
.severity-pill.medium { background: #ffedd5; color: #9a3412 !important; }
.severity-pill.high { background: #fee2e2; color: #991b1b !important; }
.report-card.high .report-title { color: #b91c1c !important; }
.report-card.medium .report-title { color: #c2410c !important; }
.report-card.low .report-title { color: #a16207 !important; }
.report-card p {
margin: 6px 0;
color: #334155 !important;
}
.gr-markdown {
color: #0f172a !important;
}
.gr-markdown h1, .gr-markdown h2, .gr-markdown h3, .gr-markdown h4 {
color: #0f172a !important;
font-weight: 700 !important;
}
.hero-section::before {
content: '';
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0;
background: rgba(15, 23, 42, 0.4);
z-index: 0;
}
.hero-section::after {
content: '';
position: absolute;
bottom: 0;
left: 0;
right: 0;
height: 200px;
background: linear-gradient(to bottom, transparent 0%, rgba(255, 255, 255, 1) 100%);
z-index: 1;
pointer-events: none;
}
.hero-content {
position: relative;
z-index: 2;
text-align: center;
max-width: 1000px;
margin: 0 15% 0 auto;
opacity: 1 !important;
visibility: visible !important;
display: block !important;
}
.hero-content * {
opacity: 1 !important;
visibility: visible !important;
}
.hero-tag {
display: inline-block;
padding: 10px 28px;
background: rgba(255, 255, 255, 0.15);
backdrop-filter: blur(10px);
border: 1px solid rgba(255, 255, 255, 0.2);
color: white !important;
border-radius: 9999px;
font-size: 14px;
font-weight: 600;
letter-spacing: 2px;
text-transform: uppercase;
margin-bottom: 32px;
}
.hero-title {
font-size: 52px;
font-weight: 800;
line-height: 1.2;
margin-bottom: 28px;
color: white !important;
letter-spacing: -0.5px;
}
.hero-subtitle {
font-size: 24px;
font-weight: 600;
color: rgba(255, 255, 255, 0.9) !important;
margin-bottom: 48px;
letter-spacing: 1px;
text-transform: uppercase;
}
.hero-btn {
display: inline-block;
padding: 18px 48px;
background: white !important;
color: #0f172a !important;
border: none;
border-radius: 9999px;
font-size: 16px;
font-weight: 700;
cursor: pointer;
transition: all 0.3s ease;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.2);
text-transform: uppercase;
letter-spacing: 1px;
}
.hero-btn:hover {
transform: translateY(-3px);
box-shadow: 0 15px 50px rgba(0, 0, 0, 0.3);
}
@keyframes float {
0%, 100% { transform: translateY(0px); }
50% { transform: translateY(-20px); }
}
.gradient-text {
background: linear-gradient(135deg, #1a365d 0%, #319795 100%);
-webkit-background-clip: text;
-webkit-text-fill-color: transparent;
background-clip: text;
}
.btn-primary {
background: linear-gradient(135deg, #1a365d 0%, #319795 100%) !important;
color: white !important;
border: none !important;
border-radius: 9999px !important;
padding: 16px 40px !important;
font-weight: 600 !important;
font-size: 16px !important;
box-shadow: 0 10px 40px rgba(26, 54, 93, 0.2) !important;
transition: all 0.3s ease !important;
}
.btn-primary:hover {
transform: translateY(-2px) !important;
box-shadow: 0 15px 50px rgba(26, 54, 93, 0.3) !important;
}
.feature-card {
background: white;
border-radius: 24px;
padding: 32px;
box-shadow: 0 4px 24px rgba(0, 0, 0, 0.06);
transition: all 0.3s ease;
border: 1px solid rgba(0, 0, 0, 0.04);
}
.home-demo-video {
display: block;
width: 100%;
height: auto;
max-height: 720px;
object-fit: cover;
background: #0f172a;
}
.demo-video-fallback {
min-height: 320px;
display: flex;
align-items: center;
justify-content: center;
background: #f1f5f9;
color: #1a365d !important;
font-weight: 700;
border-radius: 20px;
}
.feature-card:hover {
transform: translateY(-8px);
box-shadow: 0 20px 60px rgba(0, 0, 0, 0.1);
}
.section-light {
background: #f8fafc;
}
.section-dark {
background: #1a365d;
color: white;
}
.demo-video-container {
position: relative;
width: 180%;
margin-left: -40%;
margin-right: -40%;
overflow: hidden;
box-shadow: 0 25px 80px rgba(26, 54, 93, 0.2);
margin-bottom: -20px;
}
.demo-video {
width: 100% !important;
height: auto !important;
display: block !important;
border-radius: 0 !important;
object-fit: cover !important;
}
.tab-nav {
border: none !important;
background: transparent !important;
}
.tab-nav button {
border: none !important;
background: transparent !important;
color: #64748b !important;
font-weight: 500 !important;
padding: 12px 24px !important;
border-radius: 12px !important;
transition: all 0.2s ease !important;
}
.tab-nav button.selected {
background: #1a365d !important;
color: white !important;
}
.gr-button {
border-radius: 16px !important;
font-weight: 700 !important;
transition: all 0.2s ease !important;
color: #1a365d !important;
background: white !important;
border: 2px solid #1a365d !important;
box-shadow: 0 4px 12px rgba(26, 54, 93, 0.15) !important;
}
.gr-button:hover {
transform: translateY(-1px);
box-shadow: 0 8px 25px rgba(26, 54, 93, 0.25) !important;
background: #f0f7ff !important;
}
.gr-button-primary {
background: linear-gradient(135deg, #1a365d 0%, #319795 100%) !important;
color: white !important;
border: none !important;
}
.gr-button-primary:hover {
background: linear-gradient(135deg, #2d4a7c 0%, #2d8a87 100%) !important;
color: white !important;
}
.action-btn {
border: 2px solid #1a365d !important;
color: #1a365d !important;
background: white !important;
font-weight: 700 !important;
box-shadow: 0 4px 12px rgba(26, 54, 93, 0.2) !important;
border-radius: 16px !important;
}
.action-btn:hover {
background: #f0f7ff !important;
border-color: #2d4a7c !important;
box-shadow: 0 6px 20px rgba(26, 54, 93, 0.3) !important;
transform: translateY(-2px);
}
.back-home-btn {
border: 3px solid #1a365d !important;
color: #1a365d !important;
background: white !important;
font-weight: 700 !important;
font-size: 18px !important;
box-shadow: 0 4px 12px rgba(26, 54, 93, 0.2) !important;
border-radius: 16px !important;
padding: 12px 24px !important;
}
.back-home-btn:hover {
background: #f0f7ff !important;
border-color: #2d4a7c !important;
box-shadow: 0 6px 20px rgba(26, 54, 93, 0.3) !important;
}
.gr-video {
border-radius: 20px !important;
overflow: hidden !important;
box-shadow: 0 10px 40px rgba(0, 0, 0, 0.1) !important;
}
.gr-slider input[type="range"]::-webkit-slider-thumb {
background: #1a365d !important;
}
.report-container {
max-height: 500px;
overflow-y: auto;
padding: 24px;
background: linear-gradient(135deg, #f8fafc 0%, #ffffff 100%);
border-radius: 20px;
border: 1px solid #e2e8f0;
color: #1a365d;
}
.upload-zone {
border: 3px dashed #cbd5e1 !important;
border-radius: 24px !important;
min-height: 300px !important;
transition: all 0.3s ease !important;
}
.upload-zone:hover {
border-color: #1a365d !important;
background: #f8fafc !important;
}
.home-content, .tool-content {
padding-top: 0 !important;
width: 100% !important;
overflow: visible !important;
}
.main-tabs {
display: block !important;
visibility: visible !important;
opacity: 1 !important;
background: #ffffff !important;
}
.main-tabs > div,
.main-tabs [role="tabpanel"],
.home-content,
.tool-content {
visibility: visible !important;
opacity: 1 !important;
}
.tool-header {
padding: 24px 32px !important;
align-items: center !important;
border-bottom: 1px solid #f1f5f9 !important;
margin-bottom: 24px !important;
}
.tool-header button {
background: transparent !important;
border: 1px solid #e2e8f0 !important;
color: #64748b !important;
border-radius: 12px !important;
padding: 8px 20px !important;
font-weight: 500 !important;
transition: all 0.2s ease !important;
}
.tool-header button:hover {
border-color: #1a365d !important;
color: #1a365d !important;
background: transparent !important;
}
.usage-panel {
border: 1px solid #e2e8f0;
background: #ffffff;
border-radius: 20px;
padding: 24px;
box-shadow: 0 10px 40px rgba(26, 54, 93, 0.08);
}
.usage-grid {
display: grid;
grid-template-columns: repeat(6, minmax(0, 1fr));
gap: 12px;
margin-bottom: 18px;
}
.usage-card {
border: 1px solid #e2e8f0;
background: #f8fafc;
border-radius: 16px;
padding: 16px;
}
.usage-card span {
display: block;
color: #64748b !important;
font-size: 12px;
margin-bottom: 8px;
}
.usage-card strong {
display: block;
color: #1a365d !important;
font-size: 30px;
line-height: 1;
}
.usage-note {
color: #475569 !important;
font-size: 13px;
line-height: 1.8;
word-break: break-word;
}
.rv-home {
width: 100% !important;
overflow: hidden !important;
background: #ffffff !important;
}
.rv-hero {
min-height: 680px;
display: flex;
align-items: center;
justify-content: center;
padding: 96px 32px;
position: relative;
background-size: cover;
background-position: center;
background-repeat: no-repeat;
}
.rv-hero-panel {
width: min(1080px, 100%);
text-align: center;
position: relative;
z-index: 2;
}
.rv-eyebrow {
display: inline-flex;
align-items: center;
justify-content: center;
padding: 8px 18px;
border-radius: 999px;
background: rgba(255,255,255,0.18);
border: 1px solid rgba(255,255,255,0.35);
color: #ffffff !important;
font-size: 14px;
font-weight: 800;
margin-bottom: 24px;
}
.rv-hero h1 {
color: #ffffff !important;
font-size: 56px;
line-height: 1.1;
margin: 0 auto 22px;
max-width: 980px;
font-weight: 850;
}
.rv-hero p {
color: rgba(255,255,255,0.92) !important;
font-size: 24px;
font-weight: 650;
margin: 0 0 36px;
}
.rv-hero-actions {
display: flex;
justify-content: center;
gap: 14px;
flex-wrap: wrap;
}
.rv-primary-link,
.rv-secondary-link {
display: inline-flex;
align-items: center;
justify-content: center;
min-height: 48px;
padding: 0 26px;
border-radius: 999px;
font-weight: 800;
text-decoration: none !important;
cursor: pointer;
}
.rv-primary-link {
background: #ffffff !important;
color: #12325b !important;
}
.rv-secondary-link {
background: rgba(255,255,255,0.14) !important;
color: #ffffff !important;
border: 1px solid rgba(255,255,255,0.45);
}
.rv-section {
padding: 72px 32px;
background: #ffffff;
}
.rv-section.alt {
background: #f8fafc;
}
.rv-section-inner {
max-width: 1120px;
margin: 0 auto;
}
.rv-section-title {
color: #1a365d !important;
font-size: 34px;
line-height: 1.2;
font-weight: 850;
margin: 0 0 14px;
text-align: center;
}
.rv-section-subtitle {
color: #64748b !important;
font-size: 16px;
line-height: 1.7;
max-width: 680px;
margin: 0 auto 34px;
text-align: center;
}
.rv-card-grid {
display: grid;
grid-template-columns: repeat(3, minmax(0, 1fr));
gap: 18px;
}
.rv-info-card {
background: #ffffff;
border: 1px solid #e2e8f0;
border-radius: 18px;
padding: 24px;
box-shadow: 0 12px 36px rgba(26,54,93,0.08);
}
.rv-info-card h3 {
color: #1a365d !important;
font-size: 18px;
margin: 0 0 10px;
font-weight: 800;
}
.rv-info-card p {
color: #475569 !important;
font-size: 14px;
line-height: 1.65;
margin: 0;
}
.rv-demo-frame {
width: min(980px, 100%);
margin: 0 auto;
overflow: hidden;
border-radius: 20px;
background: #f1f5f9;
box-shadow: 0 20px 60px rgba(26,54,93,0.14);
border: 1px solid #dbe4ef;
}
.rv-cta {
padding: 82px 32px;
text-align: center;
background-size: cover;
background-position: center;
position: relative;
}
.rv-cta::before {
content: "";
position: absolute;
inset: 0;
background: rgba(26,54,93,0.68);
}
.rv-cta-inner {
position: relative;
z-index: 1;
max-width: 720px;
margin: 0 auto;
}
.rv-cta h2,
.rv-cta p {
color: #ffffff !important;
}
.rv-cta h2 {
font-size: 34px;
margin: 0 0 16px;
}
.rv-cta p {
font-size: 18px;
margin: 0 0 28px;
}
@media (max-width: 800px) {
.rv-hero {
min-height: 560px;
padding: 72px 20px;
}
.rv-hero h1 {
font-size: 36px;
}
.rv-hero p {
font-size: 18px;
}
.rv-card-grid {
grid-template-columns: 1fr;
}
}
@media (max-width: 900px) {
.usage-grid {
grid-template-columns: repeat(2, minmax(0, 1fr));
}
}
"""
def t(lang: str, key: str) -> str:
lang_map = i18n.get(lang, i18n["zh"])
return lang_map.get(key, i18n["zh"].get(key, key))
def tool_header_html(lang: str) -> str:
return f"""
<div style="position: relative; padding: 20px; border: 3px solid #1a365d; border-radius: 16px; overflow: hidden; margin-bottom: 24px;">
<img src="data:image/png;base64,{bg_base64}" style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; object-fit: cover; z-index: 0;">
<div style="position: relative; z-index: 1; display: flex; align-items: center; gap: 20px;">
<button onclick="switchToHome()" style="border: 3px solid #1a365d; color: #1a365d; background: rgba(255,255,255,0.9); font-weight: 700; font-size: 18px; padding: 12px 24px; border-radius: 16px; cursor: pointer; transition: all 0.2s; box-shadow: 0 4px 12px rgba(26,54,93,0.2);">{t(lang, "back_home")}</button>
<div style="flex: 1; text-align: center;">
<div style="display: inline-block; background: rgba(255,255,255,0.9); padding: 12px 30px; border-radius: 12px; border: 2px solid #1a365d; box-shadow: 0 4px 12px rgba(0,0,0,0.15);">
<h1 style="font-size: 36px; font-weight: 700; color: #1a365d; margin: 0; white-space: nowrap;">{t(lang, "tool_title")}</h1>
<p style="font-size: 18px; color: #1a365d; margin: 8px 0 0; font-weight: 500; white-space: nowrap;">{t(lang, "tool_subtitle")}</p>
</div>
</div>
</div>
</div>
"""
def navbar_html(lang: str) -> str:
return f"""
<div style="position: fixed; top: 0; left: 0; right: 0; z-index: 1000; background: rgba(255, 255, 255, 0.95); backdrop-filter: blur(20px); border-bottom: 1px solid rgba(0,0,0,0.06);">
<div style="max-width: 1200px; margin: 0 auto; padding: 16px 32px; display: flex; align-items: center; justify-content: space-between;">
<div style="display: flex; align-items: center; gap: 12px; cursor: pointer;" id="nav-logo">
<div style="width: 40px; height: 40px; background: linear-gradient(135deg, #1a365d 0%, #319795 100%); border-radius: 12px; display: flex; align-items: center; justify-content: center;">
<svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2.5" stroke-linecap="round" stroke-linejoin="round"><path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
</div>
<span style="font-size: 20px; font-weight: 700; color: #1a365d;">RowingValidator Beta</span>
</div>
<div style="display: flex; align-items: center; gap: 24px; padding-right: 160px;">
<a href="#features" style="color: #64748b; text-decoration: none; font-size: 15px; font-weight: 500;">{t(lang, "nav_features")}</a>
<a href="#demo" style="color: #64748b; text-decoration: none; font-size: 15px; font-weight: 500;">{t(lang, "nav_demo")}</a>
</div>
</div>
</div>
<div style="height: 72px;"></div>
"""
def home_html(lang: str) -> str:
hero_background = (
f"linear-gradient(90deg, rgba(15,23,42,0.70), rgba(15,23,42,0.36)), url(data:image/png;base64,{bg_base64})"
if bg_base64
else "linear-gradient(135deg, #1a365d 0%, #319795 100%)"
)
cta_background = (
f"linear-gradient(90deg, rgba(26,54,93,0.72), rgba(49,151,149,0.48)), url(data:image/png;base64,{bg_cta_base64})"
if bg_cta_base64
else "linear-gradient(135deg, #1a365d 0%, #319795 100%)"
)
return f"""
<div class="rv-home">
<section class="rv-hero" style="background-image: {hero_background};">
<div class="rv-hero-panel">
<div class="rv-eyebrow">{t(lang, "for_coaches")}</div>
<h1>{t(lang, "hero_title")}</h1>
<p>{t(lang, "hero_subtitle")}</p>
<div class="rv-hero-actions">
<button class="rv-primary-link" onclick="switchToTool()">{t(lang, "start_free")}</button>
<a class="rv-secondary-link" href="#demo">{t(lang, "nav_demo")}</a>
</div>
</div>
</section>
<section id="features" class="rv-section">
<div class="rv-section-inner">
<h2 class="rv-section-title">{t(lang, "why_title")}</h2>
<p class="rv-section-subtitle">{t(lang, "why_subtitle")}</p>
<div class="rv-card-grid">
<div class="rv-info-card">
<h3>{t(lang, "feature_1_title")}</h3>
<p>{t(lang, "feature_1_desc")}</p>
</div>
<div class="rv-info-card">
<h3>{t(lang, "feature_2_title")}</h3>
<p>{t(lang, "feature_2_desc")}</p>
</div>
<div class="rv-info-card">
<h3>{t(lang, "feature_3_title")}</h3>
<p>{t(lang, "feature_3_desc")}</p>
</div>
</div>
</div>
</section>
<section class="rv-section alt">
<div class="rv-section-inner">
<h2 class="rv-section-title">{t(lang, "compare_title")}</h2>
<p class="rv-section-subtitle">{t(lang, "compare_subtitle")}</p>
<div class="rv-card-grid">
<div class="rv-info-card">
<h3>{t(lang, "why_1_title")}</h3>
<p>{t(lang, "why_1_desc")}</p>
</div>
<div class="rv-info-card">
<h3>{t(lang, "why_2_title")}</h3>
<p>{t(lang, "why_2_desc")}</p>
</div>
<div class="rv-info-card">
<h3>{t(lang, "why_3_title")}</h3>
<p>{t(lang, "why_3_desc")}</p>
</div>
</div>
</div>
</section>
<section id="demo" class="rv-section">
<div class="rv-section-inner">
<h2 class="rv-section-title">{t(lang, "demo_title")}</h2>
<p class="rv-section-subtitle">{t(lang, "demo_subtitle")}</p>
<div class="rv-demo-frame">{demo_video_html()}</div>
</div>
</section>
<section class="rv-cta" style="background-image: {cta_background};">
<div class="rv-cta-inner">
<h2>{t(lang, "cta_title")}</h2>
<p>{t(lang, "cta_subtitle")}</p>
<button class="rv-primary-link" onclick="switchToTool()">{t(lang, "start_free")}</button>
</div>
</section>
</div>
"""
def localize_diagnosis(diagnosis: dict, lang: str) -> dict:
lang = lang if lang in ("zh", "en") else "zh"
error_id = diagnosis.get("error_id", "")
localized = ERROR_LOCALIZATION.get(error_id, {}).get(lang, {})
severity = diagnosis.get("severity", "normal")
return {
**diagnosis,
"phase": localized.get("phase", diagnosis.get("phase", "")),
"error_name": localized.get("name", diagnosis.get("error_name", "")),
"description": localized.get("description", diagnosis.get("description", "")),
"suggestion": localized.get("suggestion", diagnosis.get("suggestion", "")),
"severity_text": SEVERITY_LOCALIZATION.get(lang, SEVERITY_LOCALIZATION["zh"]).get(severity, severity),
}
def make_error_table_rows(diagnoses, lang: str):
if not diagnoses:
return [["-", "-", "-", "-", "-"]]
rows = []
for d in diagnoses:
if not isinstance(d, dict):
rows.append([str(d), "", "", "", ""])
continue
item = localize_diagnosis(d, lang)
rows.append([
item.get("phase", ""),
item.get("error_name", ""),
item.get("severity_text", ""),
item.get("description", ""),
item.get("suggestion", ""),
])
return rows
def localize_evidence(evidence: str, lang: str) -> str:
if lang != "en" or not evidence:
return evidence or "-"
replacements = [
("躯干角度", "Trunk angle "),
("上半身误差比", ", upper-body error ratio "),
("手肘误差比", "Elbow error ratio "),
("座板速度是手柄的", "Seat speed is "),
("膝盖误差比", "Knee error ratio "),
("躯干后仰", "Trunk layback "),
("膝盖角度", "Knee angle "),
("手腕误差比", "Wrist error ratio "),
("抓水误差比", "Catch error ratio "),
("速度数据不足", "Insufficient speed data"),
("检测失败", "Detection failed"),
("倍", "x"),
("°", " deg"),
]
translated = evidence
for zh, en in replacements:
translated = translated.replace(zh, en)
translated = translated.replace("手柄的", "the handle speed")
return translated
def severity_icon(severity: str) -> str:
return {
"normal": "✓",
"low": "!",
"medium": "!!",
"high": "!!!",
}.get(severity, "!")
def make_report_markdown(diagnoses, score: str, lang: str) -> str:
if not diagnoses:
return ""
ordered = sorted(
[d for d in diagnoses if isinstance(d, dict)],
key=lambda item: {"high": 0, "medium": 1, "low": 2, "normal": 3}.get(item.get("severity", "normal"), 4),
)
if lang == "en":
cards = [f"<h2>Technical Diagnosis Report</h2><p><strong>Score:</strong> {score or '-'}</p><h3>Findings</h3>"]
for d in ordered:
item = localize_diagnosis(d, "en")
sev = item.get("severity", "normal")
cards.append(f"""
<div class="report-card {sev}">
<div class="report-head">
<span class="severity-pill {sev}">{severity_icon(sev)} {item['severity_text']}</span>
<span class="report-title">{item['phase']} | {item['error_name']}</span>
</div>
<p><strong>Description:</strong> {item['description']}</p>
<p><strong>Evidence:</strong> {localize_evidence(d.get('evidence', '-'), 'en')}</p>
<p><strong>Suggestion:</strong> {item['suggestion']}</p>
</div>
""")
return "\n".join(cards)
cards = [f"<h2>技术诊断报告</h2><p><strong>评分:</strong>{score or '-'}</p><h3>检测结果</h3>"]
for d in ordered:
item = localize_diagnosis(d, "zh")
sev = item.get("severity", "normal")
cards.append(f"""
<div class="report-card {sev}">
<div class="report-head">
<span class="severity-pill {sev}">{severity_icon(sev)} {item['severity_text']}</span>
<span class="report-title">{item['phase']} | {item['error_name']}</span>
</div>
<p><strong>描述:</strong>{item['description']}</p>
<p><strong>证据:</strong>{d.get('evidence', '-')}</p>
<p><strong>建议:</strong>{item['suggestion']}</p>
</div>
""")
return "\n".join(cards)
with gr.Blocks(title="RowingValidator Beta - AI Rowing Analysis") as demo:
lang_state = gr.State("zh")
current_page = gr.State("home")
clip_state = gr.State("")
cycles_state = gr.State([])
score_state = gr.State("")
report_state = gr.State("")
diagnoses_state = gr.State([])
comparison_video_state = gr.State("")
mse_state = gr.State(None)
overlap_state = gr.State(None)
session_state = gr.State("")
upload_guard_input = gr.Textbox(value="empty", visible=False)
nav_output = gr.HTML(navbar_html("zh"))
language_button = gr.Button(
"🌐 EN / 中文",
elem_id="global-language-toggle",
elem_classes=["global-language-toggle"],
)
with gr.Tabs(elem_classes=["main-tabs"]) as main_tabs:
with gr.TabItem("首页 / Home", id="home-tab"):
with gr.Column(elem_classes=["home-content"]):
home_output = gr.HTML(home_html("zh"))
gr.HTML("""<div style="display:none">
<div style="min-height: 100vh; padding-top: 0;">
<div class="hero-section">
<div class="hero-content">
<div class="hero-tag" data-i18n="for_coaches">FOR COACHES & ATHLETES</div>
<h1 class="hero-title" data-i18n="hero_title">ADVANCED AI ROWING VIDEO ANALYSIS AND VIRTUAL COACHING PLATFORM</h1>
<div class="hero-subtitle" data-i18n="hero_subtitle">ROW SAFELY & EFFICIENTLY</div>
<button class="hero-btn" onclick="switchToTool()" data-i18n="start_free">START FOR FREE</button>
</div>
</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 24px; max-width: 900px; margin: -40px auto 0; padding: 0 40px; position: relative; z-index: 10;">
<div class="feature-card" style="background: white; border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.06); transition: all 0.3s ease;">
<div style="width: 56px; height: 56px; background: linear-gradient(135deg, #fbbf24 0%, #f97316 100%); border-radius: 18px; display: flex; align-items: center; justify-content: center; margin-bottom: 20px;">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 10V3L4 14h7v7l9-11h-7z"/></svg>
</div>
<h3 style="font-size: 18px; font-weight: 600; color: #1a365d; margin-bottom: 8px;" data-i18n="feature_1_title">提高速度</h3>
<p style="font-size: 14px; color: #64748b; line-height: 1.6;" data-i18n="feature_1_desc">通过技术优化,提升划行速度</p>
</div>
<div class="feature-card" style="background: white; border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.06); transition: all 0.3s ease;">
<div style="width: 56px; height: 56px; background: linear-gradient(135deg, #60a5fa 0%, #06b6d4 100%); border-radius: 18px; display: flex; align-items: center; justify-content: center; margin-bottom: 20px;">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6"/></svg>
</div>
<h3 style="font-size: 18px; font-weight: 600; color: #1a365d; margin-bottom: 8px;" data-i18n="feature_2_title">提升效率</h3>
<p style="font-size: 14px; color: #64748b; line-height: 1.6;" data-i18n="feature_2_desc">提高能量转换效率,划得更省力</p>
</div>
<div class="feature-card" style="background: white; border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.06); transition: all 0.3s ease;">
<div style="width: 56px; height: 56px; background: linear-gradient(135deg, #4ade80 0%, #10b981 100%); border-radius: 18px; display: flex; align-items: center; justify-content: center; margin-bottom: 20px;">
<svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z"/></svg>
</div>
<h3 style="font-size: 18px; font-weight: 600; color: #1a365d; margin-bottom: 8px;" data-i18n="feature_3_title">减少受伤</h3>
<p style="font-size: 14px; color: #64748b; line-height: 1.6;" data-i18n="feature_3_desc">纠正错误动作,减少运动损伤</p>
</div>
</div>
<div class="why-section" style="position: relative; overflow: visible; padding: 160px 40px 200px;">
<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.3); z-index: 1;"></div>
<div style="max-width: 1000px; margin: 0 auto; text-align: center; position: relative; z-index: 2;">
<div style="background: rgba(0,0,0,0.5); backdrop-filter: blur(10px); border-radius: 24px; padding: 40px 60px; margin-bottom: 64px;">
<div style="display: inline-block; padding: 8px 24px; background: rgba(49, 151, 149, 0.8); color: white; border-radius: 9999px; font-size: 18px; font-weight: 500; margin-bottom: 24px;" data-i18n="why_title">
为什么选择我们
</div>
<h2 style="font-size: 44px; font-weight: 700; color: white; margin-bottom: 16px;" data-i18n="why_title">为什么选择我们</h2>
<p style="font-size: 20px; color: white; font-weight: 600; max-width: 500px; margin: 0 auto;" data-i18n="why_subtitle">
我们的AI技术帮助您深入分析划船动作,发现问题并提供专业指导
</p>
</div>
<div style="display: grid; grid-template-columns: repeat(3, 1fr); gap: 32px; text-align: left;">
<div style="background: rgba(255,255,255,0.9); border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.1);">
<div style="width: 64px; height: 64px; background: linear-gradient(135deg, #a855f7 0%, #4f46e5 100%); border-radius: 20px; display: flex; align-items: center; justify-content: center; margin-bottom: 24px;">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z"/></svg>
</div>
<h3 style="font-size: 20px; font-weight: 600; color: #1a365d; margin-bottom: 12px;" data-i18n="why_1_title">AI精准分析</h3>
<p style="font-size: 15px; color: #1a365d; line-height: 1.6;" data-i18n="why_1_desc">基于YOLO和自编码器模型,精准识别动作细节,提供专业反馈</p>
</div>
<div style="background: rgba(255,255,255,0.9); border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.1);">
<div style="width: 64px; height: 64px; background: linear-gradient(135deg, #3b82f6 0%, #06b6d4 100%); border-radius: 20px; display: flex; align-items: center; justify-content: center; margin-bottom: 24px;">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M8 7h12m0 0l-4-4m4 4l-4 4m0 6H4m0 0l4 4m-4-4l4-4"/></svg>
</div>
<h3 style="font-size: 20px; font-weight: 600; color: #1a365d; margin-bottom: 12px;" data-i18n="why_2_title">实时对比</h3>
<p style="font-size: 15px; color: #1a365d; line-height: 1.6;" data-i18n="why_2_desc">将您的动作与标准动作进行实时对比,直观展示差异</p>
</div>
<div style="background: rgba(255,255,255,0.9); border-radius: 24px; padding: 32px; box-shadow: 0 4px 24px rgba(0,0,0,0.1);">
<div style="width: 64px; height: 64px; background: linear-gradient(135deg, #f43f5e 0%, #ec4899 100%); border-radius: 20px; display: flex; align-items: center; justify-content: center; margin-bottom: 24px;">
<svg width="32" height="32" viewBox="0 0 24 24" fill="none" stroke="white" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M19.428 15.428a2 2 0 00-1.022-.547l-2.387-.477a6 6 0 00-3.86.517l-.318.158a6 6 0 01-3.86.517L6.05 15.21a2 2 0 00-1.806.547M8 4h8l-1 1v5.172a2 2 0 00.586 1.414l5 5c1.26 1.26.367 3.414-1.415 3.414H4.828c-1.782 0-2.674-2.154-1.414-3.414l5-5A2 2 0 009 10.172V5L8 4z"/></svg>
</div>
<h3 style="font-size: 20px; font-weight: 600; color: #1a365d; margin-bottom: 12px;" data-i18n="why_3_title">个性化建议</h3>
<p style="font-size: 15px; color: #1a365d; line-height: 1.6;" data-i18n="why_3_desc">根据您的动作特点,提供针对性的改进建议和训练计划</p>
</div>
</div>
</div>
</div>
<div style="padding: 80px 0;">
<div style="max-width: 900px; margin: 0 auto; text-align: center; position: relative; z-index: 2;">
<h2 style="font-size: 36px; font-weight: 700; color: #1a365d; margin-bottom: 16px;" data-i18n="demo_title">观看使用演示</h2>
<p style="font-size: 16px; color: #64748b; margin-bottom: 48px;" data-i18n="demo_subtitle">了解如何使用我们的工具分析划船动作</p>
</div>
</div>
<div class="cta-section" style="position: relative; width: 150%; margin-left: -25%; margin-right: -25%; padding: 220px 40px 340px; overflow: visible; margin-top: -60px;">
<div style="position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(26,54,93,0.6); z-index: 1;"></div>
<div style="max-width: 600px; margin: 0 auto; text-align: center; position: relative; z-index: 2;">
<h2 style="font-size: 44px; font-weight: 800; color: white; margin-bottom: 24px;" data-i18n="cta_title">准备好提升您的划船技术了吗?</h2>
<p style="font-size: 22px; font-weight: 600; color: white; margin-bottom: 48px;" data-i18n="cta_subtitle">
加入数千名使用我们的AI分析提升技术的运动员
</p>
<button class="btn-primary" style="background: linear-gradient(135deg, #1a365d 0%, #319795 100%); color: white; font-size: 18px; font-weight: 600; padding: 16px 48px; border: none; border-radius: 9999px; cursor: pointer; box-shadow: 0 4px 20px rgba(26, 54, 93, 0.3); transition: all 0.2s;" onclick="document.querySelector('#tool-tab').click()" data-i18n="start_btn">免费开始 →</button>
</div>
</div>
<div style="background: transparent; padding: 32px; text-align: center; border-top: none; margin-top: -230px; position: relative; z-index: 10;">
<p style="color: white; font-size: 18px; font-weight: 600;" data-i18n="footer">© 2026 RowingValidator Beta. All rights reserved.</p>
</div>
</div>
""")
with gr.TabItem("工具 / Tool", id="tool-tab"):
with gr.Column(elem_classes=["tool-content"]):
tool_header = gr.HTML(tool_header_html("zh"))
with gr.Tabs(elem_classes=["tab-nav"]):
with gr.TabItem("📹 视频处理 / Process"):
with gr.Row():
with gr.Column(scale=1):
video_input = gr.Video(
label="上传视频",
format=None,
elem_classes=["upload-zone"],
)
clip_settings_md = gr.Markdown("### 视频裁剪设置")
with gr.Row():
start_input = gr.Number(value=0, precision=2, label="开始时间(秒)")
end_input = gr.Number(value=0, precision=2, label="结束时间(0=视频末尾)")
create_clip_button = gr.Button("创建裁剪片段", variant="primary", elem_classes=["action-btn"])
clip_preview = gr.Video(label="裁剪预览", format="mp4", include_audio=False)
clip_summary = gr.Textbox(label="裁剪摘要", lines=3)
with gr.Row():
process_button = gr.Button("提取火柴人并叠加原视频", variant="primary", elem_classes=["action-btn"])
stop_button = gr.Button("停止处理", variant="stop", elem_classes=["action-btn"])
with gr.Column(scale=1):
stickman_result_md = gr.Markdown("### 🎬 火柴人叠加结果")
video_output = gr.Video(label="火柴人叠加视频", format="mp4", include_audio=False)
file_output = gr.File(label="下载叠加视频")
summary_output = gr.Textbox(label="处理摘要", lines=5)
with gr.TabItem("🔄 动作对比 / Compare"):
with gr.Row():
with gr.Column(scale=3):
compare_title_md = gr.Markdown("### 🆚 动作对比")
fast_frame_viewer = gr.HTML(
"<div class='fast-frame-viewer-placeholder'>验证动作后可使用快速帧浏览器。</div>"
)
comparison_output = gr.Image(label="逐帧对比:实际动作 vs 模型重建", type="filepath", height=720, elem_classes=["comparison-frame"], visible=False)
comparison_file = gr.File(label="下载对比视频")
mse_analysis_md = gr.Markdown("### MSE 逐帧分析")
mse_plot_output = gr.Image(label="总 MSE 与各关节 MSE", type="filepath", height=680, visible=False)
with gr.Column(scale=1):
score_md = gr.Markdown("### 动作评分")
score_output = gr.Textbox(label="评分", value="", interactive=False)
cycle_select_md = gr.Markdown("### 周期选择")
cycle_dropdown = gr.Dropdown(label="选择分析周期", choices=[], interactive=False)
validate_button = gr.Button("验证动作并生成对比", variant="primary", elem_classes=["action-btn"])
cycle_info_md = gr.Markdown("### 周期信息")
cycle_info_output = gr.Textbox(label="周期详情", lines=3)
frame_slider = gr.Slider(0, 99, value=0, step=1, label="选择归一化帧", interactive=False, visible=False)
with gr.Row():
frame_joint_mse_table = gr.Dataframe(
headers=["关键点", "原始名称", "当前帧 MSE"],
datatype=["str", "str", "str"],
label="各关节 MSE 详情",
)
with gr.TabItem("📋 诊断报告 / Report"):
with gr.Column():
report_title_md = gr.Markdown("## 技术诊断报告")
report_markdown = gr.Markdown()
error_list_md = gr.Markdown("### 错误检测列表")
error_table = gr.Dataframe(
headers=["阶段", "错误类型", "严重程度", "描述", "建议"],
datatype=["str", "str", "str", "str", "str"],
label="错误详情",
)
error_stats_md = gr.Markdown("### 错误分布统计")
error_stats_output = gr.HTML()
# Keep usage tracking connected to existing callbacks without exposing
# a user-facing Usage tab.
usage_title_md = gr.Markdown("", visible=False)
usage_stats_output = gr.HTML(usage_summary_html(), visible=False)
refresh_usage_button = gr.Button("", visible=False)
# 辅助函数
def update_tool_language(current_lang, session_id, diagnoses, score):
lang_state_value = "en" if current_lang == "zh" else "zh"
log_usage_event("language_changed", session_id=session_id, details={"language": lang_state_value})
if lang_state_value == "en":
joint_headers = ["Keypoint", "Original Name", "Current Frame MSE"]
error_headers = ["Phase", "Error Type", "Severity", "Description", "Suggestion"]
else:
joint_headers = ["关键点", "原始名称", "当前帧 MSE"]
error_headers = ["阶段", "错误类型", "严重程度", "描述", "建议"]
return (
lang_state_value,
gr.update(value="🌐 中文 / EN" if lang_state_value == "en" else "🌐 EN / 中文"),
navbar_html(lang_state_value),
home_html(lang_state_value),
tool_header_html(lang_state_value),
f"### {t(lang_state_value, 'clip_settings')}",
gr.update(label=t(lang_state_value, "upload_label")),
gr.update(label=t(lang_state_value, "start_time")),
gr.update(label=t(lang_state_value, "end_time")),
gr.update(value=t(lang_state_value, "create_clip")),
gr.update(label=t(lang_state_value, "clip_preview")),
gr.update(label=t(lang_state_value, "clip_summary")),
gr.update(value=t(lang_state_value, "process_video")),
gr.update(value=t(lang_state_value, "stop_process")),
f"### {t(lang_state_value, 'stickman_result')}",
gr.update(label=t(lang_state_value, "stickman_video")),
gr.update(label=t(lang_state_value, "download_video")),
gr.update(label=t(lang_state_value, "process_summary")),
f"### {t(lang_state_value, 'compare_title')}",
gr.update(label=t(lang_state_value, "compare_subtitle")),
gr.update(label=t(lang_state_value, "download_compare")),
f"### {t(lang_state_value, 'action_score')}",
gr.update(label=t(lang_state_value, "score_label")),
f"### {t(lang_state_value, 'cycle_select')}",
gr.update(label=t(lang_state_value, "select_cycle")),
gr.update(value=t(lang_state_value, "validate_action")),
f"### {t(lang_state_value, 'cycle_info')}",
gr.update(label=t(lang_state_value, "cycle_detail")),
f"### {t(lang_state_value, 'mse_analysis')}",
gr.update(label=t(lang_state_value, "select_frame")),
gr.update(label=t(lang_state_value, "mse_plot")),
gr.update(label=t(lang_state_value, "joint_mse"), headers=joint_headers),
f"## {t(lang_state_value, 'report_title')}",
make_report_markdown(diagnoses, score, lang_state_value),
f"### {t(lang_state_value, 'error_list')}",
gr.update(label=t(lang_state_value, "error_details"), headers=error_headers, value=make_error_table_rows(diagnoses, lang_state_value)),
f"### {t(lang_state_value, 'error_stats')}",
update_error_stats(diagnoses, lang_state_value),
f"## {t(lang_state_value, 'usage_title')}",
gr.update(value=t(lang_state_value, "usage_refresh")),
usage_summary_html(),
)
def update_cycle_dropdown(cycles_payload):
cycles = cycles_payload.get("cycles", []) if isinstance(cycles_payload, dict) else cycles_payload
if not cycles:
return gr.update(choices=[], value=None, interactive=False)
fps = float(cycles_payload.get("output_fps", 30)) if isinstance(cycles_payload, dict) else 30
choices = [
(f"{i+1}. {label} (frames {s}-{e}, {e - s + 1}f, {(e - s + 1) / max(fps, 1e-6):.2f}s)", i)
for i, (s, e, label) in enumerate(cycles)
]
return gr.update(choices=choices, value=0, interactive=True)
def update_cycle_info(cycles_payload, cycle_idx, lang="zh"):
cycles = cycles_payload.get("cycles", []) if isinstance(cycles_payload, dict) else cycles_payload
if not cycles or cycle_idx is None:
return ""
idx = int(cycle_idx)
if idx < 0 or idx >= len(cycles):
return ""
s, e, label = cycles[idx]
fps = float(cycles_payload.get("output_fps", 30)) if isinstance(cycles_payload, dict) else 30
duration = (e - s + 1) / fps
if lang == "en":
return f"Cycle {idx+1}: {label}\nFrames: {s}-{e}\nDuration: {duration:.2f}s"
return f"周期 {idx+1}: {label}\n帧范围: {s}-{e}\n时长: {duration:.2f}秒"
def update_first_cycle_info(cycles_payload, lang="zh"):
cycles = cycles_payload.get("cycles", []) if isinstance(cycles_payload, dict) else cycles_payload
if not cycles:
return ""
return update_cycle_info(cycles_payload, 0, lang)
def update_overlap_frame(overlap_payload, frame_idx):
return render_overlap_frame(overlap_payload, frame_idx)
def update_mse_frame(mse_payload, frame_idx):
return render_mse_frame(mse_payload, frame_idx), make_frame_joint_mse_rows(mse_payload, frame_idx)
def update_analysis_frame(overlap_payload, mse_payload, frame_idx):
return (
render_overlap_frame(overlap_payload, frame_idx),
render_mse_frame(mse_payload, frame_idx),
make_frame_joint_mse_rows(mse_payload, frame_idx),
)
def update_error_table(diagnoses, lang="zh"):
return make_error_table_rows(diagnoses, lang)
def update_error_stats(diagnoses, lang="zh"):
if not diagnoses:
empty_text = "No diagnostics yet" if lang == "en" else "暂无诊断数据"
return f'<div style="text-align:center; padding:20px; color:#94a3b8;">{empty_text}</div>'
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"""
<div style="display: flex; gap: 12px; justify-content: center; flex-wrap: wrap;">
<div style="background: rgba(107, 203, 119, 0.1); border: 1px solid rgba(107, 203, 119, 0.3); border-radius: 12px; padding: 16px 24px; text-align: center; min-width: 100px;">
<div style="font-size: 28px; font-weight: bold; color: #6BCB77;">{severity_counts['normal']}</div>
<div style="font-size: 12px; color: #94a3b8;">{labels['normal']} ({normal_pct:.1f}%)</div>
</div>
<div style="background: rgba(255, 217, 61, 0.1); border: 1px solid rgba(255, 217, 61, 0.3); border-radius: 12px; padding: 16px 24px; text-align: center; min-width: 100px;">
<div style="font-size: 28px; font-weight: bold; color: #FFD93D;">{severity_counts['low']}</div>
<div style="font-size: 12px; color: #94a3b8;">{labels['low']} ({low_pct:.1f}%)</div>
</div>
<div style="background: rgba(255, 159, 67, 0.1); border: 1px solid rgba(255, 159, 67, 0.3); border-radius: 12px; padding: 16px 24px; text-align: center; min-width: 100px;">
<div style="font-size: 28px; font-weight: bold; color: #FF9F43;">{severity_counts['medium']}</div>
<div style="font-size: 12px; color: #94a3b8;">{labels['medium']} ({medium_pct:.1f}%)</div>
</div>
<div style="background: rgba(255, 107, 107, 0.1); border: 1px solid rgba(255, 107, 107, 0.3); border-radius: 12px; padding: 16px 24px; text-align: center; min-width: 100px;">
<div style="font-size: 28px; font-weight: bold; color: #FF6B6B;">{severity_counts['high']}</div>
<div style="font-size: 12px; color: #94a3b8;">{labels['high']} ({high_pct:.1f}%)</div>
</div>
</div>
"""
def format_score_output(score):
return str(score or "")
def initialize_session():
session_id = str(uuid.uuid4())
log_usage_event("page_visit", session_id=session_id)
return session_id, usage_summary_html()
def track_video_input(video_path, session_id):
source = resolve_uploaded_video_path(video_path)
if not source or not source.exists():
return "empty", usage_summary_html()
details = {
"file_extension": source.suffix.lower(),
"file_size_mb": round(source.stat().st_size / (1024 * 1024), 3),
}
log_usage_event("video_upload", session_id=session_id, details=details)
return "uploaded", usage_summary_html()
def refresh_usage(session_id):
log_usage_event("usage_refreshed", session_id=session_id)
return usage_summary_html()
def request_stop_processing(session_id):
PROCESS_STOP_EVENT.set()
log_usage_event("processing_stop_requested", session_id=session_id)
return usage_summary_html()
def create_clip_with_usage(video_path, start_sec, end_sec, upload_guard, session_id, progress=gr.Progress(track_tqdm=False)):
try:
clip_path, preview_path, summary = create_monitored_clip(
video_path,
start_sec,
end_sec,
upload_guard,
progress,
)
if clip_path:
log_usage_event(
"clip_created",
session_id=session_id,
details={
"start_sec": float(start_sec or 0),
"end_sec": float(end_sec or 0),
},
)
return clip_path, preview_path, summary, usage_summary_html()
except Exception as exc:
log_usage_event("error", session_id=session_id, details={"stage": "clip", "message": str(exc)})
raise
def build_stickman_with_usage(video_path, clip_path, upload_guard, session_id, progress=gr.Progress(track_tqdm=False)):
log_usage_event("stickman_started", session_id=session_id)
try:
video_out, file_out, summary, cycles = build_stickman_video(
video_path,
clip_path,
upload_guard,
progress,
)
cycle_list = cycles.get("cycles", []) if isinstance(cycles, dict) else cycles
log_usage_event(
"stickman_completed",
session_id=session_id,
details={
"cycles_detected": len(cycle_list or []),
"has_output_video": bool(video_out),
},
)
return video_out, file_out, summary, cycles, usage_summary_html()
except Exception as exc:
log_usage_event("error", session_id=session_id, details={"stage": "stickman", "message": str(exc)})
raise
def validate_with_usage(video_path, clip_path, cycles, cycle_index, lang, session_id, progress=gr.Progress(track_tqdm=False)):
cycle_list = cycles.get("cycles", []) if isinstance(cycles, dict) else cycles
selected_label = ""
if cycle_list and cycle_index is not None and 0 <= int(cycle_index) < len(cycle_list):
selected_label = cycle_list[int(cycle_index)][2]
log_usage_event(
"diagnosis_started",
session_id=session_id,
details={"cycle_index": cycle_index, "cycle_label": selected_label},
)
try:
result = validate_cycle_and_compare(video_path, clip_path, cycles, cycle_index, progress)
score = result[3] if len(result) > 3 else ""
diagnoses = result[4] if len(result) > 4 else []
result = list(result)
result[2] = make_report_markdown(diagnoses, score, lang)
log_usage_event(
"diagnosis_completed",
session_id=session_id,
details={
"cycle_index": cycle_index,
"cycle_label": selected_label,
"score": score,
"diagnosis_count": len(diagnoses or []),
},
)
return (*result, usage_summary_html())
except Exception as exc:
log_usage_event("error", session_id=session_id, details={"stage": "diagnosis", "message": str(exc)})
raise
# 导航按钮事件 - 前端JS处理切换,后端仅占位
demo.load(
fn=initialize_session,
inputs=None,
outputs=[session_state, usage_stats_output],
show_progress="hidden",
)
video_input.change(
fn=track_video_input,
inputs=[video_input, session_state],
outputs=[upload_guard_input, usage_stats_output],
show_progress="hidden",
)
refresh_usage_button.click(
fn=refresh_usage,
inputs=[session_state],
outputs=[usage_stats_output],
show_progress="hidden",
)
language_button.click(
fn=update_tool_language,
inputs=[lang_state, session_state, diagnoses_state, score_state],
outputs=[
lang_state,
language_button,
nav_output,
home_output,
tool_header,
clip_settings_md,
video_input,
start_input,
end_input,
create_clip_button,
clip_preview,
clip_summary,
process_button,
stop_button,
stickman_result_md,
video_output,
file_output,
summary_output,
compare_title_md,
comparison_output,
comparison_file,
score_md,
score_output,
cycle_select_md,
cycle_dropdown,
validate_button,
cycle_info_md,
cycle_info_output,
mse_analysis_md,
frame_slider,
mse_plot_output,
frame_joint_mse_table,
report_title_md,
report_markdown,
error_list_md,
error_table,
error_stats_md,
error_stats_output,
usage_title_md,
refresh_usage_button,
usage_stats_output,
],
show_progress="hidden",
)
clip_event = create_clip_button.click(
fn=create_clip_with_usage,
inputs=[video_input, start_input, end_input, upload_guard_input, session_state],
outputs=[clip_state, clip_preview, clip_summary, usage_stats_output],
show_progress="full",
)
process_event = process_button.click(
fn=build_stickman_with_usage,
inputs=[
video_input,
clip_state,
upload_guard_input,
session_state,
],
outputs=[video_output, file_output, summary_output, cycles_state, usage_stats_output],
show_progress="full",
).then(
fn=update_cycle_dropdown,
inputs=[cycles_state],
outputs=[cycle_dropdown],
).then(
fn=update_first_cycle_info,
inputs=[cycles_state, lang_state],
outputs=[cycle_info_output],
)
validate_event = validate_button.click(
fn=validate_with_usage,
inputs=[
video_input,
clip_state,
cycles_state,
cycle_dropdown,
lang_state,
session_state,
],
outputs=[
comparison_output,
comparison_file,
report_markdown,
score_state,
diagnoses_state,
mse_state,
overlap_state,
frame_slider,
mse_plot_output,
frame_joint_mse_table,
fast_frame_viewer,
usage_stats_output,
],
show_progress="full",
).then(
fn=format_score_output,
inputs=[score_state],
outputs=[score_output],
).then(
fn=update_error_table,
inputs=[diagnoses_state, lang_state],
outputs=[error_table],
).then(
fn=update_error_stats,
inputs=[diagnoses_state, lang_state],
outputs=[error_stats_output],
)
cycle_dropdown.change(
fn=update_cycle_info,
inputs=[cycles_state, cycle_dropdown, lang_state],
outputs=[cycle_info_output],
)
frame_slider.change(
fn=update_analysis_frame,
inputs=[overlap_state, mse_state, frame_slider],
outputs=[comparison_output, mse_plot_output, frame_joint_mse_table],
queue=False,
show_progress="hidden",
)
stop_button.click(
fn=request_stop_processing,
inputs=[session_state],
outputs=[usage_stats_output],
queue=False,
show_progress="hidden",
cancels=[clip_event, process_event, validate_event],
)
if __name__ == "__main__":
logger.info("Starting app...")
configure_cpu_runtime()
log_runtime_versions()
if os.getenv("SPACE_ID"):
logger.info("Skipping eager YOLO load on Space; model will load inside the processing callback.")
else:
logger.info("Loading YOLO model...")
try:
model = load_yolo_model()
logger.info(f"YOLO model loaded: {YOLO_MODEL_PATH.name}")
except Exception as e:
logger.error(f"YOLO model load failed: {e}", exc_info=True)
logger.info("Launching Gradio demo...")
launch_kwargs = {
"show_error": True,
"allowed_paths": [str(SCRIPT_DIR), tempfile.gettempdir()],
"ssr_mode": False,
"css": custom_css,
"theme": gr.themes.Default(),
"head": '''
<script>
const i18nData = {
"zh": {
"app_title": "RowingValidator Beta",
"app_subtitle": "AI划船动作分析",
"for_coaches": "FOR COACHES & ATHLETES",
"hero_title": "先进的AI划船视频分析与虚拟教练平台",
"hero_subtitle": "安全高效地划船",
"start_free": "免费开始 →",
"feature_1_title": "提高速度",
"feature_1_desc": "通过技术优化,提升划行速度",
"feature_2_title": "提升效率",
"feature_2_desc": "提高能量转换效率,划得更省力",
"feature_3_title": "减少受伤",
"feature_3_desc": "纠正错误动作,减少运动损伤",
"why_title": "为什么选择我们",
"why_subtitle": "我们的AI技术帮助您深入分析划船动作,发现问题并提供专业指导",
"why_1_title": "AI精准分析",
"why_1_desc": "基于YOLO和自编码器模型,精准识别动作细节,提供专业反馈",
"why_2_title": "实时对比",
"why_2_desc": "将您的动作与标准动作进行实时对比,直观展示差异",
"why_3_title": "个性化建议",
"why_3_desc": "根据您的动作特点,提供针对性的改进建议和训练计划",
"demo_title": "观看使用演示",
"demo_subtitle": "了解如何使用我们的工具分析划船动作",
"cta_title": "准备好提升您的划船技术了吗?",
"cta_subtitle": "加入数千名使用我们的AI分析提升技术的运动员",
"footer": "© 2026 RowingValidator Beta. All rights reserved.",
"back_home": "← 返回首页",
"tool_title": "视频上传与分析",
"tool_subtitle": "上传您的划船视频,让AI分析您的技术动作",
},
"en": {
"app_title": "RowingValidator Beta",
"app_subtitle": "AI Rowing Analysis",
"for_coaches": "FOR COACHES & ATHLETES",
"hero_title": "ADVANCED AI ROWING VIDEO ANALYSIS AND VIRTUAL COACHING PLATFORM",
"hero_subtitle": "ROW SAFELY & EFFICIENTLY",
"start_free": "START FOR FREE",
"feature_1_title": "Increase Speed",
"feature_1_desc": "Improve rowing speed through technical optimization",
"feature_2_title": "Boost Efficiency",
"feature_2_desc": "Improve energy conversion efficiency, row with less effort",
"feature_3_title": "Reduce Injuries",
"feature_3_desc": "Correct improper form and reduce sports injuries",
"why_title": "Why Choose Us",
"why_subtitle": "Our AI technology helps you deeply analyze rowing technique, identify issues, and provide professional guidance",
"why_1_title": "AI-Powered Analysis",
"why_1_desc": "Based on YOLO and autoencoder models, precisely identify movement details and provide professional feedback",
"why_2_title": "Real-Time Comparison",
"why_2_desc": "Compare your movements with standard form in real-time with intuitive visual differences",
"why_3_title": "Personalized Advice",
"why_3_desc": "Provide targeted improvement suggestions and training plans based on your movement characteristics",
"demo_title": "Watch the Demo",
"demo_subtitle": "Learn how to use our tool to analyze your rowing technique",
"cta_title": "Ready to Improve Your Rowing Technique?",
"cta_subtitle": "Join thousands of athletes improving their technique with our AI analysis",
"footer": "© 2026 RowingValidator Beta. All rights reserved.",
"back_home": "← Back to Home",
"tool_title": "Video Upload & Analysis",
"tool_subtitle": "Upload your rowing video and let AI analyze your technique",
}
};
let currentLang = 'zh';
function applyLanguage(lang) {
currentLang = lang;
document.documentElement.lang = lang;
const translations = i18nData[lang];
if (!translations) return;
document.querySelectorAll('[data-i18n]').forEach(el => {
const key = el.getAttribute('data-i18n');
if (translations[key]) {
el.textContent = translations[key];
}
});
const langBtn = document.getElementById('lang-toggle');
if (langBtn) {
langBtn.textContent = lang === 'zh' ? '🌐 EN / 中文' : '🌐 中文 / EN';
}
document.dispatchEvent(new CustomEvent('lang-change', { detail: { lang: lang } }));
}
function toggleLanguage(e) {
if (e) {
e.stopPropagation();
e.preventDefault();
}
applyLanguage(currentLang === 'zh' ? 'en' : 'zh');
}
window.addEventListener('DOMContentLoaded', function() {
setTimeout(() => applyLanguage(currentLang), 500);
setTimeout(applyTabLabels, 900);
});
function getMainTabs() {
return document.querySelector('.main-tabs');
}
function inferCurrentLangFromButton() {
const btn = document.querySelector('.global-language-toggle button') || document.querySelector('.global-language-toggle');
const text = btn ? btn.textContent : '';
return text.includes('中文 / EN') ? 'en' : 'zh';
}
function applyTabLabels() {
const lang = inferCurrentLangFromButton();
const labels = lang === 'en'
? ['Home', 'Tool', 'Video Process', 'Compare', 'Report']
: ['首页', '工具', '视频处理', '动作对比', '诊断报告'];
const buttons = Array.from(document.querySelectorAll('button')).filter(b => !b.closest('.global-language-toggle'));
const patterns = [
['首页', 'Home'],
['工具', 'Tool'],
['视频处理', 'Video Process', 'Process'],
['动作对比', 'Compare'],
['诊断报告', 'Report'],
];
patterns.forEach((pattern, idx) => {
const btn = buttons.find(b => pattern.some(p => b.textContent.includes(p)));
if (btn) btn.textContent = labels[idx];
});
}
function switchToTool() {
const tabs = getMainTabs();
if (!tabs) return;
const tabWrapper = tabs.querySelector(':scope > .tab-wrapper') || tabs.querySelector('.tab-wrapper') || tabs.querySelector('[role="tablist"]');
if (!tabWrapper) return;
const buttons = tabWrapper.querySelectorAll('button, [role="tab"]');
let lastToolBtn = null;
for (const btn of buttons) {
if (btn.textContent.includes('工具') || btn.textContent.includes('Tool')) {
lastToolBtn = btn;
}
}
if (lastToolBtn) lastToolBtn.click();
window.scrollTo({top: 0, behavior: 'smooth'});
}
function switchToHome() {
const tabs = getMainTabs();
if (!tabs) return;
const tabWrapper = tabs.querySelector(':scope > .tab-wrapper') || tabs.querySelector('.tab-wrapper') || tabs.querySelector('[role="tablist"]');
if (!tabWrapper) return;
const buttons = tabWrapper.querySelectorAll('button, [role="tab"]');
let lastHomeBtn = null;
for (const btn of buttons) {
if (btn.textContent.includes('首页') || btn.textContent.includes('Home')) {
lastHomeBtn = btn;
}
}
if (lastHomeBtn) lastHomeBtn.click();
window.scrollTo({top: 0, behavior: 'smooth'});
}
function initPageSwitcher() {
const buttons = document.querySelectorAll('button');
buttons.forEach(btn => {
if (btn._navBound) return;
if (btn.textContent.includes('免费开始') || btn.textContent.includes('START') || btn.textContent.includes('Start')) {
btn._navBound = true;
btn.addEventListener('click', function(e) {
setTimeout(switchToTool, 50);
});
}
if (btn.textContent.includes('返回首页') || btn.textContent.includes('Back to Home')) {
btn._navBound = true;
btn.addEventListener('click', function(e) {
setTimeout(switchToHome, 50);
});
}
});
const logo = document.getElementById('nav-logo');
if (logo && !logo._navBound) {
logo._navBound = true;
logo.style.cursor = 'pointer';
logo.addEventListener('click', function(e) {
switchToHome();
});
}
}
window._navInitAttempts = 0;
function tryInitNav() {
window._navInitAttempts++;
const tabs = getMainTabs();
if (tabs) {
initPageSwitcher();
}
if (window._navInitAttempts < 30) {
setTimeout(tryInitNav, 500);
}
}
tryInitNav();
window.rvFrameViewers = window.rvFrameViewers || {};
function rvInitFrameViewer(id) {
if (window.rvFrameViewers[id]) return window.rvFrameViewers[id];
const viewer = document.getElementById(id);
if (!viewer || !viewer.dataset.payload) return null;
const binary = atob(viewer.dataset.payload);
const bytes = Uint8Array.from(binary, (char) => char.charCodeAt(0));
const data = JSON.parse(new TextDecoder().decode(bytes));
const state = {
data,
idx: Number(data.initial || 0),
playing: false,
timer: null,
raf: null,
ready: false,
loading: false,
compareFrames: new Array(Number(data.total || 0)).fill(null),
mseFrames: new Array(Number(data.total || 0)).fill(null),
loadedPairs: 0,
};
window.rvFrameViewers[id] = state;
rvSetViewerEnabled(id, false);
rvLoadFrameViewer(id);
return state;
}
function rvSetViewerEnabled(id, enabled) {
const viewer = document.getElementById(id);
if (!viewer) return;
const range = document.getElementById(id + '_range');
if (range) range.disabled = !enabled;
viewer.querySelectorAll('.rv-fast-btn').forEach((btn) => {
btn.disabled = !enabled;
btn.style.opacity = enabled ? '1' : '0.5';
btn.style.cursor = enabled ? 'pointer' : 'default';
});
}
function rvSetLoadLabel(id, text) {
const label = document.getElementById(id + '_load');
if (label) label.textContent = text;
}
async function rvLoadBitmap(url) {
const response = await fetch(url, {cache: 'force-cache'});
if (!response.ok) throw new Error(`Frame load failed: ${response.status}`);
const blob = await response.blob();
if ('createImageBitmap' in window) {
return await createImageBitmap(blob);
}
return await new Promise((resolve, reject) => {
const image = new Image();
image.onload = () => resolve(image);
image.onerror = reject;
image.src = URL.createObjectURL(blob);
});
}
async function rvLoadFramePair(state, idx) {
if (state.compareFrames[idx] && state.mseFrames[idx]) return;
const [compareFrame, mseFrame] = await Promise.all([
rvLoadBitmap(state.data.compare[idx]),
rvLoadBitmap(state.data.mse[idx]),
]);
state.compareFrames[idx] = compareFrame;
state.mseFrames[idx] = mseFrame;
state.loadedPairs += 1;
}
async function rvLoadFrameViewer(id) {
const state = window.rvFrameViewers[id];
if (!state || state.loading) return;
state.loading = true;
const total = Number(state.data.total || 0);
rvSetLoadLabel(id, `Loading frames 0/${total}`);
try {
await rvLoadFramePair(state, state.idx);
rvDrawFrame(id, state.idx);
rvRenderJointRows(id, state.idx);
rvSetLoadLabel(id, `Loading frames ${state.loadedPairs}/${total}`);
const indices = [];
for (let i = 0; i < total; i++) {
if (i !== state.idx) indices.push(i);
}
let cursor = 0;
const worker = async () => {
while (cursor < indices.length) {
const idx = indices[cursor++];
await rvLoadFramePair(state, idx);
rvSetLoadLabel(id, `Loading frames ${Math.min(state.loadedPairs, total)}/${total}`);
}
};
const workers = Array.from({length: Math.min(8, indices.length || 1)}, worker);
await Promise.all(workers);
state.ready = true;
rvSetViewerEnabled(id, true);
rvSetLoadLabel(id, 'Ready');
rvFrameUpdate(id, state.idx);
} catch (error) {
console.error(error);
rvSetLoadLabel(id, 'Frame loading failed. Try validating again.');
}
}
function rvRenderJointRows(id, idx) {
const state = rvInitFrameViewer(id);
if (!state) return;
const holder = document.getElementById(id + '_joints');
if (!holder) return;
const rows = (state.data.rows || [])[idx] || [];
holder.innerHTML = rows.map((row) => {
const name = row[0] || '';
const value = row[2] || '';
return `<div class="rv-fast-joint-row"><span>${name}</span><strong>${value}</strong></div>`;
}).join('');
}
function rvFrameUpdate(id, value) {
const state = rvInitFrameViewer(id);
if (!state) return;
const total = Number(state.data.total || 0);
const idx = Math.max(0, Math.min(Number(value || 0), total - 1));
state.idx = idx;
if (!state.ready) {
const range = document.getElementById(id + '_range');
if (range && Number(range.value) !== idx) range.value = String(idx);
return;
}
if (state.raf) cancelAnimationFrame(state.raf);
state.raf = requestAnimationFrame(() => {
const range = document.getElementById(id + '_range');
if (range && Number(range.value) !== idx) range.value = String(idx);
rvDrawFrame(id, idx);
rvRenderJointRows(id, idx);
});
}
function rvDrawFrame(id, idx) {
const state = window.rvFrameViewers[id];
if (!state) return;
const total = Number(state.data.total || 0);
const compareCanvas = document.getElementById(id + '_compare');
const mseCanvas = document.getElementById(id + '_mse');
const label = document.getElementById(id + '_label');
if (label) label.textContent = `Frame ${idx + 1}/${total}`;
if (compareCanvas && state.compareFrames[idx]) {
const ctx = compareCanvas.getContext('2d', {alpha: false});
ctx.clearRect(0, 0, compareCanvas.width, compareCanvas.height);
ctx.drawImage(state.compareFrames[idx], 0, 0, compareCanvas.width, compareCanvas.height);
}
if (mseCanvas && state.mseFrames[idx]) {
const ctx = mseCanvas.getContext('2d', {alpha: false});
ctx.clearRect(0, 0, mseCanvas.width, mseCanvas.height);
ctx.drawImage(state.mseFrames[idx], 0, 0, mseCanvas.width, mseCanvas.height);
}
}
function rvFrameNext(id) {
const state = rvInitFrameViewer(id);
if (!state) return;
const total = Number(state.data.total || 0);
rvFrameUpdate(id, (state.idx + 1) % total);
}
function rvFramePrev(id) {
const state = rvInitFrameViewer(id);
if (!state) return;
const total = Number(state.data.total || 0);
rvFrameUpdate(id, (state.idx - 1 + total) % total);
}
function rvFramePlay(id) {
const state = rvInitFrameViewer(id);
if (!state || !state.ready) return;
const btn = document.querySelector(`#${id} .rv-play-btn`);
state.playing = !state.playing;
if (btn) btn.textContent = state.playing ? '⏸ Pause' : '▶ Play';
if (state.timer) {
clearInterval(state.timer);
state.timer = null;
}
if (state.playing) {
state.timer = setInterval(() => rvFrameNext(id), 83);
}
}
function rvInitAllFrameViewers() {
document.querySelectorAll('.rv-fast-viewer[data-payload]').forEach((viewer) => {
rvInitFrameViewer(viewer.id);
});
}
setInterval(function() {
initPageSwitcher();
applyTabLabels();
rvInitAllFrameViewers();
}, 3000);
</script>
''',
}
if os.getenv("SPACE_ID"):
demo.queue().launch(**launch_kwargs)
else:
try:
demo.queue().launch(
server_name="127.0.0.1",
server_port=int(os.getenv("GRADIO_SERVER_PORT", os.getenv("PORT", "7872"))),
share=False,
**launch_kwargs,
)
except Exception as e:
logger.warning(f"Gradio startup check failed but server may be running: {e}")
logger.info(f"Server should be available at http://127.0.0.1:{os.getenv('PORT', '7872')}")
import time
while True:
time.sleep(3600)
from __future__ import annotations
import base64
import json
import logging
import math
import os
import platform
import shutil
import subprocess
import tempfile
import threading
import time
import uuid
from datetime import datetime, timezone
from functools import lru_cache
from importlib import metadata
from pathlib import Path
from urllib.parse import quote
import cv2
import gradio as gr
import matplotlib
import numpy as np
import torch
import torch.nn as nn
from scipy.interpolate import interp1d
from scipy.signal import find_peaks
SCRIPT_DIR = Path(__file__).parent.resolve()
def resolve_runtime_log_dir() -> Path:
configured_dir = os.getenv("USAGE_LOG_DIR") or os.getenv("LOG_DIR")
if configured_dir:
return Path(configured_dir).expanduser().resolve()
data_dir = Path("/data")
if data_dir.exists() and os.access(data_dir, os.W_OK):
return data_dir / "rowing_validator_logs"
return SCRIPT_DIR / "logs"
LOG_DIR = resolve_runtime_log_dir()
LOG_DIR.mkdir(parents=True, exist_ok=True)
USAGE_LOG_DIR = LOG_DIR / "usage"
USAGE_LOG_DIR.mkdir(parents=True, exist_ok=True)
USAGE_EVENTS_PATH = USAGE_LOG_DIR / "usage_events.jsonl"
USAGE_SUMMARY_PATH = USAGE_LOG_DIR / "usage_summary.json"
USAGE_LOG_LOCK = threading.Lock()
PROCESS_STOP_EVENT = threading.Event()
APP_STARTED_AT = datetime.now(timezone.utc).isoformat()
logging.basicConfig(
level=getattr(logging, os.getenv("LOG_LEVEL", "INFO").upper(), logging.INFO),
format="%(asctime)s - %(levelname)s - %(message)s",
handlers=[
logging.FileHandler(LOG_DIR / "app.log", encoding="utf-8"),
logging.StreamHandler(),
],
)
logger = logging.getLogger(__name__)
FFMPEG_TIMEOUT_SECONDS = int(os.getenv("FFMPEG_TIMEOUT_SECONDS", "180"))
WEIGHT_DIR = SCRIPT_DIR / "Weight"
YOLO_MODEL_PATH = WEIGHT_DIR / "yolo11x-pose.pt"
DRIVE_MODEL_PATH = WEIGHT_DIR / "best_drive_ae_model.pt"
DRIVE_THRESHOLD_PATH = WEIGHT_DIR / "drive_threshold.npy"
RECOVERY_MODEL_PATH = WEIGHT_DIR / "best_recovery_ae_model.pt"
RECOVERY_THRESHOLD_PATH = WEIGHT_DIR / "recovery_threshold.npy"
KEYPOINT_NAMES = [
"nose",
"left_eye",
"right_eye",
"left_ear",
"right_ear",
"left_shoulder",
"right_shoulder",
"left_elbow",
"right_elbow",
"left_wrist",
"right_wrist",
"left_hip",
"right_hip",
"left_knee",
"right_knee",
"left_ankle",
"right_ankle",
]
MODEL_KEYPOINT_NAMES = [
"nose",
"left_eye",
"left_ear",
"left_shoulder",
"left_elbow",
"left_wrist",
"left_hip",
"left_knee",