利用 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): publish final MP4 only after successful encode
Rudy Celekli4023d8ecb4a4
diff --git a/app/services/video.py b/app/services/video.pyindex 276c1779..6b3a971c 100644--- a/app/services/video.py+++ b/app/services/video.py@@ -404,13 +404,43 @@ def _fallback_write_videofile(clip, output_file: str, failed_codec: str, reason:return _DEFAULT_VIDEO_CODEC-def _write_videofile_with_codec_fallback(clip, output_file: str, codec: str, **kwargs):+def _write_videofile_with_codec_fallback(+ clip, output_file: str, codec: str, atomic_output: bool = False, **kwargs+):"""使用指定编码器写出视频,失败时自动用 libx264 重试一次。硬件编码器是否可用不仅取决于 FFmpeg,还取决于显卡、驱动和当前运行环境。生成任务不能因为高级编码器不可用而整体失败,所以这里把回退集中处理。"""+ if atomic_output:+ # Final videos can be downloaded by path while they are being rendered.+ # Keep both failed encodes and in-progress writes away from that path.+ output_dir = os.path.dirname(os.path.abspath(output_file))+ descriptor, temp_output = tempfile.mkstemp(+ prefix=f".{os.path.basename(output_file)}.",+ suffix=os.path.splitext(output_file)[1] or ".mp4",+ dir=output_dir,+ )+ os.close(descriptor)+ os.unlink(temp_output)+ try:+ used_codec = _write_videofile_with_codec_fallback(+ clip, temp_output, codec, **kwargs+ )+ os.replace(temp_output, output_file)+ return used_codec+ finally:+ try:+ os.unlink(temp_output)+ except FileNotFoundError:+ pass+ except OSError as exc:+ logger.warning(+ f"failed to remove temporary final video: {temp_output}, "+ f"error: {exc}"+ )+effective_codec = _get_effective_video_codec(codec)try:clip.write_videofile(output_file, codec=effective_codec, **kwargs)@@ -1568,6 +1598,7 @@ def generate_video(final_video_clip,output_file=output_file,codec=_get_configured_video_codec(),+ atomic_output=True,audio_codec=audio_codec,audio_fps=output_audio_fps,audio_bitrate=audio_bitrate,diff --git a/test/services/test_video.py b/test/services/test_video.pyindex e6a2b784..4fcee5f3 100644--- a/test/services/test_video.py+++ b/test/services/test_video.py@@ -286,6 +286,7 @@ class TestVideoService(unittest.TestCase):self.assertTrue(result)writer.assert_called_once()+ self.assertTrue(writer.call_args.kwargs["atomic_output"])self.assertEqual(writer.call_args.kwargs["audio_fps"], 48000)self.assertEqual(source_video.close_calls, 1)self.assertEqual(voice_source.close_calls, 1)@@ -652,6 +653,52 @@ class TestVideoService(unittest.TestCase):self.assertNotIn("h264_nvenc", vd._runtime_disabled_video_codecs)+ def test_failed_final_encode_keeps_previous_video_and_removes_partial_file(self):+ """A failed encode must not replace a downloadable final video with partial bytes."""++ class FailingClip:+ def write_videofile(self, output_file, codec, **_kwargs):+ Path(output_file).write_bytes(b"partial mp4")+ raise RuntimeError("encoder stopped")++ with tempfile.TemporaryDirectory() as temp_dir:+ final_path = Path(temp_dir, "final-1.mp4")+ final_path.write_bytes(b"previous complete mp4")++ with self.assertRaisesRegex(RuntimeError, "encoder stopped"):+ vd._write_videofile_with_codec_fallback(+ FailingClip(),+ str(final_path),+ codec="libx264",+ atomic_output=True,+ )++ self.assertEqual(final_path.read_bytes(), b"previous complete mp4")+ self.assertEqual(list(Path(temp_dir).iterdir()), [final_path])++ def test_final_encode_publishes_only_after_writer_returns(self):+ """Readers keep the old final video until the new encode completes."""+ test = self++ class SuccessfulClip:+ def write_videofile(self, output_file, codec, **_kwargs):+ test.assertNotEqual(Path(output_file), final_path)+ test.assertEqual(final_path.read_bytes(), b"previous complete mp4")+ Path(output_file).write_bytes(b"new complete mp4")++ with tempfile.TemporaryDirectory() as temp_dir:+ final_path = Path(temp_dir, "final-1.mp4")+ final_path.write_bytes(b"previous complete mp4")+ vd._write_videofile_with_codec_fallback(+ SuccessfulClip(),+ str(final_path),+ codec="libx264",+ atomic_output=True,+ )++ self.assertEqual(final_path.read_bytes(), b"new complete mp4")+ self.assertEqual(list(Path(temp_dir).iterdir()), [final_path])+def test_format_ffmpeg_concat_path_normalizes_windows_path(self):"""concat demuxer 的文件列表对 Windows 反斜杠较敏感,写入 list 前统一