fix: correct face detection threshold defaults

- Changed min_confidence from 50.0 to 0.5 (Vision uses 0.0-1.0 range)
- Changed min_size from 32 to 1 (was filtering out all small faces)
- Changed min_capture_quality from 25.0 to 0.25
- Fixes issue where all videos showed 0 faces detected

Root cause: admin_config.rs used wrong defaults (50.0/32) instead of
config.rs constants (0.5/1), causing Vision framework to filter out
ALL faces because confidence threshold exceeded valid range.

Verified: IMG_9449 now correctly detects 191 faces (was 0).
This commit is contained in:
Accusys
2026-09-18 02:42:21 +08:00
parent e4b8ddab94
commit 31d1b4050f
59 changed files with 11110 additions and 6163 deletions
+129
View File
@@ -0,0 +1,129 @@
#!/opt/homebrew/bin/python3.11
"""
Admin Config Loader for Python Scripts
Loads configuration from config/admin_config.json
"""
import json
from pathlib import Path
from typing import Optional, Dict, Any
import os
class AdminConfigManager:
_instance = None
_config = None
@classmethod
def get_instance(cls):
if cls._instance is None:
cls._instance = cls()
return cls._instance
def __init__(self):
config_path = os.environ.get(
"MOMENTRY_ADMIN_CONFIG_PATH",
str(Path(__file__).parent.parent / "config" / "admin_config.json")
)
self._config = self._load_config(config_path)
def _load_config(self, config_path: str) -> Dict[str, Any]:
if not Path(config_path).exists():
raise FileNotFoundError(f"Config file not found: {config_path}")
with open(config_path, 'r') as f:
return json.load(f)
def get_vlm_prompt(self, key: str) -> Optional[Dict[str, Any]]:
"""Get VLM prompt by key"""
prompts = self._config.get('vlm_prompts', {})
return prompts.get(key)
def get_prompt_text(self, key: str) -> Optional[str]:
"""Get prompt text by key"""
prompt_data = self.get_vlm_prompt(key)
if not prompt_data:
return None
return prompt_data.get('prompt') or prompt_data.get('system_prompt')
def get_max_tokens(self, key: str) -> int:
"""Get max tokens for prompt"""
prompt_data = self.get_vlm_prompt(key)
return prompt_data.get('max_tokens', 100) if prompt_data else 100
def get_llm_config(self, key: str) -> Optional[Dict[str, Any]]:
"""Get LLM config by key"""
return self._config.get('llm_config', {}).get(key)
def get_processor_config(self, key: str) -> Optional[Dict[str, Any]]:
"""Get processor config by key"""
return self._config.get('processor_config', {}).get(key)
def get_system_config(self) -> Dict[str, Any]:
"""Get system config"""
return self._config.get('system_config', {})
def get_all_vlm_prompts(self) -> Dict[str, Any]:
"""Get all VLM prompts"""
return self._config.get('vlm_prompts', {})
def reload(self):
"""Reload config from file"""
config_path = os.environ.get(
"MOMENTRY_ADMIN_CONFIG_PATH",
str(Path(__file__).parent.parent / "config" / "admin_config.json")
)
self._config = self._load_config(config_path)
# Convenience functions
def get_vlm_prompt(key: str) -> Optional[Dict[str, Any]]:
"""Get VLM prompt by key"""
return AdminConfigManager.get_instance().get_vlm_prompt(key)
def get_prompt_text(key: str) -> Optional[str]:
"""Get prompt text by key"""
return AdminConfigManager.get_instance().get_prompt_text(key)
def get_max_tokens(key: str) -> int:
"""Get max tokens for prompt"""
return AdminConfigManager.get_instance().get_max_tokens(key)
def get_llm_config(key: str) -> Optional[Dict[str, Any]]:
"""Get LLM config by key"""
return AdminConfigManager.get_instance().get_llm_config(key)
def get_processor_config(key: str) -> Optional[Dict[str, Any]]:
"""Get processor config by key"""
return AdminConfigManager.get_instance().get_processor_config(key)
def get_system_config() -> Dict[str, Any]:
"""Get system config"""
return AdminConfigManager.get_instance().get_system_config()
def get_all_vlm_prompts() -> Dict[str, Any]:
"""Get all VLM prompts"""
return AdminConfigManager.get_instance().get_all_vlm_prompts()
if __name__ == "__main__":
# Test
print("Testing Admin Config Loader...")
manager = AdminConfigManager.get_instance()
print("\n1. Testing VLM prompts:")
for key in ["rust_vlm_summary", "trace_desc", "scene_desc"]:
prompt = manager.get_vlm_prompt(key)
if prompt:
print(f" {key}: {prompt.get('description', 'N/A')}")
print("\n2. Testing LLM config:")
for key in ["chat", "vision", "embedding"]:
config = manager.get_llm_config(key)
if config:
print(f" {key}: {config.get('model', 'N/A')}")
print("\n3. Testing system config:")
sys_config = manager.get_system_config()
print(f" Output dir: {sys_config.get('output_dir', 'N/A')}")
print("\n✅ Admin Config Loader test passed")
+57
View File
@@ -0,0 +1,57 @@
#!/bin/bash
# TKG 进度监控脚本
# 用途:监控 Roman_Holiday 文件的 TKG 处理进度
FILE_UUID="bfba056f5021e2404b0870cc0b1fa851"
OUTPUT_DIR="/Users/accusys/momentry/output"
echo "=============================================="
echo " TKG 进度监控"
echo "=============================================="
echo ""
echo "文件: Roman_Holiday(1953).mp4"
echo "UUID: $FILE_UUID"
echo ""
# 统计 trace 目录
TRACE_COUNT=$(ls -d $OUTPUT_DIR/$FILE_UUID/trace_* 2>/dev/null | wc -l | tr -d ' ')
KEY_FRAME_COUNT=$(find $OUTPUT_DIR/$FILE_UUID/ -name "key_frame.jpg" 2>/dev/null | wc -l | tr -d ' ')
KEY_FACE_COUNT=$(find $OUTPUT_DIR/$FILE_UUID/ -name "key_face.jpg" 2>/dev/null | wc -l | tr -d ' ')
# 计算进度
PERCENT=$(echo "scale=2; $TRACE_COUNT * 100 / 7254" | bc)
echo "【当前进度】"
echo "Trace 目录: $TRACE_COUNT / 7254 ($PERCENT%)"
echo "Key frames: $KEY_FRAME_COUNT / 7254"
echo "Key faces: $KEY_FACE_COUNT / 7254"
echo ""
# 计算预计完成时间
if [ $TRACE_COUNT -gt 0 ]; then
REMAINING=$((7254 - TRACE_COUNT))
# 假设平均速度为 0.2 个/秒
SECONDS=$(echo "scale=0; $REMAINING / 0.2" | bc)
HOURS=$((SECONDS / 3600))
MINUTES=$(((SECONDS % 3600) / 60))
echo "【预计完成时间】"
echo "剩余数量: $REMAINING 个"
echo "预计时间: $HOURS 小时 $MINUTES 分钟"
echo ""
fi
# 检查 Worker 进程
echo "【Worker 状态】"
WORKER_PID=$(ps aux | grep "target/debug/momentry worker" | grep -v grep | awk '{print $2}')
if [ -n "$WORKER_PID" ]; then
echo "✅ Worker 正在运行 (PID: $WORKER_PID)"
ps aux | grep "target/debug/momentry worker" | grep -v grep | awk '{print "CPU: "$3"%, Memory: "$4"%"}'
else
echo "❌ Worker 未运行"
fi
echo ""
echo "✅ 监控完成"
+7 -6
View File
@@ -24,6 +24,7 @@ VERSION = "v1.0.0"
DB_USER = os.environ.get("USER", "accusys")
DB_NAME = "momentry"
DB_SCHEMA = os.environ.get("DATABASE_SCHEMA", "dev")
QDRANT_URL = os.environ.get("QDRANT_URL", "http://localhost:6333")
QDRANT_COLLECTION = os.environ.get("QDRANT_COLLECTION", "momentry_dev_rule1_v2")
PG_BIN = "/Users/accusys/pgsql/18.3/bin"
@@ -61,25 +62,25 @@ def pack_phase(file_uuid: str, phase: int) -> Path:
schema_path = pkg_dir / "schema.sql"
with open(schema_path, "w") as fh:
subprocess.run(
[f"{PG_BIN}/pg_dump", "-U", DB_USER, "-d", DB_NAME, "--schema=dev", "--schema-only",
"-T", "dev.monitor_jobs", "-T", "dev.processor_results"],
[f"{PG_BIN}/pg_dump", "-U", DB_USER, "-d", DB_NAME, f"--schema={DB_SCHEMA}", "--schema-only",
"-T", f"{DB_SCHEMA}.monitor_jobs", "-T", f"{DB_SCHEMA}.processor_results"],
stdout=fh, text=True, timeout=60,
)
# 收集 chunks
chunks_csv = pkg_dir / "chunks.csv"
run_sql(f"\\COPY (SELECT * FROM dev.chunks WHERE file_uuid='{file_uuid}') TO '{chunks_csv}' CSV HEADER")
run_sql(f"\\COPY (SELECT * FROM {DB_SCHEMA}.chunks WHERE file_uuid='{file_uuid}') TO '{chunks_csv}' CSV HEADER")
# 收集 vectors
vecs_csv = pkg_dir / "vectors.csv"
run_sql(f"\\COPY (SELECT * FROM dev.chunk_vectors WHERE uuid='{file_uuid}') TO '{vecs_csv}' CSV HEADER")
run_sql(f"\\COPY (SELECT * FROM {DB_SCHEMA}.chunk_vectors WHERE uuid='{file_uuid}') TO '{vecs_csv}' CSV HEADER")
idents_csv = pkg_dir / "identities.csv"
run_sql(f"\\COPY (SELECT * FROM dev.identities) TO '{idents_csv}' CSV HEADER")
run_sql(f"\\COPY (SELECT * FROM {DB_SCHEMA}.identities) TO '{idents_csv}' CSV HEADER")
if phase >= 2:
faces_csv = pkg_dir / "face_detections.csv"
run_sql(f"\\COPY (SELECT * FROM dev.face_detections WHERE file_uuid='{file_uuid}') TO '{faces_csv}' CSV HEADER")
run_sql(f"\\COPY (SELECT * FROM {DB_SCHEMA}.face_detections WHERE file_uuid='{file_uuid}') TO '{faces_csv}' CSV HEADER")
# 匯出 Qdrant collection 快照
import urllib.request
+23 -10
View File
@@ -26,6 +26,14 @@ import os
import sys
from pathlib import Path
# Import admin config loader
try:
from admin_config_loader import get_prompt_text, get_max_tokens
except ImportError:
print("Warning: admin_config_loader not found, using default prompts", file=sys.stderr)
def get_prompt_text(key): return None
def get_max_tokens(key): return 100
# VLM configuration from environment variables
VLM_URL = os.environ.get("MOMENTRY_LLM_VISION_URL", "http://localhost:8091/v1/chat/completions")
VLM_MODEL = os.environ.get("MOMENTRY_LLM_VISION_MODEL", "llava-v1.6-vicuna-13b")
@@ -182,12 +190,17 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool =
print(f"[vlm] Analyzing {trace_path.name}...")
# Prompt 1: Person description
desc_prompt = "Describe this person briefly. For EVERY item, include COLOR: hair color, skin tone, clothing colors. If uncertain, say 'unknown color'. Be concise and honest."
# Helper function to get prompt with fallback
def get_prompt(key, default):
prompt = get_prompt_text(key)
return prompt if prompt else default
# Prompt 1: Person description
desc_prompt = get_prompt("trace_desc", "Describe this person briefly. For EVERY item, include COLOR: hair color, skin tone, clothing colors. If uncertain, say 'unknown color'. Be concise and honest.")
description = call_vlm(image_to_analyze, desc_prompt, model)
# Prompt 2: Clothing details
clothing_prompt = "Describe this person's clothing in detail. For EACH item, you MUST specify the COLOR: shirt color, pants color, jacket color, hat color, glasses frame color, shoe color. Format: 'color + item' (e.g., 'black hoodie', 'blue jeans'). If color is unclear, say 'unclear color'. Do not skip colors. Include any visible text or logos."
clothing_prompt = get_prompt("trace_clothing", "Describe this person's clothing in detail. For EACH item, you MUST specify the COLOR: shirt color, pants color, jacket color, hat color, glasses frame color, shoe color. Format: 'color + item' (e.g., 'black hoodie', 'blue jeans'). If color is unclear, say 'unclear color'. Do not skip colors. Include any visible text or logos.")
clothing = call_vlm(image_to_analyze, clothing_prompt, model)
# Prompt 3: Tags - auto-extract from description
@@ -207,15 +220,15 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool =
tags = tags[:5] if tags else ["unknown"]
# Prompt 5: Objects in hand
hand_prompt = "Look at the person's hands. What objects are they holding or touching? For EACH object, state its COLOR and type (e.g., 'red cup', 'black phone'). If hands not visible, say 'hands not visible'. If empty, say 'empty hands'."
hand_prompt = get_prompt("trace_hand_objects", "Look at the person's hands. What objects are they holding or touching? For EACH object, state its COLOR and type (e.g., 'red cup', 'black phone'). If hands not visible, say 'hands not visible'. If empty, say 'empty hands'.")
hand_objects = call_vlm(image_to_analyze, hand_prompt, model)
# Prompt 6: Lighting (day/night)
light_prompt = "What is the lighting condition? Answer one word: day, night, indoor-light, mixed, or unknown. If uncertain, answer 'unknown'."
light_prompt = get_prompt("trace_lighting", "What is the lighting condition? Answer one word: day, night, indoor-light, mixed, or unknown. If uncertain, answer 'unknown'.")
lighting = call_vlm(image_to_analyze, light_prompt, model).lower().strip()
# Prompt 7: Scene classification
scene_prompt = "Classify the scene. Answer in JSON: {\"location\": \"indoor/outdoor/unknown\", \"weather\": \"sunny/cloudy/rainy/night/unknown\", \"setting\": \"office/street/home/nature/studio/unknown\", \"transportation\": \"car/train/bus/none/unknown\"}. Use 'unknown' if uncertain."
scene_prompt = get_prompt("trace_scene", "Classify the scene. Answer in JSON: {\"location\": \"indoor/outdoor/unknown\", \"weather\": \"sunny/cloudy/rainy/night/unknown\", \"setting\": \"office/street/home/nature/studio/unknown\", \"transportation\": \"car/train/bus/none/unknown\"}. Use 'unknown' if uncertain.")
scene_raw = call_vlm(image_to_analyze, scene_prompt, model)
# Parse scene JSON (handle markdown code blocks)
@@ -228,11 +241,11 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool =
scene_data = {}
# Prompt 8: Background description
bg_prompt = "Describe the background and environment. For EACH visible object, state its COLOR and type. Include: wall color, monitor colors, furniture colors, equipment colors. If color unclear, say 'unclear'."
bg_prompt = get_prompt("trace_background", "Describe the background and environment. For EACH visible object, state its COLOR and type. Include: wall color, monitor colors, furniture colors, equipment colors. If color unclear, say 'unclear'.")
background = call_vlm(image_to_analyze, bg_prompt, model)
# Prompt 9: Plants detection
plants_prompt = "What plants, trees, or flowers are clearly visible? Answer in JSON: {\"has_plants\": true/false, \"plants\": [\"list recognizable plants by name. If not recognizable, describe briefly what you see. Use empty list if none or uncertain.\"]}"
plants_prompt = get_prompt("trace_plants", "What plants, trees, or flowers are clearly visible? Answer in JSON: {\"has_plants\": true/false, \"plants\": [\"list recognizable plants by name. If not recognizable, describe briefly what you see. Use empty list if none or uncertain.\"]}")
plants_raw = call_vlm(image_to_analyze, plants_prompt, model)
# Parse plants JSON
@@ -244,7 +257,7 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool =
plants_data = {"has_plants": False, "plants": []}
# Prompt 10: Animals detection
animals_prompt = "What animals are clearly visible? Answer in JSON: {\"has_animals\": true/false, \"animals\": [\"list recognizable animals by name. If not recognizable, describe briefly what you see. Use empty list if none or uncertain.\"]}"
animals_prompt = get_prompt("trace_animals", "What animals are clearly visible? Answer in JSON: {\"has_animals\": true/false, \"animals\": [\"list recognizable animals by name. If not recognizable, describe briefly what you see. Use empty list if none or uncertain.\"]}")
animals_raw = call_vlm(image_to_analyze, animals_prompt, model)
# Parse animals JSON
@@ -256,7 +269,7 @@ def analyze_trace(trace_dir: str, model: str = "llava:7b", store_qdrant: bool =
animals_data = {"has_animals": False, "animals": []}
# Prompt 11: Background tags
bg_tags_prompt = "List 5 tags for the background/scene, comma-separated. Examples: office, street, sunny, building, car, trees."
bg_tags_prompt = get_prompt("trace_bg_tags", "List 5 tags for the background/scene, comma-separated. Examples: office, street, sunny, building, car, trees.")
bg_tags_raw = call_vlm(image_to_analyze, bg_tags_prompt, model)
bg_tags = [t.strip() for t in bg_tags_raw.replace(",", " ").split() if t.strip()][:5]
-272
View File
@@ -1,272 +0,0 @@
#!/opt/homebrew/bin/python3.11
"""
YOLO Processor Benchmark Runner
測試 YOLO CPU vs MPS 性能對比
測試版本:
A. yolo_processor.py (CPU)
B. yolo_processor_mps.py (MPS Metal GPU)
C. yolo_processor_contract_v1.py (Contract)
測試指標:
- 處理時間
- 內存峰值 (MB)
- 檢測物件數
- 檢測類別數
- 輸出大小 (KB)
"""
import os
import sys
import json
import time
import subprocess
from pathlib import Path
from datetime import datetime
SCRIPTS_DIR = Path(__file__).parent
OUTPUT_DIR = SCRIPTS_DIR.parent / "output" / "benchmark" / "yolo_processor"
def get_video_info(video_path):
"""獲取視頻基本信息"""
cmd = [
"ffprobe",
"-v", "quiet",
"-print_format", "json",
"-show_format",
"-show_streams",
video_path
]
try:
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
data = json.loads(result.stdout)
video_stream = next((s for s in data["streams"] if s["codec_type"] == "video"), None)
return {
"duration": float(data["format"].get("duration", 0)),
"size_mb": int(data["format"].get("size", 0)) / 1024 / 1024,
"width": video_stream.get("width", 0) if video_stream else 0,
"height": video_stream.get("height", 0) if video_stream else 0,
"fps": video_stream.get("r_frame_rate", "0/1") if video_stream else "0/1",
"total_frames": int(video_stream.get("nb_frames", 0)) if video_stream else 0
}
except Exception as e:
print(f"獲取視頻信息失敗: {e}")
return {}
def get_memory_peak(pid):
"""獲取進程內存峰值"""
try:
cmd = ["ps", "-p", str(pid), "-o", "rss="]
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode == 0:
return int(result.stdout.strip()) / 1024
except:
pass
return 0
def run_processor(script_name, video_path, output_path, uuid="", sample_interval=30):
"""運行指定 YOLO processor"""
script_path = SCRIPTS_DIR / script_name
if not script_path.exists():
print(f"❌ 腳本不存在: {script_path}")
return None
# 不同处理器使用不同参数格式
if script_name == "yolo_processor_mps.py":
cmd = [sys.executable, str(script_path), "--video", video_path, "--output", output_path]
if uuid:
cmd.extend(["--uuid", uuid])
cmd.extend(["--device", "mps"]) # 强制使用 MPS
elif script_name == "yolo_processor_contract_v1.py":
cmd = [sys.executable, str(script_path), video_path, output_path, "--uuid", uuid if uuid else "bench"]
else:
cmd = [sys.executable, str(script_path), video_path, output_path]
if uuid:
cmd.extend(["--uuid", uuid])
print(f"\n執行: {script_name}")
print(f"命令: {' '.join(cmd)}")
start_time = time.time()
process = subprocess.Popen(
cmd,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True
)
peak_memory = 0
while process.poll() is None:
mem = get_memory_peak(process.pid)
if mem > peak_memory:
peak_memory = mem
time.sleep(0.5)
stdout, stderr = process.communicate()
elapsed_time = time.time() - start_time
if process.returncode != 0:
print(f"❌ 处理失败: {stderr}")
return None
if os.path.exists(output_path):
with open(output_path) as f:
result = json.load(f)
# 分析输出
frames_data = result.get("frames", [])
if isinstance(frames_data, dict):
frames_data = list(frames_data.values())
total_objects = 0
classes_detected = set()
for frame in frames_data:
if isinstance(frame, dict):
detections = frame.get("detections", [])
for det in detections:
total_objects += 1
class_name = det.get("class_name", det.get("class", "unknown"))
classes_detected.add(class_name)
file_size_kb = os.path.getsize(output_path) / 1024
return {
"elapsed_time": elapsed_time,
"peak_memory_mb": peak_memory,
"total_frames": len(frames_data),
"total_objects": total_objects,
"classes_detected": list(classes_detected),
"class_count": len(classes_detected),
"file_size_kb": file_size_kb,
"stdout": stdout,
"stderr": stderr
}
return None
def main():
print("=" * 80)
print("YOLO Processor Benchmark 測試")
print("=" * 80)
OUTPUT_DIR.mkdir(parents=True, exist_ok=True)
video_uuid = "ac625815183a21e1"
video_path = "/Users/accusys/momentry/var/sftpgo/data/demo/Gamma Carry Saves the World..mp4"
if not os.path.exists(video_path):
print(f"❌ 測試視頻不存在: {video_path}")
sys.exit(1)
video_info = get_video_info(video_path)
print("\n測試視頻:")
print(f" UUID: {video_uuid}")
print(f" 文件: {video_info.get('size_mb', 0):.1f} MB")
print(f" 時長: {video_info.get('duration', 0):.1f} 秒")
print(f" 分辨率: {video_info.get('width', 0)}x{video_info.get('height', 0)}")
print(f" FPS: {video_info.get('fps', 'unknown')}")
print(f" 总帧数: {video_info.get('total_frames', 0)}")
processors = [
("A", "yolo_processor.py", "YOLOv8n CPU"),
("B", "yolo_processor_mps.py", "YOLOv8n MPS (Metal)"),
("C", "yolo_processor_contract_v1.py", "Contract v1"),
]
results = []
for scheme_id, script_name, description in processors:
print(f"\n{'=' * 80}")
print(f"方案 {scheme_id}: {description}")
print(f"{'=' * 80}")
output_path = OUTPUT_DIR / f"scheme_{scheme_id}_{script_name.replace('.py', '.json')}"
if os.path.exists(output_path):
os.remove(output_path)
result = run_processor(
script_name,
video_path,
str(output_path),
uuid=f"yolo_bench_{scheme_id}",
sample_interval=30
)
if result:
duration = video_info.get("duration", 0)
speed = duration / result["elapsed_time"] if result["elapsed_time"] > 0 else 0
results.append({
"scheme": scheme_id,
"script": script_name,
"description": description,
"elapsed_time": result["elapsed_time"],
"peak_memory_mb": result["peak_memory_mb"],
"total_frames": result["total_frames"],
"total_objects": result["total_objects"],
"class_count": result["class_count"],
"classes_detected": result["classes_detected"],
"file_size_kb": result["file_size_kb"],
"speed_ratio": speed
})
print("\n✅ 处理完成:")
print(f" 时间: {result['elapsed_time']:.2f}秒")
print(f" 速度: {speed:.2f}x 实时倍速")
print(f" 内存峰值: {result['peak_memory_mb']:.1f} MB")
print(f" 处理帧数: {result['total_frames']}")
print(f" 检测物件: {result['total_objects']}")
print(f" 检测类别: {result['class_count']}")
print(f" 输出大小: {result['file_size_kb']:.1f} KB")
if result['classes_detected']:
print(f" 类别列表: {', '.join(result['classes_detected'][:10])}")
else:
print(f"❌ 方案 {scheme_id} 处理失败")
results.append({
"scheme": scheme_id,
"script": script_name,
"description": description,
"error": "processing failed"
})
report = {
"test_date": datetime.now().isoformat(),
"video_info": video_info,
"video_uuid": video_uuid,
"results": results
}
report_path = OUTPUT_DIR / "YOLO_BENCHMARK_REPORT.json"
with open(report_path, "w") as f:
json.dump(report, f, indent=2, ensure_ascii=False)
print(f"\n{'=' * 80}")
print("测试报告已保存:")
print(f" {report_path}")
print(f"{'=' * 80}")
print("\n【对比总结】")
print("\n| 方案 | 脚本 | 时间(秒) | 速度 | 内存(MB) | 物件数 | 类别数 |")
print("|------|------|---------|------|---------|--------|--------|")
for r in results:
if "error" not in r:
print(f"| {r['scheme']} | {r['script']} | {r['elapsed_time']:.2f} | {r['speed_ratio']:.2f}x | {r['peak_memory_mb']:.1f} | {r['total_objects']} | {r['class_count']} |")
else:
print(f"| {r['scheme']} | {r['script']} | - | - | - | - | ❌ |")
if __name__ == "__main__":
main()
-210
View File
@@ -1,210 +0,0 @@
#!/opt/homebrew/bin/python3.11
"""
YOLO Detection Count Comparison
对比 YOLO processor 的检测物体数量和类别
"""
import json
from pathlib import Path
from collections import defaultdict
def load_yolo_results(filepath):
"""加载 YOLO 检测结果"""
if not filepath.exists():
print(f"❌ 文件不存在: {filepath}")
return None
with open(filepath) as f:
data = json.load(f)
results = {
'total_frames': 0,
'total_objects': 0,
'classes': defaultdict(int),
'confidence_avg': 0.0,
'frames_with_objects': 0,
'frames_empty': 0,
}
frames_data = data.get('frames', [])
if isinstance(frames_data, dict):
frames_list = list(frames_data.values())
elif isinstance(frames_data, list):
frames_list = frames_data
else:
return results
results['total_frames'] = len(frames_list)
total_confidence = 0.0
total_objects = 0
for frame in frames_list:
if isinstance(frame, dict):
detections = frame.get('detections', frame.get('objects', []))
if detections and len(detections) > 0:
results['frames_with_objects'] += 1
for det in detections:
if isinstance(det, dict):
total_objects += 1
class_name = det.get('class_name', det.get('name', det.get('class', 'unknown')))
results['classes'][class_name] += 1
confidence = det.get('confidence', det.get('score', 1.0))
if isinstance(confidence, (int, float)):
total_confidence += confidence
else:
results['frames_empty'] += 1
results['total_objects'] = total_objects
if total_objects > 0:
results['confidence_avg'] = total_confidence / total_objects
return results
def compare_classes(results_a, results_b, results_c):
"""对比检测类别"""
all_classes = set()
if results_a:
all_classes.update(results_a['classes'].keys())
if results_b:
all_classes.update(results_b['classes'].keys())
if results_c:
all_classes.update(results_c['classes'].keys())
comparison = []
for class_name in sorted(all_classes):
count_a = results_a['classes'].get(class_name, 0) if results_a else 0
count_b = results_b['classes'].get(class_name, 0) if results_b else 0
count_c = results_c['classes'].get(class_name, 0) if results_c else 0
if count_a != count_b or count_a != count_c or count_b != count_c:
comparison.append({
'class_name': class_name,
'cpu': count_a,
'mps': count_b,
'contract': count_c,
'max': max(count_a, count_b, count_c),
'min': min(count_a, count_b, count_c),
})
return comparison
def main():
benchmark_dir = Path('/Users/accusys/momentry_core_0.1/output/benchmark/yolo_processor')
print("=" * 80)
print("YOLO Detection Count Comparison")
print("=" * 80)
print()
# 加载三个版本的结果
results_a = load_yolo_results(benchmark_dir / 'scheme_A_yolo_processor.json')
results_b = load_yolo_results(benchmark_dir / 'scheme_B_yolo_processor_mps.json')
results_c = load_yolo_results(benchmark_dir / 'scheme_C_yolo_processor_contract_v1.json')
if not results_a and not results_b and not results_c:
print("❌ 没有可用的检测结果文件")
return
# 统计概览
print("【检测统计】")
print()
print("| 版本 | 总帧数 | 检测物体数 | 有物体帧 | 空帧 | 平均置信度 |")
print("|------|--------|-----------|---------|------|------------|")
for name, results in [('CPU', results_a), ('MPS', results_b), ('Contract', results_c)]:
if results:
print(f"| {name} | {results['total_frames']} | {results['total_objects']} | {results['frames_with_objects']} | {results['frames_empty']} | {results['confidence_avg']:.2f} |")
else:
print(f"| {name} | - | - | - | - | - |")
print()
# 类别统计
print("【检测类别统计】")
print()
if results_a and results_a['classes']:
print("CPU版本检测类别:")
print("| 类别 | 数量 |")
print("|------|------|")
for class_name, count in sorted(results_a['classes'].items(), key=lambda x: -x[1]):
print(f"| {class_name} | {count} |")
print(f"| **总计** | {sum(results_a['classes'].values())} |")
print()
# 类别对比
print("【类别数量对比】")
print()
comparison = compare_classes(results_a, results_b, results_c)
if comparison:
print(f"共有 {len(comparison)} 个类别检测数量不同")
print()
print("| 类别 | CPU | MPS | Contract | 最大差异 |")
print("|------|-----|-----|----------|---------|")
for item in comparison[:20]:
diff = item['max'] - item['min']
print(f"| {item['class_name']} | {item['cpu']} | {item['mps']} | {item['contract']} | {diff} |")
if len(comparison) > 20:
print("| ... | ... | ... | ... | ... |")
else:
print("所有类别检测数量一致")
print()
# 检测率分析
print("【检测率分析】")
print()
if results_a and results_a['total_objects'] > 0:
baseline = results_a['total_objects']
print(f"以CPU版本为基准({baseline}个物体):")
print()
print("| 版本 | 检测数 | 检测率 | 漏检数 |")
print("|------|--------|--------|--------|")
for name, results in [('CPU', results_a), ('MPS', results_b), ('Contract', results_c)]:
if results:
rate = results['total_objects'] / baseline * 100
missed = baseline - results['total_objects']
print(f"| {name} | {results['total_objects']} | {rate:.1f}% | {missed} |")
else:
print(f"| {name} | - | - | - |")
print()
print("=" * 80)
print("对比完成")
print("=" * 80)
# 保存结果
output = {
'cpu': results_a,
'mps': results_b,
'contract': results_c,
'comparison': comparison,
}
output_path = benchmark_dir / 'YOLO_COUNT_COMPARISON.json'
with open(output_path, 'w') as f:
json.dump(output, f, indent=2, ensure_ascii=False)
print(f"\n对比结果已保存: {output_path}")
if __name__ == '__main__':
main()
-497
View File
@@ -1,497 +0,0 @@
#!/opt/homebrew/bin/python3.11
"""
YOLO Processor - Object Detection with Resume Support
Uses YOLOv8 via ultralytics (local model)
Resume Feature (integrated from video_yolo_player):
- Auto-detect existing results and resume from last frame
- Auto-save at configurable intervals (default: 30 seconds)
- Ctrl+C gracefully saves and exits
"""
import sys
import json
import argparse
import os
import signal
import time
from datetime import datetime
from typing import Dict, Optional, Set
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
YOLO_NAMES = [
"person",
"bicycle",
"car",
"motorbike",
"aeroplane",
"bus",
"train",
"truck",
"boat",
"traffic light",
"fire hydrant",
"stop sign",
"parking meter",
"bench",
"bird",
"cat",
"dog",
"horse",
"sheep",
"cow",
"elephant",
"bear",
"zebra",
"giraffe",
"backpack",
"umbrella",
"handbag",
"tie",
"suitcase",
"frisbee",
"skis",
"snowboard",
"sports ball",
"kite",
"baseball bat",
"baseball glove",
"skateboard",
"surfboard",
"tennis racket",
"bottle",
"wine glass",
"cup",
"fork",
"knife",
"spoon",
"bowl",
"banana",
"apple",
"sandwich",
"orange",
"broccoli",
"carrot",
"hot dog",
"pizza",
"donut",
"cake",
"chair",
"sofa",
"pottedplant",
"bed",
"diningtable",
"toilet",
"tvmonitor",
"laptop",
"mouse",
"remote",
"keyboard",
"cell phone",
"microwave",
"oven",
"toaster",
"sink",
"refrigerator",
"book",
"clock",
"vase",
"scissors",
"teddy bear",
"hair drier",
"toothbrush",
]
# Global state for signal handling
g_detection_data: Optional[Dict] = None
g_output_file: Optional[str] = None
g_auto_save_interval: int = 30
g_auto_save_frames: int = 300 # Save every N frames (in addition to time-based)
def format_time(seconds: float) -> str:
"""Format seconds to HH:MM:SS"""
hours = int(seconds // 3600)
minutes = int((seconds % 3600) // 60)
secs = int(seconds % 60)
return f"{hours:02d}:{minutes:02d}:{secs:02d}"
def load_existing_data(output_file: str) -> tuple[Optional[Dict], int]:
"""Load existing detection data from file. Returns (data, last_processed_frame)"""
if not os.path.exists(output_file):
return None, 0
try:
with open(output_file, "r", encoding="utf-8") as f:
data = json.load(f)
frames = data.get("frames", {})
if frames:
last_frame = max(int(k) for k in frames.keys())
return data, last_frame
except (json.JSONDecodeError, KeyError, ValueError) as e:
print(f"Warning: Could not load existing file: {e}")
return None, 0
def save_detection_data(
output_file: str,
detection_data: Dict,
is_interrupted: bool = False,
silent: bool = False,
last_saved_frame: int = 0,
) -> tuple[bool, int]:
"""Save detection data to JSON file"""
try:
metadata = detection_data.get("metadata", {})
metadata["last_saved_at"] = datetime.now().isoformat()
metadata["status"] = "interrupted" if is_interrupted else "in_progress"
metadata["last_saved_frame"] = last_saved_frame
detection_data["metadata"] = metadata
with open(output_file, "w", encoding="utf-8") as f:
json.dump(detection_data, f, indent=2, ensure_ascii=False)
if not silent:
return True, os.path.getsize(output_file)
return True, 0
except Exception as e:
print(f"Error saving data: {e}")
return False, 0
def signal_handler(signum, frame):
"""Handle Ctrl+C to pause and save progress"""
global g_detection_data, g_output_file
print(f"\n\n{'=' * 60}")
print("PAUSE - Saving progress...")
print(f"{'=' * 60}")
if g_detection_data and g_output_file:
success, _ = save_detection_data(
g_output_file, g_detection_data, is_interrupted=True
)
if success:
print(f"Progress saved to: {g_output_file}")
print("Run the same command again to resume")
print(f"{'=' * 60}\n")
sys.exit(0)
def get_detections_list(result, model) -> list:
"""Extract detection info as list of dicts"""
detections = []
if result.boxes is None:
return detections
boxes = result.boxes.xyxy.cpu().numpy()
confidences = result.boxes.conf.cpu().numpy()
class_ids = result.boxes.cls.cpu().numpy().astype(int)
for box, conf, class_id in zip(boxes, confidences, class_ids):
x1, y1, x2, y2 = box
class_name = YOLO_NAMES[class_id] if class_id < len(YOLO_NAMES) else "unknown"
detections.append(
{
"class_id": int(class_id),
"class_name": class_name,
"confidence": float(conf),
"x1": float(x1),
"y1": float(y1),
"x2": float(x2),
"y2": float(y2),
"width": int(x2 - x1),
"height": int(y2 - y1),
}
)
return detections
def process_yolo(
video_path: str,
output_path: str,
uuid: str = "",
auto_save_interval: int = 30,
force_restart: bool = False,
auto_save_frames: int = 300,
):
"""Process video for object detection using YOLOv8 with resume support"""
global g_detection_data, g_output_file, g_auto_save_interval, g_auto_save_frames
g_auto_save_interval = auto_save_interval
g_auto_save_frames = auto_save_frames
publisher = RedisPublisher(uuid) if uuid else None
if publisher:
publisher.info("yolo", "YOLO_START")
# Set up signal handler for graceful pause
signal.signal(signal.SIGINT, signal_handler)
# Check for existing results (resume support)
existing_data, last_processed_frame = load_existing_data(output_path)
resume_mode = (
existing_data is not None and last_processed_frame > 0 and not force_restart
)
if resume_mode:
print(f"\nFound existing data: {output_path}")
print(f"Last processed frame: {last_processed_frame}")
print(f"Will resume from frame {last_processed_frame + 1}")
try:
from ultralytics import YOLO
except ImportError:
if publisher:
publisher.error("yolo", "ultralytics not installed")
result = {
"metadata": {"status": "error", "error": "ultralytics not installed"},
"frames": {},
}
with open(output_path, "w") as f:
json.dump(result, f, indent=2)
if publisher:
publisher.complete("yolo", "0 frames")
return result
if publisher:
publisher.info("yolo", "YOLO_LOADING_MODEL")
# Load YOLO model (prefer CoreML for ANE acceleration, fallback to PyTorch)
model_path_mlpackage = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "yolov8s.mlpackage"
)
model_path_pt = os.path.join(
os.path.dirname(os.path.abspath(__file__)), "..", "yolov8s.pt"
)
if os.path.exists(model_path_mlpackage):
model = YOLO(model_path_mlpackage)
print("YOLO: CoreML model loaded (YOLOv8s, ANE accelerated)")
elif os.path.exists(model_path_pt):
model = YOLO(model_path_pt)
print("YOLO: PyTorch model loaded (YOLOv8s)")
else:
model = YOLO("yolov8s.pt") # will auto-download
# Get video info
import cv2
cap = cv2.VideoCapture(video_path)
if not cap.isOpened():
print(f"Error: Cannot open video: {video_path}")
return {"metadata": {"status": "error"}, "frames": {}}
fps = cap.get(cv2.CAP_PROP_FPS)
width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
total_duration = total_frames / fps if fps > 0 else 0
cap.release()
if publisher:
publisher.info("yolo", f"fps={fps}, total={total_frames}")
publisher.progress("yolo", 0, total_frames, "Starting")
# Initialize or load detection data
if resume_mode and existing_data:
detection_data = existing_data
frame_count = last_processed_frame
processed_frames: Set[int] = set(
int(k) for k in existing_data.get("frames", {}).keys()
)
# Seek to resume position
cap = cv2.VideoCapture(video_path)
cap.set(cv2.CAP_PROP_POS_FRAMES, frame_count)
else:
# Initialize new detection data
detection_data = {
"metadata": {
"video_path": os.path.abspath(video_path),
"fps": fps,
"width": width,
"height": height,
"total_frames": total_frames,
"total_duration": total_duration,
"processed_at": datetime.now().isoformat(),
"auto_save_interval": auto_save_interval,
"auto_save_frames": auto_save_frames,
"status": "in_progress",
"last_saved_at": datetime.now().isoformat(),
"last_saved_frame": 0,
},
"frames": {},
}
frame_count = 0
processed_frames = set()
cap = cv2.VideoCapture(video_path)
# Set global for signal handler
g_detection_data = detection_data
g_output_file = output_path
start_time = time.time()
last_save_time = start_time
last_save_frame_count = frame_count # Track which frame we last saved at
auto_save_count = 0
print(f"\nProcessing video: {total_frames} frames @ {fps:.2f} fps")
print(
f"Auto-save every {auto_save_interval}s or {auto_save_frames} frames (whichever comes first)"
)
print(f"Resume from frame {frame_count + 1 if resume_mode else 1}")
print()
# Process frames
while True:
ret, frame = cap.read()
if not ret:
break
frame_count += 1
current_time = (frame_count - 1) / fps if fps > 0 else 0
# Skip already processed frames in resume mode
if frame_count in processed_frames:
continue
# Run YOLO detection
results = model(frame, verbose=False)
detections = get_detections_list(results[0], model)
# Store detection data
detection_data["frames"][str(frame_count)] = {
"frame_number": frame_count,
"time_seconds": round(current_time, 3),
"time_formatted": format_time(current_time),
"detections": detections,
}
processed_frames.add(frame_count)
# Progress indicator every 500 frames
if frame_count % 500 == 0:
elapsed = time.time() - start_time
progress = (frame_count / total_frames) * 100
eta = (
(elapsed / frame_count) * (total_frames - frame_count)
if frame_count > 0
else 0
)
print(
f" Progress: {frame_count}/{total_frames} ({progress:.1f}%) - "
f"ETA: {eta:.0f}s - {len(detections)} objects"
)
if publisher:
publisher.progress(
"yolo", frame_count, total_frames, f"frame {frame_count}"
)
# Auto-save check (time-based OR frame-based)
current_time_val = time.time()
time_elapsed = current_time_val - last_save_time >= auto_save_interval
frames_since_save = frame_count - last_save_frame_count >= auto_save_frames
if time_elapsed or frames_since_save:
success, file_size = save_detection_data(
output_path,
detection_data,
is_interrupted=False,
silent=True,
last_saved_frame=frame_count,
)
if success:
auto_save_count += 1
reason = "time" if time_elapsed else "frames"
print(
f" Auto-saved (#{auto_save_count}, {reason}): frame {last_save_frame_count}-{frame_count}"
)
last_save_time = current_time_val
last_save_frame_count = frame_count
cap.release()
processing_time = time.time() - start_time
# Update final metadata
total_detections = sum(
len(f.get("detections", [])) for f in detection_data.get("frames", {}).values()
)
detection_data["metadata"]["status"] = "completed"
detection_data["metadata"]["completed_at"] = datetime.now().isoformat()
detection_data["metadata"]["processing_time"] = processing_time
detection_data["metadata"]["total_detections"] = total_detections
detection_data["metadata"]["auto_save_count"] = auto_save_count
# Save final data
save_detection_data(output_path, detection_data, is_interrupted=False)
# Print summary
print(f"\n{'=' * 60}")
print("YOLO Detection complete!")
print(f" Total frames processed: {frame_count}")
print(f" Frames with detections: {len(detection_data['frames'])}")
print(f" Total objects detected: {total_detections}")
print(f" Processing time: {processing_time:.1f}s")
print(f" Auto-saves: {auto_save_count}")
print(f" Output: {output_path}")
print(f"{'=' * 60}")
if publisher:
publisher.complete(
"yolo", f"{len(detection_data['frames'])} frames with objects"
)
return detection_data
if __name__ == "__main__":
parser = argparse.ArgumentParser(
description="YOLO Object Detection with Resume Support"
)
parser.add_argument("video_path", help="Path to video file")
parser.add_argument("output_path", help="Output JSON path")
parser.add_argument("--uuid", "-u", help="UUID for Redis progress", default="")
parser.add_argument(
"--auto-save",
type=int,
default=30,
help="Auto-save interval in seconds (default: 30)",
)
parser.add_argument(
"--auto-save-frames",
type=int,
default=300,
help="Auto-save after N frames (default: 300)",
)
parser.add_argument(
"--force",
action="store_true",
help="Force restart from beginning (ignore existing data)",
)
parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS)
args = parser.parse_args()
process_yolo(
args.video_path,
args.output_path,
args.uuid,
args.auto_save,
args.force,
args.auto_save_frames,
)
-685
View File
@@ -1,685 +0,0 @@
#!/opt/homebrew/bin/python3.11
"""
YOLO Processor - AI-Driven Processor Contract Version 1.0
Compliant with AI-Driven Processor Contract v1.0
Effective Date: 2026-03-27
Features:
1. Standardized command-line interface
2. Redis progress reporting
3. Signal handling (SIGTERM, SIGINT)
4. Health check mode
5. Resource monitoring
6. Contract-compliant JSON output
7. Unified configuration
8. Resume support with auto-save
"""
import sys
import json
import os
import argparse
import signal
import time
import subprocess
import traceback
from datetime import datetime
from typing import Dict, Any, Optional, Tuple
import atexit
# Redis Publisher for progress reporting
try:
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
REDIS_AVAILABLE = True
except ImportError:
REDIS_AVAILABLE = False
print(
"WARNING: RedisPublisher not available, progress reporting disabled",
file=sys.stderr,
)
# Contract version
CONTRACT_VERSION = "1.0"
PROCESSOR_NAME = (
"/Users/accusys/momentry_core_0.1/scripts/yolo_processor_contract_v1.py"
)
PROCESSOR_VERSION = "1.0.0"
MODEL_NAME = "yolov8n.pt"
MODEL_VERSION = "8.0"
# YOLO class names (COCO dataset 80 classes)
YOLO_NAMES = [
"person",
"bicycle",
"car",
"motorbike",
"aeroplane",
"bus",
"train",
"truck",
"boat",
"traffic light",
"fire hydrant",
"stop sign",
"parking meter",
"bench",
"bird",
"cat",
"dog",
"horse",
"sheep",
"cow",
"elephant",
"bear",
"zebra",
"giraffe",
"backpack",
"umbrella",
"handbag",
"tie",
"suitcase",
"frisbee",
"skis",
"snowboard",
"sports ball",
"kite",
"baseball bat",
"baseball glove",
"skateboard",
"surfboard",
"tennis racket",
"bottle",
"wine glass",
"cup",
"fork",
"knife",
"spoon",
"bowl",
"banana",
"apple",
"sandwich",
"orange",
"broccoli",
"carrot",
"hot dog",
"pizza",
"donut",
"cake",
"chair",
"sofa",
"pottedplant",
"bed",
"diningtable",
"toilet",
"tvmonitor",
"laptop",
"mouse",
"remote",
"keyboard",
"cell phone",
"microwave",
"oven",
"toaster",
"sink",
"refrigerator",
"book",
"clock",
"vase",
"scissors",
"teddy bear",
"hair drier",
"toothbrush",
]
class YOLOProcessor:
"""YOLO Object Detection Processor with Resume Support"""
def __init__(
self,
video_path: str,
output_path: str,
uuid: Optional[str] = None,
check_health: bool = False,
):
self.video_path = video_path
self.output_path = output_path
self.uuid = uuid
self.check_health = check_health
# Configuration from environment variables with defaults
self.timeout = int(os.environ.get("MOMENTRY_YOLO_TIMEOUT", "7200"))
self.model_size = os.environ.get("MOMENTRY_YOLO_MODEL_SIZE", "yolov8n.pt")
self.confidence = float(os.environ.get("MOMENTRY_YOLO_CONFIDENCE", "0.25"))
self.iou = float(os.environ.get("MOMENTRY_YOLO_IOU", "0.45"))
self.gpu_enabled = (
os.environ.get("MOMENTRY_YOLO_GPU", "false").lower() == "true"
)
self.auto_save_interval = int(
os.environ.get("MOMENTRY_YOLO_AUTO_SAVE_INTERVAL", "30")
)
self.auto_save_frames = int(
os.environ.get("MOMENTRY_YOLO_AUTO_SAVE_FRAMES", "300")
)
# Parse classes to detect (empty list = all classes)
classes_str = os.environ.get("MOMENTRY_YOLO_CLASSES", "")
self.classes_to_detect = (
[c.strip() for c in classes_str.split(",") if c.strip()]
if classes_str
else []
)
# Initialize Redis publisher if available
self.publisher = None
if REDIS_AVAILABLE and uuid:
self.publisher = RedisPublisher(uuid)
# State tracking
self.start_time = None
self.is_interrupted = False
self.last_save_time = time.time()
self.last_save_frame = 0
self.detection_data = None
self.last_processed_frame = 0
# Set up signal handlers
signal.signal(signal.SIGTERM, self._signal_handler)
signal.signal(signal.SIGINT, self._signal_handler)
# Register cleanup
atexit.register(self._cleanup)
def _signal_handler(self, signum, frame):
"""Handle termination signals gracefully"""
self.is_interrupted = True
self.publish(
"warning", f"Received signal {signum}, saving progress and exiting..."
)
# Save current progress
if self.detection_data:
self._save_detection_data(is_interrupted=True)
sys.exit(130 if signum == signal.SIGINT else 143)
def _cleanup(self):
"""Cleanup resources on exit"""
if self.detection_data and not self.is_interrupted:
self._save_detection_data(is_interrupted=False)
def publish(self, level: str, message: str):
"""Publish message to Redis if available"""
if self.publisher:
if level == "info":
self.publisher.info(PROCESSOR_NAME, message)
elif level == "warning":
self.publisher.warning(PROCESSOR_NAME, message)
elif level == "error":
self.publisher.error(PROCESSOR_NAME, message)
elif level == "complete":
self.publisher.complete(PROCESSOR_NAME, message)
else:
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
print(
f"[{timestamp}] [{PROCESSOR_NAME}] [{level.upper()}] {message}",
file=sys.stderr,
)
def validate_input(self) -> Tuple[bool, str]:
"""Validate input video file"""
if not os.path.exists(self.video_path):
return False, f"Video file not found: {self.video_path}"
if not self.video_path.lower().endswith(
(".mp4", ".avi", ".mov", ".mkv", ".webm")
):
return False, f"Unsupported video format: {self.video_path}"
# Check if output directory is writable
output_dir = os.path.dirname(self.output_path)
if output_dir and not os.path.exists(output_dir):
try:
os.makedirs(output_dir, exist_ok=True)
except Exception as e:
return False, f"Cannot create output directory: {e}"
return True, "Input validation passed"
def _load_existing_data(self) -> Tuple[Optional[Dict], int]:
"""Load existing detection data from file"""
if not os.path.exists(self.output_path):
return None, 0
try:
with open(self.output_path, "r", encoding="utf-8") as f:
data = json.load(f)
frames = data.get("frames", {})
if frames:
last_frame = max(int(k) for k in frames.keys())
return data, last_frame
except (json.JSONDecodeError, KeyError, ValueError) as e:
self.publish("warning", f"Could not load existing file: {e}")
return None, 0
def _save_detection_data(self, is_interrupted: bool = False):
"""Save detection data to file"""
if not self.detection_data:
return
try:
# Update metadata
metadata = self.detection_data.get("metadata", {})
metadata["last_saved_at"] = datetime.now().isoformat()
metadata["last_saved_frame"] = self.last_processed_frame
if is_interrupted:
metadata["status"] = "interrupted"
self.detection_data["metadata"] = metadata
# Save to file
with open(self.output_path, "w", encoding="utf-8") as f:
json.dump(self.detection_data, f, indent=2, default=str)
self.last_save_time = time.time()
self.publish(
"info",
f"Saved progress to {self.output_path} (frame {self.last_processed_frame})",
)
except Exception as e:
self.publish("error", f"Failed to save detection data: {e}")
def _should_auto_save(self, current_frame: int) -> bool:
"""Check if we should auto-save based on time or frame count"""
time_elapsed = time.time() - self.last_save_time
frames_elapsed = current_frame - self.last_save_frame
return (
time_elapsed >= self.auto_save_interval
or frames_elapsed >= self.auto_save_frames
)
def check_dependencies(self) -> Dict[str, Any]:
"""Check if all dependencies are available"""
dependencies = {
"ultralytics": {"status": "unknown", "version": None},
"opencv": {"status": "unknown", "version": None},
"ffprobe": {"status": "unknown", "version": None},
"redis": {
"status": "available" if REDIS_AVAILABLE else "unavailable",
"version": None,
},
"python": {"status": "available", "version": sys.version.split()[0]},
}
# Check ultralytics
try:
import ultralytics
dependencies["ultralytics"]["status"] = "available"
dependencies["ultralytics"]["version"] = getattr(
ultralytics, "__version__", "unknown"
)
except ImportError:
dependencies["ultralytics"]["status"] = "unavailable"
# Check opencv
try:
import cv2
dependencies["opencv"]["status"] = "available"
dependencies["opencv"]["version"] = cv2.__version__
except ImportError:
dependencies["opencv"]["status"] = "unavailable"
# Check ffprobe
try:
result = subprocess.run(
["ffprobe", "-version"],
capture_output=True,
text=True,
timeout=5,
)
if result.returncode == 0:
dependencies["ffprobe"]["status"] = "available"
dependencies["ffprobe"]["version"] = result.stdout.split("\n")[0]
else:
dependencies["ffprobe"]["status"] = "unavailable"
except (subprocess.SubprocessError, FileNotFoundError):
dependencies["ffprobe"]["status"] = "unavailable"
return dependencies
def perform_health_check(self) -> Dict[str, Any]:
"""Perform comprehensive health check"""
dependencies = self.check_dependencies()
# Check if essential dependencies are available
essential_deps = ["ultralytics", "opencv", "ffprobe"]
all_available = all(
dependencies.get(dep, {}).get("status") == "available"
for dep in essential_deps
)
status = "healthy" if all_available else "unhealthy"
return {
"processor_name": PROCESSOR_NAME,
"processor_version": PROCESSOR_VERSION,
"contract_version": CONTRACT_VERSION,
"model_name": MODEL_NAME,
"model_version": MODEL_VERSION,
"status": status,
"dependencies": dependencies,
"timestamp": datetime.now().isoformat(),
}
def get_video_info(self) -> Dict[str, Any]:
"""Get video information using ffprobe"""
try:
cmd = [
"ffprobe",
"-v",
"quiet",
"-print_format",
"json",
"-show_format",
"-show_streams",
self.video_path,
]
result = subprocess.run(cmd, capture_output=True, text=True, timeout=10)
if result.returncode != 0:
raise subprocess.CalledProcessError(result.returncode, cmd)
info = json.loads(result.stdout)
# Extract video stream
video_stream = None
for stream in info.get("streams", []):
if stream.get("codec_type") == "video":
video_stream = stream
break
if not video_stream:
raise ValueError("No video stream found")
return {
"duration": float(info.get("format", {}).get("duration", 0)),
"width": int(video_stream.get("width", 0)),
"height": int(video_stream.get("height", 0)),
"fps": eval(video_stream.get("r_frame_rate", "0/1")),
"codec": video_stream.get("codec_name", "unknown"),
"bitrate": int(info.get("format", {}).get("bit_rate", 0)),
"size": int(info.get("format", {}).get("size", 0)),
}
except Exception as e:
self.publish("warning", f"Could not get video info: {e}")
return {
"duration": 0,
"width": 0,
"height": 0,
"fps": 0,
"codec": "unknown",
"bitrate": 0,
"size": 0,
}
def process(self) -> Dict[str, Any]:
"""Main processing method"""
self.start_time = time.time()
self.publish("info", f"Starting YOLO processing: {self.video_path}")
self.publish(
"info",
f"Configuration: timeout={self.timeout}s, model={self.model_size}, "
f"confidence={self.confidence}, iou={self.iou}, gpu={self.gpu_enabled}",
)
# Validate input
is_valid, validation_msg = self.validate_input()
if not is_valid:
self.publish("error", f"Input validation failed: {validation_msg}")
return {
"processor_name": PROCESSOR_NAME,
"processor_version": PROCESSOR_VERSION,
"contract_version": CONTRACT_VERSION,
"model_name": MODEL_NAME,
"model_version": MODEL_VERSION,
"status": "error",
"error": validation_msg,
"timestamp": datetime.now().isoformat(),
}
# Check for existing results (resume support)
existing_data, self.last_processed_frame = self._load_existing_data()
resume_mode = existing_data is not None and self.last_processed_frame > 0
if resume_mode:
self.detection_data = existing_data
self.publish("info", f"Resuming from frame {self.last_processed_frame + 1}")
else:
# Initialize new detection data
video_info = self.get_video_info()
self.detection_data = {
"metadata": {
"video_path": self.video_path,
"fps": video_info["fps"],
"width": video_info["width"],
"height": video_info["height"],
"total_frames": 0, # Will be updated during processing
"total_duration": video_info["duration"],
"processed_at": datetime.now().isoformat(),
"auto_save_interval": self.auto_save_interval,
"auto_save_frames": self.auto_save_frames,
"status": "processing",
"last_saved_at": datetime.now().isoformat(),
"last_saved_frame": 0,
"completed_at": None,
"model": self.model_size,
"confidence_threshold": self.confidence,
"iou_threshold": self.iou,
"classes_to_detect": self.classes_to_detect,
},
"frames": {},
}
try:
# Import ultralytics
from ultralytics import YOLO
# Load model
self.publish("info", f"Loading YOLO model: {self.model_size}")
model = YOLO(self.model_size)
# Set device
device = "0" if self.gpu_enabled else "cpu"
self.publish("info", f"Using device: {device}")
# Process video
self.publish("info", "Starting video processing...")
# Use ultralytics to process video
results = model.track(
source=self.video_path,
conf=self.confidence,
iou=self.iou,
device=device,
classes=self.classes_to_detect if self.classes_to_detect else None,
verbose=False,
stream=True, # Stream results to save memory
)
frame_count = 0
for frame_idx, result in enumerate(results):
if self.is_interrupted:
break
# Skip frames if resuming
if resume_mode and frame_idx <= self.last_processed_frame:
continue
frame_count += 1
self.last_processed_frame = frame_idx
# Extract detections
frame_detections = []
if result.boxes is not None:
boxes = result.boxes
for box_idx in range(len(boxes)):
class_id = int(boxes.cls[box_idx])
confidence = float(boxes.conf[box_idx])
bbox = boxes.xyxy[box_idx].cpu().numpy()
# Convert to YOLO format
frame_detections.append(
{
"class_name": YOLO_NAMES[class_id]
if class_id < len(YOLO_NAMES)
else f"class_{class_id}",
"class_id": class_id,
"x": int(bbox[0]),
"y": int(bbox[1]),
"width": int(bbox[2] - bbox[0]),
"height": int(bbox[3] - bbox[1]),
"confidence": confidence,
}
)
# Store frame results
self.detection_data["frames"][str(frame_idx)] = {
"frame": frame_idx,
"timestamp": frame_idx / video_info["fps"]
if video_info["fps"] > 0
else 0,
"objects": frame_detections,
}
# Auto-save check
if self._should_auto_save(frame_idx):
self._save_detection_data()
self.last_save_frame = frame_idx
# Progress reporting
if frame_count % 100 == 0:
elapsed = time.time() - self.start_time
fps = frame_count / elapsed if elapsed > 0 else 0
self.publish(
"info", f"Processed {frame_count} frames ({fps:.1f} fps)"
)
# Update metadata
self.detection_data["metadata"]["total_frames"] = frame_count
self.detection_data["metadata"]["status"] = (
"completed" if not self.is_interrupted else "interrupted"
)
self.detection_data["metadata"]["completed_at"] = (
datetime.now().isoformat() if not self.is_interrupted else None
)
# Final save
self._save_detection_data()
elapsed = time.time() - self.start_time
self.publish(
"complete",
f"Processing completed: {frame_count} frames in {elapsed:.1f}s",
)
return {
"processor_name": PROCESSOR_NAME,
"processor_version": PROCESSOR_VERSION,
"contract_version": CONTRACT_VERSION,
"model_name": MODEL_NAME,
"model_version": MODEL_VERSION,
"status": "success",
"frames_processed": frame_count,
"total_frames": frame_count,
"elapsed_time": elapsed,
"timestamp": datetime.now().isoformat(),
"output_file": self.output_path,
}
except ImportError:
error_msg = "ultralytics package not installed"
self.publish("error", error_msg)
return {
"processor_name": PROCESSOR_NAME,
"processor_version": PROCESSOR_VERSION,
"contract_version": CONTRACT_VERSION,
"model_name": MODEL_NAME,
"model_version": MODEL_VERSION,
"status": "error",
"error": error_msg,
"timestamp": datetime.now().isoformat(),
}
except Exception as e:
error_msg = f"Processing error: {str(e)}"
self.publish("error", error_msg)
self.publish("error", traceback.format_exc())
return {
"processor_name": PROCESSOR_NAME,
"processor_version": PROCESSOR_VERSION,
"contract_version": CONTRACT_VERSION,
"model_name": MODEL_NAME,
"model_version": MODEL_VERSION,
"status": "error",
"error": error_msg,
"timestamp": datetime.now().isoformat(),
}
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="YOLO Processor - AI-Driven Processor Contract Version 1.0"
)
parser.add_argument("video_path", help="Path to input video file")
parser.add_argument("output_path", help="Path where JSON output should be written")
parser.add_argument("--uuid", "-u", help="UUID for Redis progress reporting")
parser.add_argument(
"--check-health", action="store_true", help="Perform health check and exit"
)
args = parser.parse_args()
# Create processor instance
processor = YOLOProcessor(
video_path=args.video_path,
output_path=args.output_path,
uuid=args.uuid,
check_health=args.check_health,
)
# Health check mode
if args.check_health:
health_result = processor.perform_health_check()
print(json.dumps(health_result, indent=2))
sys.exit(0 if health_result["status"] == "healthy" else 1)
# Process video
try:
result = processor.process()
# Print result summary
if result["status"] == "success":
print(f"Successfully processed {result['frames_processed']} frames")
print(f"Output saved to: {result['output_file']}")
else:
print(f"Error: {result.get('error', 'Unknown error')}")
sys.exit(1)
except KeyboardInterrupt:
print("\nProcessing interrupted by user")
sys.exit(130)
except Exception as e:
print(f"Fatal error: {e}")
traceback.print_exc()
sys.exit(1)
if __name__ == "__main__":
main()
-406
View File
@@ -1,406 +0,0 @@
#!/opt/homebrew/bin/python3.11
"""
YOLO Processor - Apple MPS Optimized Version
Uses YOLOv8 via ultralytics with Apple Silicon MPS acceleration
Features:
- Automatic MPS/CPU fallback
- Metal GPU acceleration for inference
- Batch processing for efficiency
- Memory-optimized for unified memory architecture
"""
import sys
import json
import argparse
import os
import signal
import time
from datetime import datetime
from typing import Dict
import torch
from ultralytics import YOLO
YOLO_NAMES = [
"person",
"bicycle",
"car",
"motorbike",
"aeroplane",
"bus",
"train",
"truck",
"boat",
"traffic light",
"fire hydrant",
"stop sign",
"parking meter",
"bench",
"bird",
"cat",
"dog",
"horse",
"sheep",
"cow",
"elephant",
"bear",
"zebra",
"giraffe",
"backpack",
"umbrella",
"handbag",
"tie",
"suitcase",
"frisbee",
"skis",
"snowboard",
"sports ball",
"kite",
"baseball bat",
"baseball glove",
"skateboard",
"surfboard",
"tennis racket",
"bottle",
"wine glass",
"cup",
"fork",
"knife",
"spoon",
"bowl",
"banana",
"apple",
"sandwich",
"orange",
"broccoli",
"carrot",
"hot dog",
"pizza",
"donut",
"cake",
"chair",
"sofa",
"pottedplant",
"bed",
"diningtable",
"toilet",
"tvmonitor",
"laptop",
"mouse",
"remote",
"keyboard",
"cell phone",
"microwave",
"oven",
"toaster",
"sink",
"refrigerator",
"book",
"clock",
"vase",
"scissors",
"teddy bear",
"hair drier",
"toothbrush",
]
def get_device() -> str:
"""Determine the best available device for inference"""
if torch.backends.mps.is_available():
return "mps"
elif torch.cuda.is_available():
return "cuda"
else:
return "cpu"
def signal_handler(signum, frame):
"""Handle interrupt signals gracefully"""
print(f"\n[YOLO] Received signal {signum}, saving results and exiting...")
sys.exit(0)
def process_video_yolo(
video_path: str,
output_path: str,
model_name: str = "yolov8n",
confidence: float = 0.25,
iou_threshold: float = 0.45,
device: str = "auto",
batch_size: int = 8,
skip_frames: int = 1,
resume: bool = True,
save_interval: int = 30,
) -> Dict:
"""
Process video for YOLO object detection with MPS acceleration
Args:
video_path: Path to input video file
output_path: Path to output JSON file
model_name: YOLO model name (yolov8n, yolov8s, yolov8m, yolov8l, yolov8x)
confidence: Confidence threshold for detections
iou_threshold: IoU threshold for NMS
device: Device to use ('auto', 'mps', 'cuda', 'cpu')
batch_size: Number of frames to process in parallel
skip_frames: Process every N frames (1 = all frames)
resume: Whether to resume from existing results
save_interval: Save results every N seconds
Returns:
Dictionary with detection results and metadata
"""
# Set up signal handlers
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
# Determine device
if device == "auto":
device = get_device()
print(f"[YOLO] Starting YOLO processing with device: {device}")
print(f"[YOLO] Model: {model_name}, Confidence: {confidence}, IoU: {iou_threshold}")
# Load model
print(f"[YOLO] Loading model: {model_name}")
model = YOLO(f"{model_name}.pt")
# Move to device
if device in ["mps", "cuda"]:
model.to(device)
# Load existing data if resuming
existing_data = None
last_processed_frame = 0
if resume and os.path.exists(output_path):
try:
with open(output_path, "r") as f:
existing_data = json.load(f)
frames = existing_data.get("frames", {})
if frames:
last_processed_frame = max(int(k) for k in frames.keys())
print(f"[YOLO] Resuming from frame {last_processed_frame}")
except (json.JSONDecodeError, KeyError):
pass
# Initialize result structure
result = {
"video_path": video_path,
"model": model_name,
"device": device,
"confidence_threshold": confidence,
"iou_threshold": iou_threshold,
"processed_at": datetime.now().isoformat(),
"frames": {},
}
if existing_data:
result["frames"] = existing_data.get("frames", {})
# Process video
print(f"[YOLO] Processing video: {video_path}")
start_time = time.time()
frame_count = 0
detection_count = 0
last_save_time = start_time
try:
# Use stream mode for memory efficiency
results = model(
video_path,
conf=confidence,
iou=iou_threshold,
device=device,
stream=True,
imgsz=640, # Smaller size for faster processing
verbose=False,
)
for idx, r in enumerate(results):
# Skip frames based on skip_frames setting
if idx % skip_frames != 0:
continue
# Get frame detections
boxes = r.boxes
if boxes is not None and len(boxes) > 0:
frame_detections = []
for box in boxes:
xyxy = box.xyxy[0].cpu().numpy()
conf = float(box.conf[0].cpu())
cls = int(box.cls[0].cpu())
detection = {
"x": int(xyxy[0]),
"y": int(xyxy[1]),
"width": int(xyxy[2] - xyxy[0]),
"height": int(xyxy[3] - xyxy[1]),
"confidence": round(conf, 4),
"class": YOLO_NAMES[cls]
if cls < len(YOLO_NAMES)
else f"class_{cls}",
"class_id": cls,
}
frame_detections.append(detection)
detection_count += 1
result["frames"][str(idx)] = {
"timestamp": r.boxes.data[0].cpu().numpy()[4]
if len(r.boxes.data) > 0
else idx / 30.0,
"detections": frame_detections,
}
frame_count += 1
# Progress reporting
if frame_count % 100 == 0:
elapsed = time.time() - start_time
fps = frame_count / elapsed if elapsed > 0 else 0
print(
f"[YOLO] Processed {frame_count} frames, {detection_count} detections, {fps:.1f} FPS"
)
# Periodic save
if save_interval > 0 and time.time() - last_save_time > save_interval:
with open(output_path, "w") as f:
json.dump(result, f, indent=2)
last_save_time = time.time()
print(f"[YOLO] Auto-saved at frame {frame_count}")
except Exception as e:
print(f"[YOLO] Error during processing: {e}")
raise
# Final save
elapsed_time = time.time() - start_time
avg_fps = frame_count / elapsed_time if elapsed_time > 0 else 0
result["summary"] = {
"total_frames": frame_count,
"total_detections": detection_count,
"processing_time": round(elapsed_time, 2),
"average_fps": round(avg_fps, 2),
"device": device,
}
# Save final results
with open(output_path, "w") as f:
json.dump(result, f, indent=2)
print(
f"[YOLO] Completed: {frame_count} frames, {detection_count} detections in {elapsed_time:.1f}s ({avg_fps:.1f} FPS)"
)
print(f"[YOLO] Results saved to: {output_path}")
return result
def benchmark_models(video_path: str, num_frames: int = 100) -> Dict:
"""Benchmark different YOLO models and devices"""
devices = ["cpu"]
if torch.backends.mps.is_available():
devices.append("mps")
if torch.cuda.is_available():
devices.append("cuda")
models = ["yolov8n", "yolov8s", "yolov8m"]
results = {}
for model_name in models:
for device in devices:
print(f"[YOLO] Benchmarking {model_name} on {device}...")
model = YOLO(f"{model_name}.pt")
if device != "cpu":
model.to(device)
start_time = time.time()
count = 0
try:
for idx, r in enumerate(
model(video_path, device=device, stream=True, imgsz=320)
):
if idx >= num_frames:
break
count += 1
except Exception as e:
print(f"[YOLO] Error: {e}")
continue
elapsed = time.time() - start_time
fps = count / elapsed if elapsed > 0 else 0
key = f"{model_name}_{device}"
results[key] = {
"frames": count,
"time": round(elapsed, 2),
"fps": round(fps, 2),
}
return results
def main():
parser = argparse.ArgumentParser(description="YOLO Processor with MPS Support")
parser.add_argument("--video", required=True, help="Input video path")
parser.add_argument("--output", required=True, help="Output JSON path")
parser.add_argument(
"--model", default="yolov8n", help="YOLO model (yolov8n/s/m/l/x)"
)
parser.add_argument(
"--confidence", type=float, default=0.25, help="Confidence threshold"
)
parser.add_argument("--iou", type=float, default=0.45, help="IoU threshold for NMS")
parser.add_argument(
"--device",
default="auto",
choices=["auto", "mps", "cuda", "cpu"],
help="Device to use",
)
parser.add_argument(
"--batch-size", type=int, default=8, help="Batch size for processing"
)
parser.add_argument(
"--skip-frames", type=int, default=1, help="Process every N frames"
)
parser.add_argument(
"--no-resume", action="store_true", help="Do not resume from existing results"
)
parser.add_argument(
"--save-interval", type=int, default=30, help="Auto-save interval in seconds"
)
parser.add_argument(
"--benchmark", action="store_true", help="Run benchmark instead of processing"
)
args = parser.parse_args()
if args.benchmark:
results = benchmark_models(args.video)
print("\n[Benchmark Results]")
print(json.dumps(results, indent=2))
else:
process_video_yolo(
video_path=args.video,
output_path=args.output,
model_name=args.model,
confidence=args.confidence,
iou_threshold=args.iou,
device=args.device,
batch_size=args.batch_size,
skip_frames=args.skip_frames,
resume=not args.no_resume,
save_interval=args.save_interval,
)
if __name__ == "__main__":
main()