Skip to content

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

fix(webui): validate local materials before task submission

Rudy Celekli97e8cab66387
diff --git a/test/services/test_webui_local_material_upload.py b/test/services/test_webui_local_material_upload.py
new file mode 100644
index 00000000..b61ba028
--- /dev/null
+++ b/test/services/test_webui_local_material_upload.py
@@ -0,0 +1,144 @@
+import ast
+import io
+import os
+import tempfile
+from pathlib import Path
+from uuid import uuid4
+from unittest.mock import patch
+
+from loguru import logger
+from PIL import Image
+
+from app.models.schema import MaterialInfo, VideoParams
+from app.services import material_upload as material_upload_service
+from app.utils import utils
+
+
+WEBUI_MAIN = Path(__file__).parents[2] / "webui" / "Main.py"
+
+
+class _StoppedUpload(Exception):
+ pass
+
+
+class _FakeStreamlit:
+ def __init__(self):
+ self.session_state = {}
+ self.errors = []
+
+ def error(self, message):
+ self.errors.append(message)
+
+ def stop(self):
+ raise _StoppedUpload()
+
+
+def _upload(name: str, content: bytes) -> io.BytesIO:
+ uploaded = io.BytesIO(content)
+ uploaded.name = name
+ return uploaded
+
+
+def _image_bytes() -> bytes:
+ output = io.BytesIO()
+ Image.new("RGB", (2, 2), "red").save(output, format="PNG")
+ return output.getvalue()
+
+
+def _run_webui_upload_block(files, temp_dir):
+ """Execute the actual generation handler's local-material branch headlessly."""
+ tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))
+ generation = next(
+ node for node in tree.body
+ if isinstance(node, ast.FunctionDef)
+ and node.name == "_render_generation_controls"
+ )
+ upload_branch = next(
+ node for node in ast.walk(generation)
+ if isinstance(node, ast.If)
+ and isinstance(node.test, ast.Name)
+ and node.test.id == "uploaded_files"
+ )
+ helpers = [
+ node for node in tree.body
+ if isinstance(node, ast.FunctionDef)
+ and node.name in {"_build_uploaded_file_path", "_save_uploaded_local_materials"}
+ ]
+ body = ast.fix_missing_locations(
+ ast.Module(body=[*helpers, *upload_branch.body], type_ignores=[])
+ )
+ st = _FakeStreamlit()
+ params = VideoParams(video_subject="Local material test", video_source="local")
+ namespace = {
+ "os": os,
+ "uuid4": uuid4,
+ "logger": logger,
+ "utils": utils,
+ "material_upload_service": material_upload_service,
+ "MaterialInfo": MaterialInfo,
+ "LOCAL_MATERIAL_EXTENSIONS": {".mp4", ".png"},
+ "uploaded_files": files,
+ "params": params,
+ "st": st,
+ "task_id": "task-1",
+ "_remove_active_generation_task": lambda task_id: None,
+ "tr": lambda value: value,
+ }
+ with patch.object(utils, "storage_dir", return_value=temp_dir):
+ try:
+ exec(compile(body, str(WEBUI_MAIN), "exec"), namespace)
+ except _StoppedUpload:
+ pass
+ return params, st
+
+
+def test_webui_rejects_invalid_image_before_starting_task():
+ with tempfile.TemporaryDirectory() as temp_dir:
+ params, st = _run_webui_upload_block(
+ [_upload("fake.png", b"not an image")], temp_dir
+ )
+
+ assert st.errors
+ assert not params.video_materials
+ assert list(Path(temp_dir).iterdir()) == []
+
+
+def test_webui_rolls_back_earlier_files_when_later_upload_is_invalid():
+ with tempfile.TemporaryDirectory() as temp_dir:
+ params, st = _run_webui_upload_block(
+ [_upload("valid.png", _image_bytes()), _upload("invalid.png", b"bad")],
+ temp_dir,
+ )
+
+ assert st.errors
+ assert not params.video_materials
+ assert list(Path(temp_dir).iterdir()) == []
+
+
+def test_webui_enforces_image_size_limit():
+ with tempfile.TemporaryDirectory() as temp_dir:
+ with patch.object(
+ material_upload_service, "MAX_IMAGE_MATERIAL_UPLOAD_BYTES", 4
+ ):
+ params, st = _run_webui_upload_block(
+ [_upload("too-large.png", _image_bytes())], temp_dir
+ )
+
+ assert st.errors
+ assert not params.video_materials
+ assert list(Path(temp_dir).iterdir()) == []
+
+
+def test_webui_persists_valid_image_and_session_materials():
+ image_data = _image_bytes()
+ with tempfile.TemporaryDirectory() as temp_dir:
+ params, st = _run_webui_upload_block(
+ [_upload("valid.png", image_data)], temp_dir
+ )
+
+ assert st.errors == []
+ assert len(params.video_materials) == 1
+ saved_path = Path(params.video_materials[0].url)
+ assert saved_path.parent == Path(temp_dir)
+ assert saved_path.read_bytes() == image_data
+ assert st.session_state["local_video_materials"][0]["url"] == str(saved_path)
diff --git a/webui/Main.py b/webui/Main.py
index bd483144..feaece7f 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -44,6 +44,7 @@ from app.models.schema import (
VideoTransitionMode,
)
from app.services import bgm as bgm_service
+from app.services import material_upload as material_upload_service
from app.services import (
cache_manager,
llm,
@@ -613,6 +614,43 @@ def _build_uploaded_file_path(uploaded_file, target_dir, allowed_extensions, pre
return file_path
+def _save_uploaded_local_materials(uploaded_files):
+ """Validate a WebUI material batch and undo earlier files on failure."""
+ local_videos_dir = utils.storage_dir("local_videos", create=True)
+ materials = []
+ persisted = []
+ saved_paths = []
+ try:
+ for uploaded_file in uploaded_files:
+ stored_name = material_upload_service.save_material_upload(
+ uploaded_file.name, uploaded_file
+ )
+ file_path = os.path.join(local_videos_dir, stored_name)
+ saved_paths.append(file_path)
+ material_info = MaterialInfo()
+ material_info.provider = "local"
+ material_info.url = file_path
+ materials.append(material_info)
+ persisted.append(
+ {
+ "provider": material_info.provider,
+ "url": material_info.url,
+ "duration": material_info.duration,
+ }
+ )
+ except Exception:
+ for file_path in saved_paths:
+ try:
+ os.remove(file_path)
+ except OSError as exc:
+ logger.warning(
+ f"failed to remove local material after batch error: "
+ f"path={file_path}, error={exc}"
+ )
+ raise
+ return materials, persisted
+
+
def _initialize_session_state():
"""集中初始化跨 rerun 保留的页面状态。"""
if not st.session_state.get("cross_post_recovery_checked"):
@@ -8110,35 +8148,21 @@ def _render_generation_controls(
params.custom_audio_file = custom_audio_path
if uploaded_files:
- local_videos_dir = utils.storage_dir("local_videos", create=True)
# 每次重新上传时都以本次选择的素材为准,避免旧素材不断重复追加。
- params.video_materials = []
- persisted_local_materials = []
- for file in uploaded_files:
- try:
- file_path = _build_uploaded_file_path(
- file,
- local_videos_dir,
- LOCAL_MATERIAL_EXTENSIONS,
- "material",
- )
- except ValueError:
- _remove_active_generation_task(task_id)
- st.error(tr("Unsupported Upload File Type"))
- st.stop()
- with open(file_path, "wb") as f:
- f.write(file.getbuffer())
- m = MaterialInfo()
- m.provider = "local"
- m.url = file_path
- params.video_materials.append(m)
- persisted_local_materials.append(
- {
- "provider": m.provider,
- "url": m.url,
- "duration": m.duration,
- }
- )
+ try:
+ params.video_materials, persisted_local_materials = (
+ _save_uploaded_local_materials(uploaded_files)
+ )
+ except material_upload_service.MaterialUploadError as exc:
+ _remove_active_generation_task(task_id)
+ logger.warning(f"WebUI local material upload rejected: {exc}")
+ st.error(str(exc))
+ st.stop()
+ except material_upload_service.MaterialServiceError as exc:
+ _remove_active_generation_task(task_id)
+ logger.error(f"WebUI local material upload failed: {exc}")
+ st.error(str(exc))
+ st.stop()
# 将已上传并保存到本地的视频素材写入会话,供后续只改文案时直接复用。
st.session_state["local_video_materials"] = persisted_local_materials
elif (