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()