Skip to content

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

fix(webui): roll back audio staging (#1501)

Rudy Mizrahi Celeklic2f4de210038
diff --git a/test/services/test_webui_audio_staging.py b/test/services/test_webui_audio_staging.py
new file mode 100644
index 00000000..fe38d6c0
--- /dev/null
+++ b/test/services/test_webui_audio_staging.py
@@ -0,0 +1,91 @@
+import ast
+import os
+import tempfile
+import unittest
+from pathlib import Path
+from types import SimpleNamespace
+from unittest.mock import Mock, patch
+
+
+class _StopGeneration(Exception):
+ pass
+
+
+class _PartialWrite:
+ def __init__(self, file):
+ self.file = file
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ self.file.close()
+
+ def write(self, data):
+ self.file.write(data[:4])
+ raise OSError("no space left on device")
+
+
+class TestWebuiAudioStaging(unittest.TestCase):
+ def execute_audio_branch(self, kind, directory):
+ tree = ast.parse((Path(__file__).parents[2] / "webui/Main.py").read_text(encoding="utf-8"))
+ function = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "_render_generation_controls")
+ branch = next(n for n in ast.walk(function) if isinstance(n, ast.If) and isinstance(n.test, ast.Name)
+ and n.test.id == kind)
+ helpers = [n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "_stage_task_audio"]
+ target = Path(directory) / "audio.mp3"
+ removed = Mock()
+ preview = {"audio_bytes": b"complete narration", "duration": 1.0}
+ st = SimpleNamespace(stop=Mock(side_effect=_StopGeneration), error=Mock())
+ namespace = {
+ "os": os, "tempfile": tempfile, "uploaded_audio_file": SimpleNamespace(name="voice.mp3", getbuffer=lambda: b"complete narration"),
+ "reusable_voice_preview": preview, "task_id": "test-task", "params": SimpleNamespace(),
+ "utils": SimpleNamespace(task_dir=lambda _id: directory),
+ "_build_uploaded_file_path": lambda *_args: str(target), "CUSTOM_AUDIO_EXTENSIONS": (".mp3",),
+ "bgm_service": SimpleNamespace(validate_bgm_upload=Mock(), BgmUploadError=type("UploadError", (Exception,), {}), BgmServiceError=type("ServiceError", (Exception,), {})),
+ "_remove_active_generation_task": removed, "st": st, "tr": lambda value: value, "logger": Mock(),
+ }
+ original_open = open
+ original_fdopen = os.fdopen
+ namespace["open"] = lambda *args, **kwargs: _PartialWrite(original_open(*args, **kwargs))
+ module = ast.fix_missing_locations(ast.Module(body=helpers + [branch], type_ignores=[]))
+ with patch.object(os, "fdopen", side_effect=lambda *args, **kwargs: _PartialWrite(original_fdopen(*args, **kwargs))):
+ with self.assertRaises(_StopGeneration):
+ exec(compile(module, "webui-audio-branch", "exec"), namespace)
+ removed.assert_called_once_with("test-task")
+ st.error.assert_called_once()
+ self.assertEqual(list(Path(directory).iterdir()), [])
+ if kind == "reusable_voice_preview":
+ self.assertEqual(preview["audio_bytes"], b"complete narration")
+
+ def test_uploaded_narration_disk_failure_cleans_file_and_active_task(self):
+ with tempfile.TemporaryDirectory() as directory:
+ self.execute_audio_branch("uploaded_audio_file", directory)
+
+ def test_reusable_preview_disk_failure_retains_cache_and_clears_active_task(self):
+ with tempfile.TemporaryDirectory() as directory:
+ self.execute_audio_branch("reusable_voice_preview", directory)
+
+ def load_stage_helper(self):
+ tree = ast.parse((Path(__file__).parents[2] / "webui/Main.py").read_text(encoding="utf-8"))
+ helper = next(n for n in tree.body if isinstance(n, ast.FunctionDef) and n.name == "_stage_task_audio")
+ namespace = {"os": os, "tempfile": tempfile, "logger": Mock()}
+ exec(compile(ast.fix_missing_locations(ast.Module(body=[helper], type_ignores=[])), "audio-helper", "exec"), namespace)
+ return namespace["_stage_task_audio"]
+
+ def test_success_publishes_complete_audio_and_no_staging_files(self):
+ with tempfile.TemporaryDirectory() as directory:
+ target = Path(directory) / "audio.mp3"
+ self.load_stage_helper()(str(target), b"complete narration")
+ self.assertEqual(target.read_bytes(), b"complete narration")
+ self.assertEqual(list(Path(directory).iterdir()), [target])
+
+ def test_publish_failure_preserves_existing_audio_and_cleans_staging(self):
+ with tempfile.TemporaryDirectory() as directory:
+ target = Path(directory) / "audio.mp3"
+ target.write_bytes(b"existing narration")
+ with patch.object(os, "replace", side_effect=OSError("destination locked")):
+ with self.assertRaisesRegex(OSError, "destination locked"):
+ self.load_stage_helper()(str(target), b"complete narration")
+ self.assertEqual(target.read_bytes(), b"existing narration")
+ self.assertEqual(list(Path(directory).iterdir()), [target])
diff --git a/test/services/test_webui_custom_audio_upload.py b/test/services/test_webui_custom_audio_upload.py
index dbcb76ba..6d2c5468 100644
--- a/test/services/test_webui_custom_audio_upload.py
+++ b/test/services/test_webui_custom_audio_upload.py
@@ -65,7 +65,7 @@ def _run_webui_audio_block(uploaded_audio_file, task_dir, stage_dir):
helpers = [
node for node in tree.body
if isinstance(node, ast.FunctionDef)
- and node.name == "_build_uploaded_file_path"
+ and node.name in {"_build_uploaded_file_path", "_stage_task_audio"}
]
body = ast.fix_missing_locations(
ast.Module(body=[*helpers, *upload_branch.body], type_ignores=[])
@@ -74,6 +74,7 @@ def _run_webui_audio_block(uploaded_audio_file, task_dir, stage_dir):
params = VideoParams(video_subject="Custom audio test")
namespace = {
"os": os,
+ "tempfile": tempfile,
"uuid4": uuid4,
"logger": logger,
"utils": utils,
diff --git a/webui/Main.py b/webui/Main.py
index a6258f6a..7da03194 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -8,6 +8,7 @@ import re
import shutil
import subprocess
import sys
+import tempfile
import time
import webbrowser
from collections.abc import Mapping
@@ -7901,6 +7902,30 @@ def _render_subtitle_settings(panel, params):
st.toast(tr("Default Subtitle Settings Restored"))
+def _stage_task_audio(audio_path, audio_bytes):
+ """Publish task-local audio only after the complete write succeeds."""
+ descriptor = None
+ staged_path = None
+ try:
+ descriptor, staged_path = tempfile.mkstemp(
+ dir=os.path.dirname(audio_path), prefix=".task-audio-", suffix=".tmp"
+ )
+ with os.fdopen(descriptor, "wb") as file:
+ descriptor = None # The file context now owns the descriptor.
+ file.write(audio_bytes)
+ os.replace(staged_path, audio_path)
+ finally:
+ if descriptor is not None:
+ os.close(descriptor)
+ if staged_path is not None:
+ try:
+ os.unlink(staged_path)
+ except FileNotFoundError:
+ pass
+ except OSError as exc:
+ logger.warning(f"failed to remove staged task audio: {exc}")
+
+
def _render_generation_controls(
params, uploaded_files, uploaded_audio_file, uploaded_bgm_file, voice_mode
):
@@ -8207,8 +8232,8 @@ def _render_generation_controls(
params.bgm_file = ""
if uploaded_audio_file:
- task_dir = utils.task_dir(task_id)
try:
+ task_dir = utils.task_dir(task_id)
custom_audio_path = _build_uploaded_file_path(
uploaded_audio_file,
task_dir,
@@ -8221,6 +8246,12 @@ def _render_generation_controls(
bgm_service.validate_bgm_upload(
uploaded_audio_file.name, uploaded_audio_file
)
+ _stage_task_audio(custom_audio_path, uploaded_audio_file.getbuffer())
+ except OSError as exc:
+ _remove_active_generation_task(task_id)
+ logger.error(f"failed to persist uploaded task audio: {exc}")
+ st.error(tr("Video Generation Failed"))
+ st.stop()
except bgm_service.BgmUploadError as exc:
_remove_active_generation_task(task_id)
logger.warning(f"WebUI custom audio upload rejected: {exc}")
@@ -8235,8 +8266,6 @@ def _render_generation_controls(
_remove_active_generation_task(task_id)
st.error(tr("Unsupported Upload File Type"))
st.stop()
- with open(custom_audio_path, "wb") as f:
- f.write(uploaded_audio_file.getbuffer())
params.custom_audio_file = custom_audio_path
if uploaded_files:
@@ -8278,12 +8307,18 @@ def _render_generation_controls(
# 试听缓存只存在当前 Streamlit 会话。提交前把音频写入目标任务目录,
# 后台线程随后只读取任务自己的文件;即使页面 rerun、浏览器关闭或
# 用户试听其它音色,也不会影响已经入队的生成任务。
- preview_audio_file = os.path.join(
- utils.task_dir(task_id),
- "audio.mp3",
- )
- with open(preview_audio_file, "wb") as file:
- file.write(reusable_voice_preview.pop("audio_bytes"))
+ try:
+ preview_audio_file = os.path.join(
+ utils.task_dir(task_id),
+ "audio.mp3",
+ )
+ _stage_task_audio(preview_audio_file, reusable_voice_preview["audio_bytes"])
+ except OSError as exc:
+ _remove_active_generation_task(task_id)
+ logger.error(f"failed to persist preview task audio: {exc}")
+ st.error(tr("Video Generation Failed"))
+ st.stop()
+ reusable_voice_preview.pop("audio_bytes")
reusable_voice_preview["audio_file"] = preview_audio_file
logger.info(
f"reuse full voice preview for task: "