Skip to content

Open-source AI podcast clipper. Generate vertical clips with face tracking and burned-in captions. CLI, MCP server, web app.

backend: extract cut_segment / cut_multi_segment into video_cut

Nika Siradze96d565048820
diff --git a/backend/services/video_cut.py b/backend/services/video_cut.py
new file mode 100644
index 0000000..55aea80
--- /dev/null
+++ b/backend/services/video_cut.py
@@ -0,0 +1,98 @@
+"""Video cutting helpers — extract time ranges and stitch them together.
+
+Extracted from video_processor.py. These are the two entry points used
+by the clip generator to slice the source video before any cropping or
+caption rendering.
+"""
+
+from __future__ import annotations
+
+import os
+
+from services.media_probe import FFMPEG_TIMEOUT
+from utils.proc import run as proc_run
+
+
+def cut_segment(
+ input_path: str,
+ output_path: str,
+ start_second: float,
+ end_second: float,
+) -> str:
+ """Extract a single time segment from a video file.
+
+ Uses `-ss` before `-i` with re-encoding for frame-accurate
+ timestamps. The fast preset + CRF 18 is a deliberate quality
+ trade-off: we'll re-encode again in the final pipeline, so this
+ pass prioritizes speed.
+ """
+ duration = end_second - start_second
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-ss", str(start_second),
+ "-i", input_path,
+ "-t", str(duration),
+ "-c:v", "libx264", "-crf", "18", "-preset", "fast", "-profile:v", "high",
+ "-c:a", "aac", "-b:a", "192k",
+ "-avoid_negative_ts", "make_zero",
+ output_path,
+ ]
+ result = proc_run(cmd, timeout=FFMPEG_TIMEOUT, check=False)
+ if result.returncode != 0:
+ raise RuntimeError(f"FFmpeg cut failed: {result.stderr[-500:]}")
+ return output_path
+
+
+def cut_multi_segment(
+ input_path: str,
+ output_path: str,
+ segments: list[dict],
+) -> str:
+ """Cut multiple time ranges and concatenate them seamlessly.
+
+ segments: [{"start": 10.5, "end": 25.0}, {"start": 30.2, "end": 45.0}]
+
+ Each segment is cut individually with frame-accurate encoding,
+ then concatenated with stream copy (matching codecs means no
+ re-encode needed).
+ """
+ if len(segments) == 1:
+ return cut_segment(
+ input_path, output_path, segments[0]["start"], segments[0]["end"]
+ )
+
+ work_dir = os.path.dirname(output_path) or "."
+ part_paths: list[str] = []
+ concat_file = os.path.join(work_dir, "_concat_parts.txt")
+
+ try:
+ for i, seg in enumerate(segments):
+ part_path = os.path.join(work_dir, f"_part_{i}.mp4")
+ cut_segment(input_path, part_path, seg["start"], seg["end"])
+ part_paths.append(part_path)
+
+ with open(concat_file, "w") as f:
+ for p in part_paths:
+ f.write(f"file '{os.path.abspath(p)}'\n")
+
+ cmd = [
+ "ffmpeg", "-y",
+ "-f", "concat", "-safe", "0",
+ "-i", concat_file,
+ "-c", "copy",
+ "-movflags", "+faststart",
+ output_path,
+ ]
+ result = proc_run(cmd, timeout=FFMPEG_TIMEOUT, check=False)
+ if result.returncode != 0:
+ raise RuntimeError(f"FFmpeg concat failed: {result.stderr[-500:]}")
+
+ return output_path
+
+ finally:
+ for p in part_paths:
+ if os.path.exists(p):
+ os.remove(p)
+ if os.path.exists(concat_file):
+ os.remove(concat_file)
diff --git a/backend/services/video_processor.py b/backend/services/video_processor.py
index 99dc964..ecc3ebd 100644
--- a/backend/services/video_processor.py
+++ b/backend/services/video_processor.py
@@ -26,95 +26,10 @@ from services.media_probe import (
run_ffmpeg_with_fallback as _run_ffmpeg_with_fallback,
)
from services.audio_normalize import normalize_audio
+from services.video_cut import cut_segment, cut_multi_segment
import sys
-def cut_segment(
- input_path: str,
- output_path: str,
- start_second: float,
- end_second: float,
-) -> str:
- """
- Extract a time segment from a video file.
- Uses -ss before -i with re-encoding for frame-accurate timestamps.
- """
- duration = end_second - start_second
-
- cmd = [
- "ffmpeg", "-y",
- "-ss", str(start_second),
- "-i", input_path,
- "-t", str(duration),
- "-c:v", "libx264", "-crf", "18", "-preset", "fast", "-profile:v", "high",
- "-c:a", "aac", "-b:a", "192k",
- "-avoid_negative_ts", "make_zero",
- output_path,
- ]
- result = proc_run(cmd, timeout=_FFMPEG_TIMEOUT, check=False)
- if result.returncode != 0:
- raise RuntimeError(f"FFmpeg cut failed: {result.stderr[-500:]}")
- return output_path
-
-
-def cut_multi_segment(
- input_path: str,
- output_path: str,
- segments: list[dict],
-) -> str:
- """
- Cut multiple time ranges from a video and concatenate them seamlessly.
-
- segments: [{"start": 10.5, "end": 25.0}, {"start": 30.2, "end": 45.0}]
-
- Each segment is cut individually with frame-accurate encoding, then
- concatenated with matching codec settings for gapless playback.
- """
- if len(segments) == 1:
- return cut_segment(input_path, output_path, segments[0]["start"], segments[0]["end"])
-
- work_dir = os.path.dirname(output_path) or "."
- part_paths = []
-
- try:
- # Cut each segment
- for i, seg in enumerate(segments):
- part_path = os.path.join(work_dir, f"_part_{i}.mp4")
- cut_segment(input_path, part_path, seg["start"], seg["end"])
- part_paths.append(part_path)
-
- # Build concat file
- concat_file = os.path.join(work_dir, "_concat_parts.txt")
- with open(concat_file, "w") as f:
- for p in part_paths:
- f.write(f"file '{os.path.abspath(p)}'\n")
-
- # Concatenate with stream copy — parts already have matching codecs
- # from cut_segment, so no re-encode needed
- cmd = [
- "ffmpeg", "-y",
- "-f", "concat", "-safe", "0",
- "-i", concat_file,
- "-c", "copy",
- "-movflags", "+faststart",
- output_path,
- ]
- result = proc_run(cmd, timeout=_FFMPEG_TIMEOUT, check=False)
- if result.returncode != 0:
- raise RuntimeError(f"FFmpeg concat failed: {result.stderr[-500:]}")
-
- return output_path
-
- finally:
- # Clean up temp parts
- for p in part_paths:
- if os.path.exists(p):
- os.remove(p)
- concat_file = os.path.join(work_dir, "_concat_parts.txt")
- if os.path.exists(concat_file):
- os.remove(concat_file)
-
-
def crop_to_vertical(
input_path: str,
output_path: str,
diff --git a/tests/test_video_cut.py b/tests/test_video_cut.py
new file mode 100644
index 0000000..d6a30c8
--- /dev/null
+++ b/tests/test_video_cut.py
@@ -0,0 +1,133 @@
+"""Tests for backend.services.video_cut.
+
+Mocks proc_run so no actual ffmpeg process is spawned. Verifies the
+command shapes, the single-segment shortcut path, and cleanup of
+temporary concat artifacts.
+"""
+
+import os
+import sys
+import tempfile
+import unittest
+from unittest import mock
+
+ROOT = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
+BACKEND_ROOT = os.path.join(ROOT, "backend")
+if BACKEND_ROOT not in sys.path:
+ sys.path.insert(0, BACKEND_ROOT)
+
+from services import video_cut
+
+
+def _ok() -> mock.Mock:
+ return mock.Mock(returncode=0, stdout="", stderr="")
+
+
+def _fail() -> mock.Mock:
+ return mock.Mock(returncode=1, stdout="", stderr="ffmpeg error")
+
+
+class CutSegmentTests(unittest.TestCase):
+ def test_runs_ffmpeg_with_expected_flags(self):
+ with mock.patch.object(video_cut, "proc_run", return_value=_ok()) as mocked:
+ out = video_cut.cut_segment("/in.mp4", "/out.mp4", 10.5, 20.25)
+ self.assertEqual(out, "/out.mp4")
+
+ cmd = mocked.call_args.args[0]
+ joined = " ".join(cmd)
+ self.assertIn("-ss 10.5", joined)
+ self.assertIn("-t 9.75", joined) # end - start
+ self.assertIn("-i /in.mp4", joined)
+ self.assertTrue(cmd[-1] == "/out.mp4")
+
+ def test_raises_on_failure(self):
+ with mock.patch.object(video_cut, "proc_run", return_value=_fail()):
+ with self.assertRaises(RuntimeError) as ctx:
+ video_cut.cut_segment("/in.mp4", "/out.mp4", 0, 5)
+ self.assertIn("FFmpeg cut failed", str(ctx.exception))
+
+
+class CutMultiSegmentTests(unittest.TestCase):
+ def test_single_segment_delegates_to_cut_segment(self):
+ with mock.patch.object(video_cut, "cut_segment", return_value="/out.mp4") as cs:
+ out = video_cut.cut_multi_segment(
+ "/in.mp4", "/out.mp4", [{"start": 0, "end": 5}]
+ )
+ self.assertEqual(out, "/out.mp4")
+ cs.assert_called_once_with("/in.mp4", "/out.mp4", 0, 5)
+
+ def test_multi_segment_invokes_cut_then_concat(self):
+ # Two-segment flow: two cut_segment calls + one proc_run for concat
+ tmpdir = tempfile.mkdtemp(prefix="podcli-cut-test-")
+ out_path = os.path.join(tmpdir, "out.mp4")
+
+ def fake_cut(input_path, out_path, start, end):
+ # Create a stub file so cleanup works
+ with open(out_path, "w") as f:
+ f.write("stub")
+ return out_path
+
+ try:
+ with mock.patch.object(
+ video_cut, "cut_segment", side_effect=fake_cut
+ ) as cs, mock.patch.object(
+ video_cut, "proc_run", return_value=_ok()
+ ) as mocked:
+ out = video_cut.cut_multi_segment(
+ "/in.mp4",
+ out_path,
+ [
+ {"start": 0, "end": 5},
+ {"start": 10, "end": 15},
+ ],
+ )
+ self.assertEqual(out, out_path)
+ self.assertEqual(cs.call_count, 2)
+ # concat call
+ cmd = mocked.call_args.args[0]
+ self.assertIn("concat", cmd)
+ self.assertIn("-c", cmd)
+ self.assertIn("copy", cmd)
+
+ # Temp parts should be cleaned up
+ for i in range(2):
+ self.assertFalse(os.path.exists(os.path.join(tmpdir, f"_part_{i}.mp4")))
+ self.assertFalse(os.path.exists(os.path.join(tmpdir, "_concat_parts.txt")))
+ finally:
+ import shutil
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+ def test_multi_segment_cleans_up_on_failure(self):
+ tmpdir = tempfile.mkdtemp(prefix="podcli-cut-test-")
+ out_path = os.path.join(tmpdir, "out.mp4")
+
+ def fake_cut(input_path, out_path, start, end):
+ with open(out_path, "w") as f:
+ f.write("stub")
+ return out_path
+
+ try:
+ with mock.patch.object(video_cut, "cut_segment", side_effect=fake_cut), \
+ mock.patch.object(video_cut, "proc_run", return_value=_fail()):
+ with self.assertRaises(RuntimeError):
+ video_cut.cut_multi_segment(
+ "/in.mp4", out_path,
+ [{"start": 0, "end": 5}, {"start": 10, "end": 15}],
+ )
+ # Even on failure, temp parts are cleaned up
+ for i in range(2):
+ self.assertFalse(os.path.exists(os.path.join(tmpdir, f"_part_{i}.mp4")))
+ finally:
+ import shutil
+ shutil.rmtree(tmpdir, ignore_errors=True)
+
+
+class ReExportTests(unittest.TestCase):
+ def test_video_processor_reexports_cut_helpers(self):
+ from services import video_processor as vp
+ self.assertIs(vp.cut_segment, video_cut.cut_segment)
+ self.assertIs(vp.cut_multi_segment, video_cut.cut_multi_segment)
+
+
+if __name__ == "__main__":
+ unittest.main()