Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion backend/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -1181,7 +1181,7 @@ def _parse_content_text(raw: str) -> dict:
}


def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, results, interrupted):
def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, results, interrupted, transcript=None):
payload_clips = []
for i, result in enumerate(results):
clip = clips[i] if i < len(clips) else {}
Expand Down Expand Up @@ -1210,6 +1210,7 @@ def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, resu
"start_second": result.get("start_second", clip.get("start_second")),
"end_second": result.get("end_second", clip.get("end_second")),
"score": clip.get("score"),
"crop_strategy": result.get("crop_strategy_used"),
"file_size_mb": result.get("file_size_mb"),
"status": result.get("status", "ok" if path else "error"),
"error": result.get("error"),
Expand All @@ -1224,6 +1225,7 @@ def _emit_process_json(*, json_out, video_path, output_dir, quality, clips, resu
"video": video_path,
"output_dir": output_dir,
"quality": quality,
"transcript": transcript,
"clips": payload_clips,
}
print(json.dumps(payload, ensure_ascii=False), file=json_out, flush=True)
Expand Down Expand Up @@ -1659,6 +1661,11 @@ def _transcribe_progress(pct, msg):
language=config.get("language"),
)

transcript_info = None if args.transcript or not result.get("words") else {
"engine": result.get("engine") or cache_key["engine"],
"model": result.get("model_size") or cache_key["model_size"],
}

# Apply word corrections (Whisper misheard proper nouns, brand names)
from services.corrections import apply_corrections
apply_corrections(words, segments)
Expand Down Expand Up @@ -2274,6 +2281,7 @@ def _transcribe_progress(pct, msg):
clips=clips,
results=results,
interrupted=interrupted,
transcript=transcript_info,
)

# ── Post-render iteration ──
Expand Down
116 changes: 116 additions & 0 deletions scripts/bench_clips.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,116 @@
import argparse
import csv
import json
import os
import re
import subprocess
import sys
import time

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
BACKEND = os.path.join(ROOT, "backend")

STAGE_RE = re.compile(r"\[([1-4])/4\]")
STAGE_NAMES = {"1": "transcribe", "2": "audio", "3": "select", "4": "render"}
CLIP_FIELDS = [
"clip_id", "format", "start", "end", "duration", "title", "crop_strategy",
"engine", "model", "transcribe_s", "audio_s", "select_s", "render_s", "total_s",
]
SCORE_FIELDS = [
"clip_id", "file", "start_clean", "end_clean", "hook", "standalone",
"captions", "framing", "post_as_is", "notes",
]


def stage_times(marks: list[tuple[str, float]], finished: float) -> dict[str, float]:
times = {name: 0.0 for name in STAGE_NAMES.values()}
for i, (stage, started) in enumerate(marks):
ended = marks[i + 1][1] if i + 1 < len(marks) else finished
times[STAGE_NAMES[stage]] += ended - started
return {k: round(v, 1) for k, v in times.items()}


def run_format(video: str, fmt: str, out_dir: str, top: int) -> tuple[dict, dict[str, float], float]:
cmd = [
sys.executable, os.path.join(BACKEND, "cli.py"), "process", video,
"--format", fmt, "--output", out_dir, "--top", str(top),
"--no-resume", "--json", "--yes",
]
marks: list[tuple[str, float]] = []
started = time.perf_counter()
proc = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, bufsize=1)
assert proc.stderr is not None
for line in proc.stderr:
sys.stderr.write(line)
match = STAGE_RE.search(line)
if match and (not marks or marks[-1][0] != match.group(1)):
marks.append((match.group(1), time.perf_counter()))
stdout = proc.stdout.read() if proc.stdout else ""
proc.wait()
finished = time.perf_counter()
if proc.returncode != 0:
raise SystemExit(f"podcli process failed for format {fmt} (exit {proc.returncode})")
payload = json.loads(stdout.strip().splitlines()[-1])
return payload, stage_times(marks, finished), round(finished - started, 1)


def main() -> int:
parser = argparse.ArgumentParser(description="Run podcli on one episode and write benchmark CSVs.")
parser.add_argument("video")
parser.add_argument("output_dir")
parser.add_argument("--formats", default="vertical,topic")
parser.add_argument("--top", type=int, default=5)
args = parser.parse_args()

video = os.path.abspath(args.video)
if not os.path.exists(video):
print(f"File not found: {video}", file=sys.stderr)
return 1
os.makedirs(args.output_dir, exist_ok=True)

clip_rows, score_rows, failed = [], [], []
for fmt in [f.strip() for f in args.formats.split(",") if f.strip()]:
fmt_dir = os.path.join(os.path.abspath(args.output_dir), fmt)
payload, times, total = run_format(video, fmt, fmt_dir, args.top)
transcript = payload.get("transcript") or {}
for clip in payload.get("clips", []):
Comment thread
nmbrthirteen marked this conversation as resolved.
Resolved
if clip.get("status") != "ok" or not clip.get("path"):
failed.append(f"{fmt}-{clip.get('index')}: {clip.get('error') or 'no output file'}")
continue
clip_id = f"{fmt}-{clip.get('index')}"
clip_rows.append({
"clip_id": clip_id,
"format": fmt,
"start": clip.get("start_second"),
"end": clip.get("end_second"),
"duration": clip.get("output_duration") or clip.get("duration"),
"title": clip.get("title"),
"crop_strategy": clip.get("crop_strategy", ""),
"engine": transcript.get("engine", ""),
"model": transcript.get("model", ""),
"transcribe_s": times["transcribe"],
"audio_s": times["audio"],
"select_s": times["select"],
"render_s": times["render"],
"total_s": total,
})
score_rows.append({"clip_id": clip_id, "file": clip["path"]})

clips_csv = os.path.join(args.output_dir, "clips.csv")
scores_csv = os.path.join(args.output_dir, "scores.csv")
with open(clips_csv, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=CLIP_FIELDS)
writer.writeheader()
writer.writerows(clip_rows)
with open(scores_csv, "w", newline="", encoding="utf-8") as f:
writer = csv.DictWriter(f, fieldnames=SCORE_FIELDS)
writer.writeheader()
writer.writerows(score_rows)
for line in failed:
print(f"Failed export, not scored: {line}", file=sys.stderr)
print(f"{len(clip_rows)} clips. Wrote {clips_csv} and {scores_csv}")
return 0 if clip_rows else 1


if __name__ == "__main__":
sys.exit(main())
79 changes: 79 additions & 0 deletions tests/test_bench_clips.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
import csv
import importlib.util
import os
import shutil
import sys
import tempfile
import unittest
from unittest import mock

ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
spec = importlib.util.spec_from_file_location("bench_clips", os.path.join(ROOT, "scripts", "bench_clips.py"))
bench = importlib.util.module_from_spec(spec)
spec.loader.exec_module(bench)



class StageTimesTests(unittest.TestCase):
def test_each_stage_runs_until_the_next_one_starts(self):
marks = [("1", 0.0), ("2", 30.0), ("3", 35.0), ("4", 95.0)]
self.assertEqual(
bench.stage_times(marks, 215.0),
{"transcribe": 30.0, "audio": 5.0, "select": 60.0, "render": 120.0},
)

def test_a_skipped_stage_reports_zero(self):
self.assertEqual(
bench.stage_times([("1", 0.0), ("3", 2.0), ("4", 12.0)], 20.0),
{"transcribe": 2.0, "audio": 0.0, "select": 10.0, "render": 8.0},
)


class MainWritesCsvTests(unittest.TestCase):
def test_writes_one_clip_row_and_one_blank_score_row_per_clip(self):
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
video = os.path.join(tmp, "ep.mp4")
with open(video, "wb") as f:
f.write(b"x")
payload = {
"transcript": {"engine": "whispercpp", "model": "small"},
"clips": [
{"index": 1, "title": "Why we quit", "start_second": 61.2, "end_second": 98.4, "duration": 37.2,
"crop_strategy": "speaker", "path": "/out/1.mp4", "status": "ok"},
{"index": 2, "title": "Broken", "status": "error", "error": "ffmpeg died"},
],
}
times = {"transcribe": 40.0, "audio": 3.0, "select": 50.0, "render": 20.0}
with mock.patch.object(bench, "run_format", return_value=(payload, times, 113.0)), \
mock.patch.object(sys, "argv", ["bench_clips.py", video, tmp, "--formats", "topic"]):
self.assertEqual(bench.main(), 0)
with open(os.path.join(tmp, "clips.csv"), encoding="utf-8") as f:
rows = list(csv.DictReader(f))
self.assertEqual(rows, [{
"clip_id": "topic-1", "format": "topic", "start": "61.2", "end": "98.4", "duration": "37.2",
"title": "Why we quit", "crop_strategy": "speaker", "engine": "whispercpp", "model": "small",
"transcribe_s": "40.0", "audio_s": "3.0", "select_s": "50.0", "render_s": "20.0", "total_s": "113.0",
}])
with open(os.path.join(tmp, "scores.csv"), encoding="utf-8") as f:
scores = list(csv.DictReader(f))
self.assertEqual(scores[0]["clip_id"], "topic-1")
self.assertEqual(scores[0]["file"], "/out/1.mp4")
self.assertEqual(scores[0]["post_as_is"], "")
self.assertEqual(len(scores), 1)

def test_exits_with_failure_when_no_clip_rendered(self):
tmp = tempfile.mkdtemp()
self.addCleanup(shutil.rmtree, tmp, True)
video = os.path.join(tmp, "ep.mp4")
with open(video, "wb") as f:
f.write(b"x")
payload = {"clips": [{"index": 1, "status": "error", "error": "ffmpeg died"}]}
times = {"transcribe": 1.0, "audio": 1.0, "select": 1.0, "render": 1.0}
with mock.patch.object(bench, "run_format", return_value=(payload, times, 4.0)), \
mock.patch.object(sys, "argv", ["bench_clips.py", video, tmp, "--formats", "vertical"]):
self.assertEqual(bench.main(), 1)


if __name__ == "__main__":
unittest.main()
2 changes: 2 additions & 0 deletions tests/test_cli_helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,9 +181,11 @@ def test_emit_process_json_writes_one_object(self):
clips=[{"title": "A", "start_second": 1, "end_second": 12, "score": 9}],
results=[{"output_path": "/out/a.mp4", "duration": 11, "status": "ok"}],
interrupted=False,
transcript={"engine": "whispercpp", "model": "base"},
)
payload = json.loads(buf.getvalue())
self.assertTrue(payload["ok"])
self.assertEqual(payload["transcript"], {"engine": "whispercpp", "model": "base"})
self.assertEqual(payload["quality"], "high")
self.assertEqual(payload["clips"][0]["title"], "A")
self.assertEqual(payload["clips"][0]["path"], "/out/a.mp4")
Expand Down
Loading