Skip to content

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

feat(webui): add subject-named video downloads

harry0703dbe2695e3740
diff --git a/test/services/test_webui_task.py b/test/services/test_webui_task.py
index d17c7941..49b188ae 100644
--- a/test/services/test_webui_task.py
+++ b/test/services/test_webui_task.py
@@ -1,10 +1,12 @@
import ast
+import os
import re
import threading
import time
+from collections.abc import Mapping
from contextlib import nullcontext
from pathlib import Path
-from unittest.mock import patch
+from unittest.mock import MagicMock, patch
import pytest
from loguru import logger
@@ -54,6 +56,106 @@ def test_generation_controls_submit_background_task_instead_of_blocking_page():
assert "tm.start" not in calls
+def test_completed_task_renders_subject_named_video_download(tmp_path):
+ """完成任务应提供主题命名的下载,且下载数据必须来自实际成片。"""
+ tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))
+ selected_nodes = []
+ target_names = {
+ "_DOWNLOAD_FILENAME_INVALID_PATTERN",
+ "_build_video_download_name",
+ "_normalize_task_state",
+ "_render_generation_task_snapshot",
+ }
+ for node in tree.body:
+ if isinstance(node, ast.Assign) and any(
+ isinstance(target, ast.Name) and target.id in target_names
+ for target in node.targets
+ ):
+ selected_nodes.append(node)
+ elif isinstance(node, ast.FunctionDef) and node.name in target_names:
+ selected_nodes.append(node)
+
+ class FakeColumn:
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_args):
+ return False
+
+ class FakeStreamlit:
+ def __init__(self):
+ self.session_state = {}
+ self.downloads = []
+ self.videos = []
+
+ def columns(self, count):
+ return [FakeColumn() for _ in range(count)]
+
+ def video(self, video_path):
+ self.videos.append(video_path)
+
+ def download_button(self, label, data, **kwargs):
+ self.downloads.append((label, data.read(), kwargs))
+
+ def success(self, _message):
+ pass
+
+ def warning(self, _message):
+ pass
+
+ def error(self, _message):
+ pass
+
+ video_path = tmp_path / "final-1.mp4"
+ video_path.write_bytes(b"video-content")
+ fake_st = FakeStreamlit()
+ open_task_folder = MagicMock()
+ namespace = {
+ "Mapping": Mapping,
+ "const": const,
+ "logger": MagicMock(),
+ "mimetypes": __import__("mimetypes"),
+ "open_task_folder": open_task_folder,
+ "os": os,
+ "re": re,
+ "st": fake_st,
+ "tr": lambda key: key,
+ "_render_generation_logs": lambda _task_id: None,
+ }
+ module = ast.fix_missing_locations(
+ ast.Module(body=selected_nodes, type_ignores=[])
+ )
+ exec(compile(module, str(WEBUI_MAIN), "exec"), namespace)
+
+ namespace["_render_generation_task_snapshot"](
+ "download-test",
+ {
+ "state": const.TASK_STATE_COMPLETE,
+ "progress": 100,
+ "videos": [str(video_path)],
+ "warnings": [],
+ "video_subject": "A day: in / Shanghai?",
+ },
+ )
+
+ assert fake_st.videos == [str(video_path)]
+ assert fake_st.downloads == [
+ (
+ "Download Video",
+ b"video-content",
+ {
+ "file_name": "A day in Shanghai.mp4",
+ "mime": "video/mp4",
+ "key": "download_generated_video_download-test_0",
+ "icon": ":material/download:",
+ "on_click": "ignore",
+ "use_container_width": True,
+ },
+ )
+ ]
+ open_task_folder.assert_called_once_with("download-test")
+
+
def test_submit_generation_returns_while_pipeline_is_still_running():
"""后台流水线未结束时,提交函数必须已经返回,让 Streamlit 完成本次渲染。"""
task_id = "background-submit-test"
diff --git a/test/services/test_webui_task_history.py b/test/services/test_webui_task_history.py
index c1429257..56b33a82 100644
--- a/test/services/test_webui_task_history.py
+++ b/test/services/test_webui_task_history.py
@@ -9,11 +9,13 @@ ROOT_DIR = Path(__file__).parent.parent.parent
WEBUI_MAIN = ROOT_DIR / "webui" / "Main.py"
TASK_HISTORY_HELPERS = {
"_find_final_task_video",
+ "_build_video_download_name",
"_build_restore_upload_requirements",
"_get_unmet_restore_upload_requirements",
}
TASK_HISTORY_CONSTANTS = {
"_FINAL_VIDEO_PATTERN",
+ "_DOWNLOAD_FILENAME_INVALID_PATTERN",
"VOICE_MODE_TTS",
"VOICE_MODE_UPLOAD",
"VOICE_MODE_NONE",
@@ -46,6 +48,7 @@ def _load_task_history_helpers():
TASK_HISTORY_NAMESPACE = _load_task_history_helpers()
find_final_task_video = TASK_HISTORY_NAMESPACE["_find_final_task_video"]
+build_video_download_name = TASK_HISTORY_NAMESPACE["_build_video_download_name"]
build_restore_upload_requirements = TASK_HISTORY_NAMESPACE[
"_build_restore_upload_requirements"
]
@@ -75,6 +78,18 @@ def test_find_final_task_video_returns_first_numbered_output(tmp_path):
assert find_final_task_video(str(tmp_path)) == str(tmp_path / "final-1.mp4")
+def test_build_video_download_name_uses_subject_and_output_index():
+ assert (
+ build_video_download_name("A day: in / Shanghai?", 2, 3)
+ == "A day in Shanghai-2.mp4"
+ )
+
+
+def test_build_video_download_name_handles_empty_and_long_subjects():
+ assert build_video_download_name(" ... ", 1, 1) == "video.mp4"
+ assert len(build_video_download_name("a" * 100, 1, 1)) == 84
+
+
def test_restore_requirements_block_missing_uploaded_files():
params = {
"video_source": "local",
diff --git a/webui/Main.py b/webui/Main.py
index 6000bca2..8e200030 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -120,6 +120,7 @@ _FINAL_VIDEO_PATTERN = re.compile(
r"^final-(?P<index>\d+)\.(?P<extension>mp4|mov|mkv|webm)$",
re.IGNORECASE,
)
+_DOWNLOAD_FILENAME_INVALID_PATTERN = re.compile(r'[<>:"/\\|?*\x00-\x1f]')
# -----------------------------------------------------------------------------
@@ -664,6 +665,17 @@ def _task_manager_label(processing_count):
return f"{label} · {processing_count}"
+def _build_video_download_name(subject, index, total):
+ """根据视频主题生成跨平台安全的下载文件名。"""
+ safe_subject = _DOWNLOAD_FILENAME_INVALID_PATTERN.sub(" ", str(subject or ""))
+ safe_subject = re.sub(r"\s+", " ", safe_subject).strip(" .")[:80].rstrip(" .")
+ if not safe_subject:
+ safe_subject = "video"
+
+ suffix = f"-{index}" if total > 1 else ""
+ return f"{safe_subject}{suffix}.mp4"
+
+
def _render_task_table(filtered_tasks, key_prefix):
with st.container(key=f"task_table_header_{key_prefix}"):
header_cols = st.columns([1.1, 1.7, 3.0, 0.8, 1.6], vertical_alignment="center")
@@ -1373,7 +1385,34 @@ def _render_generation_task_snapshot(task_id, task):
try:
player_cols = st.columns(len(video_files) * 2 + 1)
for i, url in enumerate(video_files):
- player_cols[i * 2 + 1].video(url)
+ with player_cols[i * 2 + 1]:
+ st.video(url)
+ if not os.path.isfile(url):
+ logger.warning(
+ f"generated video is unavailable for download: "
+ f"task_id={task_id}, video_file={url}"
+ )
+ continue
+
+ download_label = tr("Download Video")
+ if len(video_files) > 1:
+ download_label = f"{download_label} {i + 1}"
+ download_name = _build_video_download_name(
+ task.get("video_subject"),
+ i + 1,
+ len(video_files),
+ )
+ with open(url, "rb") as video_file:
+ st.download_button(
+ download_label,
+ data=video_file,
+ file_name=download_name,
+ mime=mimetypes.guess_type(url)[0] or "video/mp4",
+ key=f"download_generated_video_{task_id}_{i}",
+ icon=":material/download:",
+ on_click="ignore",
+ use_container_width=True,
+ )
except Exception as exc:
logger.exception(
f"failed to render generated video preview: task_id={task_id}, "
diff --git a/webui/i18n/de.json b/webui/i18n/de.json
index 3d3fa61c..fae984c0 100644
--- a/webui/i18n/de.json
+++ b/webui/i18n/de.json
@@ -171,6 +171,7 @@
"Start Generating Video": "Beginne mit der Generierung",
"Video Generation Completed": "Video erfolgreich generiert",
"Video Generation Failed": "Video Generierung fehlgeschlagen",
+ "Download Video": "Video herunterladen",
"You can download the generated video from the following links": "Sie können das generierte Video über die folgenden Links herunterladen",
"Basic Settings": "**Grundeinstellungen** (:blue[Klicken zum Erweitern])",
"Language": "Sprache",
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index f6978935..e0719b83 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -168,6 +168,7 @@
"Start Generating Video": "Start Generating Video",
"Video Generation Completed": "Video Generation Completed",
"Video Generation Failed": "Video Generation Failed",
+ "Download Video": "Download Video",
"You can download the generated video from the following links": "You can download the generated video from the following links",
"Pexels API Key": "Pexels API Key ([Get API Key](https://www.pexels.com/api/))",
"Pixabay API Key": "Pixabay API Key ([Get API Key](https://pixabay.com/api/docs/#api_search_videos))",
diff --git a/webui/i18n/es.json b/webui/i18n/es.json
index 3348d064..e8b4c83d 100644
--- a/webui/i18n/es.json
+++ b/webui/i18n/es.json
@@ -168,6 +168,7 @@
"Start Generating Video": "Comenzar a generar vídeo",
"Video Generation Completed": "Generación de vídeo completada",
"Video Generation Failed": "Error en la generación de vídeo",
+ "Download Video": "Descargar vídeo",
"You can download the generated video from the following links": "Puedes descargar el vídeo generado desde los siguientes enlaces",
"Pexels API Key": "Pexels API Key ([Obtener API Key](https://www.pexels.com/api/))",
"Pixabay API Key": "Pixabay API Key ([Obtener API Key](https://pixabay.com/api/docs/#api_search_videos))",
diff --git a/webui/i18n/id.json b/webui/i18n/id.json
index b7ace153..490d6706 100644
--- a/webui/i18n/id.json
+++ b/webui/i18n/id.json
@@ -168,6 +168,7 @@
"Start Generating Video": "Mulai Menghasilkan Video",
"Video Generation Completed": "Pembuatan Video Selesai",
"Video Generation Failed": "Pembuatan Video Gagal",
+ "Download Video": "Unduh video",
"You can download the generated video from the following links": "Anda dapat mengunduh video yang dihasilkan dari tautan berikut",
"Pexels API Key": "Kunci API Pexels ([Dapatkan Kunci API](https://www.pexels.com/api/))",
"Pixabay API Key": "Kunci API Pixabay ([Dapatkan Kunci API](https://pixabay.com/api/docs/#api_search_videos))",
diff --git a/webui/i18n/pt.json b/webui/i18n/pt.json
index 948deb76..a33b5802 100644
--- a/webui/i18n/pt.json
+++ b/webui/i18n/pt.json
@@ -168,6 +168,7 @@
"Start Generating Video": "Começar a Gerar Vídeo",
"Video Generation Completed": "Geração do Vídeo Concluída",
"Video Generation Failed": "Falha na Geração do Vídeo",
+ "Download Video": "Baixar vídeo",
"You can download the generated video from the following links": "Você pode baixar o vídeo gerado a partir dos seguintes links",
"Basic Settings": "**Configurações Básicas** (:blue[Clique para expandir])",
"Language": "Idioma",
diff --git a/webui/i18n/ru.json b/webui/i18n/ru.json
index 5582ea3e..b1f426a2 100644
--- a/webui/i18n/ru.json
+++ b/webui/i18n/ru.json
@@ -165,6 +165,7 @@
"Start Generating Video": "Создание видео запущено",
"Video Generation Completed": "Видео готово",
"Video Generation Failed": "Не удалось создать видео",
+ "Download Video": "Скачать видео",
"You can download the generated video from the following links": "Скачать созданное видео можно по ссылкам ниже",
"Pexels API Key": "API-ключ Pexels ([получить API-ключ](https://www.pexels.com/api/))",
"Pixabay API Key": "API-ключ Pixabay ([получить API-ключ](https://pixabay.com/api/docs/#api_search_videos))",
diff --git a/webui/i18n/tr.json b/webui/i18n/tr.json
index e4ab6926..e05297ae 100644
--- a/webui/i18n/tr.json
+++ b/webui/i18n/tr.json
@@ -166,6 +166,7 @@
"Start Generating Video": "Video Oluşturmaya Başla",
"Video Generation Completed": "Video Oluşturma Tamamlandı",
"Video Generation Failed": "Video Oluşturma Başarısız",
+ "Download Video": "Videoyu indir",
"You can download the generated video from the following links": "Oluşturulan videoyu aşağıdaki bağlantılardan indirebilirsiniz",
"Pexels API Key": "Pexels API Anahtarı ([API Anahtarı Al](https://www.pexels.com/api/))",
"Pixabay API Key": "Pixabay API Anahtarı ([API Anahtarı Al](https://pixabay.com/api/docs/#api_search_videos))",
diff --git a/webui/i18n/vi.json b/webui/i18n/vi.json
index f4e3f2fb..06d8788b 100644
--- a/webui/i18n/vi.json
+++ b/webui/i18n/vi.json
@@ -168,6 +168,7 @@
"Start Generating Video": "Bắt Đầu Tạo Video",
"Video Generation Completed": "Hoàn Tất Tạo Video",
"Video Generation Failed": "Tạo Video Thất Bại",
+ "Download Video": "Tải video",
"You can download the generated video from the following links": "Bạn có thể tải video được tạo ra từ các liên kết sau",
"Basic Settings": "**Cài Đặt Cơ Bản** (:blue[Nhấp để mở rộng])",
"Language": "Ngôn Ngữ",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index 1ff8b2cb..f9c70ce2 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -168,6 +168,7 @@
"Start Generating Video": "开始生成视频",
"Video Generation Completed": "视频生成完成",
"Video Generation Failed": "视频生成失败",
+ "Download Video": "下载视频",
"You can download the generated video from the following links": "你可以从以下链接下载生成的视频",
"Basic Settings": "**基础设置** (:blue[点击展开])",
"Language": "界面语言",