from __future__ import annotations
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"""
Demo video is not available. Upload a rowing clip in the Tool tab to start analysis.
"""
return f"""
FOR COACHES & ATHLETES
ADVANCED AI ROWING VIDEO ANALYSIS AND VIRTUAL COACHING PLATFORM
ROW SAFELY & EFFICIENTLY
START FOR FREE
为什么选择我们
为什么选择我们
我们的AI技术帮助您深入分析划船动作,发现问题并提供专业指导
AI精准分析
基于YOLO和自编码器模型,精准识别动作细节,提供专业反馈
实时对比
将您的动作与标准动作进行实时对比,直观展示差异
个性化建议
根据您的动作特点,提供针对性的改进建议和训练计划
准备好提升您的划船技术了吗?
加入数千名使用我们的AI分析提升技术的运动员
免费开始 →
© 2026 RowingValidator Beta. All rights reserved.
""")
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=2):
compare_title_md = gr.Markdown("### 🆚 动作对比")
comparison_output = gr.Image(label="逐帧对比:实际动作 vs 模型重建", type="filepath", height=440, elem_classes=["comparison-frame"])
comparison_file = gr.File(label="下载对比视频")
mse_analysis_md = gr.Markdown("### MSE 逐帧分析")
mse_plot_output = gr.Plot(label="总 MSE 与各关节 MSE")
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)
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()
with gr.TabItem("📈 使用统计 / Usage"):
usage_title_md = gr.Markdown("## 使用统计")
usage_stats_output = gr.HTML(usage_summary_html())
refresh_usage_button = gr.Button("刷新使用统计", variant="secondary")
# 辅助函数
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)
choices = [
(f"{i+1}. {label} (frames {s}-{e})", 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 make_mse_plot(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'
{empty_text}
'
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"""
{severity_counts['normal']}
{labels['normal']} ({normal_pct:.1f}%)
{severity_counts['low']}
{labels['low']} ({low_pct:.1f}%)
{severity_counts['medium']}
{labels['medium']} ({medium_pct:.1f}%)
{severity_counts['high']}
{labels['high']} ({high_pct:.1f}%)
"""
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,
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_overlap_frame,
inputs=[overlap_state, frame_slider],
outputs=[comparison_output],
show_progress="hidden",
)
frame_slider.change(
fn=update_mse_frame,
inputs=[mse_state, frame_slider],
outputs=[mse_plot_output, frame_joint_mse_table],
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()
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)],
"ssr_mode": False,
"css": custom_css,
"theme": gr.themes.Default(),
"head": '''
''',
}
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)