preflight.py 7.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177
  1. #!/usr/bin/env python3
  2. """Validate a presenter-video job and write a machine-readable preflight report."""
  3. from __future__ import annotations
  4. import json
  5. import shutil
  6. import subprocess
  7. import sys
  8. from pathlib import Path
  9. from typing import Any
  10. def probe(path: Path) -> dict[str, Any]:
  11. result = subprocess.run(
  12. [
  13. "ffprobe",
  14. "-v",
  15. "error",
  16. "-show_entries",
  17. "stream=index,codec_type,codec_name,width,height,pix_fmt,sample_rate,channels,r_frame_rate:format=duration,size,bit_rate",
  18. "-of",
  19. "json",
  20. str(path),
  21. ],
  22. stdin=subprocess.DEVNULL, check=True,
  23. capture_output=True,
  24. text=True,
  25. )
  26. return json.loads(result.stdout)
  27. def require_file(value: str, label: str, errors: list[str]) -> Path | None:
  28. if not value:
  29. errors.append(f"missing {label}")
  30. return None
  31. path = Path(value).expanduser().resolve()
  32. if not path.is_file():
  33. errors.append(f"{label} is not a file: {path}")
  34. return None
  35. return path
  36. def write_atomic(path: Path, text: str) -> None:
  37. temporary = path.with_suffix(path.suffix + ".tmp")
  38. temporary.write_text(text, encoding="utf-8")
  39. temporary.replace(path)
  40. def main() -> int:
  41. if len(sys.argv) != 2:
  42. print("Usage: preflight.py ~/Videos/my-presenter-video/job.json", file=sys.stderr)
  43. return 64
  44. if not shutil.which("ffprobe"):
  45. print("ERROR: ffprobe is required", file=sys.stderr)
  46. return 2
  47. job_path = Path(sys.argv[1]).expanduser().resolve()
  48. if not job_path.is_file():
  49. print(f"ERROR: job manifest does not exist: {job_path}", file=sys.stderr)
  50. return 2
  51. job = json.loads(job_path.read_text(encoding="utf-8"))
  52. job_dir = job_path.parent
  53. errors: list[str] = []
  54. remote_blockers: list[str] = []
  55. warnings: list[str] = []
  56. media: dict[str, Any] = {}
  57. input_data = job.get("input", {})
  58. topic = str(input_data.get("topic", "")).strip()
  59. script_text = str(input_data.get("script_path", "")).strip()
  60. if not topic and not script_text:
  61. errors.append("topic or script_path is required")
  62. if script_text:
  63. require_file(script_text, "script", errors)
  64. image = require_file(str(input_data.get("presenter_image", "")), "presenter image", errors)
  65. if image:
  66. try:
  67. media["presenter_image"] = probe(image)
  68. streams = [
  69. stream
  70. for stream in media["presenter_image"].get("streams", [])
  71. if stream.get("codec_type") == "video"
  72. ]
  73. if not streams:
  74. errors.append("presenter image has no decodable image/video stream")
  75. else:
  76. width = int(streams[0].get("width") or 0)
  77. height = int(streams[0].get("height") or 0)
  78. if min(width, height) < 512:
  79. warnings.append(f"presenter image is low resolution: {width}x{height}")
  80. except (subprocess.CalledProcessError, json.JSONDecodeError) as exc:
  81. errors.append(f"could not decode presenter image: {exc}")
  82. voice_value = str(input_data.get("voice_sample", "")).strip()
  83. if voice_value:
  84. voice = require_file(voice_value, "voice sample", errors)
  85. if voice:
  86. try:
  87. media["voice_sample"] = probe(voice)
  88. streams = [
  89. stream
  90. for stream in media["voice_sample"].get("streams", [])
  91. if stream.get("codec_type") == "audio"
  92. ]
  93. if not streams:
  94. errors.append("voice sample has no audio stream")
  95. duration = float(media["voice_sample"].get("format", {}).get("duration") or 0)
  96. if duration < 4:
  97. warnings.append(f"voice sample is short: {duration:.3f}s")
  98. if duration > 60:
  99. warnings.append(f"voice sample is unusually long: {duration:.3f}s")
  100. except (subprocess.CalledProcessError, json.JSONDecodeError, ValueError) as exc:
  101. errors.append(f"could not decode voice sample: {exc}")
  102. if not input_data.get("voice_clone_approved"):
  103. remote_blockers.append("voice_clone_approved must be true before voice cloning")
  104. else:
  105. warnings.append("no voice sample supplied; use and record a stock voice")
  106. supporting_reports = []
  107. for value in input_data.get("supporting_media", []):
  108. path = require_file(str(value), "supporting media", errors)
  109. if path:
  110. try:
  111. supporting_reports.append({"file": path.name, "probe": probe(path)})
  112. except (subprocess.CalledProcessError, json.JSONDecodeError) as exc:
  113. errors.append(f"could not decode supporting media {path}: {exc}")
  114. media["supporting_media"] = supporting_reports
  115. if not input_data.get("rights_confirmed"):
  116. remote_blockers.append("rights_confirmed must be true before presenter synthesis")
  117. if not input_data.get("adult_presenter_confirmed"):
  118. remote_blockers.append("adult_presenter_confirmed must be true before presenter synthesis")
  119. if not input_data.get("remote_upload_approved"):
  120. remote_blockers.append("remote_upload_approved must be true before remote generation")
  121. manual = job.get("manual_input_review", {})
  122. for key in ("image_viewed", "single_clear_face", "image_has_no_unwanted_text"):
  123. if not manual.get(key):
  124. errors.append(f"manual_input_review.{key} must be true")
  125. if voice_value:
  126. for key in ("voice_sample_listened", "single_clear_speaker"):
  127. if not manual.get(key):
  128. errors.append(f"manual_input_review.{key} must be true")
  129. creative = job.get("creative", {})
  130. duration = float(creative.get("duration_target_s") or 0)
  131. if not 5 <= duration <= 1800:
  132. errors.append("creative.duration_target_s must be between 5 and 1800")
  133. width = int(creative.get("width") or 0)
  134. height = int(creative.get("height") or 0)
  135. if min(width, height) < 256 or max(width, height) > 7680:
  136. errors.append("creative width/height must be between 256 and 7680")
  137. if int(creative.get("fps") or 0) not in (24, 25, 30, 50, 60):
  138. errors.append("creative.fps must be one of 24, 25, 30, 50, or 60")
  139. report_path = job_dir / "qa" / "reports" / "preflight.json"
  140. report_path.parent.mkdir(parents=True, exist_ok=True)
  141. report = {
  142. "ok": not errors,
  143. "remote_ready": not errors and not remote_blockers,
  144. "job": job_path.name,
  145. "errors": errors,
  146. "remote_blockers": remote_blockers,
  147. "warnings": warnings,
  148. "media": media,
  149. }
  150. write_atomic(report_path, json.dumps(report, ensure_ascii=False, indent=2) + "\n")
  151. job.setdefault("qa", {})["preflight_report"] = "qa/reports/preflight.json"
  152. write_atomic(job_path, json.dumps(job, ensure_ascii=False, indent=2) + "\n")
  153. print(json.dumps(report, ensure_ascii=False, indent=2))
  154. return 0 if not errors else 1
  155. if __name__ == "__main__":
  156. raise SystemExit(main())