feat: declarative pipeline config, non-blocking Scene VLM, rust_asrx

Consolidated snapshot (previously WIP in working tree).

- core/pipeline_config: new module loading config/pipeline_flows.json as the
  source of truth for stage execution mode (parallel/blocking) and dependencies
- worker/job_worker: dispatch Scene VLM to a background task when the stage is
  declared parallel, unblocking the worker poll loop; resolve processor
  dependencies from pipeline_flows.json (fallback to built-in)
- config/pipeline_flows.json: asrx depends on [cut, asr]
- scripts/fix_stuck_jobs: fix UTC timezone comparison, raise default threshold
  to 6h, skip jobs with recent processor activity
- rust_asrx: Rust speaker diarization CLI + processor wiring
- processor metadata helper; fast_face_clustering script; file_progress pipeline
  API; scan API; VAD updates
This commit is contained in:
Accusys
2026-10-15 13:01:12 +08:00
parent 667e279768
commit 882e31ab96
76 changed files with 10117 additions and 300 deletions
+41
View File
@@ -0,0 +1,41 @@
#!/bin/bash
# 检查卡住的 Job 状态
# 用法: ./check_stuck_jobs.sh
echo "=========================================="
echo " 卡住的 Job 状态检查"
echo "=========================================="
echo ""
# 检查自动修复服务
echo "1. 自动修复服务状态"
echo "------------------------------------------"
SERVICE_STATUS=$(launchctl list 2>/dev/null | grep fix_stuck_jobs)
if [ -n "$SERVICE_STATUS" ]; then
echo "✅ 服务运行中"
echo " $SERVICE_STATUS"
else
echo "❌ 服务未运行"
echo " 启动: launchctl load ~/Library/LaunchAgents/com.momentry.fix_stuck_jobs.plist"
fi
echo ""
# 检查卡住的 Job
echo "2. 当前卡住的 Job"
echo "------------------------------------------"
python3 /Users/accusys/momentry_core/scripts/fix_stuck_jobs.py --dry-run
echo ""
# 显示最近的修复日志
echo "3. 最近修复记录"
echo "------------------------------------------"
if [ -f /Users/accusys/momentry_core/logs/fix_stuck_jobs.log ]; then
tail -20 /Users/accusys/momentry_core/logs/fix_stuck_jobs.log
else
echo "暂无修复记录"
fi
echo ""
echo "=========================================="
echo "完成时间: $(date '+%Y-%m-%d %H:%M:%S')"
echo "=========================================="
+142
View File
@@ -0,0 +1,142 @@
#!/usr/bin/env python3
"""
自动修复卡住和失败的 Job
功能:
1. 查找所有 running 状态超过阈值(默认 6 小时)的 job
(且该文件最近 30 分钟无 processor_results 活动,避免误判仍在进行的 job)
2. 查找所有 failed 状态但实际已完成的 job
3. 标记为 completed
注意:
monitor_jobs/videos 的 created_at/updated_at 为 "timestamp without time zone",
内容为 UTC-naive;DB session 为 Asia/Taipei。因此比较/写入必须显式转换到 UTC,
否则会出现 +8 小时偏移而使阈值判断错误。
用法:
python3 fix_stuck_jobs.py [--dry-run] [--hours N]
"""
import sys
import argparse
from datetime import datetime, timedelta
sys.path.insert(0, '/Users/accusys/momentry_core')
import psycopg2
def main():
parser = argparse.ArgumentParser(description='Fix stuck and failed jobs')
parser.add_argument('--dry-run', action='store_true', help='Only show, do not fix')
parser.add_argument('--hours', type=int, default=6, help='Hours threshold (default: 6)')
args = parser.parse_args()
conn = psycopg2.connect("postgres://accusys@localhost:5432/momentry")
cur = conn.cursor()
fixed_count = 0
# 1. 查找卡住的 job (running 超过阈值)
print("=== 检查卡住的 Job (running) ===")
cur.execute("""
SELECT m.id, m.video_id, v.file_uuid, v.file_name, m.created_at,
m.completed_processors, m.failed_processors
FROM monitor_jobs m
JOIN videos v ON m.video_id = v.id
WHERE m.status = 'running'
AND m.created_at < (NOW() AT TIME ZONE 'UTC') - INTERVAL '%s hours'
AND NOT EXISTS (
SELECT 1 FROM processor_results pr
WHERE pr.file_uuid = v.file_uuid
AND pr.updated_at > NOW() - INTERVAL '30 minutes'
)
ORDER BY m.created_at DESC
""", (args.hours,))
stuck_jobs = cur.fetchall()
if stuck_jobs:
print(f"⚠️ 发现 {len(stuck_jobs)} 个卡住的 Job:\n")
for job_id, video_id, file_uuid, file_name, created_at, completed, failed in stuck_jobs:
print(f"Job {job_id}: {file_name}")
print(f" UUID: {file_uuid}")
print(f" Created: {created_at}")
print(f" Completed: {completed}")
print(f" Failed: {failed}")
if args.dry_run:
print(" [DRY-RUN] Would mark as completed")
else:
cur.execute("""
UPDATE monitor_jobs
SET status = 'completed', updated_at = (NOW() AT TIME ZONE 'UTC')
WHERE id = %s
""", (job_id,))
cur.execute("""
UPDATE videos
SET status = 'completed'
WHERE id = %s
""", (video_id,))
print(" ✅ 已修复")
fixed_count += 1
print()
# 2. 查找失败但实际已完成的 job
print("=== 检查失败但已完成的 Job (failed) ===")
cur.execute("""
SELECT m.id, m.video_id, v.file_uuid, v.file_name, m.created_at,
m.completed_processors, m.failed_processors
FROM monitor_jobs m
JOIN videos v ON m.video_id = v.id
WHERE m.status = 'failed'
AND m.completed_processors IS NOT NULL
AND array_length(m.completed_processors, 1) >= 3
ORDER BY m.created_at DESC
""")
failed_jobs = cur.fetchall()
if failed_jobs:
print(f"⚠️ 发现 {len(failed_jobs)} 个失败但已完成的 Job:\n")
for job_id, video_id, file_uuid, file_name, created_at, completed, failed in failed_jobs:
print(f"Job {job_id}: {file_name}")
print(f" UUID: {file_uuid}")
print(f" Completed: {completed}")
print(f" Failed: {failed}")
if args.dry_run:
print(" [DRY-RUN] Would mark as completed")
else:
cur.execute("""
UPDATE monitor_jobs
SET status = 'completed', updated_at = (NOW() AT TIME ZONE 'UTC')
WHERE id = %s
""", (job_id,))
cur.execute("""
UPDATE videos
SET status = 'completed'
WHERE id = %s
""", (video_id,))
print(" ✅ 已修复")
fixed_count += 1
print()
if not stuck_jobs and not failed_jobs:
print("✅ 没有 Job 需要修复")
if not args.dry_run and fixed_count > 0:
conn.commit()
print(f"✅ 总共修复 {fixed_count} 个 Job")
cur.close()
conn.close()
if __name__ == '__main__':
main()
-138
View File
@@ -1,138 +0,0 @@
#!/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")
+1
View File
@@ -0,0 +1 @@
/Users/accusys/momentry_core/tools/script/ocr/ocr_processor.py