feat: restructure tools directory

新結構:
- tools/script/ (Python 處理器腳本)
- tools/cli/ (Swift/Rust CLI 工具)

遷移內容:
- Python 腳本: ASR, Face, Pose, Cut, OCR, VLM, Embedding, Identity
- Swift CLI: 24 個 Swift 處理器和測試文件
- Rust CLI: Face Cluster, Appearance, Pose

保留向後兼容:
- 舊路徑 scripts/ 仍然存在
- 環境變數可配置新路徑

文檔:
- tools/README.md
- docs_v1.0/DESIGN/Tools_Directory_Restructure.md
This commit is contained in:
Accusys
2026-09-27 12:04:23 +08:00
parent db74b11e21
commit af028ab8f4
54 changed files with 15459 additions and 0 deletions
+119
View File
@@ -0,0 +1,119 @@
#!/opt/homebrew/bin/python3.11
import sys
import json
import os
import argparse
import signal
import subprocess
from faster_whisper import WhisperModel
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
def signal_handler(signum, frame):
print(f"ASR: Received signal {signum}, exiting...")
sys.exit(1)
def has_audio_stream(video_path):
"""Check if video file has audio stream using ffprobe."""
try:
cmd = [
"ffprobe",
"-v",
"error",
"-select_streams",
"a",
"-show_entries",
"stream=codec_type",
"-of",
"csv=p=0",
video_path,
]
result = subprocess.run(cmd, capture_output=True, text=True, check=True)
return bool(result.stdout.strip())
except subprocess.CalledProcessError:
return False
except FileNotFoundError:
print("WARNING: ffprobe not found, assuming audio exists")
return True
def run_asr(video_path, output_path, uuid: str = ""):
# Set up signal handlers
signal.signal(signal.SIGTERM, signal_handler)
signal.signal(signal.SIGINT, signal_handler)
publisher = RedisPublisher(uuid) if uuid else None
if publisher:
publisher.info("asr", "ASR_START")
# Check for audio stream
if not has_audio_stream(video_path):
if publisher:
publisher.info("asr", "No audio stream detected, skipping transcription")
output = {"language": "", "language_probability": 0.0, "segments": []}
with open(output_path, "w") as f:
json.dump(output, f, indent=2)
if publisher:
publisher.complete("asr", "0 segments (no audio)")
sys.stderr.write("ASR: No audio stream, skipping transcription\n")
sys.stderr.flush()
sys.exit(0)
if publisher:
publisher.info("asr", "Loading Whisper model...")
# Use base model with CPU (MPS not supported by faster_whisper)
model = WhisperModel("base", device="cpu", compute_type="int8")
if publisher:
publisher.info("asr", f"Transcribing: {video_path}")
segments, info = model.transcribe(video_path, beam_size=5)
if publisher:
publisher.info("asr", f"ASR_LANGUAGE:{info.language}")
results = []
total_segments = 0
for segment in segments:
results.append(
{"start": segment.start, "end": segment.end, "text": segment.text.strip()}
)
total_segments += 1
if total_segments % 100 == 0:
if publisher:
publisher.progress(
"asr", total_segments, 0, f"Segment {total_segments}"
)
output = {
"language": info.language,
"language_probability": info.language_probability,
"segments": results,
}
with open(output_path, "w") as f:
json.dump(output, f, indent=2)
if publisher:
publisher.complete("asr", f"{len(results)} segments")
sys.stderr.write(
f"ASR: Transcription complete, {len(results)} segments written to {output_path}\n"
)
sys.stderr.flush()
sys.exit(0)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="ASR Transcription (base model)")
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="")
args = parser.parse_args()
run_asr(args.video_path, args.output_path, args.uuid)
@@ -0,0 +1,543 @@
#!/opt/homebrew/bin/python3.11
"""
ASR Processor - AI-Driven Processor Contract Version 1.0
Compliant with AI-Driven Processor Contract v1.0
Effective Date: 2025-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
"""
import sys
import json
import os
import argparse
import signal
import tempfile
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/asr_processor_contract_v1.py"
PROCESSOR_VERSION = "2.0.0"
MODEL_NAME = "base"
MODEL_VERSION = "unknown"
# Signal handling
class SignalHandler:
"""Handle system signals for graceful shutdown"""
def __init__(self):
self.shutdown_requested = False
self.original_handlers = {}
def setup(self):
"""Set up signal handlers"""
self.original_handlers[signal.SIGTERM] = signal.signal(
signal.SIGTERM, self.handle_signal
)
self.original_handlers[signal.SIGINT] = signal.signal(
signal.SIGINT, self.handle_signal
)
def handle_signal(self, signum, frame):
"""Handle received signal"""
signal_name = "SIGTERM" if signum == signal.SIGTERM else "SIGINT"
print(
f"[{PROCESSOR_NAME}] Received {signal_name}, initiating graceful shutdown...",
file=sys.stderr,
)
self.shutdown_requested = True
def restore(self):
"""Restore original signal handlers"""
for sig, handler in self.original_handlers.items():
signal.signal(sig, handler)
# Health check functions
def check_environment() -> Dict[str, Any]:
"""Check environment and dependencies"""
checks = []
# Check 1: Whisper
try:
import whisper
checks.append(
{
"name": "whisper",
"status": "available",
"version": whisper.__version__
if hasattr(whisper, "__version__")
else "unknown",
}
)
except ImportError:
checks.append(
{
"name": "whisper",
"status": "missing",
"message": "openai-whisper package not installed",
}
)
# Check 2: FFmpeg/FFprobe
try:
result = subprocess.run(["ffprobe", "-version"], capture_output=True, text=True)
if result.returncode == 0:
version_line = result.stdout.split("\n")[0] if result.stdout else "unknown"
checks.append(
{"name": "ffprobe", "status": "available", "version": version_line}
)
else:
checks.append(
{
"name": "ffprobe",
"status": "unavailable",
"message": "ffprobe command failed",
}
)
except Exception as e:
checks.append(
{
"name": "ffprobe",
"status": "missing",
"message": f"ffprobe not found: {e}",
}
)
# Check 3: Redis (optional)
checks.append(
{
"name": "redis",
"status": "available" if REDIS_AVAILABLE else "optional_missing",
"message": "Redis progress reporting available"
if REDIS_AVAILABLE
else "Redis progress reporting disabled",
}
)
# Determine overall status
critical_checks = [
c
for c in checks
if c["name"] in ["whisper", "ffprobe"]
and c["status"] not in ["available", "optional_missing"]
]
if critical_checks:
overall_status = "unhealthy"
else:
overall_status = "healthy"
return {
"status": overall_status,
"dependencies": checks,
"timestamp": datetime.now().isoformat(),
}
# Whisper model cache
_whisper_model_cache = {}
def get_whisper_model(model_name: str = "base"):
"""Get Whisper model with caching"""
if model_name not in _whisper_model_cache:
import whisper
print(
f"[{PROCESSOR_NAME}] Loading Whisper model: {model_name}", file=sys.stderr
)
_whisper_model_cache[model_name] = whisper.load_model(model_name)
return _whisper_model_cache[model_name]
# Main processor class
class ASRProcessor:
"""ASR Processor compliant with AI-Driven Processor Contract"""
def __init__(
self,
video_path: str,
output_path: str,
uuid: str = "",
model_name: str = "base",
chunk_size: int = 300,
publisher=None,
):
self.video_path = video_path
self.output_path = output_path
self.uuid = uuid
self.model_name = model_name
self.chunk_size = chunk_size
self.publisher = publisher
self.start_time = time.time()
self.signal_handler = SignalHandler()
self.cleanup_files = []
# Set up signal handling
self.signal_handler.setup()
atexit.register(self.cleanup)
def publish(self, msg_type: str, message: str, progress: Optional[float] = None):
"""Publish message to Redis if available"""
if self.publisher and REDIS_AVAILABLE:
try:
if msg_type == "progress" and progress is not None:
self.publisher.progress(
PROCESSOR_NAME, int(progress * 100), 0, message
)
else:
getattr(self.publisher, msg_type)(PROCESSOR_NAME, message)
except Exception as e:
print(f"[{PROCESSOR_NAME}] Redis publish error: {e}", file=sys.stderr)
def validate_input(self) -> Tuple[bool, str]:
"""Validate input file"""
if not os.path.exists(self.video_path):
return False, f"Video file not found: {self.video_path}"
# Check for audio stream
if not self._has_audio_stream():
return False, f"No audio stream found in: {self.video_path}"
return True, "Input validation passed"
def _has_audio_stream(self) -> bool:
"""Check if video has audio stream"""
try:
cmd = [
"ffprobe",
"-v",
"error",
"-select_streams",
"a",
"-show_entries",
"stream=codec_type",
"-of",
"csv=p=0",
self.video_path,
]
result = subprocess.run(cmd, capture_output=True, text=True)
return "audio" in result.stdout
except Exception:
return False
def _get_media_duration(self) -> float:
"""Get media duration in seconds"""
try:
cmd = [
"ffprobe",
"-v",
"error",
"-show_entries",
"format=duration",
"-of",
"csv=p=0",
self.video_path,
]
result = subprocess.run(cmd, capture_output=True, text=True)
return float(result.stdout.strip())
except Exception as e:
print(
f"[{PROCESSOR_NAME}] Warning: Failed to get duration: {e}",
file=sys.stderr,
)
return 0.0
def _extract_audio(self, audio_path: str) -> bool:
"""Extract audio to temporary file"""
try:
cmd = [
"ffmpeg",
"-i",
self.video_path,
"-vn",
"-acodec",
"pcm_s16le",
"-ar",
"16000",
"-ac",
"1",
"-y",
audio_path,
]
self.publish("info", f"Extracting audio to: {audio_path}")
result = subprocess.run(cmd, capture_output=True, text=True)
if result.returncode != 0:
self.publish("error", f"Audio extraction failed: {result.stderr[:100]}")
return False
return os.path.exists(audio_path) and os.path.getsize(audio_path) > 0
except Exception as e:
self.publish("error", f"Audio extraction error: {e}")
return False
def process(self) -> Dict[str, Any]:
"""Main processing method"""
try:
# Check for shutdown request
if self.signal_handler.shutdown_requested:
raise KeyboardInterrupt("Shutdown requested by signal")
# 1. Prepare working directory
work_dir = tempfile.mkdtemp(prefix=f"{PROCESSOR_NAME}_")
self.cleanup_files.append(work_dir)
self.publish("info", f"Working directory: {work_dir}")
# 2. Get media duration
duration = self._get_media_duration()
self.publish("info", f"Media duration: {duration:.2f} seconds")
# 3. Process based on duration
self.publish("info", "Starting transcription...")
if duration <= self.chunk_size or self.chunk_size <= 0:
# Single file processing
result = self._process_single_file(work_dir)
processing_mode = "direct"
chunk_count = 1
else:
# Chunked processing (simplified for now)
result = self._process_single_file(work_dir)
processing_mode = "chunked"
chunk_count = max(1, int(duration / self.chunk_size))
# 4. Add contract-compliant metadata
processing_time = time.time() - self.start_time
result.update(
{
"processor_name": PROCESSOR_NAME,
"processor_version": PROCESSOR_VERSION,
"contract_version": CONTRACT_VERSION,
"model_name": MODEL_NAME,
"model_version": MODEL_VERSION,
"processing_mode": processing_mode,
"chunk_count": chunk_count,
"chunk_duration": self.chunk_size
if processing_mode == "chunked"
else 0,
"metadata": {
"processing_time_seconds": processing_time,
"video_path": self.video_path,
"duration_seconds": duration,
"model": self.model_name,
"timestamp": datetime.now().isoformat(),
},
}
)
# 5. Cleanup
self.cleanup()
self.publish(
"complete", f"Processing completed in {processing_time:.2f} seconds"
)
return result
except KeyboardInterrupt:
self.publish("warning", "Processing interrupted by user")
raise
except Exception as e:
self.publish("error", f"Processing failed: {e}")
raise
def _process_single_file(self, work_dir: str) -> Dict[str, Any]:
"""Process single file (no chunking)"""
# 1. Extract audio
audio_path = os.path.join(work_dir, "audio.wav")
self.cleanup_files.append(audio_path)
if not self._extract_audio(audio_path):
raise RuntimeError("Failed to extract audio")
# 2. Load model
self.publish("info", f"Loading Whisper model: {self.model_name}")
model = get_whisper_model(self.model_name)
# 3. Transcribe
self.publish("progress", "Transcribing audio...", 0.3)
result = model.transcribe(audio_path)
# 4. Format segments
segments = []
total_segments = len(result.get("segments", []))
for i, segment in enumerate(result.get("segments", [])):
segments.append(
{
"start": segment.get("start", 0.0),
"end": segment.get("end", 0.0),
"text": segment.get("text", "").strip(),
"confidence": segment.get("confidence", 0.0),
}
)
# Update progress
if i % 10 == 0 and total_segments > 0:
progress = 0.3 + 0.7 * (i / total_segments)
self.publish(
"progress",
f"Transcribing segment {i + 1}/{total_segments}",
progress,
)
return {
"language": result.get("language"),
"language_probability": result.get("language_probability"),
"segments": segments,
"summary": {
"segment_count": len(segments),
"total_duration": result.get("duration", 0.0),
},
}
def save_result(self, result: Dict[str, Any]):
"""Save result to output file"""
# Ensure output directory exists
output_dir = os.path.dirname(self.output_path)
if output_dir and not os.path.exists(output_dir):
os.makedirs(output_dir, exist_ok=True)
with open(self.output_path, "w", encoding="utf-8") as f:
json.dump(result, f, ensure_ascii=False, indent=2)
self.publish("info", f"Result saved to: {self.output_path}")
def cleanup(self):
"""Clean up temporary resources"""
for file_path in self.cleanup_files:
try:
if os.path.isdir(file_path):
import shutil
shutil.rmtree(file_path)
elif os.path.exists(file_path):
os.remove(file_path)
except Exception as e:
print(f"[{PROCESSOR_NAME}] Cleanup warning: {e}", file=sys.stderr)
self.cleanup_files.clear()
self.signal_handler.restore()
# Main function
def main():
parser = argparse.ArgumentParser(
description=f"{PROCESSOR_NAME} Processor - AI-Driven Processor Contract v{CONTRACT_VERSION}",
formatter_class=argparse.RawDescriptionHelpFormatter,
)
# Required arguments
parser.add_argument("video_path", help="Path to input video file")
parser.add_argument("output_path", help="Path where JSON output should be written")
# Optional arguments
parser.add_argument(
"--uuid", "-u", default="", help="UUID for Redis progress reporting"
)
parser.add_argument(
"--check-health",
action="store_true",
help="Perform health check and exit (does not process video)",
)
# Hidden/configuration arguments
parser.add_argument(
"--model", default="base", help=argparse.SUPPRESS
) # Hidden from help
parser.add_argument(
"--chunk-size", type=int, default=300, help=argparse.SUPPRESS
) # Hidden from help
args = parser.parse_args()
# Health check mode
if args.check_health:
health = check_environment()
print(json.dumps(health, indent=2))
sys.exit(0 if health["status"] == "healthy" else 1)
# Create Redis publisher if UUID provided
publisher = None
if args.uuid and REDIS_AVAILABLE:
try:
publisher = RedisPublisher(args.uuid)
except Exception as e:
print(f"WARNING: Failed to create Redis publisher: {e}", file=sys.stderr)
# Create and run processor
processor = ASRProcessor(
video_path=args.video_path,
output_path=args.output_path,
uuid=args.uuid,
model_name=args.model,
chunk_size=args.chunk_size,
publisher=publisher,
)
# Validate input
valid, msg = processor.validate_input()
if not valid:
print(f"ERROR: {msg}", file=sys.stderr)
sys.exit(1)
try:
# Process video
result = processor.process()
# Save result
processor.save_result(result)
# Print success message
print(f"[{PROCESSOR_NAME}] Processing completed successfully", file=sys.stderr)
print(
f"[{PROCESSOR_NAME}] Output saved to: {args.output_path}", file=sys.stderr
)
sys.exit(0)
except KeyboardInterrupt:
print(f"[{PROCESSOR_NAME}] Processing interrupted by user", file=sys.stderr)
sys.exit(130)
except Exception as e:
print(f"ERROR: {e}", file=sys.stderr)
if os.environ.get("ASR_DEBUG") == "1":
print(f"DEBUG: {traceback.format_exc()}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
@@ -0,0 +1,604 @@
#!/opt/homebrew/bin/python3.11
"""
ASR Processor - AI-Driven Processor Contract Version 2.0
Compliant with AI-Driven Processor Contract v1.0
With unified configuration and timeout handling
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 with timeout handling
8. Model caching for performance
"""
import sys
import json
import os
import argparse
import signal
import tempfile
import time
import subprocess
import traceback
import threading
from datetime import datetime
from typing import Dict, Any, Optional, Tuple
import atexit
# Whisper import at module level for proper error handling
try:
import whisper
WHISPER_AVAILABLE = True
WHISPER_VERSION = getattr(whisper, "__version__", "unknown")
except ImportError:
WHISPER_AVAILABLE = False
WHISPER_VERSION = None
# 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 = "asr"
PROCESSOR_VERSION = "2.1.0"
# Unified configuration defaults
DEFAULT_OVERALL_TIMEOUT = 3600 # 1 hour
DEFAULT_PROCESS_TIMEOUT = 1800 # 30 minutes
DEFAULT_CHUNK_TIMEOUT = 300 # 5 minutes
DEFAULT_MODEL_SIZE = "medium"
DEFAULT_DEVICE = "cpu"
DEFAULT_LANGUAGE = "auto"
# Signal handling with timeout support
class SignalHandler:
"""Handle system signals for graceful shutdown"""
def __init__(self):
self.shutdown_requested = False
self.timeout_reached = False
self.original_handlers = {}
def setup(self):
"""Set up signal handlers"""
self.original_handlers[signal.SIGTERM] = signal.signal(
signal.SIGTERM, self.handle_signal
)
self.original_handlers[signal.SIGINT] = signal.signal(
signal.SIGINT, self.handle_signal
)
def handle_signal(self, signum, frame):
"""Handle received signal"""
signal_name = "SIGTERM" if signum == signal.SIGTERM else "SIGINT"
print(
f"[{PROCESSOR_NAME}] Received {signal_name}, initiating graceful shutdown...",
file=sys.stderr,
)
self.shutdown_requested = True
def timeout_handler(self):
"""Handle timeout signal"""
print(
f"[{PROCESSOR_NAME}] Processing timeout reached, initiating graceful shutdown...",
file=sys.stderr,
)
self.timeout_reached = True
self.shutdown_requested = True
def restore(self):
"""Restore original signal handlers"""
for sig, handler in self.original_handlers.items():
signal.signal(sig, handler)
# Timeout manager
class TimeoutManager:
"""Manage processing timeouts"""
def __init__(self, overall_timeout: int, process_timeout: int, chunk_timeout: int):
self.overall_timeout = overall_timeout
self.process_timeout = process_timeout
self.chunk_timeout = chunk_timeout
self.start_time = time.time()
self.timeout_thread = None
self.timeout_event = threading.Event()
def start_overall_timer(self):
"""Start overall timeout timer"""
if self.overall_timeout > 0:
self.timeout_thread = threading.Thread(
target=self._overall_timeout_watcher, daemon=True
)
self.timeout_thread.start()
def _overall_timeout_watcher(self):
"""Watch for overall timeout"""
time.sleep(self.overall_timeout)
if not self.timeout_event.is_set():
self.timeout_event.set()
print(
f"[{PROCESSOR_NAME}] Overall timeout ({self.overall_timeout}s) reached",
file=sys.stderr,
)
def check_timeout(self, operation: str = "processing") -> Tuple[bool, str]:
"""Check if timeout has been reached"""
elapsed = time.time() - self.start_time
if self.timeout_event.is_set():
return True, f"{operation} timeout reached"
if self.overall_timeout > 0 and elapsed > self.overall_timeout:
return True, f"Overall timeout ({self.overall_timeout}s) reached"
return False, ""
def get_remaining_time(self, timeout_type: str = "overall") -> float:
"""Get remaining time for specified timeout type"""
elapsed = time.time() - self.start_time
if timeout_type == "overall":
return max(0, self.overall_timeout - elapsed)
elif timeout_type == "process":
return max(0, self.process_timeout - elapsed)
elif timeout_type == "chunk":
return max(0, self.chunk_timeout - elapsed)
return 0.0
def cleanup(self):
"""Clean up timeout resources"""
self.timeout_event.set()
if self.timeout_thread and self.timeout_thread.is_alive():
self.timeout_thread.join(timeout=1.0)
# Health check functions
def check_environment() -> Dict[str, Any]:
"""Check environment and dependencies"""
checks = []
# Check 1: Whisper
if WHISPER_AVAILABLE:
checks.append(
{
"name": "whisper",
"status": "available",
"version": WHISPER_VERSION,
}
)
else:
checks.append({"name": "whisper", "status": "missing", "version": None})
# Check 2: FFmpeg/FFprobe
try:
result = subprocess.run(["ffprobe", "-version"], capture_output=True, text=True)
if result.returncode == 0:
version_line = result.stdout.split("\n")[0]
checks.append(
{"name": "ffprobe", "status": "available", "version": version_line}
)
else:
checks.append({"name": "ffprobe", "status": "error", "version": None})
except Exception:
checks.append({"name": "ffprobe", "status": "missing", "version": None})
# Check 3: Redis (optional)
if REDIS_AVAILABLE:
checks.append({"name": "redis", "status": "available", "version": "1.0.0"})
else:
checks.append({"name": "redis", "status": "optional_missing", "version": None})
# Check 4: Python version
checks.append(
{
"name": "python",
"status": "available",
"version": f"{sys.version_info.major}.{sys.version_info.minor}.{sys.version_info.micro}",
}
)
return {"status": "healthy", "dependencies": checks}
# Model cache for performance
_model_cache = {}
def get_whisper_model(model_size: str = "medium", device: str = "cpu"):
"""Get Whisper model with caching"""
if not WHISPER_AVAILABLE:
raise RuntimeError("Whisper library not available")
cache_key = f"{model_size}_{device}"
if cache_key in _model_cache:
return _model_cache[cache_key]
try:
print(f"[{PROCESSOR_NAME}] Loading Whisper model: {model_size} on {device}")
model = whisper.load_model(model_size, device=device)
_model_cache[cache_key] = model
return model
except Exception as e:
raise RuntimeError(f"Failed to load Whisper model: {e}")
# Main processor class
class ASRProcessor:
"""ASR Processor compliant with AI-Driven Processor Contract"""
def __init__(
self,
video_path: str,
output_path: str,
uuid: Optional[str] = None,
check_health: bool = False,
model_size: Optional[str] = None,
device: Optional[str] = None,
language: Optional[str] = None,
):
self.video_path = video_path
self.output_path = output_path
self.uuid = uuid or ""
self.check_health = check_health
# Get unified configuration: command-line args override environment variables
self.overall_timeout = int(
os.environ.get("MOMENTRY_ASR_TIMEOUT", str(DEFAULT_OVERALL_TIMEOUT))
)
self.process_timeout = int(
os.environ.get("MOMENTRY_ASR_PROCESS_TIMEOUT", str(DEFAULT_PROCESS_TIMEOUT))
)
self.chunk_timeout = int(
os.environ.get("MOMENTRY_ASR_CHUNK_TIMEOUT", str(DEFAULT_CHUNK_TIMEOUT))
)
self.model_size = model_size or os.environ.get("MOMENTRY_ASR_MODEL_SIZE", DEFAULT_MODEL_SIZE)
self.device = device or os.environ.get("MOMENTRY_ASR_DEVICE", DEFAULT_DEVICE)
self.language = language or os.environ.get("MOMENTRY_ASR_LANGUAGE", DEFAULT_LANGUAGE)
# Initialize components
self.publisher = None
if REDIS_AVAILABLE and self.uuid:
try:
self.publisher = RedisPublisher(self.uuid)
except Exception as e:
print(
f"[{PROCESSOR_NAME}] Failed to initialize Redis publisher: {e}",
file=sys.stderr,
)
self.timeout_manager = TimeoutManager(
self.overall_timeout, self.process_timeout, self.chunk_timeout
)
self.signal_handler = SignalHandler()
self.start_time = time.time()
self.cleanup_files = []
# Set up signal handling
self.signal_handler.setup()
atexit.register(self.cleanup)
def publish(self, msg_type: str, message: str, progress: Optional[float] = None):
"""Publish message to Redis if available"""
if self.publisher and REDIS_AVAILABLE:
try:
if msg_type == "progress" and progress is not None:
self.publisher.progress(
PROCESSOR_NAME, int(progress * 100), 0, message
)
else:
getattr(self.publisher, msg_type)(PROCESSOR_NAME, message)
except Exception as e:
print(f"[{PROCESSOR_NAME}] Redis publish error: {e}", file=sys.stderr)
def validate_input(self) -> Tuple[bool, str]:
"""Validate input file"""
if not os.path.exists(self.video_path):
return False, f"Video file not found: {self.video_path}"
# Check for audio stream
if not self._has_audio_stream():
return False, f"No audio stream found in: {self.video_path}"
return True, "Input validation passed"
def _has_audio_stream(self) -> bool:
"""Check if video has audio stream"""
try:
cmd = [
"ffprobe",
"-v",
"error",
"-select_streams",
"a",
"-show_entries",
"stream=codec_type",
"-of",
"csv=p=0",
self.video_path,
]
result = subprocess.run(cmd, capture_output=True, text=True)
return "audio" in result.stdout
except Exception:
return False
def extract_audio(self, video_path: str) -> str:
"""Extract audio from video file"""
temp_dir = tempfile.mkdtemp(prefix="asr_audio_")
audio_path = os.path.join(temp_dir, "audio.wav")
self.cleanup_files.append(temp_dir)
cmd = [
"ffmpeg",
"-i",
video_path,
"-vn",
"-acodec",
"pcm_s16le",
"-ar",
"16000",
"-ac",
"1",
"-y",
audio_path,
]
try:
result = subprocess.run(
cmd, capture_output=True, text=True, timeout=self.chunk_timeout
)
if result.returncode != 0:
raise RuntimeError(f"FFmpeg failed: {result.stderr}")
return audio_path
except subprocess.TimeoutExpired:
raise RuntimeError(f"Audio extraction timeout after {self.chunk_timeout}s")
except Exception as e:
raise RuntimeError(f"Audio extraction failed: {e}")
def transcribe_audio(self, audio_path: str) -> Dict[str, Any]:
"""Transcribe audio using Whisper"""
if not WHISPER_AVAILABLE:
raise RuntimeError("Whisper library not available")
self.publish("info", f"Starting transcription with model: {self.model_size}")
print(
f"[DEBUG] WHISPER_AVAILABLE: {WHISPER_AVAILABLE}, whisper module: {'available' if 'whisper' in globals() else 'not in globals'}"
)
try:
model = get_whisper_model(self.model_size, self.device)
print(f"[DEBUG] Model loaded: {model}")
# Start timeout monitoring for transcription
self.timeout_manager.start_overall_timer()
# Set language for transcription
language = self.language
if language == "auto":
# For auto, let Whisper handle language detection internally
language = None
self.publish("info", "Language detection will be handled by Whisper")
else:
self.publish("info", f"Using specified language: {language}")
# Perform transcription
transcribe_language = language if language != "auto" else None
self.publish(
"info",
f"Transcribing audio (language: {transcribe_language if transcribe_language else 'auto'})...",
)
result = model.transcribe(
audio_path,
language=transcribe_language,
task="transcribe",
beam_size=5,
best_of=5,
)
# Check for timeout during transcription
timeout_reached, timeout_msg = self.timeout_manager.check_timeout(
"transcription"
)
if timeout_reached:
raise RuntimeError(f"Transcription {timeout_msg}")
return {
"language": result.get("language"),
"language_probability": result.get("language_probability"),
"segments": [
{
"start": segment["start"],
"end": segment["end"],
"text": segment["text"].strip(),
}
for segment in result.get("segments", [])
],
}
except RuntimeError as e:
if "timeout" in str(e).lower():
raise
else:
raise RuntimeError(f"Transcription failed: {e}")
except Exception as e:
raise RuntimeError(f"Transcription error: {e}")
def process(self) -> Dict[str, Any]:
"""Main processing method"""
self.publish("info", f"Starting ASR processing: {self.video_path}")
self.publish(
"info",
f"Configuration: timeout={self.overall_timeout}s, model={self.model_size}, device={self.device}",
)
# Validate input
is_valid, validation_msg = self.validate_input()
if not is_valid:
raise RuntimeError(f"Input validation failed: {validation_msg}")
self.publish("info", "Input validation passed")
# Extract audio
self.publish("info", "Extracting audio from video...")
audio_path = self.extract_audio(self.video_path)
self.publish("progress", "Audio extraction complete", 0.3)
# Check for timeout
timeout_reached, timeout_msg = self.timeout_manager.check_timeout(
"audio extraction"
)
if timeout_reached:
raise RuntimeError(f"Audio extraction {timeout_msg}")
# Transcribe audio
self.publish("info", "Transcribing audio...")
transcription_result = self.transcribe_audio(audio_path)
self.publish("progress", "Transcription complete", 0.8)
# Check for timeout
timeout_reached, timeout_msg = self.timeout_manager.check_timeout(
"transcription"
)
if timeout_reached:
raise RuntimeError(f"Transcription {timeout_msg}")
# Prepare final result
result = {
"processor_name": PROCESSOR_NAME,
"processor_version": PROCESSOR_VERSION,
"contract_version": CONTRACT_VERSION,
"video_path": self.video_path,
"timestamp": datetime.utcnow().isoformat() + "Z",
"processing_time_seconds": time.time() - self.start_time,
"configuration": {
"model_size": self.model_size,
"device": self.device,
"language": self.language,
"timeout_seconds": self.overall_timeout,
},
**transcription_result,
}
self.publish("progress", "ASR processing complete", 1.0)
self.publish(
"complete",
f"ASR processing completed successfully in {result['processing_time_seconds']:.1f}s",
)
return result
def cleanup(self):
"""Clean up temporary resources"""
self.timeout_manager.cleanup()
self.signal_handler.restore()
# Clean up temporary files
for path in self.cleanup_files:
try:
if os.path.isdir(path):
import shutil
shutil.rmtree(path, ignore_errors=True)
elif os.path.exists(path):
os.unlink(path)
except Exception:
pass
def main():
"""Main entry point"""
parser = argparse.ArgumentParser(
description="ASR Processor - AI-Driven Processor Contract Version 2.0"
)
# Required arguments
parser.add_argument("video_path", help="Path to input video file")
parser.add_argument("output_path", help="Path where JSON output should be written")
# Optional arguments
parser.add_argument(
"--uuid", "-u", default="", help="UUID for Redis progress reporting"
)
parser.add_argument(
"--check-health", action="store_true", help="Perform health check and exit"
)
# Hidden configuration arguments (following contract)
parser.add_argument("--model-size", help=argparse.SUPPRESS)
parser.add_argument("--device", help=argparse.SUPPRESS)
parser.add_argument("--language", help=argparse.SUPPRESS)
parser.add_argument("--timeout", type=int, help=argparse.SUPPRESS)
args = parser.parse_args()
# Health check mode
if args.check_health:
health_result = check_environment()
print(json.dumps(health_result, indent=2))
sys.exit(0 if health_result["status"] == "healthy" else 1)
# Create processor
processor = ASRProcessor(
video_path=args.video_path,
output_path=args.output_path,
uuid=args.uuid if args.uuid else None,
check_health=args.check_health,
model_size=args.model_size,
device=args.device,
language=args.language,
)
try:
# Process video
result = processor.process()
# Write output
with open(args.output_path, "w", encoding="utf-8") as f:
json.dump(result, f, indent=2, ensure_ascii=False)
print(f"[{PROCESSOR_NAME}] Processing completed successfully")
print(f"[{PROCESSOR_NAME}] Output written to: {args.output_path}")
sys.exit(0)
except RuntimeError as e:
error_msg = f"ASR processing failed: {e}"
processor.publish("error", error_msg)
print(f"[{PROCESSOR_NAME}] ERROR: {error_msg}", file=sys.stderr)
sys.exit(1)
except KeyboardInterrupt:
processor.publish("warning", "Processing interrupted by user")
print(f"[{PROCESSOR_NAME}] Processing interrupted by user", file=sys.stderr)
sys.exit(130) # Standard exit code for SIGINT
except Exception as e:
error_msg = f"Unexpected error: {e}\n{traceback.format_exc()}"
processor.publish("error", error_msg)
print(f"[{PROCESSOR_NAME}] CRITICAL ERROR: {error_msg}", file=sys.stderr)
sys.exit(1)
if __name__ == "__main__":
main()
+301
View File
@@ -0,0 +1,301 @@
#! /opt/homebrew/bin/python3.11
"""
CUT Processor - Scene Detection & Video Quality Check
Dual-detector: ffprobe scene filter + PySceneDetect ContentDetector (merged).
Always produces at least 1 scene.
"""
import json
import argparse
import os
import subprocess
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
try:
from scenedetect import open_video, SceneManager
from scenedetect.detectors import ContentDetector, AdaptiveDetector
HAS_SCENEDETECT = True
except ImportError:
HAS_SCENEDETECT = False
def get_video_info(video_path: str) -> dict:
"""Get video info via ffprobe"""
try:
result = subprocess.run(
[
"ffprobe",
"-v",
"quiet",
"-print_format",
"json",
"-show_format",
"-show_streams",
video_path,
],
capture_output=True,
text=True,
timeout=30,
)
info = json.loads(result.stdout)
for stream in info.get("streams", []):
if stream.get("codec_type") == "video":
nb_frames = stream.get("nb_frames")
if nb_frames:
fr = stream.get("r_frame_rate", "0/1")
fps = eval(fr) if "/" in fr else float(fr)
return {
"frame_count": int(nb_frames),
"fps": fps,
"duration": float(stream.get("duration", 0)),
"width": int(stream.get("width", 0)),
"height": int(stream.get("height", 0)),
"codec": stream.get("codec_name", ""),
}
dur = float(stream.get("duration", 0))
afr = stream.get("avg_frame_rate", "0/1")
avg_fps = eval(afr) if "/" in afr else float(afr)
if dur > 0 and avg_fps > 0:
return {
"frame_count": int(dur * avg_fps),
"fps": avg_fps,
"duration": dur,
"width": int(stream.get("width", 0)),
"height": int(stream.get("height", 0)),
"codec": stream.get("codec_name", ""),
}
return {
"frame_count": 0,
"fps": 0.0,
"duration": dur,
"width": 0,
"height": 0,
"codec": "",
}
return {
"frame_count": 0,
"fps": 0.0,
"duration": 0,
"width": 0,
"height": 0,
"codec": "",
}
except Exception:
return {
"frame_count": 0,
"fps": 0.0,
"duration": 0,
"width": 0,
"height": 0,
"codec": "",
}
def detect_scenes_ffmpeg(video_path: str, fps: float, duration: float) -> list:
"""Detect scene change times using ffmpeg scene filter
Returns:
List of cut times in seconds (empty if failed or no cuts found)
"""
try:
result = subprocess.run(
[
"ffprobe",
"-v",
"quiet",
"-show_entries",
"frame=pts_time",
"-of",
"default=nk=0",
"-f",
"lavfi",
f"movie={video_path},select='gt(scene\\,0.3)',showinfo",
"-show_frames",
],
capture_output=True,
text=True,
timeout=300,
)
times = set()
for line in (result.stderr + "\n" + result.stdout).split("\n"):
for prefix in ("pts_time=", "pts_time:"):
if prefix in line:
rest = line.split(prefix)[1].split()[0]
try:
t = float(rest)
times.add(t)
except ValueError:
pass
return sorted(times)
except Exception:
return []
def detect_scenes_scenedetect(video_path: str, fps: float, duration: float) -> list:
"""Detect scene change times using PySceneDetect (ContentDetector + AdaptiveDetector)
Runs both detectors and merges results for maximum recall.
Returns:
List of cut times in seconds (empty if failed or no cuts found)
"""
if not HAS_SCENEDETECT:
return []
try:
all_times = set()
# ContentDetector with lower threshold for higher recall
video = open_video(video_path)
sm = SceneManager()
sm.add_detector(ContentDetector(threshold=15.0))
sm.detect_scenes(video)
for i, (start_tc, _) in enumerate(sm.get_scene_list()):
if i == 0:
continue
t = start_tc.get_seconds()
if 0 < t < duration:
all_times.add(t)
# AdaptiveDetector (self-tuning, catches gradual transitions)
video = open_video(video_path)
sm = SceneManager()
sm.add_detector(AdaptiveDetector())
sm.detect_scenes(video)
for i, (start_tc, _) in enumerate(sm.get_scene_list()):
if i == 0:
continue
t = start_tc.get_seconds()
if 0 < t < duration:
all_times.add(t)
return sorted(all_times)
except Exception as e:
print(f"[CUT] scenedetect failed: {e}", file=sys.stderr)
return []
def rebuild_scenes(
cut_times: list, fps: float, total_frames: int, duration: float
) -> list:
"""Rebuild scene list from sorted cut times
Args:
cut_times: Sorted list of cut times in seconds
fps: Frames per second
total_frames: Total frame count
duration: Video duration in seconds
Returns:
List of {scene_number, start_frame, end_frame, start_time, end_time}
"""
scenes = []
prev_time = 0.0
prev_frame = 0
for i, t in enumerate(cut_times):
end_frame = round(t * fps)
if end_frame > prev_frame:
scenes.append(
{
"scene_number": len(scenes) + 1,
"start_frame": prev_frame,
"end_frame": end_frame - 1,
"start_time": round(prev_time, 2),
"end_time": round(t - (1.0 / fps) if fps > 0 else t, 2),
}
)
prev_time = t
prev_frame = end_frame
# Final scene
last_frame = total_frames
if last_frame > prev_frame:
scenes.append(
{
"scene_number": len(scenes) + 1,
"start_frame": prev_frame,
"end_frame": last_frame - 1,
"start_time": round(prev_time, 2),
"end_time": round(duration, 2),
}
)
return scenes
def process_cut(video_path: str, output_path: str, uuid: str = ""):
"""Process video for scene detection using dual detectors (ffmpeg + scenedetect)"""
publisher = RedisPublisher(uuid) if uuid else None
if publisher:
publisher.info("cut", "CUT_START")
vinfo = get_video_info(video_path)
if publisher:
publisher.info(
"cut",
f"fps={vinfo['fps']}, frames={vinfo['frame_count']}, codec={vinfo['codec']}",
)
total_frames = vinfo["frame_count"]
fps = vinfo["fps"]
duration = vinfo["duration"]
# Phase 1: ffmpeg scene filter
cut_times_ffmpeg = detect_scenes_ffmpeg(video_path, fps, duration)
# Phase 2: scenedetect ContentDetector
cut_times_sd = detect_scenes_scenedetect(video_path, fps, duration)
# Merge: union of cut points from both detectors
all_cut_times = sorted(set(cut_times_ffmpeg + cut_times_sd))
scenes = rebuild_scenes(all_cut_times, fps, total_frames, duration)
# Always ensure at least 1 scene
if not scenes and total_frames > 0:
scenes = [
{
"scene_number": 1,
"start_frame": 0,
"end_frame": total_frames - 1,
"start_time": 0.0,
"end_time": round(duration, 2),
}
]
if publisher:
publisher.info(
"cut", "No scene changes detected, using whole video as single scene"
)
result = {
"frame_count": total_frames,
"fps": round(fps, 2),
"scenes": scenes,
}
with open(output_path, "w") as f:
json.dump(result, f, indent=2)
if publisher:
publisher.complete(
"cut",
f"{len(scenes)} scenes ({len(cut_times_ffmpeg)} ffmpeg + {len(cut_times_sd)} scenedetect)",
)
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Scene Detection")
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="")
args = parser.parse_args()
process_cut(args.video_path, args.output_path, args.uuid)
@@ -0,0 +1,85 @@
#!/usr/bin/env python3
"""EmbeddingGemma HTTP server - Metal GPU (MPS) accelerated, compatible with M4/M5."""
import argparse, json, time, torch
from flask import Flask, request, jsonify
from transformers import AutoModel, AutoTokenizer
import numpy as np
app = Flask(__name__)
MODEL = None
TOKENIZER = None
DEVICE = None
def load_model(model_path: str = "google/embeddinggemma-300m"):
global MODEL, TOKENIZER, DEVICE
if MODEL is not None:
return
DEVICE = "mps" if torch.backends.mps.is_available() else "cpu"
dtype = torch.float32
print(f"[EmbeddingGemma] Loading model on {DEVICE} (dtype={dtype})...")
t0 = time.time()
MODEL = AutoModel.from_pretrained(
model_path,
torch_dtype=dtype,
trust_remote_code=True,
).eval().to(DEVICE)
TOKENIZER = AutoTokenizer.from_pretrained(model_path, trust_remote_code=True)
print(f"[EmbeddingGemma] Loaded in {time.time()-t0:.1f}s on {DEVICE}")
def embed(texts: list[str]) -> list[list[float]]:
inputs = TOKENIZER(texts, padding=True, truncation=True, return_tensors="pt").to(DEVICE)
with torch.no_grad():
outputs = MODEL(**inputs)
mask = inputs["attention_mask"].unsqueeze(-1).to(outputs.last_hidden_state.dtype)
pooled = (outputs.last_hidden_state * mask).sum(dim=1) / (mask.sum(dim=1) + 1e-9)
pooled = torch.nn.functional.normalize(pooled, p=2, dim=1)
return pooled.cpu().numpy().tolist()
@app.route("/v1/embeddings", methods=["POST"])
def embeddings():
start_time = time.time()
data = request.get_json()
texts = data.get("input", [])
if isinstance(texts, str):
texts = [texts]
if not texts:
return jsonify({"error": "empty input"}), 400
try:
# Tokenize to get token count
inputs = TOKENIZER(texts, padding=True, truncation=True, return_tensors="pt")
total_tokens = inputs["input_ids"].shape[1] * len(texts)
# Generate embeddings
emb = embed(texts)
duration_ms = int((time.time() - start_time) * 1000)
result = {
"data": [{"embedding": e, "index": i} for i, e in enumerate(emb)],
"model": "embeddinggemma-300m",
"usage": {
"prompt_tokens": total_tokens,
"completion_tokens": 0,
"total_tokens": total_tokens
},
"timings": {
"duration_ms": duration_ms
}
}
return jsonify(result)
except Exception as e:
return jsonify({"error": str(e)}), 500
@app.route("/health", methods=["GET"])
def health():
return jsonify({"status": "ok", "device": str(DEVICE)})
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument("--port", type=int, default=11436)
parser.add_argument("--model", type=str, default="google/embeddinggemma-300m")
args = parser.parse_args()
load_model(args.model)
app.run(host="0.0.0.0", port=args.port, threaded=True)
+421
View File
@@ -0,0 +1,421 @@
#!/opt/homebrew/bin/python3.11
"""
Face Processor V2 - Apple Vision detection + CoreML FaceNet embedding
Flow:
1. swift_face (Vision/ANE) → bbox + pose per frame
2. cv2 opens video, crops faces from bbox
3. CoreML FaceNet → 512D embedding per face
4. Output face.json in standard format
Replaces face_processor.py (no more InsightFace CPU detection).
Detection cost: near-zero CPU (Vision ANE)
Embedding cost: near-zero CPU (CoreML ANE)
"""
import re
import sys
import os
import json
import argparse
import subprocess
import time
from typing import Optional, Dict
import cv2
import numpy as np
from pathlib import Path
# CoreML
import coremltools as ct
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils"))
from redis_publisher import RedisPublisher
from qdrant_faces import push_face_embeddings_batch
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SWIFT_BIN = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "release", "swift_face")
SWIFT_BIN_DEBUG = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "debug", "swift_face")
FACENET_PATH = os.path.join(SCRIPT_DIR, "..", "models", "facenet512.mlpackage")
# Pose angle classification from roll/yaw
def classify_pose(roll: float, yaw: float) -> str:
"""Convert roll/yaw to pose angle label"""
abs_yaw = abs(yaw)
abs_roll = abs(roll)
if abs_yaw < 15 and abs_roll < 15:
return "frontal"
elif abs_yaw > 30:
return "profile_right" if yaw > 0 else "profile_left"
else:
return "three_quarter"
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only).
Intentionally leaves Qdrant push payloads untouched (they use raw values).
"""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
class FaceProcessorVision:
def __init__(self, video_path: str, output_path: str, uuid: str = "",
sample_interval: int = 3, publisher: RedisPublisher = None):
self.video_path = video_path
self.output_path = output_path
self.uuid = uuid
self.sample_interval = sample_interval
self.publisher = publisher
# Load CoreML FaceNet
self.coreml_model = None
facenet = os.path.normpath(FACENET_PATH)
if os.path.exists(facenet):
try:
self.coreml_model = ct.models.MLModel(facenet)
print(f"[FACE_V2] CoreML FaceNet loaded: {facenet}")
except Exception as e:
print(f"[FACE_V2] CoreML load failed: {e}")
self.video = None
self.fps = 30.0
self.total_frames = 0
self.width = 0
self.height = 0
def open_video(self):
self.video = cv2.VideoCapture(self.video_path)
if not self.video.isOpened():
raise RuntimeError(f"Cannot open: {self.video_path}")
self.fps = self.video.get(cv2.CAP_PROP_FPS)
self.total_frames = int(self.video.get(cv2.CAP_PROP_FRAME_COUNT))
self.width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
self.height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))
# Calculate 8Hz sample interval based on FPS
self.sample_interval = max(1, round(self.fps / 8))
print(f"[FACE_V2] Video: {self.width}x{self.height}, {self.fps:.1f}fps, {self.total_frames}f")
print(f"[FACE_V2] 8Hz sample interval: {self.fps:.1f}/8 = {self.sample_interval}")
def extract_face_embedding(self, face_img: np.ndarray) -> Optional[list]:
"""Run CoreML FaceNet on cropped face"""
if self.coreml_model is None:
return None
try:
# Resize to 160x160
resized = cv2.resize(face_img, (160, 160))
# Convert HWC to CHW and normalize to [-1, 1]
normalized = (resized.astype(np.float32) / 127.5) - 1.0
normalized = np.transpose(normalized, (2, 0, 1)) # HWC -> CHW
# Add batch dim: (1, 3, 160, 160)
input_array = np.expand_dims(normalized, axis=0)
result = self.coreml_model.predict({"input": input_array})
# Find output key (var_xxx)
emb_key = [k for k in result.keys() if k.startswith("var_")][0]
emb = result[emb_key].flatten().tolist()
return emb
except Exception as e:
print(f"[FACE_V2] Embedding error: {e}")
return None
def process_with_swift(self) -> Dict:
"""Step 1: Run swift_face to get bbox (generates face_detect.json only)
Note: swift_face only does face detection.
Pose and appearance expansion happen later via separate processors:
- swift_pose_expansion reads face_traced.json (with trace_id)
- swift_appearance_expansion reads pose.json
"""
print(f"[FACE_V2] Step 1: Vision detection (face only)...")
# Build swift_face if missing or stale (source newer than binary)
src = os.path.join(SCRIPT_DIR, "swift_processors", "swift_face.swift")
def _stale(bin_path):
return os.path.exists(bin_path) and os.path.exists(src) and \
os.path.getmtime(src) > os.path.getmtime(bin_path)
if _stale(SWIFT_BIN):
print(f"[FACE_V2] swift_face release binary stale (source newer), removing to force rebuild...")
os.remove(SWIFT_BIN)
if _stale(SWIFT_BIN_DEBUG):
os.remove(SWIFT_BIN_DEBUG)
if not os.path.exists(SWIFT_BIN) and not os.path.exists(SWIFT_BIN_DEBUG):
build_dir = os.path.join(SCRIPT_DIR, "swift_processors")
print(f"[FACE_V2] Building swift_face in {build_dir}...")
subprocess.run(
["swift", "build", "-c", "release", "--product", "swift_face"],
cwd=build_dir, check=True
)
# Determine which binary to use
swift_bin = SWIFT_BIN if os.path.exists(SWIFT_BIN) else SWIFT_BIN_DEBUG
swift_face_out = self.output_path.replace(".json", "_detect.json")
cmd = [
swift_bin,
self.video_path,
swift_face_out,
"--sample-interval", str(self.sample_interval),
]
if self.uuid:
cmd.extend(["--uuid", self.uuid])
print(f"[FACE_V2] Running: {' '.join(cmd)}")
# Log face detection settings being passed to swift_face.
# Defaults mirror src/core/config.rs FACE_MIN_CONFIDENCE_DEFAULT / FACE_MIN_SIZE_DEFAULT (0.5 / 1).
min_conf = os.environ.get("FACE_MIN_CONFIDENCE", "not set (default 0.5)")
min_size = os.environ.get("FACE_MIN_SIZE", "not set (default 1)")
print(f"[FACE_V2] Settings passed to swift_face: FACE_MIN_CONFIDENCE={min_conf}, FACE_MIN_SIZE={min_size}")
t0 = time.time()
log_path = swift_face_out + ".log"
log_f = open(log_path, "w")
# Pass environment variables to swift_face subprocess (FACE_MIN_CONFIDENCE, FACE_MIN_SIZE)
proc = subprocess.Popen(cmd, stdout=log_f, stderr=subprocess.STDOUT, text=True, env=os.environ)
last_pct = -1
while proc.poll() is None:
time.sleep(10)
# Read latest log lines
try:
with open(log_path) as lf:
for line in lf:
line = line.strip()
m = re.search(r'(\d+)% complete', line)
if m:
pct = int(m.group(1))
if pct > last_pct:
last_pct = pct
if self.publisher:
self.publisher.progress("face", pct, 100, f"swift detect {pct}%")
except Exception:
pass
log_f.close()
if proc.returncode != 0:
stderr_out = proc.stderr.read() if proc.stderr else ""
if stderr_out:
print(stderr_out.strip(), file=sys.stderr)
raise RuntimeError(f"swift_face exited with code {proc.returncode}")
elapsed = time.time() - t0
print(f"[FACE_V2] Detection done in {elapsed:.1f}s")
with open(swift_face_out) as f:
face_data = json.load(f)
return face_data
def embed_and_save(self, detection_data: Dict):
"""Step 2: Crop faces + CoreML embedding + save face.json"""
print(f"[FACE_V2] Step 2: CoreML embedding...")
frames = detection_data.get("frames", [])
self.open_video()
face_data = {
"metadata": {
"video_path": os.path.abspath(self.video_path),
"fps": self.fps, "width": self.width, "height": self.height,
"sample_interval": self.sample_interval,
"detection_method": "apple_vision",
"embedding_method": "coreml_facenet",
"status": "in_progress",
"total_frames": self.total_frames,
},
"frames": {}
}
t0 = time.time()
embed_count = 0
total_face_count = 0
last_pct = -1
all_embeddings = [] # Collect embeddings for Qdrant push
for frame_info in frames:
frame_num = frame_info["frame"]
faces = []
for face_idx, face in enumerate(frame_info.get("faces", [])):
bb = face["bbox"]
x, y, w, h = bb["x"], bb["y"], bb["width"], bb["height"]
if w <= 10 or h <= 10:
continue # skip tiny faces
# Seek to frame and read
self.video.set(cv2.CAP_PROP_POS_FRAMES, frame_num)
ret, frame = self.video.read()
if not ret:
continue
# Crop face
x1, y1 = max(0, x), max(0, y)
x2, y2 = min(self.width, x + w), min(self.height, y + h)
if x2 <= x1 or y2 <= y1:
continue
face_img = frame[y1:y2, x1:x2]
if face_img.size == 0:
continue
# CoreML embedding - push to Qdrant _faces collection
emb = self.extract_face_embedding(face_img)
if emb is not None:
embed_count += 1
# Collect for batch Qdrant push
# Use face_idx to distinguish multiple faces in same frame
all_embeddings.append({
"frame": frame_num,
"trace_id": face_idx, # Use face_idx as unique identifier within frame
"bbox": {"x": x, "y": y, "width": w, "height": h},
"confidence": face.get("confidence", 0.5),
"capture_quality": face.get("captureQuality", 0),
"embedding": emb,
})
# Pose classification
pose_info = face.get("pose", {})
pose_angle = classify_pose(
pose_info.get("roll", 0),
pose_info.get("yaw", 0)
)
faces.append({
"x": x, "y": y, "width": w, "height": h,
"confidence": face.get("confidence", 0.5),
"captureQuality": face.get("captureQuality", 0),
"pose_angle": {
"angle": pose_angle,
"roll": pose_info.get("roll", 0),
"yaw": pose_info.get("yaw", 0),
"pitch": pose_info.get("pitch", 0),
},
"lips": face.get("lips"),
"landmarks": face.get("landmarks"),
"attributes": None,
})
if faces:
face_data["frames"][str(frame_num)] = {
"frame_number": frame_num,
"time_seconds": frame_info.get("timestamp", frame_num / self.fps),
"time_formatted": f"{frame_num / self.fps:.1f}s",
"faces": faces,
}
if len(face_data["frames"]) % 100 == 0:
elapsed = time.time() - t0
print(f"[FACE_V2] {len(face_data['frames'])} frames, {elapsed:.0f}s")
if self.publisher:
pct = int(len(face_data["frames"]) * 100 / max(len(frames), 1))
if pct > last_pct:
last_pct = pct
self.publisher.progress("face", len(face_data["frames"]), len(frames),
"", 0, "faces")
self.video.release()
face_data["metadata"]["status"] = "completed"
# Convert dict frames to list for Rust FaceResult format
frames_list = []
total_faces = 0
for fnum_str, fdata in sorted(face_data["frames"].items(), key=lambda x: int(x[0])):
faces = fdata["faces"]
total_faces += len(faces)
frames_list.append({
"frame": int(fnum_str),
"timestamp": fdata["time_seconds"],
"faces": faces,
})
# Determine status based on face count
if total_faces > 0:
status = "has_faces"
else:
status = "no_faces"
output = {
"status": status,
"frame_count": len(frames_list),
"fps": round(self.fps, 2),
"frames": frames_list,
"total_faces": total_faces,
}
with open(self.output_path, "w") as f:
json.dump(round_json_numbers(output), f, indent=2, ensure_ascii=False)
# Push embeddings to Qdrant _faces collection
if all_embeddings:
try:
pushed = push_face_embeddings_batch(self.uuid, all_embeddings, self.publisher)
if pushed != len(all_embeddings):
raise RuntimeError(
f"Qdrant push incomplete: {pushed}/{len(all_embeddings)} embeddings pushed"
)
except Exception as e:
print(f"[FACE_V2] ERROR: Qdrant push failed: {e}", file=sys.stderr)
raise RuntimeError(f"Qdrant push failed: {e}")
elapsed = time.time() - t0
print(f"[FACE_V2] Done: {len(frames_list)} frames, {embed_count} embeddings, {elapsed:.0f}s")
def main():
parser = argparse.ArgumentParser(description="Apple Vision Face Processor V2")
parser.add_argument("video_path", help="Video file path")
parser.add_argument("output_path", help="Output JSON path")
parser.add_argument("--uuid", "-u", default="")
parser.add_argument("--sample-interval", type=int, default=3)
parser.add_argument("--force", action="store_true")
parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS)
args = parser.parse_args()
publisher = RedisPublisher(args.uuid) if args.uuid else None
if publisher:
publisher.info("face", "FACE_START")
if args.force and os.path.exists(args.output_path):
os.remove(args.output_path)
processor = FaceProcessorVision(
args.video_path, args.output_path,
args.uuid, args.sample_interval, publisher
)
# Open video to get FPS and calculate sample_interval
processor.open_video()
# Step 1: Vision detection (bbox + pose via ANE)
try:
detection = processor.process_with_swift()
except Exception as e:
if publisher:
publisher.error("face", f"Detection failed: {e}")
raise
# Step 2: CoreML embedding + save
try:
processor.embed_and_save(detection)
except Exception as e:
if publisher:
publisher.error("face", f"Embedding failed: {e}")
raise
if publisher:
publisher.complete("face", f"{len(detection.get('frames',[]))} frames")
# Clean up temp detection file
swift_out = args.output_path.replace(".json", "_detect.json")
if os.path.exists(swift_out):
os.remove(swift_out)
if __name__ == "__main__":
main()
+358
View File
@@ -0,0 +1,358 @@
#!/opt/homebrew/bin/python3.11
"""
Store Traced Faces - Pipeline integration for face trace + position data
Flow:
1. Reads face.json output from face_processor.py
2. Runs face_tracker.py to assign trace_id per face (IoU + embedding)
3. Inserts traced faces into face_detections table with trace_id and position (x,y,w,h)
Usage:
python store_traced_faces.py --file-uuid <uuid> [--face-json <path>]
TKG Export:
trace_id + position (x,y,w,h) per frame enables spatial-temporal graph construction.
Each trace is a temporal entity; position tracks movement across frames.
"""
import sys
import os
import json
import argparse
from collections import defaultdict
import numpy as np
from datetime import datetime
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils"))
from qdrant_faces import update_trace_ids
# Config
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev")
SCHEMA = os.environ.get("DATABASE_SCHEMA", "public")
def strip_embeddings_and_round(obj):
"""Remove face embeddings from face_traced.json and round floats to 2 dp.
Embeddings live in Qdrant _faces (512D); storing them in the JSON bloats the
file (~2MB+ per 1000 faces). face_tracker consumes embeddings in-memory (loaded
from Qdrant before tracking), so stripping at write time is safe: all downstream
consumers (TKG, clustering, cluster_agent) read Qdrant or trace IDs instead.
"""
if isinstance(obj, dict):
return {
k: strip_embeddings_and_round(v)
for k, v in obj.items()
if not (k == "embedding")
}
if isinstance(obj, list):
return [strip_embeddings_and_round(v) for v in obj]
if isinstance(obj, float):
return round(obj, 2)
return obj
def merge_traces_within_cuts(face_data: dict, cut_scenes: list) -> dict:
"""Merge traces within the same cut - DISABLED (no embeddings)."""
# TODO: Reimplement with Qdrant _faces collection
return face_data
def filter_traces(
face_data: dict, min_trace_len: int = 0, min_confidence: float = 0.0
) -> dict:
"""Optionally drop low-quality traces before writing face_traced.json.
A trace is dropped when:
- its path length (total_appearances) < min_trace_len, OR
- its avg_confidence < min_confidence (only when min_confidence > 0).
For every dropped trace, the corresponding faces in `frames` have their
`trace_id` set to None (NOT deleted) so frames/traces stay consistent and
downstream readers (`trace_id is None` → skip) are unaffected. Trace ids of
surviving traces are NOT renumbered.
Both thresholds default to "no filtering" so existing behaviour is unchanged
unless the caller opts in (env vars / CLI flags).
"""
traces = face_data.get("traces", {})
if not traces or (min_trace_len <= 0 and min_confidence <= 0.0):
return face_data
drop_ids = set()
for tid_str, trace in traces.items():
appearances = trace.get("total_appearances", len(trace.get("path", [])))
avg_conf = trace.get("avg_confidence", 1.0)
if appearances < min_trace_len:
drop_ids.add(tid_str)
elif min_confidence > 0.0 and avg_conf < min_confidence:
drop_ids.add(tid_str)
if not drop_ids:
return face_data
# Remove dropped traces from the traces dict
for tid_str in drop_ids:
traces.pop(tid_str, None)
# Clear trace_id on frames for dropped traces (keep the face detection itself)
drop_ints = {int(t) for t in drop_ids}
for frame_data in face_data.get("frames", {}).values():
for face in frame_data.get("faces", []):
if face.get("trace_id") in drop_ints:
face["trace_id"] = None
print(
f"[TRACE] Quality filter: dropped {len(drop_ids)} traces "
f"(min_trace_len={min_trace_len}, min_confidence={min_confidence}), "
f"kept {len(traces)}"
)
return face_data
def run_face_tracker(
face_json_path: str, traced_json_path: str, filter_eyes: bool = False
) -> str:
"""Run face_tracker.py on face.json, returns path to face_traced.json"""
from face_tracker import track_faces
with open(face_json_path) as f:
face_data = json.load(f)
# Check if faces already have trace_id (from Rust face_tracker)
frames_to_check = face_data.get("frames", {})
if isinstance(frames_to_check, list):
# List format (FaceResult)
has_trace = any(
face.get("trace_id") is not None
for frame in frames_to_check
for face in frame.get("faces", [])
)
else:
# Dict format (legacy)
has_trace = any(
face.get("trace_id") is not None
for frame_data in frames_to_check.values()
for face in frame_data.get("faces", [])
)
if has_trace:
print(f"[TRACE] face.json already contains trace_id, skipping tracking")
# Copy face.json to traced_json_path (no re-tracking needed)
import shutil
shutil.copy(face_json_path, traced_json_path)
return traced_json_path
# V2.0 uses list format (FaceResult), convert to dict for face_tracker
if isinstance(face_data.get("frames"), list):
frames_dict = {}
for frame in face_data["frames"]:
fnum = str(frame["frame"])
faces = []
for f in frame.get("faces", []):
bbox = f.get("bbox", f)
face = {
"x": bbox.get("x", f.get("x", 0)),
"y": bbox.get("y", f.get("y", 0)),
"width": bbox.get("width", f.get("width", 0)),
"height": bbox.get("height", f.get("height", 0)),
"confidence": f.get("confidence", 0.0),
"captureQuality": f.get("captureQuality", 0.0),
}
if "landmarks" in f:
face["landmarks"] = f["landmarks"]
if "embedding" in f:
face["embedding"] = f["embedding"]
faces.append(face)
frames_dict[fnum] = {
"frame_number": frame["frame"],
"time_seconds": frame.get("timestamp", 0),
"faces": faces,
}
face_data["frames"] = frames_dict
# Preserve metadata (fps needed by face_tracker)
if "metadata" not in face_data:
face_data["metadata"] = {
"fps": face_data.get("fps", 30.0),
"total_frames": face_data.get("frame_count", 0),
}
# Eye filter: remove faces without at least one eye landmark
if filter_eyes:
removed = 0
for fnum_str, frm_data in face_data.get("frames", {}).items():
faces = frm_data.get("faces", [])
kept = []
for face in faces:
lm = face.get("landmarks", {})
if len(lm.get("left_eye", [])) > 0 or len(lm.get("right_eye", [])) > 0:
kept.append(face)
else:
removed += 1
frm_data["faces"] = kept
print(f"[TRACE] Eye filter: {removed} faces without eyes removed")
print(f"[TRACE] Processing {len(face_data.get('frames', {}))} frames")
# Load embeddings from Qdrant _faces collection
file_uuid = (
face_json_path.split("/")[-1]
.replace(".face.json", "")
.replace("_traced.json", "")
)
print(f"[TRACE] Loading embeddings from Qdrant for {file_uuid}...")
try:
from qdrant_faces import get_file_faces
qdrant_points = get_file_faces(file_uuid, with_vector=True)
# Build lookup: (frame, x, y) -> embedding
emb_lookup = {}
for p in qdrant_points:
pl = p.get("payload", {})
frame = pl.get("frame")
bbox = pl.get("bbox", {})
x, y = bbox.get("x"), bbox.get("y")
vec = p.get("vector")
if frame is not None and vec:
emb_lookup[(frame, x, y)] = vec
print(f"[TRACE] Loaded {len(emb_lookup)} embeddings from Qdrant")
# Attach embeddings to face data
attached = 0
for fnum_str, frm_data in face_data.get("frames", {}).items():
fnum = int(fnum_str)
for face in frm_data.get("faces", []):
key = (fnum, face.get("x"), face.get("y"))
if key in emb_lookup:
face["embedding"] = emb_lookup[key]
attached += 1
print(f"[TRACE] Attached {attached} embeddings to face data")
except Exception as e:
print(f"[TRACE] Warning: Failed to load embeddings from Qdrant: {e}")
# Load cut boundaries from cut.json (same directory as face.json)
cut_boundaries = None
cut_scenes = None
cuts_path = face_json_path.replace("_traced.json", ".cut.json").replace(
".face.json", ".cut.json"
)
if os.path.exists(cuts_path):
with open(cuts_path) as f:
cuts = json.load(f)
cut_scenes = cuts.get("scenes", [])
cut_boundaries = {s["start_frame"] for s in cut_scenes if s["start_frame"] > 0}
print(f"[TRACE] Loaded {len(cut_boundaries)} cut boundaries")
face_data = track_faces(
face_data, use_embedding=True, cut_boundaries=cut_boundaries
)
# Merge traces within same cut (same person re-appearing after occlusion/pose change)
if cut_scenes and len(cut_scenes) > 0:
face_data = merge_traces_within_cuts(face_data, cut_scenes)
# Optional quality filter (opt-in via env; both default to 0 = disabled).
min_trace_len = int(os.environ.get("MOMENTRY_FACE_MIN_TRACE_LEN", "0"))
min_confidence = float(os.environ.get("MOMENTRY_FACE_MIN_CONFIDENCE", "0.0"))
if min_trace_len > 0 or min_confidence > 0.0:
face_data = filter_traces(face_data, min_trace_len, min_confidence)
metadata = face_data.get("metadata", {})
metadata["tracking_method"] = "iou_only"
metadata["tracked_at"] = datetime.now().isoformat()
face_data["metadata"] = metadata
with open(traced_json_path, "w") as f:
json.dump(
strip_embeddings_and_round(face_data), f, indent=2, ensure_ascii=False
)
trace_count = len(face_data.get("traces", {}))
print(f"[TRACE] Completed: {trace_count} traces -> {traced_json_path}")
return traced_json_path
def store_traced_faces(file_uuid: str, traced_json_path: str, schema: str = SCHEMA):
"""Update Qdrant _faces collection with trace_id after face tracking.
face_detections table is deprecated — trace_id is stored only in Qdrant _faces payload.
"""
with open(traced_json_path) as f:
data = json.load(f)
frames = data.get("frames", {})
# Build trace_mapping for Qdrant update: {frame: {bbox_key: trace_id}}
trace_mapping = {}
for frame_num_str, frame_data in sorted(frames.items(), key=lambda x: int(x[0])):
frame_num = int(frame_num_str)
trace_mapping[frame_num] = {}
for face in frame_data.get("faces", []):
trace_id = face.get("trace_id")
if trace_id is None:
continue
bbox_key = f"{face['x']}_{face['y']}_{face['width']}_{face['height']}"
trace_mapping[frame_num][bbox_key] = trace_id
# Update Qdrant _faces collection with trace_id.
# return_trace_ids=True makes update_trace_ids also return the trace_id set seen
# during its scroll, so we avoid a redundant third full-collection scan below.
trace_ids = set()
try:
qdrant_updated, trace_ids = update_trace_ids(
file_uuid, trace_mapping, return_trace_ids=True
)
except Exception as e:
print(f"[TRACE] Warning: Qdrant trace_id update failed: {e}")
qdrant_updated = 0
# Unique trace count from the update scroll (no extra full scan needed).
qdrant_trace_count = len(trace_ids)
total_faces = sum(
1
for fd in frames.values()
for f in fd.get("faces", [])
if f.get("trace_id") is not None
)
print(
f"[TRACE] Updated {qdrant_updated} Qdrant points with trace_id, {qdrant_trace_count} unique traces"
)
return total_faces, qdrant_trace_count
def main():
parser = argparse.ArgumentParser(description="Store traced faces in DB")
parser.add_argument("--file-uuid", required=True, help="Video file UUID")
parser.add_argument("--face-json", help="Path to face.json (default: auto-detect)")
parser.add_argument("--uuid", help="UUID for Redis tracking (accepted by executor)")
parser.add_argument(
"--filter-eyes",
action="store_true",
help="Remove faces without eye landmarks before tracking",
)
args = parser.parse_args()
face_json = args.face_json or os.path.join(
OUTPUT_DIR, f"{args.file_uuid}.face.json"
)
traced_json = os.path.join(OUTPUT_DIR, f"{args.file_uuid}.face_traced.json")
if not os.path.exists(face_json):
print(f"[TRACE] face.json not found: {face_json}", file=sys.stderr)
sys.exit(1)
# Step 1: Run face tracker
run_face_tracker(face_json, traced_json, filter_eyes=args.filter_eyes)
# Step 2: Store in Qdrant with trace_id
total, traces = store_traced_faces(args.file_uuid, traced_json)
print(f"[TRACE] Done: {total} detections, {traces} traces")
if __name__ == "__main__":
main()
+519
View File
@@ -0,0 +1,519 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Agent - Multi-Evidence Identity Inference
Core Logic:
1. Time Overlap Matching (Speaker vs Person frames)
2. Embedding Similarity Calculation
3. Multi-Evidence Fusion
4. LLM Inference for Ambiguous Cases
5. Identity Assignment
Usage:
python3 scripts/identity_agent.py --video-uuid <uuid> --analyze
python3 scripts/identity_agent.py --video-uuid <uuid> --suggest
"""
import sys
import json
import argparse
import os
import numpy as np
from typing import Dict, List, Optional, Tuple
from sklearn.metrics.pairwise import cosine_similarity
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
class IdentityAgent:
"""
Identity Agent for Multi-Evidence Identity Inference
Attributes:
video_uuid (str): Video UUID
output_dir (str): Output directory
fps (float): Video frame rate
auto_merge_threshold (float): Auto merge threshold (default: 0.8)
llm_threshold (float): LLM inference threshold (default: 0.5)
face_similarity_threshold (float): Face similarity threshold (default: 0.3)
use_llm (bool): Use LLM for ambiguous cases
model (str): LLM model name
"""
def __init__(
self,
video_uuid: str,
output_dir: str = None,
auto_merge_threshold: float = 0.8,
llm_threshold: float = 0.5,
face_similarity_threshold: float = 0.3,
use_llm: bool = True,
model: str = "gemma4",
):
self.video_uuid = video_uuid
self.output_dir = output_dir or os.getenv(
"MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev"
)
self.auto_merge_threshold = auto_merge_threshold
self.llm_threshold = llm_threshold
self.face_similarity_threshold = face_similarity_threshold
self.use_llm = use_llm
self.model = model
self.fps = 23.976 # Default FPS
self.face_data = None
self.asrx_data = None
self.persons = []
self.speakers = []
self.identities = []
self.publisher = RedisPublisher(video_uuid) if video_uuid else None
def load_data(self) -> bool:
"""Load face clustered and ASRX data from files"""
video_dir = os.path.join(self.output_dir, self.video_uuid)
face_clustered_path = os.path.join(
video_dir, f"{self.video_uuid}.face_clustered.json"
)
asrx_path = os.path.join(video_dir, f"{self.video_uuid}.asrx.json")
probe_path = os.path.join(video_dir, f"{self.video_uuid}.probe.json")
if not os.path.exists(face_clustered_path):
print(f"Error: Face clustered data not found: {face_clustered_path}")
return False
self.face_data = self._load_json(face_clustered_path)
self.asrx_data = self._load_json(asrx_path) if os.path.exists(asrx_path) else None
if os.path.exists(probe_path):
probe_data = self._load_json(probe_path)
self.fps = probe_data.get("fps", 23.976)
self.persons = self._extract_persons()
self.speakers = self._extract_speakers()
print(f"Loaded {len(self.persons)} persons, {len(self.speakers)} speakers")
return True
def _load_json(self, path: str) -> Dict:
"""Load JSON file"""
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def _extract_persons(self) -> List[Dict]:
"""Extract persons from face clustered data"""
persons = []
if not self.face_data:
return persons
if "clusters" in self.face_data:
for cluster in self.face_data["clusters"]:
person_id = cluster.get("person_id", f"Person_{len(persons) + 1}")
frames = cluster.get("frames", [])
avg_embedding = cluster.get("avg_embedding", None)
persons.append({
"person_id": person_id,
"frames": frames,
"frame_count": len(frames),
"avg_embedding": avg_embedding,
"timestamps": [f / self.fps for f in frames],
})
return persons
def _extract_speakers(self) -> List[Dict]:
"""Extract speakers from ASRX data"""
speakers = []
if not self.asrx_data:
return speakers
if "segments" in self.asrx_data:
speaker_segments_map = {}
for segment in self.asrx_data["segments"]:
speaker_id = segment.get("speaker", "SPEAKER_01")
start = segment.get("start", 0.0)
end = segment.get("end", 0.0)
if speaker_id not in speaker_segments_map:
speaker_segments_map[speaker_id] = []
speaker_segments_map[speaker_id].append({"start": start, "end": end})
for speaker_id, segments in speaker_segments_map.items():
total_duration = sum(s["end"] - s["start"] for s in segments)
speakers.append({
"speaker_id": speaker_id,
"segments": segments,
"total_duration": total_duration,
})
return speakers
def calculate_speaker_person_overlap(
self, person: Dict, speaker: Dict
) -> Tuple[int, float]:
"""
Calculate overlap between Person and Speaker
Returns:
Tuple of (overlap_frames, overlap_ratio)
"""
overlap_frames = 0
for frame in person["frames"]:
frame_time = frame / self.fps
for segment in speaker["segments"]:
if segment["start"] <= frame_time <= segment["end"]:
overlap_frames += 1
break
overlap_ratio = overlap_frames / person["frame_count"] if person["frame_count"] > 0 else 0
return overlap_frames, overlap_ratio
def calculate_person_similarity(
self, person1: Dict, person2: Dict
) -> Optional[float]:
"""
Calculate cosine similarity between two Person embeddings
Returns:
Similarity score (0-1) or None if embeddings not available
"""
if not person1.get("avg_embedding") or not person2.get("avg_embedding"):
return None
emb1 = np.array(person1["avg_embedding"]).reshape(1, -1)
emb2 = np.array(person2["avg_embedding"]).reshape(1, -1)
similarity = cosine_similarity(emb1, emb2)[0][0]
return similarity
def fuse_evidence(
self,
face_similarity: Optional[float],
speaker_overlap: float,
time_overlap: float,
frame_ratio: float,
) -> float:
"""
Fuse multiple evidence sources into a single confidence score
Args:
face_similarity: Cosine similarity between face embeddings (0-1)
speaker_overlap: Speaker-Person overlap ratio (0-1)
time_overlap: Temporal overlap ratio (0-1)
frame_ratio: Person's frame count ratio in video (0-1)
Returns:
Fused confidence score (0-1)
"""
weights = {
"face": 0.4,
"speaker": 0.3,
"time": 0.2,
"frame": 0.1,
}
face_score = face_similarity if face_similarity is not None else 0.5
confidence = (
weights["face"] * face_score
+ weights["speaker"] * speaker_overlap
+ weights["time"] * time_overlap
+ weights["frame"] * frame_ratio
)
return confidence
def analyze(self) -> Dict:
"""
Analyze video identity
Returns:
Identity analysis result
"""
if not self.load_data():
return {"success": False, "error": "Failed to load data"}
if self.publisher:
self.publisher.info("identity", "IDENTITY_ANALYZE_START")
identities = []
for i, person in enumerate(self.persons):
identity_id = f"identity_{i + 1}"
speaker_overlaps = []
max_overlap = 0.0
max_speaker_id = None
for speaker in self.speakers:
overlap_frames, overlap_ratio = self.calculate_speaker_person_overlap(
person, speaker
)
if overlap_ratio > 0.3:
speaker_overlaps.append({
"speaker_id": speaker["speaker_id"],
"overlap_frames": overlap_frames,
"overlap_ratio": overlap_ratio,
})
if overlap_ratio > max_overlap:
max_overlap = overlap_ratio
max_speaker_id = speaker["speaker_id"]
frame_ratio = person["frame_count"] / max(p["frame_count"] for p in self.persons)
confidence = self.fuse_evidence(
face_similarity=None,
speaker_overlap=max_overlap,
time_overlap=max_overlap,
frame_ratio=frame_ratio,
)
identity = {
"identity_id": identity_id,
"person_ids": [person["person_id"]],
"speaker_ids": [s["speaker_id"] for s in speaker_overlaps],
"confidence": confidence,
"evidence": {
"face_similarity": None,
"speaker_overlap": max_overlap,
"time_overlap": max_overlap,
"frame_ratio": frame_ratio,
},
"reasoning": f"Person {person['person_id']} has {max_overlap:.0%} overlap with {max_speaker_id or 'no speaker'}",
}
identities.append(identity)
if self.publisher:
self.publisher.info("identity", f"IDENTITY_ANALYZE_COMPLETE:{len(identities)}")
return {
"success": True,
"video_uuid": self.video_uuid,
"identities": identities,
"processing_status": {
"status": "completed",
"persons_analyzed": len(self.persons),
"identities_created": len(identities),
"merges_suggested": 0,
},
}
def suggest_merges(self) -> Dict:
"""
Suggest Identity merges
Returns:
Merge suggestions
"""
analyze_result = self.analyze()
if not analyze_result.get("success"):
return analyze_result
identities = analyze_result["identities"]
merge_suggestions = []
for identity in identities:
if len(identity["person_ids"]) >= 1 and len(identity["speaker_ids"]) >= 1:
confidence = identity["confidence"]
if confidence > self.auto_merge_threshold:
action = "auto_apply"
elif confidence > self.llm_threshold:
action = "review_needed"
else:
continue
reasons = [
f"Shared speaker overlap: {identity['evidence']['speaker_overlap']:.0%}",
f"Confidence: {confidence:.2f}",
]
merge_suggestions.append({
"target_person_id": identity["person_ids"][0],
"source_person_ids": identity["person_ids"][1:] if len(identity["person_ids"]) > 1 else [],
"confidence": confidence,
"reasons": reasons,
"action": action,
})
return {
"success": True,
"video_uuid": self.video_uuid,
"merge_suggestions": merge_suggestions,
"naming_suggestions": [],
}
def call_llm(self, prompt: str) -> Dict:
"""
Call LLM for inference
Args:
prompt: LLM prompt
Returns:
LLM response
"""
import requests
ollama_url = "http://localhost:11434/api/generate"
body = {
"model": self.model,
"prompt": prompt,
"stream": False,
}
try:
response = requests.post(ollama_url, json=body, timeout=30)
result = response.json()
llm_output = result.get("response", "")
try:
parsed = json.loads(llm_output)
return parsed
except json.JSONDecodeError:
return {
"decision": "keep_separate",
"confidence": 0.5,
"reasoning": llm_output,
}
except Exception as e:
print(f"LLM call failed: {e}")
return {
"decision": "keep_separate",
"confidence": 0.5,
"reasoning": f"LLM call failed: {e}",
}
def llm_identity_inference(self, evidence: Dict) -> Dict:
"""
Use LLM to infer identity for ambiguous cases
Args:
evidence: Multi-evidence data
Returns:
LLM inference result
"""
confidence = evidence.get("confidence", 0.5)
if confidence > self.auto_merge_threshold:
return {
"decision": "merge",
"confidence": confidence,
"reasoning": f"High confidence ({confidence:.2f}) - auto merge",
}
if confidence < self.llm_threshold:
return {
"decision": "keep_separate",
"confidence": confidence,
"reasoning": f"Low confidence ({confidence:.2f}) - keep separate",
}
if not self.use_llm:
return {
"decision": "review_needed",
"confidence": confidence,
"reasoning": "Medium confidence - manual review required",
}
prompt = f"""
You are an identity analyst for a video analysis system.
Given the following evidence:
- Face similarity: {evidence.get('face_similarity', 'N/A')}
- Speaker overlap: {evidence.get('speaker_overlap', 0):.2f}
- Time overlap: {evidence.get('time_overlap', 0):.2f}
- Frame ratio: {evidence.get('frame_ratio', 0):.2f}
- Person: {evidence.get('person_id', 'Unknown')} ({evidence.get('frame_count', 0)} frames)
- Shared speaker: {evidence.get('shared_speaker', 'None')}
Should this person be merged with other persons sharing the same speaker?
Provide:
1. Decision: "merge" or "keep_separate"
2. Confidence: 0.0-1.0
3. Reasoning: 1-2 sentences explaining your decision
Output in JSON format only:
{{
"decision": "merge" or "keep_separate",
"confidence": 0.85,
"reasoning": "..."
}}
"""
return self.call_llm(prompt)
def main():
parser = argparse.ArgumentParser(description="Identity Agent - Multi-Evidence Identity Inference")
parser.add_argument("--video-uuid", "-u", help="Video UUID", required=True)
parser.add_argument("--output-dir", "-o", help="Output directory", default=None)
parser.add_argument(
"--analyze", "-a", help="Analyze video identity", action="store_true"
)
parser.add_argument(
"--suggest", "-s", help="Suggest Identity merges", action="store_true"
)
parser.add_argument(
"--auto-merge-threshold",
"-t",
help="Auto merge threshold",
type=float,
default=0.8,
)
parser.add_argument(
"--llm-threshold",
"-l",
help="LLM inference threshold",
type=float,
default=0.5,
)
parser.add_argument(
"--use-llm", help="Use LLM for ambiguous cases", action="store_true"
)
parser.add_argument("--model", "-m", help="LLM model", default="gemma4")
args = parser.parse_args()
agent = IdentityAgent(
video_uuid=args.video_uuid,
output_dir=args.output_dir,
auto_merge_threshold=args.auto_merge_threshold,
llm_threshold=args.llm_threshold,
use_llm=args.use_llm,
model=args.model,
)
if args.analyze:
result = agent.analyze()
print(json.dumps(result, indent=2))
if args.suggest:
result = agent.suggest_merges()
print(json.dumps(result, indent=2))
if not args.analyze and not args.suggest:
print("Please specify --analyze or --suggest")
if __name__ == "__main__":
main()
@@ -0,0 +1,519 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Agent - Multi-Evidence Identity Inference
Core Logic:
1. Time Overlap Matching (Speaker vs Person frames)
2. Embedding Similarity Calculation
3. Multi-Evidence Fusion
4. LLM Inference for Ambiguous Cases
5. Identity Assignment
Usage:
python3 scripts/identity_agent.py --video-uuid <uuid> --analyze
python3 scripts/identity_agent.py --video-uuid <uuid> --suggest
"""
import sys
import json
import argparse
import os
import numpy as np
from typing import Dict, List, Optional, Tuple
from sklearn.metrics.pairwise import cosine_similarity
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
class IdentityAgent:
"""
Identity Agent for Multi-Evidence Identity Inference
Attributes:
video_uuid (str): Video UUID
output_dir (str): Output directory
fps (float): Video frame rate
auto_merge_threshold (float): Auto merge threshold (default: 0.8)
llm_threshold (float): LLM inference threshold (default: 0.5)
face_similarity_threshold (float): Face similarity threshold (default: 0.3)
use_llm (bool): Use LLM for ambiguous cases
model (str): LLM model name
"""
def __init__(
self,
video_uuid: str,
output_dir: str = None,
auto_merge_threshold: float = 0.8,
llm_threshold: float = 0.5,
face_similarity_threshold: float = 0.3,
use_llm: bool = True,
model: str = "gemma4",
):
self.video_uuid = video_uuid
self.output_dir = output_dir or os.getenv(
"MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output_dev"
)
self.auto_merge_threshold = auto_merge_threshold
self.llm_threshold = llm_threshold
self.face_similarity_threshold = face_similarity_threshold
self.use_llm = use_llm
self.model = model
self.fps = 23.976 # Default FPS
self.face_data = None
self.asrx_data = None
self.persons = []
self.speakers = []
self.identities = []
self.publisher = RedisPublisher(video_uuid) if video_uuid else None
def load_data(self) -> bool:
"""Load face clustered and ASRX data from files"""
video_dir = os.path.join(self.output_dir, self.video_uuid)
face_clustered_path = os.path.join(
video_dir, f"{self.video_uuid}.face_clustered.json"
)
asrx_path = os.path.join(video_dir, f"{self.video_uuid}.asrx.json")
probe_path = os.path.join(video_dir, f"{self.video_uuid}.probe.json")
if not os.path.exists(face_clustered_path):
print(f"Error: Face clustered data not found: {face_clustered_path}")
return False
self.face_data = self._load_json(face_clustered_path)
self.asrx_data = self._load_json(asrx_path) if os.path.exists(asrx_path) else None
if os.path.exists(probe_path):
probe_data = self._load_json(probe_path)
self.fps = probe_data.get("fps", 23.976)
self.persons = self._extract_persons()
self.speakers = self._extract_speakers()
print(f"Loaded {len(self.persons)} persons, {len(self.speakers)} speakers")
return True
def _load_json(self, path: str) -> Dict:
"""Load JSON file"""
with open(path, "r", encoding="utf-8") as f:
return json.load(f)
def _extract_persons(self) -> List[Dict]:
"""Extract persons from face clustered data"""
persons = []
if not self.face_data:
return persons
if "clusters" in self.face_data:
for cluster in self.face_data["clusters"]:
person_id = cluster.get("person_id", f"Person_{len(persons) + 1}")
frames = cluster.get("frames", [])
avg_embedding = cluster.get("avg_embedding", None)
persons.append({
"person_id": person_id,
"frames": frames,
"frame_count": len(frames),
"avg_embedding": avg_embedding,
"timestamps": [f / self.fps for f in frames],
})
return persons
def _extract_speakers(self) -> List[Dict]:
"""Extract speakers from ASRX data"""
speakers = []
if not self.asrx_data:
return speakers
if "segments" in self.asrx_data:
speaker_segments_map = {}
for segment in self.asrx_data["segments"]:
speaker_id = segment.get("speaker", "SPEAKER_01")
start = segment.get("start", 0.0)
end = segment.get("end", 0.0)
if speaker_id not in speaker_segments_map:
speaker_segments_map[speaker_id] = []
speaker_segments_map[speaker_id].append({"start": start, "end": end})
for speaker_id, segments in speaker_segments_map.items():
total_duration = sum(s["end"] - s["start"] for s in segments)
speakers.append({
"speaker_id": speaker_id,
"segments": segments,
"total_duration": total_duration,
})
return speakers
def calculate_speaker_person_overlap(
self, person: Dict, speaker: Dict
) -> Tuple[int, float]:
"""
Calculate overlap between Person and Speaker
Returns:
Tuple of (overlap_frames, overlap_ratio)
"""
overlap_frames = 0
for frame in person["frames"]:
frame_time = frame / self.fps
for segment in speaker["segments"]:
if segment["start"] <= frame_time <= segment["end"]:
overlap_frames += 1
break
overlap_ratio = overlap_frames / person["frame_count"] if person["frame_count"] > 0 else 0
return overlap_frames, overlap_ratio
def calculate_person_similarity(
self, person1: Dict, person2: Dict
) -> Optional[float]:
"""
Calculate cosine similarity between two Person embeddings
Returns:
Similarity score (0-1) or None if embeddings not available
"""
if not person1.get("avg_embedding") or not person2.get("avg_embedding"):
return None
emb1 = np.array(person1["avg_embedding"]).reshape(1, -1)
emb2 = np.array(person2["avg_embedding"]).reshape(1, -1)
similarity = cosine_similarity(emb1, emb2)[0][0]
return similarity
def fuse_evidence(
self,
face_similarity: Optional[float],
speaker_overlap: float,
time_overlap: float,
frame_ratio: float,
) -> float:
"""
Fuse multiple evidence sources into a single confidence score
Args:
face_similarity: Cosine similarity between face embeddings (0-1)
speaker_overlap: Speaker-Person overlap ratio (0-1)
time_overlap: Temporal overlap ratio (0-1)
frame_ratio: Person's frame count ratio in video (0-1)
Returns:
Fused confidence score (0-1)
"""
weights = {
"face": 0.4,
"speaker": 0.3,
"time": 0.2,
"frame": 0.1,
}
face_score = face_similarity if face_similarity is not None else 0.5
confidence = (
weights["face"] * face_score
+ weights["speaker"] * speaker_overlap
+ weights["time"] * time_overlap
+ weights["frame"] * frame_ratio
)
return confidence
def analyze(self) -> Dict:
"""
Analyze video identity
Returns:
Identity analysis result
"""
if not self.load_data():
return {"success": False, "error": "Failed to load data"}
if self.publisher:
self.publisher.info("identity", "IDENTITY_ANALYZE_START")
identities = []
for i, person in enumerate(self.persons):
identity_id = f"identity_{i + 1}"
speaker_overlaps = []
max_overlap = 0.0
max_speaker_id = None
for speaker in self.speakers:
overlap_frames, overlap_ratio = self.calculate_speaker_person_overlap(
person, speaker
)
if overlap_ratio > 0.3:
speaker_overlaps.append({
"speaker_id": speaker["speaker_id"],
"overlap_frames": overlap_frames,
"overlap_ratio": overlap_ratio,
})
if overlap_ratio > max_overlap:
max_overlap = overlap_ratio
max_speaker_id = speaker["speaker_id"]
frame_ratio = person["frame_count"] / max(p["frame_count"] for p in self.persons)
confidence = self.fuse_evidence(
face_similarity=None,
speaker_overlap=max_overlap,
time_overlap=max_overlap,
frame_ratio=frame_ratio,
)
identity = {
"identity_id": identity_id,
"person_ids": [person["person_id"]],
"speaker_ids": [s["speaker_id"] for s in speaker_overlaps],
"confidence": confidence,
"evidence": {
"face_similarity": None,
"speaker_overlap": max_overlap,
"time_overlap": max_overlap,
"frame_ratio": frame_ratio,
},
"reasoning": f"Person {person['person_id']} has {max_overlap:.0%} overlap with {max_speaker_id or 'no speaker'}",
}
identities.append(identity)
if self.publisher:
self.publisher.info("identity", f"IDENTITY_ANALYZE_COMPLETE:{len(identities)}")
return {
"success": True,
"video_uuid": self.video_uuid,
"identities": identities,
"processing_status": {
"status": "completed",
"persons_analyzed": len(self.persons),
"identities_created": len(identities),
"merges_suggested": 0,
},
}
def suggest_merges(self) -> Dict:
"""
Suggest Identity merges
Returns:
Merge suggestions
"""
analyze_result = self.analyze()
if not analyze_result.get("success"):
return analyze_result
identities = analyze_result["identities"]
merge_suggestions = []
for identity in identities:
if len(identity["person_ids"]) >= 1 and len(identity["speaker_ids"]) >= 1:
confidence = identity["confidence"]
if confidence > self.auto_merge_threshold:
action = "auto_apply"
elif confidence > self.llm_threshold:
action = "review_needed"
else:
continue
reasons = [
f"Shared speaker overlap: {identity['evidence']['speaker_overlap']:.0%}",
f"Confidence: {confidence:.2f}",
]
merge_suggestions.append({
"target_person_id": identity["person_ids"][0],
"source_person_ids": identity["person_ids"][1:] if len(identity["person_ids"]) > 1 else [],
"confidence": confidence,
"reasons": reasons,
"action": action,
})
return {
"success": True,
"video_uuid": self.video_uuid,
"merge_suggestions": merge_suggestions,
"naming_suggestions": [],
}
def call_llm(self, prompt: str) -> Dict:
"""
Call LLM for inference
Args:
prompt: LLM prompt
Returns:
LLM response
"""
import requests
ollama_url = "http://localhost:11434/api/generate"
body = {
"model": self.model,
"prompt": prompt,
"stream": False,
}
try:
response = requests.post(ollama_url, json=body, timeout=30)
result = response.json()
llm_output = result.get("response", "")
try:
parsed = json.loads(llm_output)
return parsed
except json.JSONDecodeError:
return {
"decision": "keep_separate",
"confidence": 0.5,
"reasoning": llm_output,
}
except Exception as e:
print(f"LLM call failed: {e}")
return {
"decision": "keep_separate",
"confidence": 0.5,
"reasoning": f"LLM call failed: {e}",
}
def llm_identity_inference(self, evidence: Dict) -> Dict:
"""
Use LLM to infer identity for ambiguous cases
Args:
evidence: Multi-evidence data
Returns:
LLM inference result
"""
confidence = evidence.get("confidence", 0.5)
if confidence > self.auto_merge_threshold:
return {
"decision": "merge",
"confidence": confidence,
"reasoning": f"High confidence ({confidence:.2f}) - auto merge",
}
if confidence < self.llm_threshold:
return {
"decision": "keep_separate",
"confidence": confidence,
"reasoning": f"Low confidence ({confidence:.2f}) - keep separate",
}
if not self.use_llm:
return {
"decision": "review_needed",
"confidence": confidence,
"reasoning": "Medium confidence - manual review required",
}
prompt = f"""
You are an identity analyst for a video analysis system.
Given the following evidence:
- Face similarity: {evidence.get('face_similarity', 'N/A')}
- Speaker overlap: {evidence.get('speaker_overlap', 0):.2f}
- Time overlap: {evidence.get('time_overlap', 0):.2f}
- Frame ratio: {evidence.get('frame_ratio', 0):.2f}
- Person: {evidence.get('person_id', 'Unknown')} ({evidence.get('frame_count', 0)} frames)
- Shared speaker: {evidence.get('shared_speaker', 'None')}
Should this person be merged with other persons sharing the same speaker?
Provide:
1. Decision: "merge" or "keep_separate"
2. Confidence: 0.0-1.0
3. Reasoning: 1-2 sentences explaining your decision
Output in JSON format only:
{{
"decision": "merge" or "keep_separate",
"confidence": 0.85,
"reasoning": "..."
}}
"""
return self.call_llm(prompt)
def main():
parser = argparse.ArgumentParser(description="Identity Agent - Multi-Evidence Identity Inference")
parser.add_argument("--video-uuid", "-u", help="Video UUID", required=True)
parser.add_argument("--output-dir", "-o", help="Output directory", default=None)
parser.add_argument(
"--analyze", "-a", help="Analyze video identity", action="store_true"
)
parser.add_argument(
"--suggest", "-s", help="Suggest Identity merges", action="store_true"
)
parser.add_argument(
"--auto-merge-threshold",
"-t",
help="Auto merge threshold",
type=float,
default=0.8,
)
parser.add_argument(
"--llm-threshold",
"-l",
help="LLM inference threshold",
type=float,
default=0.5,
)
parser.add_argument(
"--use-llm", help="Use LLM for ambiguous cases", action="store_true"
)
parser.add_argument("--model", "-m", help="LLM model", default="gemma4")
args = parser.parse_args()
agent = IdentityAgent(
video_uuid=args.video_uuid,
output_dir=args.output_dir,
auto_merge_threshold=args.auto_merge_threshold,
llm_threshold=args.llm_threshold,
use_llm=args.use_llm,
model=args.model,
)
if args.analyze:
result = agent.analyze()
print(json.dumps(result, indent=2))
if args.suggest:
result = agent.suggest_merges()
print(json.dumps(result, indent=2))
if not args.analyze and not args.suggest:
print("Please specify --analyze or --suggest")
if __name__ == "__main__":
main()
+129
View File
@@ -0,0 +1,129 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Binding: cluster face traces → identity bindings.
Uses face embeddings from face_detections, clusters per trace, creates identities.
"""
import json, sys, time
import psycopg2
import numpy as np
from sklearn.cluster import AgglomerativeClustering
UUID = sys.argv[1] if len(sys.argv) > 1 else "23b1c872379d4ec06479e5ed39eef4c5"
DB = "dbname=momentry user=accusys"
DISTANCE_THRESHOLD = 0.55 # Cosine distance threshold for clustering
print(f"=== Identity Binding for {UUID} ===")
conn = psycopg2.connect(DB)
cur = conn.cursor()
# Step 1: Get trace embeddings from face_detections
print("Loading face trace data...")
cur.execute("""
SELECT trace_id, embedding
FROM dev.face_detections
WHERE file_uuid = %s AND trace_id IS NOT NULL AND embedding IS NOT NULL
ORDER BY trace_id, id
""", (UUID,))
rows = cur.fetchall()
print(f"Face detections with embeddings: {len(rows)}")
# Group by trace_id and compute average embedding
trace_embs = {}
for trace_id, emb in rows:
if trace_id not in trace_embs:
trace_embs[trace_id] = []
trace_embs[trace_id].append(emb)
print(f"Unique traces: {len(trace_embs)}")
# Compute mean embeddings per trace
trace_ids = []
trace_vectors = []
for tid, embs in sorted(trace_embs.items()):
mean_emb = np.mean(embs, axis=0)
mean_emb = mean_emb / (np.linalg.norm(mean_emb) + 1e-10)
trace_ids.append(tid)
trace_vectors.append(mean_emb)
X = np.array(trace_vectors)
print(f"Trace vectors shape: {X.shape}")
# Step 2: Cluster traces
print("Clustering traces...")
if len(X) > 1:
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=DISTANCE_THRESHOLD,
metric='cosine',
linkage='average'
)
labels = clustering.fit_predict(X)
else:
labels = [0]
n_clusters = len(set(labels))
print(f"Clusters/identities: {n_clusters}")
# Step 3: Get or create identity records
print("Creating identity records...")
# Get existing identities
cur.execute("SELECT id, uuid FROM dev.identities")
existing = {row[0]: row[1] for row in cur.fetchall()}
# Map cluster -> identity_id
cluster_to_identity = {}
for cluster_id in sorted(set(labels)):
# Create new identity
identity_uuid = None
cur.execute("""
INSERT INTO dev.identities (name, identity_type, source, status, created_at, file_uuid)
VALUES (%s, 'face', 'auto', 'active', NOW(), %s)
ON CONFLICT (name) DO UPDATE SET status = 'active', file_uuid = COALESCE(dev.identities.file_uuid, %s)
RETURNING id
""", (f"stranger_{UUID}_{cluster_id}", UUID, UUID))
identity_id = cur.fetchone()[0]
cluster_to_identity[cluster_id] = identity_id
print(f" Cluster {cluster_id}: new identity {identity_id} (stranger_{UUID}_{cluster_id})")
# Step 4: Create identity bindings
print("Creating identity bindings...")
bindings = 0
for tid, label in zip(trace_ids, labels):
identity_id = cluster_to_identity[label]
# Get a representative face_id for this trace
cur.execute("""
SELECT face_id FROM dev.face_detections
WHERE file_uuid = %s AND trace_id = %s
LIMIT 1
""", (UUID, tid))
row = cur.fetchone()
if row:
face_id = row[0]
# Create binding
cur.execute("""
INSERT INTO dev.identity_bindings (identity_id, identity_type, identity_value, confidence, created_at)
VALUES (%s, 'trace', %s, 0.8, NOW())
ON CONFLICT DO NOTHING
""", (identity_id, str(tid)))
bindings += 1
# Also update face_detection with identity_id
cur.execute("""
UPDATE dev.face_detections SET identity_id = %s
WHERE file_uuid = %s AND trace_id = %s
""", (identity_id, UUID, tid))
conn.commit()
print(f"Created {bindings} identity bindings for {n_clusters} identities")
# Summary
print(f"\n=== Summary ===")
cur.execute("SELECT COUNT(*) FROM dev.identities WHERE source = 'auto'")
print(f"Total auto-generated identities: {cur.fetchone()[0]}")
cur.execute("SELECT COUNT(*) FROM dev.identity_bindings")
print(f"Total identity bindings: {cur.fetchone()[0]}")
cur.close()
conn.close()
print("=== Done ===")
@@ -0,0 +1,129 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Binding: cluster face traces → identity bindings.
Uses face embeddings from face_detections, clusters per trace, creates identities.
"""
import json, sys, time
import psycopg2
import numpy as np
from sklearn.cluster import AgglomerativeClustering
UUID = sys.argv[1] if len(sys.argv) > 1 else "23b1c872379d4ec06479e5ed39eef4c5"
DB = "dbname=momentry user=accusys"
DISTANCE_THRESHOLD = 0.55 # Cosine distance threshold for clustering
print(f"=== Identity Binding for {UUID} ===")
conn = psycopg2.connect(DB)
cur = conn.cursor()
# Step 1: Get trace embeddings from face_detections
print("Loading face trace data...")
cur.execute("""
SELECT trace_id, embedding
FROM dev.face_detections
WHERE file_uuid = %s AND trace_id IS NOT NULL AND embedding IS NOT NULL
ORDER BY trace_id, id
""", (UUID,))
rows = cur.fetchall()
print(f"Face detections with embeddings: {len(rows)}")
# Group by trace_id and compute average embedding
trace_embs = {}
for trace_id, emb in rows:
if trace_id not in trace_embs:
trace_embs[trace_id] = []
trace_embs[trace_id].append(emb)
print(f"Unique traces: {len(trace_embs)}")
# Compute mean embeddings per trace
trace_ids = []
trace_vectors = []
for tid, embs in sorted(trace_embs.items()):
mean_emb = np.mean(embs, axis=0)
mean_emb = mean_emb / (np.linalg.norm(mean_emb) + 1e-10)
trace_ids.append(tid)
trace_vectors.append(mean_emb)
X = np.array(trace_vectors)
print(f"Trace vectors shape: {X.shape}")
# Step 2: Cluster traces
print("Clustering traces...")
if len(X) > 1:
clustering = AgglomerativeClustering(
n_clusters=None,
distance_threshold=DISTANCE_THRESHOLD,
metric='cosine',
linkage='average'
)
labels = clustering.fit_predict(X)
else:
labels = [0]
n_clusters = len(set(labels))
print(f"Clusters/identities: {n_clusters}")
# Step 3: Get or create identity records
print("Creating identity records...")
# Get existing identities
cur.execute("SELECT id, uuid FROM dev.identities")
existing = {row[0]: row[1] for row in cur.fetchall()}
# Map cluster -> identity_id
cluster_to_identity = {}
for cluster_id in sorted(set(labels)):
# Create new identity
identity_uuid = None
cur.execute("""
INSERT INTO dev.identities (name, identity_type, source, status, created_at, file_uuid)
VALUES (%s, 'face', 'auto', 'active', NOW(), %s)
ON CONFLICT (name) DO UPDATE SET status = 'active', file_uuid = COALESCE(dev.identities.file_uuid, %s)
RETURNING id
""", (f"stranger_{UUID}_{cluster_id}", UUID, UUID))
identity_id = cur.fetchone()[0]
cluster_to_identity[cluster_id] = identity_id
print(f" Cluster {cluster_id}: new identity {identity_id} (stranger_{UUID}_{cluster_id})")
# Step 4: Create identity bindings
print("Creating identity bindings...")
bindings = 0
for tid, label in zip(trace_ids, labels):
identity_id = cluster_to_identity[label]
# Get a representative face_id for this trace
cur.execute("""
SELECT face_id FROM dev.face_detections
WHERE file_uuid = %s AND trace_id = %s
LIMIT 1
""", (UUID, tid))
row = cur.fetchone()
if row:
face_id = row[0]
# Create binding
cur.execute("""
INSERT INTO dev.identity_bindings (identity_id, identity_type, identity_value, confidence, created_at)
VALUES (%s, 'trace', %s, 0.8, NOW())
ON CONFLICT DO NOTHING
""", (identity_id, str(tid)))
bindings += 1
# Also update face_detection with identity_id
cur.execute("""
UPDATE dev.face_detections SET identity_id = %s
WHERE file_uuid = %s AND trace_id = %s
""", (identity_id, UUID, tid))
conn.commit()
print(f"Created {bindings} identity bindings for {n_clusters} identities")
# Summary
print(f"\n=== Summary ===")
cur.execute("SELECT COUNT(*) FROM dev.identities WHERE source = 'auto'")
print(f"Total auto-generated identities: {cur.fetchone()[0]}")
cur.execute("SELECT COUNT(*) FROM dev.identity_bindings")
print(f"Total identity bindings: {cur.fetchone()[0]}")
cur.close()
conn.close()
print("=== Done ===")
+421
View File
@@ -0,0 +1,421 @@
#!/opt/homebrew/bin/python3.11
"""
Identity Matcher - Multi-angle face matching against seeds
Flow:
1. Query Qdrant _faces for all traces in a file
2. Query Qdrant _seeds for all seeds (TMDb + manual + propagation)
3. Multi-angle matching: max(cosine(seed, rep)) across 3 representatives
4. Return suggestions with confidence scores
Thresholds:
- Round 1: 0.55 (TMDb seeds)
- Round 2: 0.55 (Propagation from confirmed traces)
- Round 3+: 0.50 (Propagation continues)
- Stranger clustering: 0.40
Usage:
python identity_matcher.py --file-uuid <uuid> --round 1
python identity_matcher.py --file-uuid <uuid> --round 2 --confirmed-traces 1,2,3
Output:
JSON with suggestions: {trace_id: {identity_id, identity_uuid, name, score, suggested_by}}
"""
import os
import sys
import json
import argparse
import numpy as np
from typing import Optional
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "utils"))
from qdrant_faces import (
get_trace_representatives,
get_seeds,
search_seeds,
get_trace_centroid,
)
from tkg_helper import batch_mark_suggestions, batch_mark_strangers
TH_ROUND_1 = 0.55
TH_ROUND_2 = 0.55
TH_ROUND_3 = 0.50
TH_STRANGER = 0.40
def cosine_similarity(a: list, b: list) -> float:
"""Compute cosine similarity between two vectors"""
if len(a) != len(b) or len(a) == 0:
return 0.0
dot = sum(x * y for x, y in zip(a, b))
na = sum(x * x for x in a) ** 0.5
nb = sum(x * x for x in b) ** 0.5
if na == 0.0 or nb == 0.0:
return 0.0
return dot / (na * nb)
def multi_angle_match(seed_embedding: list, trace_reps: list) -> float:
"""Multi-angle matching: max(cosine(seed, rep))"""
if not trace_reps:
return 0.0
best_score = 0.0
for rep in trace_reps:
score = cosine_similarity(seed_embedding, rep["embedding"])
if score > best_score:
best_score = score
return best_score
def match_faces_round_1(file_uuid: str) -> dict:
"""Round 1: TMDb seeds → Traces (TH=0.55)
Returns:
{trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'tmdb'}}
"""
traces = get_trace_representatives(file_uuid)
seeds = get_seeds(source="tmdb", file_uuid=file_uuid)
if not seeds:
print(f"[MATCH] No TMDb seeds available for {file_uuid}")
return {}
suggestions = {}
threshold = TH_ROUND_1
for trace_id, reps in traces.items():
best_match = None
best_score = 0.0
for seed in seeds:
seed_emb = seed.get("vector", [])
seed_payload = seed.get("payload", {})
score = multi_angle_match(seed_emb, reps)
if score >= threshold and score > best_score:
best_score = score
best_match = {
"identity_id": seed_payload.get("identity_id"),
"identity_uuid": seed_payload.get("identity_uuid"),
"name": seed_payload.get("name"),
"score": score,
"suggested_by": "tmdb",
}
if best_match:
suggestions[trace_id] = best_match
print(f"[MATCH] Round 1: {len(suggestions)}/{len(traces)} traces suggested (TH={threshold})")
return suggestions
def match_faces_round_2(
file_uuid: str,
confirmed_traces: list,
identity_map: dict,
) -> dict:
"""Round 2: Confirmed traces → Pending traces (TH=0.55)
Args:
file_uuid: Video file UUID
confirmed_traces: List of confirmed trace_ids
identity_map: {trace_id: {identity_id, identity_uuid, name}}
Returns:
{trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'propagation'}}
"""
traces = get_trace_representatives(file_uuid)
pending_traces = set(traces.keys()) - set(confirmed_traces)
if not pending_traces:
print("[MATCH] Round 2: No pending traces")
return {}
seed_pool = {}
for trace_id in confirmed_traces:
if trace_id not in traces:
continue
identity_info = identity_map.get(trace_id)
if not identity_info:
continue
centroid = get_trace_centroid(file_uuid, trace_id)
if not centroid or all(v == 0.0 for v in centroid):
continue
identity_id = identity_info.get("identity_id")
if identity_id not in seed_pool:
seed_pool[identity_id] = {
"identity_id": identity_id,
"identity_uuid": identity_info.get("identity_uuid"),
"name": identity_info.get("name"),
"embeddings": [],
}
seed_pool[identity_id]["embeddings"].append(centroid)
if not seed_pool:
print("[MATCH] Round 2: No confirmed traces with embeddings")
return {}
suggestions = {}
threshold = TH_ROUND_2
for trace_id in pending_traces:
reps = traces.get(trace_id, [])
if not reps:
continue
best_match = None
best_score = 0.0
for identity_id, seed_data in seed_pool.items():
for seed_emb in seed_data["embeddings"]:
score = multi_angle_match(seed_emb, reps)
if score >= threshold and score > best_score:
best_score = score
best_match = {
"identity_id": seed_data["identity_id"],
"identity_uuid": seed_data["identity_uuid"],
"name": seed_data["name"],
"score": score,
"suggested_by": "propagation",
}
if best_match:
suggestions[trace_id] = best_match
print(f"[MATCH] Round 2: {len(suggestions)}/{len(pending_traces)} traces suggested (TH={threshold})")
return suggestions
def match_faces_round_3_plus(
file_uuid: str,
all_confirmed: dict,
prev_suggestions: dict,
round_num: int,
) -> dict:
"""Round 3+: Propagation continues (TH=0.50)
Args:
file_uuid: Video file UUID
all_confirmed: {trace_id: {identity_id, identity_uuid, name}} - all confirmed so far
prev_suggestions: {trace_id: {...}} - suggestions from previous round
round_num: Round number (3, 4, 5...)
Returns:
{trace_id: {identity_id, identity_uuid, name, score, suggested_by: 'propagation'}}
"""
traces = get_trace_representatives(file_uuid)
confirmed_traces = set(all_confirmed.keys())
prev_suggested_traces = set(prev_suggestions.keys())
pending_traces = set(traces.keys()) - confirmed_traces - prev_suggested_traces
if not pending_traces:
print(f"[MATCH] Round {round_num}: No pending traces")
return {}
seed_pool = {}
for trace_id, identity_info in all_confirmed.items():
if trace_id not in traces:
continue
centroid = get_trace_centroid(file_uuid, trace_id)
if not centroid or all(v == 0.0 for v in centroid):
continue
identity_id = identity_info.get("identity_id")
if identity_id not in seed_pool:
seed_pool[identity_id] = {
"identity_id": identity_id,
"identity_uuid": identity_info.get("identity_uuid"),
"name": identity_info.get("name"),
"embeddings": [],
}
seed_pool[identity_id]["embeddings"].append(centroid)
if not seed_pool:
print(f"[MATCH] Round {round_num}: No seeds available")
return {}
suggestions = {}
threshold = TH_ROUND_3
for trace_id in pending_traces:
reps = traces.get(trace_id, [])
if not reps:
continue
best_match = None
best_score = 0.0
for identity_id, seed_data in seed_pool.items():
for seed_emb in seed_data["embeddings"]:
score = multi_angle_match(seed_emb, reps)
if score >= threshold and score > best_score:
best_score = score
best_match = {
"identity_id": seed_data["identity_id"],
"identity_uuid": seed_data["identity_uuid"],
"name": seed_data["name"],
"score": score,
"suggested_by": "propagation",
}
if best_match:
suggestions[trace_id] = best_match
print(f"[MATCH] Round {round_num}: {len(suggestions)}/{len(pending_traces)} traces suggested (TH={threshold})")
return suggestions
def cluster_strangers(file_uuid: str, matched_traces: list) -> dict:
"""Stranger clustering: Greedy merge unmatched traces (TH=0.40)
Args:
file_uuid: Video file UUID
matched_traces: List of trace_ids that have identity suggestions
Returns:
{stranger_cluster_id: [trace_ids]}
"""
traces = get_trace_representatives(file_uuid)
unmatched_traces = set(traces.keys()) - set(matched_traces)
if not unmatched_traces:
print("[STRANGER] All traces matched")
return {}
clusters = []
threshold = TH_STRANGER
for trace_id in unmatched_traces:
reps = traces.get(trace_id, [])
if not reps:
continue
centroid = get_trace_centroid(file_uuid, trace_id)
if not centroid or all(v == 0.0 for v in centroid):
continue
best_cluster_idx = None
best_score = 0.0
for idx, cluster in enumerate(clusters):
cluster_centroid = compute_cluster_centroid(cluster, traces)
score = cosine_similarity(centroid, cluster_centroid)
if score >= threshold and score > best_score:
best_score = score
best_cluster_idx = idx
if best_cluster_idx is not None:
clusters[best_cluster_idx].append(trace_id)
else:
clusters.append([trace_id])
stranger_clusters = {}
for idx, trace_ids in enumerate(clusters):
stranger_clusters[idx + 1] = trace_ids
print(f"[STRANGER] {len(stranger_clusters)} clusters from {len(unmatched_traces)} unmatched traces (TH={threshold})")
return stranger_clusters
def compute_cluster_centroid(cluster: list, traces: dict) -> list:
"""Compute centroid embedding for a cluster of traces"""
all_embeddings = []
for trace_id in cluster:
reps = traces.get(trace_id, [])
for rep in reps:
all_embeddings.append(rep["embedding"])
if not all_embeddings:
return [0.0] * 512
centroid = [0.0] * 512
for emb in all_embeddings:
for i, v in enumerate(emb):
centroid[i] += v
for i in range(512):
centroid[i] /= len(all_embeddings)
return centroid
def main():
parser = argparse.ArgumentParser(description="Identity Matcher")
parser.add_argument("--file-uuid", required=True, help="Video file UUID")
parser.add_argument("--round", type=int, default=1, help="Round number (1, 2, 3+)")
parser.add_argument("--confirmed-traces", help="Comma-separated confirmed trace_ids (for Round 2+)")
parser.add_argument("--identity-map", help="JSON file with {trace_id: {identity_id, uuid, name}} (for Round 2+)")
parser.add_argument("--output", help="Output JSON file path")
parser.add_argument("--stranger", action="store_true", help="Also run stranger clustering")
parser.add_argument("--mark-tkg", action="store_true", help="Mark TKG face_track nodes with suggestions")
args = parser.parse_args()
if args.round == 1:
suggestions = match_faces_round_1(args.file_uuid)
elif args.round == 2:
confirmed = []
identity_map = {}
if args.confirmed_traces:
confirmed = [int(x) for x in args.confirmed_traces.split(",")]
if args.identity_map:
with open(args.identity_map) as f:
identity_map = json.load(f)
suggestions = match_faces_round_2(args.file_uuid, confirmed, identity_map)
else:
all_confirmed = {}
prev_suggestions = {}
if args.identity_map:
with open(args.identity_map) as f:
all_confirmed = json.load(f)
suggestions = match_faces_round_3_plus(
args.file_uuid, all_confirmed, prev_suggestions, args.round
)
result = {
"file_uuid": args.file_uuid,
"round": args.round,
"suggestions": suggestions,
"total_traces": len(get_trace_representatives(args.file_uuid)),
"matched": len(suggestions),
}
if args.stranger:
matched_traces = list(suggestions.keys())
stranger_clusters = cluster_strangers(args.file_uuid, matched_traces)
result["stranger_clusters"] = stranger_clusters
# Mark TKG nodes if requested
if args.mark_tkg:
tkg_updated = batch_mark_suggestions(args.file_uuid, suggestions)
result["tkg_nodes_updated"] = tkg_updated
if args.stranger and stranger_clusters:
tkg_strangers = batch_mark_strangers(args.file_uuid, stranger_clusters)
result["tkg_strangers_updated"] = tkg_strangers
output_json = json.dumps(result, indent=2, ensure_ascii=False)
if args.output:
with open(args.output, "w") as f:
f.write(output_json)
print(f"[MATCH] Output saved to {args.output}")
else:
print(output_json)
if __name__ == "__main__":
main()
+138
View File
@@ -0,0 +1,138 @@
#!/opt/homebrew/bin/python3.11
"""
OCR Processor Wrapper
Calls Swift Vision Framework OCR (swift_ocr) with fallback to PaddleOCR.
"""
import re
import sys
import json
import os
import subprocess
import argparse
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
SWIFT_OCR_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"swift_processors/.build/debug/swift_ocr"
)
SWIFT_OCR_ALT = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"swift_processors/.build/arm64-apple-macosx/debug/swift_ocr"
)
SWIFT_PROGRESS_RE = re.compile(r"\[SwiftOCR\] Progress:\s*(\d+)%")
def _round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: _round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [_round_json_numbers(v) for v in obj]
return obj
def process_ocr(
video_path: str,
output_path: str,
uuid: str = "",
sample_interval: int = 30,
recognition_level: str = "accurate",
publisher: RedisPublisher = None,
) -> dict:
swift_bin = SWIFT_OCR_PATH
if not os.path.exists(swift_bin):
swift_bin = SWIFT_OCR_ALT
if not os.path.exists(swift_bin):
print("[OCR] Swift binary not found, using PaddleOCR", file=sys.stderr)
return _fallback(video_path, output_path, uuid, sample_interval)
cmd = [swift_bin, video_path, output_path,
"--sample-interval", str(sample_interval),
"--recognition-level", recognition_level,
"--uuid", uuid]
print(f"[OCR] Running Swift OCR", file=sys.stderr)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
last_pct = -1
stdout_lines = []
for line in proc.stdout:
line = line.strip()
stdout_lines.append(line)
m = SWIFT_PROGRESS_RE.search(line)
if m:
pct = int(m.group(1))
if pct > last_pct:
last_pct = pct
print(f"[OCR] Progress: {pct}%", file=sys.stderr)
if publisher:
publisher.progress("ocr", pct, 100, f"{pct}%")
elif line:
print(line, file=sys.stderr)
stderr_output = proc.stderr.read()
if stderr_output:
print(stderr_output.strip(), file=sys.stderr)
proc.wait()
if proc.returncode != 0 or not os.path.exists(output_path):
print(f"[OCR] Swift OCR failed (exit={proc.returncode}), falling back to PaddleOCR", file=sys.stderr)
if publisher:
publisher.error("ocr", f"Swift OCR failed, using fallback")
return _fallback(video_path, output_path, uuid, sample_interval)
with open(output_path) as f:
return json.load(f)
def _fallback(video_path, output_path, uuid, sample_interval):
"""Fallback to MPS OCR implementation"""
import importlib
spec = importlib.util.spec_from_file_location(
"ocr_mps",
os.path.join(os.path.dirname(__file__), "ocr_processor_mps.py")
)
if spec is None:
print("[OCR] No fallback available, returning empty result", file=sys.stderr)
return {"frame_count": 0, "fps": 0, "frames": []}
ocr_mps = importlib.util.module_from_spec(spec)
spec.loader.exec_module(ocr_mps)
return ocr_mps.process_video_ocr(
video_path=video_path,
output_path=output_path,
sample_interval=sample_interval
)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="OCR Processor (Swift Vision)")
parser.add_argument("video_path")
parser.add_argument("output_path")
parser.add_argument("--uuid", "-u", default="")
parser.add_argument("--sample-interval", type=int, default=30)
parser.add_argument("--recognition-level", choices=["fast", "accurate"], default="accurate")
parser.add_argument("--frames", type=str, default=None, help=argparse.SUPPRESS)
args = parser.parse_args()
publisher = RedisPublisher(args.uuid) if args.uuid else None
if publisher:
publisher.info("ocr", "OCR_START")
result = process_ocr(args.video_path, args.output_path, args.uuid,
args.sample_interval, args.recognition_level,
publisher)
with open(args.output_path, "w") as f:
json.dump(_round_json_numbers(result), f, indent=2)
print(f"OCR: {len(result.get('frames', []))} frames with text")
if publisher:
publisher.complete("ocr", f"{len(result.get('frames',[]))} frames")
+336
View File
@@ -0,0 +1,336 @@
#!/opt/homebrew/bin/python3.11
"""
Pose Processor Wrapper
Calls Swift Vision Framework pose (swift_pose) with fallback to YOLOv8 Pose.
Uses VNDetectHumanBodyPoseRequest with ANE acceleration.
"""
import re
import sys
import json
import os
import subprocess
import argparse
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
SWIFT_POSE_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"swift_processors/.build/debug/swift_pose"
)
SWIFT_POSE_ALT = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
"swift_processors/.build/arm64-apple-macosx/debug/swift_pose"
)
SWIFT_POSE_PROGRESS_RE = re.compile(r"\[SwiftPose\] Progress:\s*(\d+)%")
def round_json_numbers(obj):
"""Recursively round all float values to 2 decimal places (JSON output only)."""
if isinstance(obj, float):
return round(obj, 2)
if isinstance(obj, dict):
return {k: round_json_numbers(v) for k, v in obj.items()}
if isinstance(obj, list):
return [round_json_numbers(v) for v in obj]
return obj
def process_pose(
video_path: str,
output_path: str,
uuid: str = "",
sample_interval: int = 3, # Changed from 30 to match Face
publisher: RedisPublisher = None,
target_frames: list = None,
) -> dict:
# Check if pose.json or pose.json.tmp already exists (from swift_face_pose)
# executor.rs renames output to .json.tmp before running Python script
tmp_path = output_path.replace('.json', '.json.tmp')
source_path = None
if os.path.exists(output_path):
source_path = output_path
print(f"[Pose] Output exists from swift_face_pose: {output_path}", file=sys.stderr)
elif os.path.exists(tmp_path):
source_path = tmp_path
print(f"[Pose] Temp output exists from swift_face_pose: {tmp_path}", file=sys.stderr)
if source_path:
with open(source_path) as f:
data = json.load(f)
detected_frames = len(data.get('frames', []))
print(f"[Pose] Loaded {detected_frames} detected frames", file=sys.stderr)
# When target_frames is provided (8Hz sampling), skip interpolation
# Swift already outputs at sample_interval=3, matching 8Hz for 24fps
if target_frames is not None:
print(f"[Pose] 8Hz mode: returning {detected_frames} frames without interpolation", file=sys.stderr)
if publisher:
publisher.progress("pose", 100, 100, f"{detected_frames} frames (8Hz, no interpolation)")
return data
# Interpolate keypoints for all frames
interpolated_data = interpolate_pose(data, video_path)
# Write interpolated output
with open(output_path, 'w') as f:
json.dump(round_json_numbers(interpolated_data), f)
# Delete .json.tmp file so executor.rs won't restore it
if os.path.exists(tmp_path):
os.remove(tmp_path)
print(f"[Pose] Deleted temp file: {tmp_path}", file=sys.stderr)
total_frames = len(interpolated_data.get('frames', []))
print(f"[Pose] Interpolated to {total_frames} frames", file=sys.stderr)
if publisher:
publisher.progress("pose", 100, 100, f"Interpolated {total_frames} frames")
return interpolated_data
swift_bin = SWIFT_POSE_PATH
if not os.path.exists(swift_bin):
swift_bin = SWIFT_POSE_ALT
if not os.path.exists(swift_bin):
print("[Pose] Swift binary not found, using YOLOv8 fallback", file=sys.stderr)
if publisher:
publisher.error("pose", "Swift binary not found, using fallback")
return _fallback(video_path, output_path, uuid, sample_interval)
cmd = [swift_bin, video_path, output_path,
"--sample-interval", str(sample_interval),
"--uuid", uuid]
print(f"[Pose] Running Swift Pose (Vision Framework)", file=sys.stderr)
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
last_pct = -1
for line in proc.stdout:
line = line.strip()
m = SWIFT_POSE_PROGRESS_RE.search(line)
if m:
pct = int(m.group(1))
if pct > last_pct:
last_pct = pct
print(f"[Pose] Progress: {pct}%", file=sys.stderr)
if publisher:
publisher.progress("pose", pct, 100, f"{pct}%")
elif line:
print(f" {line}", file=sys.stderr)
stderr_output = proc.stderr.read()
if stderr_output:
print(stderr_output.strip(), file=sys.stderr)
proc.wait()
if proc.returncode != 0 or not os.path.exists(output_path):
print(f"[Pose] Swift Pose failed (exit={proc.returncode}), falling back to YOLOv8", file=sys.stderr)
if publisher:
publisher.error("pose", f"Swift Pose failed, using fallback")
return _fallback(video_path, output_path, uuid, sample_interval)
with open(output_path) as f:
return json.load(f)
def interpolate_pose(detected_data: dict, video_path: str) -> dict:
"""Interpolate keypoints for all frames between detected frames"""
import cv2
import numpy as np
cap = cv2.VideoCapture(video_path)
total_video_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
fps = detected_data.get('fps', 30.0)
detected_frames = detected_data.get('frames', [])
if not detected_frames:
cap.release()
return detected_data
# Build frame index map
frame_map = {f['frame']: f for f in detected_frames}
detected_frame_nums = sorted(frame_map.keys())
print(f"[Pose] Interpolating from {len(detected_frame_nums)} detected frames to {total_video_frames} total frames", file=sys.stderr)
# Get all persons from detected frames (assume same person tracking)
all_persons = {}
for f in detected_frames:
for i, p in enumerate(f.get('persons', [])):
if i not in all_persons:
all_persons[i] = []
all_persons[i].append((f['frame'], p))
# Interpolate each person's keypoints for each frame
interpolated_frames = []
for frame_num in range(total_video_frames):
ts = frame_num / fps
persons_in_frame = []
for person_id, person_frames in all_persons.items():
# Find closest detected frames before and after
before = None
after = None
for fn, p in person_frames:
if fn <= frame_num:
before = (fn, p)
if fn >= frame_num and after is None:
after = (fn, p)
if before is None and after is None:
continue
# Interpolate keypoints
interpolated_keypoints = []
bbox = None
if before and after and before[0] != after[0]:
# Linear interpolation
t0, t1 = before[0], after[0]
t = (frame_num - t0) / (t1 - t0) if t1 != t0 else 0
kp_before = before[1].get('keypoints', [])
kp_after = after[1].get('keypoints', [])
bbox_before = before[1].get('bbox', {})
bbox_after = after[1].get('bbox', {})
# Interpolate keypoints
for i in range(max(len(kp_before), len(kp_after))):
kp0 = kp_before[i] if i < len(kp_before) else kp_after[i]
kp1 = kp_after[i] if i < len(kp_after) else kp_before[i]
x = kp0['x'] + t * (kp1['x'] - kp0['x'])
y = kp0['y'] + t * (kp1['y'] - kp0['y'])
c = kp0['confidence'] + t * (kp1['confidence'] - kp0['confidence'])
interpolated_keypoints.append({
'name': kp0['name'],
'x': x,
'y': y,
'confidence': c
})
# Interpolate bbox
if bbox_before and bbox_after:
bbox = {
'x': int(bbox_before['x'] + t * (bbox_after['x'] - bbox_before['x'])),
'y': int(bbox_before['y'] + t * (bbox_after['y'] - bbox_before['y'])),
'width': int(bbox_before['width'] + t * (bbox_after['width'] - bbox_before['width'])),
'height': int(bbox_before['height'] + t * (bbox_after['height'] - bbox_before['height']))
}
elif before:
# Use before frame's data
interpolated_keypoints = before[1].get('keypoints', [])
bbox = before[1].get('bbox', {})
elif after:
# Use after frame's data
interpolated_keypoints = after[1].get('keypoints', [])
bbox = after[1].get('bbox', {})
if bbox and bbox.get('width', 0) > 0 and bbox.get('height', 0) > 0:
persons_in_frame.append({
'keypoints': interpolated_keypoints,
'bbox': bbox
})
if persons_in_frame:
interpolated_frames.append({
'frame': frame_num,
'timestamp': ts,
'persons': persons_in_frame
})
cap.release()
return {
'frame_count': len(interpolated_frames),
'fps': fps,
'frames': interpolated_frames
}
def _fallback(video_path, output_path, uuid, sample_interval):
"""Fallback to YOLOv8 Pose"""
from ultralytics import YOLO
import cv2
model = YOLO("yolov8n-pose.pt")
cap = cv2.VideoCapture(video_path)
fps = cap.get(cv2.CAP_PROP_FPS)
frame_count = 0
frames = []
while cap.isOpened():
ret, frame = cap.read()
if not ret:
break
if frame_count % sample_interval == 0:
ts = frame_count / fps if fps > 0 else 0
results = model(frame, verbose=False, device="cpu")
persons = []
for r in results:
if r.keypoints is None:
continue
for kp_data in r.keypoints:
kps = kp_data.xy[0].cpu().numpy() if hasattr(kp_data, 'xy') else []
confs = kp_data.conf[0].cpu().numpy() if hasattr(kp_data, 'conf') else []
keypoints = []
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"]
for j, name in enumerate(names):
if j < len(kps):
x, y = float(kps[j][0]), float(kps[j][1])
c = float(confs[j]) if j < len(confs) else 0
keypoints.append({"name": name, "x": x, "y": y, "confidence": c})
if keypoints:
xs = [k["x"] for k in keypoints if k["confidence"] > 0.1]
ys = [k["y"] for k in keypoints if k["confidence"] > 0.1]
bbox = {"x": int(min(xs)), "y": int(min(ys)), "width": int(max(xs)-min(xs)), "height": int(max(ys)-min(ys))} if xs else {"x": 0, "y": 0, "width": 0, "height": 0}
persons.append({"keypoints": keypoints, "bbox": bbox})
if persons:
frames.append({"frame": frame_count, "timestamp": ts, "persons": persons})
frame_count += 1
cap.release()
result = {"frame_count": len(frames), "fps": fps, "frames": frames}
if len(frames) == 0:
result["status"] = "no_face"
with open(output_path, "w") as f:
json.dump(round_json_numbers(result), f, indent=2)
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Pose Processor (Swift Vision)")
parser.add_argument("video_path")
parser.add_argument("output_path")
parser.add_argument("--uuid", "-u", default="")
parser.add_argument("--sample-interval", type=int, default=3) # Changed from 30 to match Face
parser.add_argument("--frames", type=str, default=None,
help="Comma-separated frame numbers for 8Hz sampling")
args = parser.parse_args()
target_frames = None
if args.frames:
target_frames = [int(f) for f in args.frames.split(",") if f.strip()]
print(f"[Pose] 8Hz target frames: {len(target_frames)} frames", file=sys.stderr)
publisher = RedisPublisher(args.uuid) if args.uuid else None
if publisher:
publisher.info("pose", "POSE_START")
result = process_pose(args.video_path, args.output_path, args.uuid,
args.sample_interval, publisher, target_frames)
with open(args.output_path, "w") as f:
json.dump(round_json_numbers(result), f, indent=2)
print(f"Pose: {len(result.get('frames', []))} frames with poses")
if publisher:
publisher.complete("pose", f"{len(result.get('frames',[]))} frames")
+164
View File
@@ -0,0 +1,164 @@
#!/opt/homebrew/bin/python3.11
"""
Appearance Expansion Processor V2
Calls swift_appearance_expansion which:
1. Reads pose.json (from pose expansion)
2. Expands appearance detection from pose frames
3. Stops when 3 consecutive frames have HSV similarity < 0.5
4. Outputs at 8Hz sampling (floor(fps/8))
Flow:
face_processor.py → face.json
store_traced_faces.py → face_traced.json (with trace_id)
pose_processor.py → pose.json
appearance_processor.py → appearance.json (this script)
"""
import sys
import os
import json
import argparse
import subprocess
import time
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from redis_publisher import RedisPublisher
SCRIPT_DIR = os.path.dirname(os.path.abspath(__file__))
SWIFT_BIN = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "release", "swift_appearance_expansion")
SWIFT_BIN_DEBUG = os.path.join(SCRIPT_DIR, "swift_processors", ".build", "debug", "swift_appearance_expansion")
OUTPUT_DIR = os.environ.get("MOMENTRY_OUTPUT_DIR", "/Users/accusys/momentry/output")
def process_appearance(
video_path: str,
output_path: str,
uuid: str = "",
publisher: RedisPublisher = None,
) -> dict:
"""Process appearance expansion from pose frames.
Args:
video_path: Path to video file
output_path: Path to output appearance.json
uuid: File UUID for logging
publisher: Redis publisher for progress updates
"""
# Check if appearance.json already exists
if os.path.exists(output_path):
with open(output_path) as f:
data = json.load(f)
frame_count = len(data.get("frames", []))
print(f"[Appearance] Output exists: {output_path} ({frame_count} frames)", file=sys.stderr)
if publisher:
publisher.progress("appearance", 100, 100, f"{frame_count} frames (exists)")
return data
# Determine file_uuid from output_path
file_uuid = os.path.basename(output_path).replace(".appearance.json", "")
# Find pose.json
pose_path = os.path.join(OUTPUT_DIR, f"{file_uuid}.pose.json")
if not os.path.exists(pose_path):
print(f"[Appearance] ERROR: pose.json not found for {file_uuid}", file=sys.stderr)
# Return empty result
empty_result = {"frame_count": 0, "fps": 0.0, "frames": []}
with open(output_path, "w") as f:
json.dump(empty_result, f)
return empty_result
# Build swift_appearance_expansion if needed
swift_bin = SWIFT_BIN if os.path.exists(SWIFT_BIN) else SWIFT_BIN_DEBUG
if not os.path.exists(swift_bin):
build_dir = os.path.join(SCRIPT_DIR, "swift_processors")
print(f"[Appearance] Building swift_appearance_expansion in {build_dir}...", file=sys.stderr)
result = subprocess.run(
["swift", "build", "-c", "release", "--product", "swift_appearance_expansion"],
cwd=build_dir, capture_output=True, text=True
)
if result.returncode != 0:
print(f"[Appearance] Build failed: {result.stderr}", file=sys.stderr)
raise RuntimeError("Failed to build swift_appearance_expansion")
swift_bin = SWIFT_BIN
# Run swift_appearance_expansion
cmd = [
swift_bin,
video_path,
pose_path,
output_path,
]
if uuid:
cmd.extend(["--uuid", uuid])
print(f"[Appearance] Running: {' '.join(cmd)}", file=sys.stderr)
t0 = time.time()
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)
# Monitor progress
last_progress = ""
while proc.poll() is None:
time.sleep(5)
# Read stderr for progress
try:
import select
if select.select([proc.stderr], [], [], 0)[0]:
line = proc.stderr.readline().strip()
if line and line != last_progress:
last_progress = line
print(f"[Appearance] {line}", file=sys.stderr)
if publisher and "frames" in line:
publisher.progress("appearance", 50, 100, line)
except Exception:
pass
# Read remaining output
stdout, stderr = proc.communicate()
if stdout:
print(stdout, file=sys.stderr)
if stderr:
print(stderr, file=sys.stderr)
elapsed = time.time() - t0
if proc.returncode != 0:
print(f"[Appearance] ERROR: swift_appearance_expansion exited with code {proc.returncode}", file=sys.stderr)
if publisher:
publisher.error("appearance", f"Process failed with code {proc.returncode}")
raise RuntimeError(f"swift_appearance_expansion failed: {proc.returncode}")
# Load result
if not os.path.exists(output_path):
print(f"[Appearance] ERROR: Output file not created: {output_path}", file=sys.stderr)
raise RuntimeError("Appearance output not created")
with open(output_path) as f:
result = json.load(f)
frame_count = len(result.get("frames", []))
print(f"[Appearance] Done: {frame_count} frames in {elapsed:.1f}s", file=sys.stderr)
if publisher:
publisher.progress("appearance", 100, 100, f"{frame_count} frames")
publisher.complete("appearance", f"{frame_count} frames")
return result
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="Appearance Expansion Processor")
parser.add_argument("video_path", help="Video file path")
parser.add_argument("output_path", help="Output appearance.json path")
parser.add_argument("--uuid", "-u", default="", help="File UUID for logging")
args = parser.parse_args()
publisher = RedisPublisher(args.uuid) if args.uuid else None
if publisher:
publisher.info("appearance", "APPEARANCE_START")
result = process_appearance(args.video_path, args.output_path, args.uuid, publisher)
print(f"Appearance: {len(result.get('frames', []))} frames with appearance")
File diff suppressed because it is too large Load Diff