Skip to content

利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.

fix: fail fast when ffmpeg is unavailable

许文涛9faef6910565
diff --git a/app/services/task.py b/app/services/task.py
index 4cb290b8..d858c0a0 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -1211,6 +1211,18 @@ def _run_pipeline(
except video_music_provider["error_type"] as exc:
return _mark_task_failed(task_id, "preflight", str(exc))
+ # 只有 script/terms 中间产物不需要 FFmpeg(它们不生成音频或视频)。API、
+ # CLI 和 WebUI 都通过这个共享入口执行任务,因此在此统一探测,而不是
+ # 分别在各个入口重复检查,能保证三条路径的行为一致。放在配乐 Key 校验
+ # 之后,是为了不改变那些校验原有的"最先失败"顺序和错误信息。
+ if stop_at not in ("script", "terms") and not utils.check_ffmpeg_ready():
+ return _mark_task_failed(
+ task_id,
+ "preflight",
+ "ffmpeg is not available; install ffmpeg or set app.ffmpeg_path "
+ "in config.toml to a working ffmpeg executable",
+ )
+
# 1. Generate script
video_script = generate_script(task_id, params)
if not video_script or "Error: " in video_script:
diff --git a/app/utils/utils.py b/app/utils/utils.py
index f2d6b927..92869693 100644
--- a/app/utils/utils.py
+++ b/app/utils/utils.py
@@ -3,6 +3,7 @@ import math
import os
import re
import shutil
+import subprocess
from functools import lru_cache
from pathlib import Path
import threading
@@ -178,6 +179,62 @@ def get_ffmpeg_binary() -> str:
return "ffmpeg"
+_FFMPEG_INSTALL_HINT = (
+ "Install FFmpeg on your system, or set app.ffmpeg_path in config.toml to "
+ "the full path of an ffmpeg executable (e.g. downloaded from "
+ "https://www.gyan.dev/ffmpeg/builds/)."
+)
+
+
+def check_ffmpeg_ready(timeout: int = 10) -> bool:
+ """
+ 在真正开始生成视频之前提前探测 FFmpeg 是否可用。
+
+ 增加原因:
+ 此前 FFmpeg 缺失/不可用只会在视频合成、静音音轨生成等环节里,以
+ ``RuntimeError: No ffmpeg exe could be found`` 或 subprocess 报错的形式
+ 出现,用户往往要等到任务跑了大半才第一次看到这个报错,且报错本身
+ 不会指向任何解决办法。这里在共享任务流水线(app/services/task.py 的
+ ``_run_pipeline``)里提前做一次探测,尽早给出可操作的英文提示(与项目
+ 里其他 logger.warning 的用语习惯保持一致),API、CLI、WebUI 都会经过
+ 这条流水线,因此三条路径能统一生效。
+
+ 仅做一次轻量的 ``-version`` 调用,不会触发下载或改变主流程;
+ 调用方需要把返回值当作硬性前置条件——项目锁定的 imageio-ffmpeg==0.6.0
+ 并不会在真正使用时自动补下载一个可用的二进制,因此检测失败必须让
+ 需要 FFmpeg 的阶段直接终止,而不是继续跑到视频合成才失败。
+ """
+ ffmpeg_bin = get_ffmpeg_binary()
+ try:
+ completed = subprocess.run(
+ [ffmpeg_bin, "-version"],
+ stdout=subprocess.DEVNULL,
+ stderr=subprocess.DEVNULL,
+ timeout=timeout,
+ )
+ except FileNotFoundError:
+ logger.warning(
+ f"no usable ffmpeg executable found (tried: {ffmpeg_bin}). "
+ f"{_FFMPEG_INSTALL_HINT}"
+ )
+ return False
+ except Exception as exc:
+ logger.warning(
+ f"failed to probe ffmpeg ({ffmpeg_bin}): {exc}. {_FFMPEG_INSTALL_HINT}"
+ )
+ return False
+
+ if completed.returncode != 0:
+ logger.warning(
+ f"ffmpeg ({ffmpeg_bin}) probe exited with status {completed.returncode}; "
+ f"video generation may fail later. {_FFMPEG_INSTALL_HINT}"
+ )
+ return False
+
+ logger.info(f"ffmpeg check passed, using: {ffmpeg_bin}")
+ return True
+
+
def run_in_background(func, *args, **kwargs):
def run():
try:
diff --git a/cli.py b/cli.py
index afa1c0f7..022bcc9e 100644
--- a/cli.py
+++ b/cli.py
@@ -655,6 +655,11 @@ def prepare_cli_files(params: VideoParams, stop_at: str) -> None:
from app.services import bgm as bgm_service
from app.utils import utils
+ # FFmpeg 探测已经移到 app/services/task.py 的共享任务流水线(task.start)
+ # 里统一做硬性检查:探测失败会让任务以 preflight 阶段失败结束,run_cli()
+ # 会据此返回非零退出码。这里不再重复一次不阻断流程的检查,避免与流水线
+ # 里的判断结果不一致。
+
local_material_extensions = {
*(f".{extension}" for extension in const.FILE_TYPE_VIDEOS),
*(f".{extension}" for extension in const.FILE_TYPE_IMAGES),
diff --git a/main.py b/main.py
index e84f32ba..af7de2cc 100644
--- a/main.py
+++ b/main.py
@@ -7,6 +7,8 @@ if __name__ == "__main__":
logger.info(
"start server, docs: http://127.0.0.1:" + str(config.listen_port) + "/docs"
)
+ # FFmpeg 探测已经移到 app/services/task.py 的共享任务流水线里,这样
+ # API、CLI 和 WebUI 三条路径都能统一覆盖,这里不再单独检查。
uvicorn.run(
app="app.asgi:app",
host=config.listen_host,
diff --git a/test/services/test_task.py b/test/services/test_task.py
index 5964563d..792d0aa5 100644
--- a/test/services/test_task.py
+++ b/test/services/test_task.py
@@ -303,6 +303,74 @@ class TestTaskService(unittest.TestCase):
self.assertEqual(warnings, [{"code": "sonilo_bgm_failed", "video_index": 1}])
self.assertTrue(generate.call_args.kwargs["bgm_file_override"].endswith(".m4a"))
+ def test_run_pipeline_fails_fast_when_ffmpeg_is_not_ready(self):
+ """完整视频流水线必须在 LLM/TTS/素材服务之前先确认 FFmpeg 可用。"""
+ params = VideoParams(video_subject="test")
+ state = MemoryState()
+ with (
+ patch.object(tm.utils, "check_ffmpeg_ready", return_value=False),
+ patch.object(tm, "generate_script") as generate_script,
+ patch.object(tm, "generate_audio") as generate_audio,
+ patch.object(tm, "get_video_materials") as get_materials,
+ patch.object(tm.sm, "state", state),
+ ):
+ result = tm.start("ffmpeg-missing", params)
+
+ generate_script.assert_not_called()
+ generate_audio.assert_not_called()
+ get_materials.assert_not_called()
+ self.assertEqual(result["state"], tm.const.TASK_STATE_FAILED)
+ self.assertEqual(result["failed_stage"], "preflight")
+ self.assertIn("ffmpeg", result["error"])
+
+ def test_run_pipeline_skips_ffmpeg_check_for_script_stage(self):
+ """脚本阶段不涉及音频/视频合成,不应因为缺少 FFmpeg 而被拒绝。"""
+ params = VideoParams(video_subject="test")
+ state = MemoryState()
+ with (
+ patch.object(tm.utils, "check_ffmpeg_ready", return_value=False) as check,
+ patch.object(tm, "generate_script", return_value="脚本") as generate_script,
+ patch.object(tm.sm, "state", state),
+ ):
+ result = tm.start("ffmpeg-missing-script-stage", params, stop_at="script")
+
+ check.assert_not_called()
+ generate_script.assert_called_once()
+ self.assertEqual(result, {"script": "脚本"})
+
+ def test_run_pipeline_skips_ffmpeg_check_for_terms_stage(self):
+ """搜索词阶段同样不需要 FFmpeg,不应触发探测。"""
+ params = VideoParams(video_subject="test")
+ state = MemoryState()
+ with (
+ patch.object(tm.utils, "check_ffmpeg_ready", return_value=False) as check,
+ patch.object(tm, "generate_script", return_value="脚本"),
+ patch.object(tm, "generate_terms", return_value=["term"]),
+ patch.object(tm, "save_script_data"),
+ patch.object(tm.sm, "state", state),
+ ):
+ result = tm.start("ffmpeg-missing-terms-stage", params, stop_at="terms")
+
+ check.assert_not_called()
+ self.assertEqual(result, {"script": "脚本", "terms": ["term"]})
+
+ def test_run_pipeline_proceeds_past_ffmpeg_preflight_when_ready(self):
+ """FFmpeg 可用时探测不应阻塞后续脚本生成。"""
+ params = VideoParams(video_subject="test")
+ state = MemoryState()
+ with (
+ patch.object(tm.utils, "check_ffmpeg_ready", return_value=True) as check,
+ patch.object(tm, "generate_script", return_value="脚本") as generate_script,
+ patch.object(tm.sm, "state", state),
+ ):
+ result = tm.start("ffmpeg-ready", params, stop_at="script")
+
+ # 即使 script 阶段不强制要求 FFmpeg,这里也验证探测函数被跳过调用,
+ # 与"仅在 script/terms 之外阶段才检查"的约定保持一致。
+ check.assert_not_called()
+ generate_script.assert_called_once()
+ self.assertEqual(result, {"script": "脚本"})
+
def test_start_rejects_missing_sonilo_key_before_costly_pipeline_steps(self):
"""完整任务缺少 Sonilo Key 时不能先调用 LLM、TTS 或素材服务。"""
params = VideoParams(video_subject="test", bgm_type="sonilo")
diff --git a/test/services/test_utils_ffmpeg_check.py b/test/services/test_utils_ffmpeg_check.py
new file mode 100644
index 00000000..cbbdc420
--- /dev/null
+++ b/test/services/test_utils_ffmpeg_check.py
@@ -0,0 +1,67 @@
+import subprocess
+import sys
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+# add project root to python path
+sys.path.insert(0, str(Path(__file__).parent.parent.parent))
+
+from app.utils import utils
+
+
+class TestCheckFfmpegReady(unittest.TestCase):
+ """覆盖 utils.check_ffmpeg_ready() 的四种探测结果。"""
+
+ def test_returns_true_when_ffmpeg_probe_succeeds(self):
+ completed = subprocess.CompletedProcess(args=["ffmpeg", "-version"], returncode=0)
+ with (
+ patch.object(utils, "get_ffmpeg_binary", return_value="/usr/bin/ffmpeg"),
+ patch.object(utils.subprocess, "run", return_value=completed) as run,
+ ):
+ self.assertTrue(utils.check_ffmpeg_ready())
+
+ run.assert_called_once()
+ self.assertEqual(run.call_args.args[0], ["/usr/bin/ffmpeg", "-version"])
+
+ def test_returns_false_when_executable_is_missing(self):
+ with (
+ patch.object(utils, "get_ffmpeg_binary", return_value="ffmpeg"),
+ patch.object(utils.subprocess, "run", side_effect=FileNotFoundError()),
+ patch.object(utils.logger, "warning") as warning,
+ ):
+ self.assertFalse(utils.check_ffmpeg_ready())
+
+ warning.assert_called_once()
+ self.assertIn("no usable ffmpeg executable found", warning.call_args.args[0])
+
+ def test_returns_false_on_non_zero_exit_code(self):
+ completed = subprocess.CompletedProcess(args=["ffmpeg", "-version"], returncode=1)
+ with (
+ patch.object(utils, "get_ffmpeg_binary", return_value="/usr/bin/ffmpeg"),
+ patch.object(utils.subprocess, "run", return_value=completed),
+ patch.object(utils.logger, "warning") as warning,
+ ):
+ self.assertFalse(utils.check_ffmpeg_ready())
+
+ warning.assert_called_once()
+ self.assertIn("exited with status 1", warning.call_args.args[0])
+
+ def test_returns_false_on_timeout(self):
+ with (
+ patch.object(utils, "get_ffmpeg_binary", return_value="/usr/bin/ffmpeg"),
+ patch.object(
+ utils.subprocess,
+ "run",
+ side_effect=subprocess.TimeoutExpired(cmd="ffmpeg", timeout=10),
+ ),
+ patch.object(utils.logger, "warning") as warning,
+ ):
+ self.assertFalse(utils.check_ffmpeg_ready(timeout=10))
+
+ warning.assert_called_once()
+ self.assertIn("failed to probe ffmpeg", warning.call_args.args[0])
+
+
+if __name__ == "__main__":
+ unittest.main()