利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
fix(video): isolate intermediate clips across combinations
Rudy Celekli2e1b30396e05
diff --git a/app/services/video.py b/app/services/video.pyindex a9d267cb..3956644a 100644--- a/app/services/video.py+++ b/app/services/video.py@@ -1086,7 +1086,12 @@ def combine_videos(# Write each candidate clip to a unique temporary file. Threads must not# share the same output path.- clip_file = f"{output_dir}/temp-clip-{index + 1}.mp4"+ # Distinct combinations can share a task/output directory. Reserve+ # an owned path so their encoders and cleanup never share a clip.+ with tempfile.NamedTemporaryFile(+ dir=output_dir or ".", prefix="temp-clip-", suffix=".mp4", delete=False+ ) as temporary_clip:+ clip_file = temporary_clip.name_write_videofile_with_codec_fallback(clip,clip_file,diff --git a/test/services/test_combine_clip_isolation.py b/test/services/test_combine_clip_isolation.pynew file mode 100644index 00000000..a065d79d--- /dev/null+++ b/test/services/test_combine_clip_isolation.py@@ -0,0 +1,62 @@+from concurrent.futures import ThreadPoolExecutor+import shutil+import subprocess+import threading+import wave++import numpy as np++from app.models.schema import VideoAspect, VideoConcatMode+from app.services import video+++def test_concurrent_combinations_own_intermediate_clips(tmp_path, monkeypatch):+ binary = video.utils.get_ffmpeg_binary()+ audio = tmp_path / "audio.wav"+ with wave.open(str(audio), "wb") as writer:+ writer.setnchannels(1)+ writer.setsampwidth(2)+ writer.setframerate(24000)+ writer.writeframes(b"\0\0" * 4800)+ sources = []+ for color in ("red", "blue"):+ source = tmp_path / f"{color}.mp4"+ subprocess.run([binary, "-y", "-f", "lavfi", "-i", f"color=c={color}:s=64x64:r=10", "-t", "0.4", "-c:v", "libx264", "-pix_fmt", "yuv420p", str(source)], check=True, capture_output=True)+ sources.append(source)+ monkeypatch.setattr(VideoAspect, "to_resolution", lambda self: (64, 64))+ monkeypatch.setattr(video, "_get_configured_video_codec", lambda: "libx264")+ monkeypatch.setattr(video, "_get_effective_video_codec", lambda *args: "libx264")+ # Serialize the two real encodes, then hold both until they have completed.+ # This deterministically exposes a shared filename before either concat.+ encode_lock = threading.Lock()+ both_encoded = threading.Barrier(2)+ real_write = video._write_videofile_with_codec_fallback+ paths = []++ def encode(clip, target, **kwargs):+ with encode_lock:+ paths.append(target)+ real_write(clip, target, threads=1, **kwargs)+ both_encoded.wait(timeout=15)++ monkeypatch.setattr(video, "_write_videofile_with_codec_fallback", encode)+ foreign = tmp_path / "temp-clip-1.mp4"+ shutil.copyfile(sources[0], foreign)+ sentinel = foreign.read_bytes()++ def combine(index):+ output = tmp_path / f"output-{index}.mp4"+ video.combine_videos(str(output), [str(sources[index])], str(audio), video_concat_mode=VideoConcatMode.sequential, threads=1)+ return output++ with ThreadPoolExecutor(max_workers=2) as executor:+ outputs = list(executor.map(combine, range(2)))+ for index, output in enumerate(outputs):+ with video.VideoFileClip(str(output), audio=False) as clip:+ pixel = np.mean(clip.get_frame(0), axis=(0, 1))+ channel = 0 if index == 0 else 2+ assert pixel[channel] > 200+ assert pixel[2 if index == 0 else 0] < 30+ assert len(set(paths)) == 2+ assert foreign.read_bytes() == sentinel+ assert sorted(p.name for p in tmp_path.iterdir()) == ["audio.wav", "blue.mp4", "output-0.mp4", "output-1.mp4", "red.mp4", "temp-clip-1.mp4"]diff --git a/test/services/test_video.py b/test/services/test_video.pyindex 3da05d8f..9171772a 100644--- a/test/services/test_video.py+++ b/test/services/test_video.py@@ -1220,7 +1220,6 @@ class TestVideoService(unittest.TestCase):with tempfile.TemporaryDirectory() as temp_dir:output_file = os.path.join(temp_dir, "combined.mp4")- temp_clip = Path(temp_dir, "temp-clip-1.mp4")with (patch.object(vd, "AudioFileClip", return_value=FakeAudioClip()),patch.object(vd, "_open_video_clip_quietly", return_value=FakeVideoClip()),@@ -1241,7 +1240,7 @@ class TestVideoService(unittest.TestCase):video_concat_mode=vd.VideoConcatMode.sequential,)- self.assertFalse(temp_clip.exists())+ self.assertFalse(list(Path(temp_dir).glob("temp-clip-*.mp4")))def test_combine_videos_cleans_failed_encoded_clip_and_reader(self):"""A bad source must not strand a partial MP4 or an FFmpeg reader."""@@ -1299,8 +1298,7 @@ class TestVideoService(unittest.TestCase):concat.assert_called_once()self.assertEqual(derived_clips[0].close_calls, 1)- self.assertFalse(Path(temp_dir, "temp-clip-1.mp4").exists())- self.assertFalse(Path(temp_dir, "temp-clip-2.mp4").exists())+ self.assertFalse(list(Path(temp_dir).glob("temp-clip-*.mp4")))def test_combine_videos_skips_unreadable_source_when_good_clip_remains(self):"""A stale corrupt cache clip must not discard healthy downloaded footage."""