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
68 changes: 62 additions & 6 deletions backend/cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,8 @@
import argparse
import json
import os
import threading
import queue
from utils.log import warn as log_warn
import re
import shlex
Expand Down Expand Up @@ -1950,6 +1952,14 @@ def _transcribe_progress(pct, msg):

_ai_label = " (+ AI titles)" if (_ai_cli_path and config.get("generate_content", True)) else ""
print(f"\n [4/4] Exporting {len(clips)} clips{_ai_label} to {output_dir}/")
_content_jobs = {}
if _ai_cli_path and config.get("generate_content", True):
from services.content_generator import generate_clip_content

_content_jobs = _start_background_jobs(
{idx: (lambda c=c: generate_clip_content(clip=c, transcript_segments=segments)) for idx, c in enumerate(clips)},
workers=3,
)
results = []
t0 = time.time()
_skip_review = (
Expand Down Expand Up @@ -2053,13 +2063,9 @@ def _transcribe_progress(pct, msg):
print(f" ⚠ thumbnail: {e}")

# Generate titles, descriptions, tags for this clip immediately
if _ai_cli_path and config.get("generate_content", True) and result.get("output_path"):
if i in _content_jobs and result.get("output_path"):
try:
from services.content_generator import generate_clip_content
content_result = generate_clip_content(
clip=clip,
transcript_segments=segments,
)
content_result = _content_jobs[i].result()
if content_result and content_result.get("raw_text"):
# Save per-clip content to file
_content_path = result["output_path"].replace(".mp4", "_content.md")
Expand Down Expand Up @@ -2249,6 +2255,9 @@ def _transcribe_progress(pct, msg):
except KeyboardInterrupt:
interrupted = True
print(f"\n ⚠ Render interrupted: keeping completed clips")
finally:
for job in _content_jobs.values():
job.cancel()

elapsed = time.time() - t0
success = sum(1 for r in results if "output_path" in r)
Expand Down Expand Up @@ -2345,6 +2354,53 @@ def _wrap_text(text: str, indent: str) -> str:
return textwrap.fill(text, width=width, initial_indent=indent, subsequent_indent=indent)


class _BackgroundJob:
"""A result computed on a daemon thread, so an interrupted run can exit while it is still going."""

def __init__(self, work):
self._work = work
self._done = threading.Event()
self._cancelled = False
self._value = None
self._error = None

def run(self):
if not self._cancelled:
try:
self._value = self._work()
except BaseException as exc:
self._error = exc
self._done.set()

def cancel(self):
self._cancelled = True

def result(self):
self._done.wait()
if self._error is not None:
raise self._error
return self._value


def _start_background_jobs(works: dict, workers: int) -> dict:
"""Start the jobs in order, at most `workers` at a time, on daemon threads."""
jobs = {key: _BackgroundJob(work) for key, work in works.items()}
pending = queue.Queue()
for job in jobs.values():
pending.put(job)

def drain():
while True:
try:
pending.get_nowait().run()
except queue.Empty:
return

for _ in range(min(workers, len(jobs))):
threading.Thread(target=drain, daemon=True).start()
return jobs


def _print_clips(clips: list):
"""Print clip list in the standard format."""
width = min(shutil.get_terminal_size((100, 24)).columns, 100)
Expand Down
19 changes: 15 additions & 4 deletions backend/services/transcription_whispercpp.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,18 @@ def _extract_wav(media_path: str, wav_path: str, ffmpeg: str = "ffmpeg") -> None
)


def _load_whisper_json(path: str) -> dict:
# whisper.cpp can split one multi-byte character across two tokens, which
# leaves invalid UTF-8 in the file. surrogateescape keeps those bytes so
# _heal_utf8 can rejoin them once the tokens are concatenated.
with open(path, encoding="utf-8", errors="surrogateescape") as f:
return json.load(f)


def _heal_utf8(text: str) -> str:
return text.encode("utf-8", "surrogateescape").decode("utf-8", "replace")


def _tokens_to_words(tokens: list[dict]) -> list[dict]:
"""Merge whisper.cpp subword tokens into words with start/end seconds."""
words: list[dict] = []
Expand All @@ -58,7 +70,7 @@ def _tokens_to_words(tokens: list[dict]) -> list[dict]:

def flush():
nonlocal cur_text, cur_start, cur_end
text = cur_text.strip().lstrip("▁").strip()
text = _heal_utf8(cur_text.strip().lstrip("▁").strip())
if text and cur_start is not None:
words.append({
"word": text,
Expand Down Expand Up @@ -221,8 +233,7 @@ def transcribe_file(
cmd += ["-l", language or "auto"]
subprocess.run(cmd, check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, text=True, timeout=7200)

with open(out_base + ".json", encoding="utf-8") as f:
data = json.load(f)
data = _load_whisper_json(out_base + ".json")

transcription = data.get("transcription", [])
segments, words = [], []
Expand All @@ -232,7 +243,7 @@ def transcribe_file(
"id": i,
"start": round((off.get("from") or 0) / 1000.0, 3),
"end": round((off.get("to") or 0) / 1000.0, 3),
"text": (seg.get("text") or "").strip(),
"text": _heal_utf8((seg.get("text") or "").strip()),
"speaker": None,
})
words.extend(_tokens_to_words(seg.get("tokens", [])))
Expand Down
6 changes: 3 additions & 3 deletions backend/services/video_cut.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ def cut_segment(
silently emits up to a full GOP of earlier content while the duration still
checks out, which offsets every burned-in caption. CRF 16 keeps this
intermediate visually lossless through the later crop/caption/audio
re-encodes; the fast preset holds the speed cost to a few percent
over the old CRF 18 pass.
re-encodes. veryfast cuts about half the time of fast at the same CRF
(SSIM within 0.001 on a 1080p podcast cut), and the file is smaller.
"""
duration = end_second - start_second

Expand All @@ -37,7 +37,7 @@ def cut_segment(
"-ss", str(start_second),
"-i", input_path,
"-t", str(duration),
"-c:v", "libx264", "-crf", "16", "-preset", "fast", "-profile:v", "high",
"-c:v", "libx264", "-crf", "16", "-preset", "veryfast", "-profile:v", "high",
"-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "192k",
"-avoid_negative_ts", "make_zero",
Expand Down
10 changes: 5 additions & 5 deletions backend/services/video_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -215,7 +215,7 @@ def _replace_layout_flash_frames(video_path: str, cut_times: list[float], durati
parts.append("".join(labels) + f"concat=n={len(labels)}:v=1:a=0[v]")
temp = video_path + ".layout-guard.mp4"
cmd = ["ffmpeg", "-y", "-i", video_path, "-filter_complex", ";".join(parts),
"-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-crf", "18", "-preset", "fast", "-pix_fmt", "yuv420p",
"-map", "[v]", "-map", "0:a?", "-c:v", "libx264", "-crf", "18", "-preset", "veryfast", "-pix_fmt", "yuv420p",
"-c:a", "copy", "-t", f"{duration:.3f}", "-movflags", "+faststart", temp]
result = proc_run(cmd, timeout=_FFMPEG_TIMEOUT, check=False)
if result.returncode != 0 or not os.path.exists(temp):
Expand Down Expand Up @@ -1796,7 +1796,7 @@ def _run_center(cxs: list[float]) -> float:
"-i", input_path,
"-vf", seg_vf,
"-an",
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
"-c:v", "libx264", "-crf", "18", "-preset", "veryfast",
"-pix_fmt", "yuv420p",
"-avoid_negative_ts", "make_zero",
part_path,
Expand Down Expand Up @@ -1861,7 +1861,7 @@ def _run_center(cxs: list[float]) -> float:
if _has_audio_stream(input_path):
cmd += ["-map", f"{source_index}:a", "-c:a", "aac", "-b:a", "192k"]
cmd += [
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
"-c:v", "libx264", "-crf", "18", "-preset", "veryfast",
# xfade answers format negotiation with yuv444p even
# when both of its inputs are yuv420p, and nothing here
# asked for a format, so this wrote High 4:4:4
Expand Down Expand Up @@ -1905,7 +1905,7 @@ def _run_center(cxs: list[float]) -> float:
"-i", input_path,
"-vf", (f"crop={crop_w}:{crop_h}:{_crop_for(r_cx)}:{crop_y},"
f"scale={target_w}:{target_h}"),
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
"-c:v", "libx264", "-crf", "18", "-preset", "veryfast",
"-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "192k", "-ar", "44100",
"-avoid_negative_ts", "make_zero",
Expand Down Expand Up @@ -2422,7 +2422,7 @@ def _is_segment_split(seg_start_t):
"-ss", str(start_t), "-t", str(seg_duration),
"-i", input_path,
"-vf", vf,
"-c:v", "libx264", "-crf", "18", "-preset", "fast",
"-c:v", "libx264", "-crf", "18", "-preset", "veryfast",
"-pix_fmt", "yuv420p",
"-c:a", "aac", "-b:a", "192k",
"-avoid_negative_ts", "make_zero",
Expand Down
63 changes: 63 additions & 0 deletions tests/test_background_jobs.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import os
import subprocess
import sys
import threading
import time
import unittest

ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
BACKEND_ROOT = os.path.join(ROOT, "backend")
if BACKEND_ROOT not in sys.path:
sys.path.insert(0, BACKEND_ROOT)
import cli as cli_mod


class BackgroundJobTests(unittest.TestCase):
def test_jobs_run_together_up_to_the_worker_limit_and_return_their_own_results(self):
running = 0
peak = 0
lock = threading.Lock()

def work(value):
def run():
nonlocal running, peak
with lock:
running += 1
peak = max(peak, running)
time.sleep(0.05)
with lock:
running -= 1
return value
return run

jobs = cli_mod._start_background_jobs({i: work(i * 10) for i in range(8)}, workers=3)

self.assertEqual([jobs[i].result() for i in range(8)], [i * 10 for i in range(8)])
self.assertEqual(peak, 3)

def test_a_failure_is_raised_for_that_job_only(self):
def boom():
raise ValueError("no")

jobs = cli_mod._start_background_jobs({"a": lambda: 1, "b": boom}, workers=2)

self.assertEqual(jobs["a"].result(), 1)
with self.assertRaises(ValueError):
jobs["b"].result()

def test_a_job_still_running_does_not_keep_the_process_alive(self):
code = (
"import sys, time\n"
f"sys.path.insert(0, {BACKEND_ROOT!r})\n"
"import cli\n"
"cli._start_background_jobs({0: lambda: time.sleep(60)}, workers=1)\n"
"time.sleep(0.2)\n"
)
started = time.time()
subprocess.run([sys.executable, "-c", code], check=True, timeout=30, capture_output=True)

self.assertLess(time.time() - started, 20)


if __name__ == "__main__":
unittest.main()
Loading