利用 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
feat(video): add image motion options
harry070390f77011d7e3
diff --git a/app/models/schema.py b/app/models/schema.pyindex e116ab42..d22355ab 100644--- a/app/models/schema.py+++ b/app/models/schema.py@@ -53,6 +53,11 @@ class VideoFitMode(str, Enum):contain = "contain"+class ImageMotion(str, Enum):+ static = "static"+ zoom = "zoom"++SubtitleDisplayMode = Literal["sentence", "word_by_word"]SubtitleAnimation = Literal["none", "pop_spring"]_SUBTITLE_DISPLAY_MODES = ("sentence", "word_by_word")@@ -108,6 +113,7 @@ class VideoParams(BaseModel):video_terms: Optional[str | List[str]] = None # Keywords used to generate the videovideo_aspect: Optional[VideoAspect] = VideoAspect.portrait.valuevideo_fit_mode: VideoFitMode = VideoFitMode.cover+ image_motion: ImageMotion = ImageMotion.zoomvideo_concat_mode: Optional[VideoConcatMode] = VideoConcatMode.random.valuevideo_transition_mode: Optional[VideoTransitionMode] = Nonevideo_clip_duration: int = Field(default=5, ge=1)diff --git a/app/services/material.py b/app/services/material.pyindex 86955b83..8b045731 100644--- a/app/services/material.py+++ b/app/services/material.py@@ -21,7 +21,7 @@ from moviepy.video.io.VideoFileClip import VideoFileClipfrom PIL import Image, UnidentifiedImageErrorfrom app.config import config-from app.models.schema import MaterialInfo, VideoAspect, VideoConcatMode+from app.models.schema import ImageMotion, MaterialInfo, VideoAspect, VideoConcatModefrom app.services import (material_cache,material_upload,@@ -1737,14 +1737,18 @@ def generate_images_openai(return [item]-def _render_openai_image_video(image_path: str, clip_duration: int) -> str:+def _render_openai_image_video(+ image_path: str, clip_duration: int, image_motion: ImageMotion = ImageMotion.zoom+) -> str:"""把生成的图片渲染成 mp4 片段,复用 local 素材的"图片 → 动态片段"管线。渲染失败返回空字符串,由调用方停止后续付费请求。"""try:- return video.render_image_zoom_video(image_path, clip_duration)+ return video.render_image_zoom_video(+ image_path, clip_duration, image_motion=image_motion+ )except Exception as e:logger.error("failed to render generated image as a video clip: "@@ -1761,6 +1765,7 @@ def _download_videos_openai_image_on_demand(audio_duration: float,max_clip_duration: int,material_directory: str,+ image_motion: ImageMotion = ImageMotion.zoom,) -> List[str]:"""按脚本片段顺序逐张生成 OpenAI 兼容文生图素材,凑够所需总时长立即停止。@@ -1771,6 +1776,8 @@ def _download_videos_openai_image_on_demand(不再发起新的付费请求。明确拒绝的单张图片可跳过;请求结果不明、付费结果下载失败或本地渲染失败时必须终止任务,避免后续关键词再次计费。"""+ # 直接调用素材服务也要在付费请求前校验,不能生成后才发现效果参数无效。+ image_motion = ImageMotion(image_motion)if not material_directory:# 生成图片按任务计费且不可复用,默认落在任务目录便于追溯。material_directory = utils.task_dir(task_id)@@ -1805,7 +1812,9 @@ def _download_videos_openai_image_on_demand(_persist_material_sources(task_id, material_sources)raisefor item in items:- video_file = _render_openai_image_video(item.url, max_clip_duration)+ video_file = _render_openai_image_video(+ item.url, max_clip_duration, image_motion=image_motion+ )if not video_file:_persist_material_sources(task_id, material_sources)raise OpenAIImagePaidResultError(@@ -2159,6 +2168,7 @@ def download_videos(max_clip_duration: int = 5,match_script_order: bool = False,progress_callback: Callable[[float], None] | None = None,+ image_motion: ImageMotion = ImageMotion.zoom,) -> List[str]:"""搜索并下载覆盖配音时长所需的素材,返回本地文件路径。@@ -2265,6 +2275,7 @@ def download_videos(audio_duration=audio_duration,max_clip_duration=max_clip_duration,material_directory=material_directory,+ image_motion=image_motion,)if match_script_order:diff --git a/app/services/task.py b/app/services/task.pyindex 7a45dbb4..aa6a7754 100644--- a/app/services/task.py+++ b/app/services/task.py@@ -730,7 +730,9 @@ def get_video_materials(if params.video_source == "local":logger.info("\n\n## preprocess local materials")materials = video.preprocess_video(- materials=params.video_materials, clip_duration=params.video_clip_duration+ materials=params.video_materials,+ clip_duration=params.video_clip_duration,+ image_motion=params.image_motion,)if not materials:_mark_task_failed(@@ -819,6 +821,7 @@ def get_video_materials(audio_duration=audio_duration * params.video_count,max_clip_duration=params.video_clip_duration,match_script_order=params.match_materials_to_script,+ image_motion=params.image_motion,# 素材阶段占用 40%~50%:每下完一个文件推进一次,慢速网络下# 进度条不再长时间停在 40%。progress_callback=_stage_progress_reporter(task_id, 40, 50),diff --git a/app/services/video.py b/app/services/video.pyindex c5f7a518..13e042c5 100644--- a/app/services/video.py+++ b/app/services/video.py@@ -33,6 +33,7 @@ from PIL import Image, ImageColor, ImageDraw, ImageFont, ImageOpsfrom app.config import configfrom app.models import constfrom app.models.schema import (+ ImageMotion,MaterialInfo,VideoAspect,VideoConcatMode,@@ -1890,31 +1891,31 @@ def generate_video(return bgm_mix_succeeded-def render_image_zoom_video(image_path: str, clip_duration: int = 5) -> str:+def render_image_zoom_video(+ image_path: str, clip_duration: int = 5, image_motion: ImageMotion = ImageMotion.zoom+) -> str:"""- 将单张本地图片渲染为带缓慢放大效果的 mp4 片段,返回输出文件路径。+ 将单张图片渲染为静止或缓慢放大的 mp4 片段,返回输出文件路径。local 素材预处理和 OpenAI 兼容文生图素材共用这段"图片 → 片段"渲染- 逻辑:ImageClip 按 clip_duration 固定时长播放,并叠加每秒约 3% 的- 动态放大,避免静态画面在成片中显得呆板。渲染异常由调用方按各自- 素材源的失败约定处理。+ 逻辑:默认保留每秒约 3% 的动态放大,静止模式只固定播放时长。+ 此设置与片段转场独立。渲染异常由调用方按各自素材源的失败约定处理。"""+ motion = ImageMotion(image_motion)clip, _ = _open_image_clip_with_fallback(image_path)clip = clip.with_duration(clip_duration).with_position("center")temp_path = ""try:- # Apply a zoom effect using the resize method.- # A lambda function is used to make the zoom effect dynamic over time.- # The zoom effect starts from the original size and gradually scales up to 120%.- # t represents the current time, and clip.duration is the total duration of the clip.- # Note: 1 represents 100% size, so 1.2 represents 120%.- zoom_clip = clip.resized(- lambda t: 1 + (clip_duration * 0.03) * (t / clip.duration)+ # 只有放大模式改变画面尺寸,静止模式保留原始构图及透明背景处理。+ image_clip = (+ clip.resized(lambda t: 1 + (clip_duration * 0.03) * (t / clip.duration))+ if motion == ImageMotion.zoom+ else clip)# Optionally, create a composite video clip containing the zoomed clip.# This is useful if you want to add other elements to the video.- final_clip = CompositeVideoClip([zoom_clip], bg_color=(0, 0, 0))+ final_clip = CompositeVideoClip([image_clip], bg_color=(0, 0, 0))try:# The duration changes the rendered content, so it must be part of# the output identity. Different tasks may render the same image@@ -1928,7 +1929,8 @@ def render_image_zoom_video(image_path: str, clip_duration: int = 5) -> str:source_identity = source_digest.hexdigest()duration_identity = hashlib.sha256(str(clip_duration).encode()).hexdigest()[:16]video_file = os.path.join(- os.path.dirname(image_path), f"{source_identity}.zoom-{duration_identity}.mp4"+ os.path.dirname(image_path),+ f"{source_identity}.{motion.value}-{duration_identity}.mp4",)descriptor, temp_path = tempfile.mkstemp(prefix=".image-zoom-",@@ -1950,7 +1952,9 @@ def render_image_zoom_video(image_path: str, clip_duration: int = 5) -> str:delete_files(temp_path)-def preprocess_video(materials: List[MaterialInfo], clip_duration=4):+def preprocess_video(+ materials: List[MaterialInfo], clip_duration=4, image_motion: ImageMotion = ImageMotion.zoom+):# WebUI 在某些二次生成场景下可能传入空素材列表,这里直接返回空结果,避免抛出 NoneType 异常。if not materials:return []@@ -2020,7 +2024,7 @@ def preprocess_video(materials: List[MaterialInfo], clip_duration=4):# 用于导出的图片片段。close_clip(clip)video_file = render_image_zoom_video(- material_source_path, clip_duration+ material_source_path, clip_duration, image_motion=image_motion)material.url = video_filelogger.success(f"image processed: {video_file}")diff --git a/cli.py b/cli.pyindex b49c07ec..53ed0aee 100644--- a/cli.py+++ b/cli.py@@ -221,6 +221,13 @@ def _video_fit_mode(value: str) -> str:return normalized+def _image_motion(value: str) -> str:+ normalized = value.strip().lower()+ if normalized not in {"static", "zoom"}:+ raise argparse.ArgumentTypeError("image-motion must be one of: static, zoom")+ return normalized++# 只有这些取值会请求外部音乐生成服务,因此只有它们消费配乐提示词。取值需与# app/services/task.py 的 _VIDEO_MUSIC_PROVIDERS 保持一致;集中定义后,新增# 配乐供应商不会再次遗漏 --bgm-type 校验、批量校验和提示词参数。@@ -434,6 +441,13 @@ Batch manifests:default=None,help="source clip concatenation order (default: random)",)+ video_group.add_argument(+ "--image-motion",+ type=_image_motion,+ choices=["static", "zoom"],+ default=None,+ help="motion for local or AI-generated images (default: zoom)",+ )video_group.add_argument("--video-transition-mode",type=_transition_mode,@@ -941,6 +955,7 @@ def build_video_params(args: argparse.Namespace) -> VideoParams:"video_script_prompt","custom_system_prompt","video_fit_mode",+ "image_motion","video_concat_mode","video_transition_mode","video_clip_duration",@@ -979,6 +994,7 @@ def build_video_params(args: argparse.Namespace) -> VideoParams:ui_defaults = (("video_clip_speed", float, _clip_speed),("video_fit_mode", str, _video_fit_mode),+ ("image_motion", str, _image_motion),("font_name", str, None),("subtitle_display_mode", str, _subtitle_display_mode),("subtitle_animation", str, _subtitle_animation),diff --git a/test/services/test_image_motion.py b/test/services/test_image_motion.pynew file mode 100644index 00000000..bbca94f8--- /dev/null+++ b/test/services/test_image_motion.py@@ -0,0 +1,152 @@+"""验证图片动态效果的兼容默认值、参数传递和真实渲染像素。"""++from pathlib import Path+from unittest.mock import patch++import numpy as np+import pytest+from moviepy import VideoFileClip+from PIL import Image, ImageDraw+from pydantic import ValidationError++import cli+from app.config import config+from app.models.schema import ImageMotion, MaterialInfo, TaskVideoRequest, VideoParams+from app.services import material, task, video+++def test_old_requests_keep_zoom_and_invalid_motion_is_rejected():+ assert TaskVideoRequest(video_subject="old task").image_motion == ImageMotion.zoom+ assert TaskVideoRequest(video_subject="still", image_motion="static").image_motion == ImageMotion.static+ with pytest.raises(ValidationError, match="image_motion"):+ TaskVideoRequest(video_subject="bad", image_motion="unknown")+++def test_api_motion_reaches_task_queue_and_rejects_invalid_input():+ from fastapi.testclient import TestClient+ from app import asgi+ from app.controllers.v1 import video as controller++ with (+ patch.dict(config.app, {"api_key": ""}),+ patch.object(controller.task_manager, "add_task") as enqueue,+ patch.object(controller.sm.state, "update_task"),+ ):+ client = TestClient(asgi.app)+ for value, expected in ((None, "zoom"), ("static", "static"), ("zoom", "zoom")):+ payload = {"video_subject": "test", "subtitle_enabled": False}+ if value is not None:+ payload["image_motion"] = value+ response = client.post("/api/v1/videos", json=payload)+ assert response.status_code == 200+ assert enqueue.call_args.kwargs["params"].image_motion == expected+ enqueue.reset_mock()+ response = client.post("/api/v1/videos", json={"video_subject": "test", "image_motion": "bad"})+ assert response.status_code == 400+ enqueue.assert_not_called()+++def test_cli_motion_uses_saved_value_but_explicit_argument_wins():+ args = ["--video-subject", "test"]+ with patch.dict(config.ui, {}, clear=True):+ assert cli.build_video_params(cli.parse_args(args)).image_motion == ImageMotion.zoom+ with patch.dict(config.ui, {"image_motion": "static"}, clear=True):+ assert cli.build_video_params(cli.parse_args(args)).image_motion == ImageMotion.static+ explicit = cli.build_video_params(cli.parse_args(args + ["--image-motion", "zoom"]))+ assert explicit.image_motion == ImageMotion.zoom+ with patch.dict(config.ui, {"image_motion": "bad"}, clear=True):+ assert cli.build_video_params(cli.parse_args(args)).image_motion == ImageMotion.zoom+ with pytest.raises(SystemExit):+ cli.parse_args(args + ["--image-motion", "bad"])++[email protected]("motion", [ImageMotion.static, ImageMotion.zoom])+def test_task_passes_motion_to_local_and_generated_images(motion):+ params = VideoParams(video_subject="test", video_source="local", image_motion=motion)+ with patch.object(video, "preprocess_video", return_value=[MaterialInfo(url="local.mp4")]) as preprocess:+ assert task.get_video_materials("motion-test", params, [], 2) == ["local.mp4"]+ assert preprocess.call_args.kwargs["image_motion"] == motion+ params.video_source = "openai_image"+ with patch.object(material, "download_videos", return_value=["generated.mp4"]) as download:+ assert task.get_video_materials("motion-test", params, ["scene"], 2) == ["generated.mp4"]+ assert download.call_args.kwargs["image_motion"] == motion+++def test_generated_image_motion_reaches_renderer_without_extra_paid_requests(tmp_path):+ item = MaterialInfo(provider="openai_image", url=str(tmp_path / "scene.png"), duration=2)+ with (+ patch.object(material, "generate_images_openai", return_value=[item]) as generate,+ patch.object(video, "render_image_zoom_video", return_value="static.mp4") as render,+ patch.object(material, "_persist_material_sources"),+ ):+ paths = material.download_videos(+ "motion-test", ["first", "unused"], source="openai_image",+ audio_duration=2, max_clip_duration=2, image_motion="static",+ )+ assert paths == ["static.mp4"]+ generate.assert_called_once()+ assert render.call_args.kwargs["image_motion"] == "static"+++def test_invalid_motion_is_rejected_before_paid_image_generation():+ with patch.object(material, "generate_images_openai") as generate:+ with pytest.raises(ValueError, match="ImageMotion"):+ material.download_videos(+ "motion-test", ["scene"], source="openai_image",+ audio_duration=2, image_motion="invalid",+ )+ generate.assert_not_called()+++def _white_width(frame):+ _, x = np.where(frame.min(axis=2) > 220)+ return int(x.max() - x.min() + 1)+++def test_native_static_pixels_zoom_default_and_output_identity(tmp_path):+ source = tmp_path / "scene.png"+ image = Image.new("RGB", (256, 256), (220, 0, 0))+ ImageDraw.Draw(image).rectangle((80, 80, 175, 175), fill="white")+ image.save(source)+ default = video.render_image_zoom_video(str(source), 3)+ zoom_bytes = Path(default).read_bytes()+ still = video.render_image_zoom_video(str(source), 3, image_motion="static")+ assert still != default+ assert Path(default).read_bytes() == zoom_bytes+ with VideoFileClip(still, audio=False) as clip:+ first, last = clip.get_frame(0), clip.get_frame(2.5)+ assert clip.size == [256, 256]+ assert clip.duration == pytest.approx(3, abs=0.04)+ assert abs(_white_width(first) - _white_width(last)) <= 1+ assert np.abs(first.astype(float) - last).mean() < 1+ with VideoFileClip(default, audio=False) as clip:+ assert _white_width(clip.get_frame(2.5)) > _white_width(clip.get_frame(0)) + 4+ assert video.render_image_zoom_video(str(source), 3, image_motion="zoom") == default+++def test_static_image_preserves_alpha_composition(tmp_path):+ source = tmp_path / "alpha.png"+ Image.new("RGBA", (64, 64), (240, 0, 0, 128)).save(source)+ output = video.render_image_zoom_video(str(source), 0.2, image_motion="static")+ with VideoFileClip(output, audio=False) as clip:+ pixel = clip.get_frame(0)[32, 32]+ assert 110 <= pixel[0] <= 130+ assert max(pixel[1:]) < 5++[email protected]("motion", ["static", "zoom"])+def test_failed_motion_render_keeps_previous_output_and_removes_partial_file(tmp_path, motion):+ source = tmp_path / "scene.png"+ Image.new("RGB", (64, 64), "red").save(source)+ output = video.render_image_zoom_video(str(source), 0.2, image_motion=motion)+ completed = Path(output).read_bytes()++ def interrupted_write(_clip, filename, **_kwargs):+ Path(filename).write_bytes(b"partial video")+ raise RuntimeError("encoder interrupted")++ with patch.object(video.CompositeVideoClip, "write_videofile", interrupted_write):+ with pytest.raises(RuntimeError, match="encoder interrupted"):+ video.render_image_zoom_video(str(source), 0.2, image_motion=motion)+ assert Path(output).read_bytes() == completed+ assert not list(tmp_path.glob(".image-zoom-*.mp4"))diff --git a/test/services/test_material_openai_image.py b/test/services/test_material_openai_image.pyindex d954f7d5..9de8dec7 100644--- a/test/services/test_material_openai_image.py+++ b/test/services/test_material_openai_image.py@@ -742,7 +742,7 @@ class TestOpenAIImageProvider(unittest.TestCase):def fake_generate(search_term, minimum_duration, video_aspect, save_dir=""):return generated[search_term]- def fake_render(image_path, clip_duration):+ def fake_render(image_path, clip_duration, image_motion="zoom"):return f"{image_path}.mp4"with (@@ -895,7 +895,7 @@ class TestOpenAIImageProvider(unittest.TestCase):def fake_generate(search_term, minimum_duration, video_aspect, save_dir=""):return generated[search_term]- def fake_render(image_path, clip_duration):+ def fake_render(image_path, clip_duration, image_motion="zoom"):return f"{image_path}.mp4"with (diff --git a/test/services/test_webui_image_motion.py b/test/services/test_webui_image_motion.pynew file mode 100644index 00000000..0dacc803--- /dev/null+++ b/test/services/test_webui_image_motion.py@@ -0,0 +1,113 @@+"""用真实 Streamlit 控件验证图片效果选择、恢复与语言切换。"""++from pathlib import Path+from unittest.mock import patch++import pytest+from streamlit.testing.v1 import AppTest++from app.config import config+from app.models.schema import VideoParams+from app.services import state as sm, version_checker+++WEBUI_MAIN = Path(__file__).resolve().parents[2] / "webui" / "Main.py"+++def _select(app, key):+ return next(v for v in app.selectbox if v.key == key or str(v.key).startswith(key + "_"))+++def test_motion_widget_persists_and_restores_old_and_new_tasks(tmp_path):+ with (+ patch.object(config, "app", {"video_source": "local", "llm_provider": "openai"}),+ patch.object(config, "ui", {"language": "zh", "voice_mode": "none"}),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(sm.state, "get_all_tasks", return_value=([], 0)),+ patch.object(version_checker, "poll_available_update", return_value=version_checker.UpdateCheckSnapshot(complete=True)),+ patch("app.utils.utils.task_dir", return_value=str(tmp_path)),+ ):+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)+ app.session_state["ui_language"] = "zh"+ app.run()+ assert not app.exception+ widget = _select(app, "image_motion_select")+ assert widget.label == "图片动态效果"+ assert widget.value == "zoom"+ assert widget.options == ["静止", "缓慢放大"]+ widget.select("static").run()+ assert not app.exception+ assert config.ui["image_motion"] == "static"+ app.session_state["video_source_select_zh"] = "pexels"+ app.run()+ assert not app.exception+ assert not any(str(v.key).startswith("image_motion_select") for v in app.selectbox)+ app.session_state["video_source_select_zh"] = "openai_image"+ app.run()+ assert not app.exception+ assert _select(app, "image_motion_select").value == "static"++ # 模拟任务恢复:新增字段必须恢复,旧任务缺失字段必须回到原来的放大效果。+ params = VideoParams(video_subject="restore", video_source="local", image_motion="static").model_dump(mode="json")+ for expected in ("static", "zoom"):+ if expected == "zoom":+ params.pop("image_motion")+ app.session_state["task_restore_payload"] = {"params": params, "task_id": "motion-test"}+ app.run()+ assert not app.exception+ assert _select(app, "image_motion_select").value == expected++ _select(app, "top_language_code_selector").select("en").run()+ assert not app.exception+ assert _select(app, "image_motion_select").label == "Image Motion"++[email protected]("rebuild", ["language", "source"])+def test_motion_selection_survives_rebuild_while_generation_holds_config(tmp_path, rebuild):+ import threading++ locked = threading.Event()+ release = threading.Event()++ def active_generation():+ with config.runtime_config_lock():+ locked.set()+ assert release.wait(30)++ with (+ patch.object(config, "app", {"video_source": "local", "llm_provider": "openai"}),+ patch.object(config, "ui", {"language": "zh", "voice_mode": "none"}),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(config, "save_config"),+ patch.object(sm.state, "get_all_tasks", return_value=([], 0)),+ patch.object(version_checker, "poll_available_update", return_value=version_checker.UpdateCheckSnapshot(complete=True)),+ patch("app.utils.utils.task_dir", return_value=str(tmp_path)),+ ):+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)+ app.session_state["ui_language"] = "zh"+ app.run()+ assert not app.exception+ worker = threading.Thread(target=active_generation)+ worker.start()+ try:+ assert locked.wait(5)+ _select(app, "image_motion_select").select("static").run()+ assert not app.exception+ assert _select(app, "image_motion_select").value == "static"+ assert config.ui["image_motion"] == "zoom"+ assert config.snapshot_config_with_pending(config.ui)["image_motion"] == "static"+ if rebuild == "language":+ _select(app, "top_language_code_selector").select("en").run()+ else:+ app.session_state["video_source_select_zh"] = "pexels"+ app.run()+ assert not app.exception+ app.session_state["video_source_select_zh"] = "local"+ app.run()+ assert not app.exception+ assert _select(app, "image_motion_select").value == "static"+ assert config.snapshot_config_with_pending(config.ui)["image_motion"] == "static"+ finally:+ release.set()+ worker.join(5)+ assert config.ui["image_motion"] == "static"diff --git a/test/services/test_webui_settings_transfer.py b/test/services/test_webui_settings_transfer.pyindex a3901553..7007a4bd 100644--- a/test/services/test_webui_settings_transfer.py+++ b/test/services/test_webui_settings_transfer.py@@ -158,6 +158,7 @@ def test_settings_preset_round_trip_preserves_generation_settings():video_subject="a cat",video_aspect="9:16",video_fit_mode="contain",+ image_motion="static",font_size=48,stroke_width=2.5,voice_volume=0.8,@@ -171,6 +172,7 @@ def test_settings_preset_round_trip_preserves_generation_settings():assert restored["video_subject"] == "a cat"assert restored["video_aspect"] == "9:16"assert restored["video_fit_mode"] == "contain"+ assert restored["image_motion"] == "static"assert restored["font_size"] == 48assert restored["stroke_width"] == 2.5assert restored["voice_volume"] == 0.8diff --git a/webui/Main.py b/webui/Main.pyindex c7274c48..c61c44af 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -37,6 +37,7 @@ from app.models.llm_provider import (normalize_provider_override,)from app.models.schema import (+ ImageMotion,MaterialInfo,VideoAspect,VideoConcatMode,@@ -1562,6 +1563,9 @@ def _apply_restored_params(params):"video_fit_mode_select",params.get("video_fit_mode") or VideoFitMode.cover.value,)+ _set_stable_widget_value(+ "image_motion_select", params.get("image_motion") or ImageMotion.zoom.value+ )_set_stable_widget_value("video_clip_duration_select", params.get("video_clip_duration", 3))@@ -5404,6 +5408,28 @@ def _render_video_settings(panel, params):"ui", "video_fit_mode", params.video_fit_mode.value)+ if params.video_source in {"local", "openai_image"}:+ image_motion_labels = {+ ImageMotion.static.value: tr("Static Image"),+ ImageMotion.zoom.value: tr("Slow Zoom"),+ }+ params.image_motion = ImageMotion(+ stable_selectbox(+ tr("Image Motion"),+ options=list(image_motion_labels),+ default_value=_saved_ui_choice(+ "image_motion", list(image_motion_labels), ImageMotion.zoom.value,+ # 生成任务持锁时,切换语言或素材来源会重建控件;+ # 此时必须恢复尚未落盘的最新选择,不能写回旧配置值。+ section=config.snapshot_config_with_pending(config.ui),+ ),+ key="image_motion_select",+ format_func=image_motion_labels.get,+ help=tr("Image Motion Help"),+ )+ )+ _set_runtime_config("ui", "image_motion", params.image_motion.value)+# MiniMax H3 的远端时长范围是 4~15 秒。选择秘塔时使用完整能力# 范围,既避免 2/3 秒被按 4 秒计费,也让 WebUI 与 CLI、服务层一致。if params.video_source == "metaso_minimax":diff --git a/webui/i18n/az.json b/webui/i18n/az.jsonindex 130fa75d..9cb59a7d 100644--- a/webui/i18n/az.json+++ b/webui/i18n/az.json@@ -100,6 +100,10 @@"Fill and Crop": "Doldurma (mərkəzdən kəsmə)","Fit with Black Bars": "Sığdırma (qara zolaqlarla)","Video Fit Mode Help": "Doldurma rejimi bütün çıxış sahəsindən istifadə edir və artıq kənarları kəsir. Sığdırma rejimi mənbə kadrını bütöv saxlayır və lazım olduqda qara zolaqlar əlavə edir.",+ "Image Motion": "Şəkil hərəkəti",+ "Static Image": "Hərəkətsiz",+ "Slow Zoom": "Yavaş böyütmə",+ "Image Motion Help": "Yalnız şəkillərə təsir edir. Kliplərarası keçidlər ayrıca tənzimlənir.","Clip Duration": "Klipin maksimum müddəti (saniyə)","Clip Duration Help": "Videonun ümumi müddətini deyil, kompozisiyada istifadə olunan hər klipin müddətini tənzimləyir.","Clip Speed": "Klipin sürəti",diff --git a/webui/i18n/ca.json b/webui/i18n/ca.jsonindex f9ddf4c1..09479c9c 100644--- a/webui/i18n/ca.json+++ b/webui/i18n/ca.json@@ -106,6 +106,10 @@"Fill and Crop": "Omple (retall central)","Fit with Black Bars": "Enquadra (franges negres)","Video Fit Mode Help": "Omple cobreix tota la imatge de sortida i retalla les vores sobrants. Enquadra conserva la imatge sencera i afegeix franges negres si cal.",+ "Image Motion": "Moviment de les imatges",+ "Static Image": "Estàtica",+ "Slow Zoom": "Ampliació lenta",+ "Image Motion Help": "Només afecta les imatges fixes. Les transicions entre clips es configuren per separat.","Clip Duration": "Durada màxima de cada clip (s)","Clip Duration Help": "Limita la durada de cada clip, no la durada total del vídeo.","Clip Speed": "Velocitat dels clips",diff --git a/webui/i18n/de.json b/webui/i18n/de.jsonindex e753cfd1..5f99cfe5 100644--- a/webui/i18n/de.json+++ b/webui/i18n/de.json@@ -106,6 +106,10 @@"Fill and Crop": "Ausfüllen (zentriert zuschneiden)","Fit with Black Bars": "Einpassen (schwarze Balken)","Video Fit Mode Help": "Ausfüllen nutzt die gesamte Ausgabefläche und schneidet überstehende Ränder ab. Einpassen erhält das vollständige Quellbild und fügt bei Bedarf schwarze Balken hinzu.",+ "Image Motion": "Bildbewegung",+ "Static Image": "Statisch",+ "Slow Zoom": "Langsamer Zoom",+ "Image Motion Help": "Gilt nur für Standbilder. Übergänge zwischen Clips werden separat eingestellt.","Clip Duration": "Max. Dauer pro Clip (Sek.)","Clip Duration Help": "Legt die Dauer jedes verwendeten Clips fest, nicht die Gesamtlänge des Videos.","Clip Speed": "Clip-Geschwindigkeit",diff --git a/webui/i18n/en.json b/webui/i18n/en.jsonindex 15c88f58..cf3d3d19 100644--- a/webui/i18n/en.json+++ b/webui/i18n/en.json@@ -110,6 +110,10 @@"Fill and Crop": "Fill (center crop)","Fit with Black Bars": "Fit (black bars)","Video Fit Mode Help": "Fill uses the entire output canvas and crops excess edges. Fit preserves the complete source frame and adds black bars when needed.",+ "Image Motion": "Image Motion",+ "Static Image": "Static",+ "Slow Zoom": "Slow Zoom",+ "Image Motion Help": "Only affects still images. Clip transitions are configured separately.","Clip Duration": "Maximum Clip Duration (seconds)","Clip Duration Help": "Controls the duration of each clip used in the composition, not the total video length.","Clip Speed": "Clip Speed",diff --git a/webui/i18n/es.json b/webui/i18n/es.jsonindex 6d74deff..400a3ab1 100644--- a/webui/i18n/es.json+++ b/webui/i18n/es.json@@ -106,6 +106,10 @@"Fill and Crop": "Rellenar (recorte central)","Fit with Black Bars": "Ajustar (barras negras)","Video Fit Mode Help": "Rellenar ocupa todo el lienzo de salida y recorta los bordes sobrantes. Ajustar conserva el encuadre completo y añade barras negras cuando sea necesario.",+ "Image Motion": "Movimiento de imágenes",+ "Static Image": "Estática",+ "Slow Zoom": "Zoom lento",+ "Image Motion Help": "Solo afecta a las imágenes fijas. Las transiciones entre clips se configuran por separado.","Clip Duration": "Duración máxima por clip (s)","Clip Duration Help": "Controla la duración de cada clip utilizado, no la duración total del vídeo.","Clip Speed": "Velocidad del clip",diff --git a/webui/i18n/fr.json b/webui/i18n/fr.jsonindex 4b03707e..54462726 100644--- a/webui/i18n/fr.json+++ b/webui/i18n/fr.json@@ -106,6 +106,10 @@"Fill and Crop": "Remplir (recadrage centré)","Fit with Black Bars": "Ajuster (bandes noires)","Video Fit Mode Help": "Remplir utilise tout le cadre de sortie et coupe les bords excédentaires. Ajuster conserve l’image source complète et ajoute des bandes noires si nécessaire.",+ "Image Motion": "Animation des images",+ "Static Image": "Image fixe",+ "Slow Zoom": "Zoom lent",+ "Image Motion Help": "Concerne uniquement les images fixes. Les transitions entre les clips se règlent séparément.","Clip Duration": "Durée maximale d'un extrait (secondes)","Clip Duration Help": "Contrôle la durée de chaque extrait utilisé dans la composition, et non la durée totale du rendu.","Clip Speed": "Vitesse de l'extrait",diff --git a/webui/i18n/id.json b/webui/i18n/id.jsonindex 26bdbbdd..5351b35d 100644--- a/webui/i18n/id.json+++ b/webui/i18n/id.json@@ -106,6 +106,10 @@"Fill and Crop": "Penuhi (potong tengah)","Fit with Black Bars": "Sesuaikan (bilah hitam)","Video Fit Mode Help": "Penuhi memakai seluruh kanvas keluaran dan memotong tepi berlebih. Sesuaikan mempertahankan bingkai sumber lengkap dan menambahkan bilah hitam bila diperlukan.",+ "Image Motion": "Gerakan gambar",+ "Static Image": "Diam",+ "Slow Zoom": "Perbesar perlahan",+ "Image Motion Help": "Hanya memengaruhi gambar diam. Transisi antarklip diatur secara terpisah.","Clip Duration": "Durasi Maks. per Klip (detik)","Clip Duration Help": "Menentukan durasi setiap klip yang digunakan, bukan durasi total video.","Clip Speed": "Kecepatan Klip",diff --git a/webui/i18n/it.json b/webui/i18n/it.jsonindex c3e808c4..88d9631c 100644--- a/webui/i18n/it.json+++ b/webui/i18n/it.json@@ -106,6 +106,10 @@"Fill and Crop": "Riempi (ritaglio centrale)","Fit with Black Bars": "Adatta (bande nere)","Video Fit Mode Help": "Riempi usa l’intera area di uscita e ritaglia i bordi in eccesso. Adatta conserva l’inquadratura sorgente completa e aggiunge bande nere quando necessario.",+ "Image Motion": "Movimento delle immagini",+ "Static Image": "Statica",+ "Slow Zoom": "Zoom lento",+ "Image Motion Help": "Si applica solo alle immagini fisse. Le transizioni tra clip si impostano separatamente.","Clip Duration": "Durata massima per clip (secondi)","Clip Duration Help": "Controlla la durata di ciascuna clip utilizzata nella composizione, non la durata totale del video.","Clip Speed": "Velocità della clip",diff --git a/webui/i18n/ko.json b/webui/i18n/ko.jsonindex 1860a1e2..c85bd30e 100644--- a/webui/i18n/ko.json+++ b/webui/i18n/ko.json@@ -106,6 +106,10 @@"Fill and Crop": "채우기 (가운데 자르기)","Fit with Black Bars": "맞추기 (검은 여백)","Video Fit Mode Help": "채우기는 출력 화면 전체를 사용하고 넘치는 가장자리를 자릅니다. 맞추기는 원본 화면 전체를 유지하고 필요할 때 검은 여백을 추가합니다.",+ "Image Motion": "이미지 움직임",+ "Static Image": "정지",+ "Slow Zoom": "느린 확대",+ "Image Motion Help": "정지 이미지에만 적용됩니다. 클립 간 전환은 별도로 설정합니다.","Clip Duration": "클립 최대 길이 (초)","Clip Duration Help": "합성에 사용되는 각 클립의 길이를 조절합니다. 전체 영상 길이가 아닙니다.","Clip Speed": "클립 재생 속도",diff --git a/webui/i18n/pt.json b/webui/i18n/pt.jsonindex f174e4c7..ea839af7 100644--- a/webui/i18n/pt.json+++ b/webui/i18n/pt.json@@ -106,6 +106,10 @@"Fill and Crop": "Preencher (recorte central)","Fit with Black Bars": "Ajustar (barras pretas)","Video Fit Mode Help": "Preencher ocupa toda a tela e recorta o excesso nas bordas. Ajustar preserva o quadro completo e adiciona barras pretas quando necessário.",+ "Image Motion": "Movimento das imagens",+ "Static Image": "Estática",+ "Slow Zoom": "Zoom lento",+ "Image Motion Help": "Afeta apenas imagens estáticas. As transições entre clipes são configuradas separadamente.","Clip Duration": "Duração máxima por clipe (s)","Clip Duration Help": "Define a duração de cada clipe utilizado, não a duração total do vídeo.","Clip Speed": "Velocidade do clipe",diff --git a/webui/i18n/ru.json b/webui/i18n/ru.jsonindex 3745587f..eaec6bda 100644--- a/webui/i18n/ru.json+++ b/webui/i18n/ru.json@@ -108,6 +108,10 @@"Fill and Crop": "Заполнить (обрезка по центру)","Fit with Black Bars": "Вместить (чёрные полосы)","Video Fit Mode Help": "Заполнение использует весь выходной кадр и обрезает лишние края. Вмещение сохраняет исходный кадр целиком и при необходимости добавляет чёрные полосы.",+ "Image Motion": "Движение изображения",+ "Static Image": "Без движения",+ "Slow Zoom": "Медленное увеличение",+ "Image Motion Help": "Применяется только к изображениям. Переходы между клипами настраиваются отдельно.","Clip Duration": "Макс. длительность фрагмента (сек.)","Clip Duration Help": "Определяет длительность каждого используемого фрагмента, а не общую длину видео.","Clip Speed": "Скорость фрагментов",diff --git a/webui/i18n/tr.json b/webui/i18n/tr.jsonindex 1128e6e0..7096d420 100644--- a/webui/i18n/tr.json+++ b/webui/i18n/tr.json@@ -106,6 +106,10 @@"Fill and Crop": "Doldur (ortadan kırp)","Fit with Black Bars": "Sığdır (siyah çubuklar)","Video Fit Mode Help": "Doldur, çıkış alanının tamamını kullanır ve taşan kenarları kırpar. Sığdır, kaynak kadrajın tamamını korur ve gerektiğinde siyah çubuklar ekler.",+ "Image Motion": "Görüntü hareketi",+ "Static Image": "Sabit",+ "Slow Zoom": "Yavaş yakınlaştırma",+ "Image Motion Help": "Yalnızca sabit görüntüleri etkiler. Klip geçişleri ayrıca ayarlanır.","Clip Duration": "Maks. Klip Süresi (sn.)","Clip Duration Help": "Toplam video süresini değil, kullanılan her klibin süresini belirler.","Clip Speed": "Klip Hızı",diff --git a/webui/i18n/vi.json b/webui/i18n/vi.jsonindex c5e576fa..3a302202 100644--- a/webui/i18n/vi.json+++ b/webui/i18n/vi.json@@ -106,6 +106,10 @@"Fill and Crop": "Lấp đầy (cắt giữa)","Fit with Black Bars": "Vừa khung (viền đen)","Video Fit Mode Help": "Lấp đầy sử dụng toàn bộ khung đầu ra và cắt phần cạnh dư. Vừa khung giữ nguyên toàn bộ hình nguồn và thêm viền đen khi cần.",+ "Image Motion": "Chuyển động hình ảnh",+ "Static Image": "Tĩnh",+ "Slow Zoom": "Phóng to chậm",+ "Image Motion Help": "Chỉ áp dụng cho ảnh tĩnh. Chuyển cảnh giữa các đoạn được cài đặt riêng.","Clip Duration": "Thời Lượng Tối Đa Mỗi Clip (giây)","Clip Duration Help": "Quy định thời lượng của từng clip được sử dụng, không phải tổng thời lượng video.","Clip Speed": "Tốc độ clip",diff --git a/webui/i18n/zh.json b/webui/i18n/zh.jsonindex 6cf48c0f..62f021a3 100644--- a/webui/i18n/zh.json+++ b/webui/i18n/zh.json@@ -110,6 +110,10 @@"Fill and Crop": "填满(居中裁剪)","Fit with Black Bars": "完整显示(黑边)","Video Fit Mode Help": "填满会占满整个输出画面并裁掉多余边缘;完整显示会保留全部素材画面,并在需要时添加黑边。",+ "Image Motion": "图片动态效果",+ "Static Image": "静止",+ "Slow Zoom": "缓慢放大",+ "Image Motion Help": "仅影响图片素材;片段之间的转场需单独设置。","Clip Duration": "单个片段最大时长(秒)","Clip Duration Help": "控制合成时使用的每个视频片段时长,不是视频总时长。","Clip Speed": "片段播放速度",