"""Provide subprocess, manifest, and preflight runtime helpers.""" import json import math import os import shlex import shutil import subprocess import sys from pathlib import Path import materials as material_lib from lib import env_bool, ffmpeg_has_subtitles_filter, file_identity, load_json, material_id_for from recap_source import audio_binding SCRIPT_DIR = Path(__file__).resolve().parent RUN_MANIFEST = "recap_run_manifest.json" MULTI_SOURCE_MANIFEST = "multi_source_manifest.json" def _run(stage, script, *cli_args): cmd = [sys.executable, str(_entry(script)), *map(str, cli_args)] print(f"[video-recap] ▶ {stage}/{script}", flush=True) # Stage scripts log Chinese; on Windows a piped stdout defaults to cp1252 and the # first log line would crash the child with UnicodeEncodeError. res = subprocess.run( cmd, env={**os.environ, "PYTHONIOENCODING": "utf-8", "PYTHONUTF8": "1"} ) if res.returncode != 0: raise SystemExit(f"{stage}/{script} 失败 (exit {res.returncode})") def _read_video_duration_or_raise(path): """Return media duration via ffprobe, or hard-fail before downstream TTS/render.""" path = Path(path) cmd = [ "ffprobe", "-v", "quiet", "-show_entries", "format=duration", "-of", "csv=p=0", str(path), ] res = subprocess.run( cmd, capture_output=True, text=True, encoding="utf-8", errors="replace" ) if res.returncode != 0: detail = (res.stderr or res.stdout or "ffprobe failed").strip() raise SystemExit(f"无法读取成片时长: {path} ({detail})") try: duration = float(res.stdout.strip()) except ValueError: raise SystemExit(f"无法读取成片时长: {path} (ffprobe 输出无效: {res.stdout!r})") from None if not math.isfinite(duration) or duration <= 0: raise SystemExit(f"无法读取成片时长: {path} (duration={duration:.3f})") return duration # Subtitle Y coordinates are display-canvas rows; a near-square SAR only changes the canvas # width (or, rotated, the row scale the renderer converts exactly). Same value as the # renderer's and the measuring tool's copies (parity-tested). SUBTITLE_BAND_SAR_TOLERANCE = 0.02 def _probe_display_size_or_raise(path, *, require_near_square_pixels=False): """Return ffmpeg's display-coordinate (width, height), accounting for rotation and SAR.""" cmd = [ "ffprobe", "-v", "error", "-select_streams", "v:0", "-show_entries", "stream=width,height,sample_aspect_ratio:stream_tags=rotate:stream_side_data=rotation", "-of", "json", str(path), ] res = subprocess.run( cmd, capture_output=True, text=True, encoding="utf-8", errors="replace" ) try: stream = json.loads(res.stdout)["streams"][0] width, height = int(stream["width"]), int(stream["height"]) except (IndexError, KeyError, ValueError): detail = (res.stderr or res.stdout or "ffprobe failed").strip() raise SystemExit(f"无法读取视频画布: {path} ({detail})") from None sar = stream.get("sample_aspect_ratio", "1:1") try: num, den = sar.split(":", 1) sar_ratio = float(num) / float(den) except (ValueError, ZeroDivisionError): sar_ratio = math.nan if sar in {"0:1", "N/A"}: sar_ratio = 1.0 # unspecified SAR: ffmpeg (and the renderer's canvas) treat it as square if require_near_square_pixels and ( not math.isfinite(sar_ratio) or abs(sar_ratio - 1.0) > SUBTITLE_BAND_SAR_TOLERANCE + 1e-9 ): raise SystemExit( "subtitle Y coordinates require square or near-square pixels " f"(SAR within {SUBTITLE_BAND_SAR_TOLERANCE:.0%} of 1:1); got {sar}" ) display_width = max(1, round(width * sar_ratio)) if math.isfinite(sar_ratio) else width rotation_values = [ stream.get("tags", {}).get("rotate"), *(item.get("rotation") for item in stream.get("side_data_list", [])), ] rotation = next( (int(round(float(value))) % 360 for value in rotation_values if value not in (None, "")), 0, ) return (height, display_width) if rotation in {90, 270} else (display_width, height) def _analysis_settings(args): return { "context": args.context, "scene_threshold": args.scene_threshold, "style": args.style, "edit_mode": args.edit_mode, "target_duration": args.target_duration, "skip_asr": bool(args.skip_asr), # Frozen at False: restore_material compares these settings by equality, so dropping a # retired key would turn every saved material into a paid re-analysis. "mimo_video_overview": False, "consolidate_asr": False, } def _run_manifest_payload(video, args): return { "schema_version": 1, "source_video": str(Path(video).resolve()), "source_video_identity": file_identity(video), "settings": _analysis_settings(args), "audio": audio_binding(args), } # Settings main() can take from the environment rather than argv, with their no-env value. # A resume shell may not carry the same environment, so the resume argv pins them. _ENV_FILLED = ( ("tts_provider", "auto"), ("voice_ref", None), ) def _resume_argv(work_dir, args): """The argv that resumes this run: what the user typed (paths made absolute by recap_cli), plus the work dir and any environment-filled setting it did not spell out. Values a --project binding filled in are re-derived from --project on resume.""" argv = list(args._argv) explicit = args._explicit_options bound = getattr(args, "_bound_from_project", frozenset()) if "--work-dir" not in explicit: argv += ["--work-dir", str(work_dir)] for dest, unset in _ENV_FILLED: flag = "--" + dest.replace("_", "-") value = getattr(args, dest) if flag not in explicit and dest not in bound and value != unset: argv += [flag, str(value)] return argv def _write_manifest_with_argv(work_dir, payload, args): extra = {} if getattr(args, "audio_mode", "narration") == "narration": provider = getattr(args, "tts_provider", None) if isinstance(provider, str) and provider.strip(): extra["tts_provider"] = provider.strip().lower() (work_dir / RUN_MANIFEST).write_text( json.dumps( {**payload, **extra, "argv": _resume_argv(work_dir, args)}, ensure_ascii=False, indent=2, ), encoding="utf-8", ) def _write_run_manifest(work_dir, video, args): _write_manifest_with_argv(work_dir, _run_manifest_payload(video, args), args) def _build_multi_source_records(videos, args): records = [] for video in videos: identity = file_identity(video) records.append( { "source_path": str(video), "source_name": video.name, "source_video_identity": identity, "settings": _analysis_settings(args), "material_id": material_id_for(video, identity), } ) records = material_lib.assign_source_ids(records) for record in records: record["source_work_dir"] = f"sources/{record['source_id']}" return records def _multi_run_manifest_payload(args, source_records): return { "schema_version": 2, "mode": "multi_source", "sources": [ { "source_id": s["source_id"], "source_path": s["source_path"], "source_video_identity": s["source_video_identity"], "source_work_dir": s["source_work_dir"], "material_id": s["material_id"], } for s in source_records ], "settings": _analysis_settings(args), "audio": audio_binding(args), } def _write_project_run_manifest(work_dir, args, source_records): _write_manifest_with_argv(work_dir, _multi_run_manifest_payload(args, source_records), args) def _write_multi_source_manifest(work_dir, source_records): path = Path(work_dir) / MULTI_SOURCE_MANIFEST payload = { "schema_version": 1, "sources": [ { "source_id": s["source_id"], "source_path": s["source_path"], "source_name": s["source_name"], "source_video_identity": s["source_video_identity"], "source_work_dir": s["source_work_dir"], "material_id": s["material_id"], } for s in source_records ], } path.write_text(json.dumps(payload, ensure_ascii=False, indent=2), encoding="utf-8") return path def _load_run_manifest(work_dir): """The run manifest, or None before Phase A has written one.""" path = Path(work_dir) / RUN_MANIFEST return load_json(path) if path.exists() else None def _burn_subtitles_intended(args): """Effective burn-subtitles state at orchestrator level. Mirrors assemble.py's CONFIG default `env_bool("BURN_SUBTITLES", True)` (burn is ON by default); an explicit CLI flag (--burn-subtitles / --no-burn-subtitles) overrides the env.""" if args.burn_subtitles is not None: return args.burn_subtitles return env_bool("BURN_SUBTITLES", True) def _ffmpeg_present_but_cannot_burn(): """True only when ffmpeg EXISTS but lacks the libass `subtitles` filter — the specific "subtitle-burn environment unsupported" case. Returns False when ffmpeg is absent entirely: that is a more fundamental problem that surfaces at the first stage (understand calls ffprobe/ffmpeg) and is reported by doctor, so this guard stays narrow — and does not fire in mocked, ffmpeg-less test environments.""" if shutil.which("ffmpeg") is None: return False return not ffmpeg_has_subtitles_filter() def _burn_subtitles_explicit(args): """Burn was asked for, not inherited: --burn-subtitles, or a truthy BURN_SUBTITLES.""" if args.burn_subtitles is not None: return args.burn_subtitles return "BURN_SUBTITLES" in os.environ and env_bool("BURN_SUBTITLES", True) def _preflight_burn_subtitles(args): """Settle subtitle burn-in BEFORE any understanding/VLM/ASR/TTS spend when this ffmpeg lacks libass. An explicit request fails fast here, since otherwise the run only dies at the final assemble `-vf subtitles=` step. The default burn only warns: assemble then delivers the .srt sidecar and records `subtitle_burn_degraded` in visual_qc.json, which final_qc.json carries in metadata.warnings.""" if not _burn_subtitles_intended(args): return if not _ffmpeg_present_but_cannot_burn(): return doctor = f"python3 {shlex.quote(str(_entry('doctor.py')))}" if _burn_subtitles_explicit(args): raise SystemExit( "已显式要求烧录字幕(--burn-subtitles 或 BURN_SUBTITLES),但当前 ffmpeg 不支持" " subtitles/libass 滤镜,整条流程会跑到最后渲染才失败。\n" " 解决其一:(1) 安装带 libass 的 ffmpeg;(2) 去掉显式烧录要求,默认运行会改为输出" " .srt 外挂字幕;(3) 加 --no-burn-subtitles。\n" f" 自检:{doctor}" ) print( "[video-recap] ⚠ 当前 ffmpeg 不支持 subtitles/libass 滤镜:本次成片不烧录字幕。" "有字幕条目时改为在成片旁输出同名 .srt 外挂字幕(final_qc.json 的 metadata.warnings" " 会记录 subtitle_burn_degraded);没有字幕条目的运行(如 source 音频模式且没有" " original_subtitles.json)不输出 .srt,也不记警告。要烧录字幕请安装带 libass 的 ffmpeg;" f"自检:{doctor}", flush=True, ) def _entry(script): return SCRIPT_DIR / script