利用 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(webui): persist reusable generation settings
HaningZS3f5842bc4835
diff --git a/config.example.toml b/config.example.tomlindex 14ced7f9..89783b5f 100644--- a/config.example.toml+++ b/config.example.toml@@ -389,11 +389,34 @@ open_task_folder_on_completion = true# The WebUI writes the remaining preferences automatically. Uncomment values# below only when you want to define initial defaults manually.# language = "zh"+# video_language = ""+# paragraph_number = 1+# video_script_prompt = ""+# custom_system_prompt = ""+# loomloom_candidate_count = 3+# loomloom_script_duration_seconds = 60+# loomloom_video_scene_count = 1+# video_concat_mode = "random" # "random" or "sequential"+# video_transition_mode = "None" # "None", "Shuffle", "FadeIn", etc.+# video_aspect_pexels = "9:16" # Stored separately for each video source.+# video_clip_duration = 3+# video_clip_speed = 1.0+# video_count = 1# tts_server = "azure-tts-v1"# voice_name = ""+# voice_volume = 1.0+# voice_rate = 1.0+# bgm_type = "random"+# bgm_volume = 0.2+# custom_bgm_file = ""+# sonilo_bgm_prompt = ""+# elevenlabs_music_prompt = ""+# subtitle_enabled = true# font_name = "MicrosoftYaHeiBold.ttc"# font_size = 60# text_fore_color = "#FFFFFF"+# stroke_color = "#000000"+# stroke_width = 1.5# subtitle_position = "bottom" # "top", "center", "bottom", or "custom"# custom_position = 70.0 # Percentage from the top when using "custom"# subtitle_background_enabled = falsediff --git a/test/services/test_webui_bgm.py b/test/services/test_webui_bgm.pyindex b507f9f1..7a0f363b 100644--- a/test/services/test_webui_bgm.py+++ b/test/services/test_webui_bgm.py@@ -255,9 +255,13 @@ class TestWebuiBackgroundMusic(unittest.TestCase):def test_zero_volume_does_not_require_sonilo_key(self):"""Sonilo 音量为 0 时,WebUI 不应继续显示 API Key 必填警告。"""test_config = dict(config.app, sonilo_api_key="")+ # BGM 音量现在是可持久化的用户偏好。显式给定本测试的+ # 非零初始条件,避免其他 AppTest 会话保存的默认值影响前置断言。+ test_ui = dict(config.ui, bgm_volume=0.2)required_warning = self._translation("en", "Sonilo API Key Required")with (patch.object(config, "app", test_config),+ patch.object(config, "ui", test_ui),patch.object(config, "save_config"),patch.object(sonilo, "is_enabled", return_value=False),):diff --git a/test/services/test_webui_generation_defaults.py b/test/services/test_webui_generation_defaults.pynew file mode 100644index 00000000..3c9fe5d7--- /dev/null+++ b/test/services/test_webui_generation_defaults.py@@ -0,0 +1,444 @@+from pathlib import Path+from unittest.mock import patch++from streamlit.testing.v1 import AppTest++from app.config import config+from app.services import voice+++ROOT_DIR = Path(__file__).parent.parent.parent+WEBUI_MAIN = ROOT_DIR / "webui" / "Main.py"+++def _widget_by_key(elements, key):+ return next(+ item+ for item in elements+ if str(getattr(item, "key", "")) == key+ or str(getattr(item, "key", "")).startswith(f"{key}_")+ )+++def _new_app():+ # A cold Python 3.11 environment can spend over 30 seconds importing the+ # full Streamlit entrypoint and optional media stack. Keep the assertion+ # timeout above that one-time startup cost so targeted runs do not flake.+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)+ app.session_state["ui_language"] = "en"+ app.run()+ assert [str(item.value) for item in app.exception] == []+ return app+++def test_reusable_generation_settings_survive_a_new_webui_session():+ """Reusable controls should persist while per-video content stays session-only."""+ test_app_config = dict(+ config.app,+ video_source="pexels",+ match_materials_to_script=False,+ )+ test_ui_config = dict(+ config.ui,+ language="en",+ voice_mode="tts",+ tts_server="azure-tts-v1",+ voice_name="en-US-JennyNeural-Female",+ )++ with (+ patch.object(config, "app", test_app_config),+ patch.object(config, "ui", test_ui_config),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(+ voice,+ "get_all_azure_voices",+ return_value=["en-US-JennyNeural-Female"],+ ),+ ):+ first_session = _new_app()+ _widget_by_key(first_session.text_area, "video_subject").set_value(+ "One-off subject"+ )+ _widget_by_key(first_session.text_area, "video_script").set_value(+ "One-off script"+ )+ _widget_by_key(first_session.text_area, "video_terms").set_value(+ "one-off, keywords"+ )+ _widget_by_key(first_session.selectbox, "script_language_select").set_value(+ "en-US"+ )+ _widget_by_key(first_session.slider, "paragraph_number_input").set_value(3)+ _widget_by_key(first_session.text_area, "video_script_prompt").set_value(+ "Keep the hook concise."+ )+ _widget_by_key(first_session.text_area, "custom_system_prompt").set_value(+ "Write a factual short-video script."+ )+ _widget_by_key(first_session.selectbox, "video_concat_mode_select").set_value(+ "sequential"+ )+ _widget_by_key(+ first_session.selectbox, "video_transition_mode_select"+ ).set_value("FadeIn")+ _widget_by_key(first_session.selectbox, "video_aspect_for_pexels").set_value(+ "16:9"+ )+ _widget_by_key(first_session.selectbox, "video_clip_duration_select").set_value(+ 7+ )+ _widget_by_key(first_session.slider, "video_clip_speed_slider").set_value(1.5)+ _widget_by_key(first_session.selectbox, "video_count_select").set_value(3)+ _widget_by_key(first_session.selectbox, "voice_volume_select").set_value(1.5)+ _widget_by_key(first_session.selectbox, "voice_rate_select").set_value(1.2)+ _widget_by_key(first_session.selectbox, "bgm_type_select").set_value("custom")+ _widget_by_key(first_session.checkbox, "subtitle_enabled_checkbox").set_value(+ True+ )+ _widget_by_key(first_session.color_picker, "stroke_color_picker").set_value(+ "#123456"+ )+ _widget_by_key(first_session.slider, "stroke_width_slider").set_value(2.5)+ first_session.run()++ # Aspect is a per-source preference: Coverr's common landscape default+ # must not replace an explicit portrait choice or the Pexels preference.+ _widget_by_key(first_session.selectbox, "video_source_select").set_value(+ "coverr"+ ).run()+ _widget_by_key(first_session.selectbox, "video_aspect_for_coverr").set_value(+ "9:16"+ ).run()+ _widget_by_key(first_session.selectbox, "video_source_select").set_value(+ "pexels"+ ).run()++ _widget_by_key(first_session.selectbox, "bgm_volume_select").set_value(0.4)+ _widget_by_key(first_session.text_input, "custom_bgm_file_input").set_value(+ "example.mp3"+ )+ first_session.run()+ _widget_by_key(first_session.selectbox, "bgm_type_select").set_value(+ "sonilo"+ ).run()+ _widget_by_key(+ first_session.text_input, "sonilo_bgm_prompt_input"+ ).set_value("Bright acoustic underscore").run()+ _widget_by_key(first_session.selectbox, "bgm_type_select").set_value(+ "elevenlabs"+ ).run()+ _widget_by_key(+ first_session.text_input, "elevenlabs_music_prompt_input"+ ).set_value("Calm cinematic underscore").run()+ _widget_by_key(first_session.selectbox, "bgm_type_select").set_value(+ "custom"+ ).run()+ assert [str(item.value) for item in first_session.exception] == []++ expected_defaults = {+ "video_language": "en-US",+ "paragraph_number": 3,+ "video_script_prompt": "Keep the hook concise.",+ "custom_system_prompt": "Write a factual short-video script.",+ "video_concat_mode": "sequential",+ "video_transition_mode": "FadeIn",+ "video_aspect_pexels": "16:9",+ "video_aspect_coverr": "9:16",+ "video_clip_duration": 7,+ "video_clip_speed": 1.5,+ "video_count": 3,+ "voice_volume": 1.5,+ "voice_rate": 1.2,+ "bgm_type": "custom",+ "bgm_volume": 0.4,+ "custom_bgm_file": "example.mp3",+ "sonilo_bgm_prompt": "Bright acoustic underscore",+ "elevenlabs_music_prompt": "Calm cinematic underscore",+ "subtitle_enabled": True,+ "stroke_color": "#123456",+ "stroke_width": 2.5,+ }+ assert {key: test_ui_config.get(key) for key in expected_defaults} == (+ expected_defaults+ )+ assert "video_subject" not in test_ui_config+ assert "video_script" not in test_ui_config+ assert "video_terms" not in test_ui_config+ assert "video_subject" not in test_app_config+ assert "video_script" not in test_app_config+ assert "video_terms" not in test_app_config++ second_session = _new_app()+ assert _widget_by_key(+ second_session.selectbox, "script_language_select"+ ).value == "en-US"+ assert _widget_by_key(+ second_session.slider, "paragraph_number_input"+ ).value == 3+ assert _widget_by_key(+ second_session.text_area, "video_script_prompt"+ ).value == "Keep the hook concise."+ assert _widget_by_key(+ second_session.text_area, "custom_system_prompt"+ ).value == "Write a factual short-video script."+ assert _widget_by_key(+ second_session.selectbox, "video_concat_mode_select"+ ).value == "sequential"+ assert _widget_by_key(+ second_session.selectbox, "video_transition_mode_select"+ ).value == "FadeIn"+ assert _widget_by_key(+ second_session.selectbox, "video_aspect_for_pexels"+ ).value == "16:9"+ _widget_by_key(second_session.selectbox, "video_source_select").set_value(+ "coverr"+ ).run()+ assert _widget_by_key(+ second_session.selectbox, "video_aspect_for_coverr"+ ).value == "9:16"+ _widget_by_key(second_session.selectbox, "video_source_select").set_value(+ "pexels"+ ).run()+ assert _widget_by_key(+ second_session.selectbox, "video_clip_duration_select"+ ).value == 7+ assert _widget_by_key(+ second_session.slider, "video_clip_speed_slider"+ ).value == 1.5+ assert _widget_by_key(second_session.selectbox, "video_count_select").value == 3+ assert _widget_by_key(+ second_session.selectbox, "voice_volume_select"+ ).value == 1.5+ assert _widget_by_key(+ second_session.selectbox, "voice_rate_select"+ ).value == 1.2+ assert _widget_by_key(second_session.selectbox, "bgm_type_select").value == (+ "custom"+ )+ assert _widget_by_key(second_session.selectbox, "bgm_volume_select").value == (+ 0.4+ )+ assert _widget_by_key(+ second_session.text_input, "custom_bgm_file_input"+ ).value == "example.mp3"+ _widget_by_key(second_session.selectbox, "bgm_type_select").set_value(+ "sonilo"+ ).run()+ assert _widget_by_key(+ second_session.text_input, "sonilo_bgm_prompt_input"+ ).value == "Bright acoustic underscore"+ _widget_by_key(second_session.selectbox, "bgm_type_select").set_value(+ "elevenlabs"+ ).run()+ assert _widget_by_key(+ second_session.text_input, "elevenlabs_music_prompt_input"+ ).value == "Calm cinematic underscore"+ assert _widget_by_key(+ second_session.checkbox, "subtitle_enabled_checkbox"+ ).value is True+ assert _widget_by_key(+ second_session.color_picker, "stroke_color_picker"+ ).value == "#123456"+ assert _widget_by_key(second_session.slider, "stroke_width_slider").value == 2.5++ # Per-video content must not leak into a new session.+ assert second_session.session_state["video_subject"] == ""+ assert second_session.session_state["video_script"] == ""+ assert second_session.session_state["video_terms"] == ""++ _widget_by_key(+ second_session.button, "restore_default_system_prompt"+ ).click().run()+ assert test_ui_config["custom_system_prompt"] == ""++ _widget_by_key(+ second_session.button, "restore_default_subtitle_settings"+ ).click().run()+ assert {+ key: test_ui_config[key]+ for key in ("subtitle_enabled", "stroke_color", "stroke_width")+ } == {+ "subtitle_enabled": True,+ "stroke_color": "#000000",+ "stroke_width": 1.5,+ }+++def test_invalid_saved_generation_settings_fall_back_without_breaking_webui():+ """Stale or manually edited TOML values must not poison Streamlit widgets."""+ test_app_config = dict(+ config.app,+ video_source="pexels",+ match_materials_to_script=False,+ )+ test_ui_config = dict(+ config.ui,+ language="en",+ voice_mode="tts",+ tts_server="azure-tts-v1",+ voice_name="en-US-JennyNeural-Female",+ video_language="not-a-language",+ paragraph_number=999,+ video_concat_mode="not-a-mode",+ video_transition_mode="not-a-transition",+ video_aspect_pexels="4:3",+ video_clip_duration=999,+ video_clip_speed="nan",+ video_count=True,+ voice_volume=999,+ voice_rate=-1,+ bgm_type="not-a-source",+ bgm_volume=999,+ subtitle_enabled="false",+ stroke_color="not-a-color",+ stroke_width="inf",+ loomloom_candidate_count=0,+ loomloom_script_duration_seconds=9999,+ loomloom_video_scene_count="nan",+ )++ with (+ patch.object(config, "app", test_app_config),+ patch.object(config, "ui", test_ui_config),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(+ voice,+ "get_all_azure_voices",+ return_value=["en-US-JennyNeural-Female"],+ ),+ ):+ app = _new_app()++ assert _widget_by_key(app.selectbox, "script_language_select").value == ""+ assert _widget_by_key(app.slider, "paragraph_number_input").value == 10+ assert _widget_by_key(app.selectbox, "video_concat_mode_select").value == "random"+ assert _widget_by_key(app.selectbox, "video_transition_mode_select").value == (+ "None"+ )+ assert _widget_by_key(app.selectbox, "video_aspect_for_pexels").value == "9:16"+ assert _widget_by_key(app.selectbox, "video_clip_duration_select").value == 3+ assert _widget_by_key(app.slider, "video_clip_speed_slider").value == 1.0+ assert _widget_by_key(app.selectbox, "video_count_select").value == 1+ assert isinstance(test_ui_config["video_count"], int)+ assert not isinstance(test_ui_config["video_count"], bool)+ assert _widget_by_key(app.selectbox, "voice_volume_select").value == 1.0+ assert _widget_by_key(app.selectbox, "voice_rate_select").value == 1.0+ assert _widget_by_key(app.selectbox, "bgm_type_select").value == "random"+ assert _widget_by_key(app.selectbox, "bgm_volume_select").value == 0.2+ assert _widget_by_key(app.checkbox, "subtitle_enabled_checkbox").value is False+ assert _widget_by_key(app.color_picker, "stroke_color_picker").value == "#000000"+ assert _widget_by_key(app.slider, "stroke_width_slider").value == 1.5+ assert app.session_state["loomloom_candidate_count"] == 1+ assert app.session_state["loomloom_script_duration_seconds"] == 600+ assert app.session_state["loomloom_video_scene_count"] == 1+++def test_loomloom_tuning_survives_restart_without_persisting_payment_state():+ """Paid-provider tuning is reusable; quotes and confirmations are not."""+ test_app_config = dict(+ config.app,+ video_source="loomloom",+ script_generation_backend="loomloom",+ loomloom_api_token="",+ match_materials_to_script=False,+ )+ test_ui_config = dict(+ config.ui,+ language="en",+ voice_mode="tts",+ tts_server="azure-tts-v1",+ voice_name="en-US-JennyNeural-Female",+ )++ with (+ patch.object(config, "app", test_app_config),+ patch.object(config, "ui", test_ui_config),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(+ voice,+ "get_all_azure_voices",+ return_value=["en-US-JennyNeural-Female"],+ ),+ ):+ first_session = _new_app()+ _widget_by_key(+ first_session.number_input, "loomloom_candidate_count"+ ).set_value(4)+ _widget_by_key(+ first_session.number_input, "loomloom_script_duration_seconds"+ ).set_value(120)+ _widget_by_key(+ first_session.number_input, "loomloom_video_scene_count"+ ).set_value(3)+ first_session.run()++ assert {+ key: test_ui_config.get(key)+ for key in (+ "loomloom_candidate_count",+ "loomloom_script_duration_seconds",+ "loomloom_video_scene_count",+ )+ } == {+ "loomloom_candidate_count": 4,+ "loomloom_script_duration_seconds": 120,+ "loomloom_video_scene_count": 3,+ }+ assert "loomloom_confirm_charge" not in test_ui_config+ assert "loomloom_video_confirm_charge" not in test_ui_config++ second_session = _new_app()+ assert _widget_by_key(+ second_session.number_input, "loomloom_candidate_count"+ ).value == 4+ assert _widget_by_key(+ second_session.number_input, "loomloom_script_duration_seconds"+ ).value == 120+ assert _widget_by_key(+ second_session.number_input, "loomloom_video_scene_count"+ ).value == 3+ assert second_session.session_state["loomloom_video_confirm_charge"] is False+++def test_script_order_constraint_does_not_replace_saved_concat_preference():+ """A derived sequential mode must not become the user's reusable default."""+ test_app_config = dict(+ config.app,+ video_source="pexels",+ match_materials_to_script=True,+ )+ test_ui_config = dict(+ config.ui,+ language="en",+ video_concat_mode="random",+ voice_mode="tts",+ tts_server="azure-tts-v1",+ voice_name="en-US-JennyNeural-Female",+ )++ with (+ patch.object(config, "app", test_app_config),+ patch.object(config, "ui", test_ui_config),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(+ voice,+ "get_all_azure_voices",+ return_value=["en-US-JennyNeural-Female"],+ ),+ ):+ constrained_session = _new_app()+ constrained_concat = _widget_by_key(+ constrained_session.selectbox, "video_concat_mode_select"+ )+ assert constrained_concat.value == "sequential"+ assert constrained_concat.disabled is True+ assert test_ui_config["video_concat_mode"] == "random"++ # A later session without the constraint should recover the user's actual+ # preference, not the derived value shown while script-order matching ran.+ test_app_config["match_materials_to_script"] = False+ unconstrained_session = _new_app()+ assert _widget_by_key(+ unconstrained_session.selectbox, "video_concat_mode_select"+ ).value == "random"diff --git a/webui/Main.py b/webui/Main.pyindex 50e154bf..0ea8e6a8 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -178,6 +178,79 @@ def _save_runtime_config():return saved+def _saved_ui_choice(key, options, default):+ """读取一个持久化选择,并把旧配置或手工编辑的非法值降级为默认值。"""+ options = list(options)+ saved = config.ui.get(key, default)+ numeric_default = isinstance(default, (int, float)) and not isinstance(+ default, bool+ )+ # bool 是 int 的子类,``True == 1``。手工把数值选项写成 TOML+ # 布尔值时必须拒绝,不能让它伪装成第一个数值 option。+ if numeric_default and isinstance(saved, bool):+ return default+ for option in options:+ if saved == option:+ # 返回 options 中的真实值,顺便把 TOML 1.0 等价归一化为+ # 整数选项 1,避免下游参数类型随配置写法漂移。+ return option++ # TOML 中的数值通常保留原类型;仍兼容用户手工写成字符串的情况。+ if numeric_default and isinstance(saved, str):+ try:+ converted = type(default)(saved)+ except (TypeError, ValueError):+ converted = None+ for option in options:+ if converted == option:+ return option+ return default+++def _saved_ui_number(key, default, minimum, maximum, number_type=float):+ """读取并限幅持久化数值,避免非法配置破坏 Streamlit slider。"""+ try:+ saved = config.ui.get(key, default)+ if isinstance(saved, bool):+ raise ValueError("boolean is not a numeric setting")+ value = number_type(saved)+ if isinstance(value, float) and not math.isfinite(value):+ raise ValueError("non-finite value")+ except (TypeError, ValueError, OverflowError):+ value = default+ return min(maximum, max(minimum, value))+++def _saved_ui_bool(key, default):+ """兼容 TOML 布尔值和常见手工字符串,拒绝含义不明的旧值。"""+ value = config.ui.get(key, default)+ if isinstance(value, bool):+ return value+ if isinstance(value, str):+ normalized = value.strip().lower()+ if normalized in {"1", "true", "yes", "on"}:+ return True+ if normalized in {"0", "false", "no", "off"}:+ return False+ return default+++def _saved_ui_color(key, default):+ """只把标准六位十六进制颜色传给 Streamlit color picker。"""+ value = str(config.ui.get(key, default) or "").strip()+ if re.fullmatch(r"#[0-9a-fA-F]{6}", value):+ return value+ return default+++def _saved_ui_text(key, default="", max_length=None):+ """读取持久化文本并遵守对应 WebUI 控件的长度上限。"""+ value = str(config.ui.get(key, default) or default)+ if max_length is not None:+ value = value[:max_length]+ return value++def _run_llm_read_operation(operation_name, operation):"""使用稳定的当前 LLM 配置执行只读请求,并避免等待视频生成任务。@@ -325,11 +398,49 @@ def _initialize_session_state():"video_subject": "","video_script": "","video_terms": "",- "video_script_prompt": "",- "custom_system_prompt": llm.DEFAULT_SCRIPT_SYSTEM_PROMPT,+ "paragraph_number_input": _saved_ui_number(+ "paragraph_number",+ 1,+ llm.MIN_SCRIPT_PARAGRAPH_NUMBER,+ llm.MAX_SCRIPT_PARAGRAPH_NUMBER,+ int,+ ),+ "video_script_prompt": _saved_ui_text(+ "video_script_prompt",+ max_length=llm.MAX_SCRIPT_PROMPT_LENGTH,+ ),+ "custom_system_prompt": _saved_ui_text(+ "custom_system_prompt",+ llm.DEFAULT_SCRIPT_SYSTEM_PROMPT,+ llm.MAX_SCRIPT_SYSTEM_PROMPT_LENGTH,+ ),"match_materials_to_script": bool(config.app.get("match_materials_to_script", False)),+ "custom_bgm_file_input": _saved_ui_text("custom_bgm_file"),+ "sonilo_bgm_prompt_input": _saved_ui_text(+ "sonilo_bgm_prompt",+ max_length=sonilo_service.MAX_PROMPT_LENGTH,+ ),+ "elevenlabs_music_prompt_input": _saved_ui_text(+ "elevenlabs_music_prompt",+ max_length=elevenlabs_music_service.MAX_PROMPT_LENGTH,+ ),+ "subtitle_enabled_checkbox": _saved_ui_bool("subtitle_enabled", True),+ "stroke_color_picker": _saved_ui_color("stroke_color", "#000000"),+ "stroke_width_slider": _saved_ui_number(+ "stroke_width", 1.5, 0.0, 10.0+ ),+ "loomloom_candidate_count": _saved_ui_number(+ "loomloom_candidate_count",+ 3,+ 1,+ loomloom.MAX_SCRIPT_CANDIDATES,+ int,+ ),+ "loomloom_script_duration_seconds": _saved_ui_number(+ "loomloom_script_duration_seconds", 60, 10, 600, int+ ),"ui_language": initial_ui_language,# 已落盘的本地素材允许用户只修改文案后继续复用。"local_video_materials": [],@@ -359,7 +470,13 @@ def _initialize_session_state():"loomloom_video_client_request_id": "","loomloom_video_confirm_charge": False,# AI 视频按素材段计费,默认只生成一段,用户确认效果后再主动增加数量。- "loomloom_video_scene_count": 1,+ "loomloom_video_scene_count": _saved_ui_number(+ "loomloom_video_scene_count",+ 1,+ 1,+ loomloom.MAX_VIDEO_SCENES,+ int,+ ),}for key, value in defaults.items():st.session_state.setdefault(key, value)@@ -1744,11 +1861,14 @@ def reset_subtitle_settings():# 同步会持久化的 UI 选项,确保恢复后刷新页面仍保持默认设置。for key in (+ "subtitle_enabled","font_name","subtitle_position","custom_position","text_fore_color","font_size",+ "stroke_color",+ "stroke_width","subtitle_background_enabled","subtitle_background_color","rounded_subtitle_background",@@ -2372,13 +2492,14 @@ def _render_loomloom_video_settings(params):token = _effective_loomloom_api_token()- st.number_input(+ scene_count = st.number_input(tr("AI Video Scene Count"),min_value=1,max_value=loomloom.MAX_VIDEO_SCENES,step=1,key="loomloom_video_scene_count",)+ _set_runtime_config("ui", "loomloom_video_scene_count", int(scene_count))batch, input_signature = _current_loomloom_video_quote_context(params)if not token:st.warning(tr("Shengsuan Cloud API Key Required"))@@ -2641,7 +2762,6 @@ def _render_loomloom_script_generation(params):tr("Script Candidate Count"),min_value=1,max_value=loomloom.MAX_SCRIPT_CANDIDATES,- value=3,step=1,key="loomloom_candidate_count",)@@ -2649,10 +2769,13 @@ def _render_loomloom_script_generation(params):tr("Target Script Duration Seconds"),min_value=10,max_value=600,- value=60,step=10,key="loomloom_script_duration_seconds",)+ _set_runtime_config("ui", "loomloom_candidate_count", int(candidate_count))+ _set_runtime_config(+ "ui", "loomloom_script_duration_seconds", int(duration_seconds)+ )input_signature = _loomloom_script_signature(subject=params.video_subject,language=params.video_language,@@ -2831,13 +2954,18 @@ def _render_script_settings(panel, params):selected_language_code = stable_selectbox(tr("Script Language"),options=[value for _, value in video_languages],- default_value="",+ default_value=_saved_ui_choice(+ "video_language",+ [value for _, value in video_languages],+ "",+ ),key="script_language_select",format_func=lambda value: dict((v, label) for label, v in video_languages)[value],)params.video_language = selected_language_code+ _set_runtime_config("ui", "video_language", params.video_language)# 使用带 key 的局部容器限定折叠入口样式,保持 expander 的原生交互,# 同时避免样式误伤页面顶部的“基础设置”等其他折叠区域。@@ -2860,13 +2988,15 @@ def _render_script_settings(panel, params):"app", "script_generation_backend", script_generation_backend)- st.session_state.setdefault("paragraph_number_input", 1)params.paragraph_number = st.slider(tr("Script Paragraph Number"),min_value=llm.MIN_SCRIPT_PARAGRAPH_NUMBER,max_value=llm.MAX_SCRIPT_PARAGRAPH_NUMBER,key="paragraph_number_input",)+ _set_runtime_config(+ "ui", "paragraph_number", params.paragraph_number+ )params.video_script_prompt = st.text_area(tr("Custom Script Requirements"),height=100,@@ -2874,6 +3004,9 @@ def _render_script_settings(panel, params):placeholder=tr("Custom Script Requirements Placeholder"),key="video_script_prompt",).strip()+ _set_runtime_config(+ "ui", "video_script_prompt", params.video_script_prompt+ )system_prompt = st.text_area(tr("Custom System Prompt"),@@ -2888,6 +3021,9 @@ def _render_script_settings(panel, params):if system_prompt == llm.DEFAULT_SCRIPT_SYSTEM_PROMPT.strip()else system_prompt)+ _set_runtime_config(+ "ui", "custom_system_prompt", params.custom_system_prompt+ )restore_prompt_col, preview_prompt_col = st.columns(2)if restore_prompt_col.button(@@ -3016,7 +3152,11 @@ def _render_video_settings(panel, params):selected_concat_mode = stable_selectbox(tr("Video Concat Mode"),options=[value for _, value in video_concat_modes],- default_value=VideoConcatMode.random.value,+ default_value=_saved_ui_choice(+ "video_concat_mode",+ [value for _, value in video_concat_modes],+ VideoConcatMode.random.value,+ ),key="video_concat_mode_select",format_func=lambda value: dict((v, label) for label, v in video_concat_modes@@ -3036,6 +3176,12 @@ def _render_video_settings(panel, params):"match_materials_to_script",params.match_materials_to_script,)+ # 顺序匹配开启时,sequential 是派生出的强制值,不应覆盖用户在关闭+ # 该功能时选择的拼接偏好;关闭后仍能恢复此前的 random/sequential。+ if not params.match_materials_to_script:+ _set_runtime_config(+ "ui", "video_concat_mode", params.video_concat_mode.value+ )# 视频转场模式video_transition_modes = [@@ -3051,13 +3197,22 @@ def _render_video_settings(panel, params):selected_transition_mode = stable_selectbox(tr("Video Transition Mode"),options=[value for _, value in video_transition_modes],- default_value=VideoTransitionMode.none.value,+ default_value=_saved_ui_choice(+ "video_transition_mode",+ [value for _, value in video_transition_modes],+ VideoTransitionMode.none.value,+ ),key="video_transition_mode_select",format_func=lambda value: dict((v, label) for label, v in video_transition_modes)[value],)params.video_transition_mode = VideoTransitionMode(selected_transition_mode)+ _set_runtime_config(+ "ui",+ "video_transition_mode",+ params.video_transition_mode.value,+ )video_aspect_ratios = [(tr("Portrait"), VideoAspect.portrait.value),@@ -3070,30 +3225,48 @@ def _render_video_settings(panel, params):# - 用户在某 source 下手动改过 aspect,session_state 会记住,# 下次回到同一 source 时尊重用户选择,不会再被强制覆盖。default_aspect_index = 1 if params.video_source == "coverr" else 0+ video_aspect_values = [value for _, value in video_aspect_ratios]+ video_aspect_config_key = f"video_aspect_{params.video_source}"selected_aspect_ratio = stable_selectbox(tr("Video Ratio"),- options=[value for _, value in video_aspect_ratios],- default_value=video_aspect_ratios[default_aspect_index][1],+ options=video_aspect_values,+ default_value=_saved_ui_choice(+ video_aspect_config_key,+ video_aspect_values,+ video_aspect_ratios[default_aspect_index][1],+ ),key=f"video_aspect_for_{params.video_source}",format_func=lambda value: dict((v, label) for label, v in video_aspect_ratios)[value],)params.video_aspect = VideoAspect(selected_aspect_ratio)+ _set_runtime_config(+ "ui", video_aspect_config_key, params.video_aspect.value+ )+ video_clip_durations = [2, 3, 4, 5, 6, 7, 8, 9, 10]params.video_clip_duration = stable_selectbox(tr("Clip Duration"),- options=[2, 3, 4, 5, 6, 7, 8, 9, 10],- default_value=3,+ options=video_clip_durations,+ default_value=_saved_ui_choice(+ "video_clip_duration", video_clip_durations, 3+ ),key="video_clip_duration_select",help=tr("Clip Duration Help"),)+ _set_runtime_config(+ "ui", "video_clip_duration", params.video_clip_duration+ )clip_speed_key = localized_widget_key("video_clip_speed_slider")# session_state 可能来自旧任务、API 参数或旧版页面状态。控件创建前# 统一归一化,既保留合法选择,也确保 slider 始终收到 0.5~2.0# 范围内的有限浮点数。st.session_state[clip_speed_key] = utils.normalize_clip_speed(- st.session_state.get(clip_speed_key, 1.0)+ st.session_state.get(+ clip_speed_key,+ _saved_ui_number("video_clip_speed", 1.0, 0.5, 2.0),+ ))params.video_clip_speed = st.slider(tr("Clip Speed"),@@ -3104,12 +3277,17 @@ def _render_video_settings(panel, params):key=clip_speed_key,help=tr("Clip Speed Help"),)+ _set_runtime_config("ui", "video_clip_speed", params.video_clip_speed)+ video_count_options = [1, 2, 3, 4, 5]params.video_count = stable_selectbox(tr("Number of Videos Generated Simultaneously"),- options=[1, 2, 3, 4, 5],- default_value=1,+ options=video_count_options,+ default_value=_saved_ui_choice(+ "video_count", video_count_options, 1+ ),key="video_count_select",)+ _set_runtime_config("ui", "video_count", params.video_count)video_codec_options = [(tr("Default Video Encoder"), DEFAULT_VIDEO_CODEC_OPTION),@@ -3740,6 +3918,7 @@ def _render_elevenlabs_api_key_input(label_key):def _render_background_music_settings(params, elevenlabs_api_key_rendered=False):"""渲染背景音乐来源与音量设置,并返回本次待保存的上传文件。"""uploaded_bgm_file = None+ previous_bgm_type = st.session_state.get("last_rendered_bgm_type")st.divider()bgm_options = [(tr("No Background Music"), ""),@@ -3751,11 +3930,16 @@ def _render_background_music_settings(params, elevenlabs_api_key_rendered=False)selected_bgm_type = stable_selectbox(tr("Background Music Source"),options=[value for _, value in bgm_options],- default_value="random",+ default_value=_saved_ui_choice(+ "bgm_type",+ [value for _, value in bgm_options],+ "random",+ ),key="bgm_type_select",format_func=lambda value: dict((v, label) for label, v in bgm_options)[value],)params.bgm_type = selected_bgm_type+ _set_runtime_config("ui", "bgm_type", params.bgm_type)if params.bgm_type == "sonilo":configured_key = str(config.app.get("sonilo_api_key", "") or "").strip()effective_key = configured_key or os.getenv("SONILO_API_KEY", "").strip()@@ -3778,14 +3962,16 @@ def _render_background_music_settings(params, elevenlabs_api_key_rendered=False)else:_render_elevenlabs_api_key_input("ElevenLabs Music API Key")+ bgm_volume_options = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0]params.bgm_volume = stable_selectbox(tr("Background Music Volume"),- options=[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0],- default_value=0.2,+ options=bgm_volume_options,+ default_value=_saved_ui_choice("bgm_volume", bgm_volume_options, 0.2),key="bgm_volume_select",format_func=lambda value: f"{int(value * 100)}%",disabled=not params.bgm_type,)+ _set_runtime_config("ui", "bgm_volume", params.bgm_volume)bgm_enabled = bgm_service.should_use_bgm(params.bgm_type, params.bgm_volume)if params.bgm_type == "custom":@@ -3878,11 +4064,21 @@ def _render_background_music_settings(params, elevenlabs_api_key_rendered=False)st.info(f"{tr('Background Music Ready')}: {safe_name}")params.bgm_file = safe_name+ # Streamlit 会在条件控件暂时不渲染时清理其 widget state。+ # 从其它 BGM 来源切回时用已持久化值恢复;同一来源下+ # 用户主动清空时 previous_bgm_type 不变,因此不会被旧值反弹。+ if previous_bgm_type != "custom":+ st.session_state["custom_bgm_file_input"] = _saved_ui_text(+ "custom_bgm_file"+ )custom_bgm_file = st.text_input(tr("Custom Background Music File"),key="custom_bgm_file_input",disabled=uploaded_bgm_file is not None,)+ _set_runtime_config(+ "ui", "custom_bgm_file", custom_bgm_file.strip()+ )if uploaded_bgm_file is None and custom_bgm_file and bgm_enabled:# 文件名由服务层映射到 storage/bgm 或 resource/songs 后校验,# UI 不接受两个白名单目录之外的任意路径。@@ -3893,12 +4089,20 @@ def _render_background_music_settings(params, elevenlabs_api_key_rendered=False)params.bgm_file = ""if params.bgm_type == "sonilo":+ if previous_bgm_type != "sonilo":+ st.session_state["sonilo_bgm_prompt_input"] = _saved_ui_text(+ "sonilo_bgm_prompt",+ max_length=sonilo_service.MAX_PROMPT_LENGTH,+ )params.video_music_prompt = st.text_input(tr("Sonilo Music Prompt"),key="sonilo_bgm_prompt_input",max_chars=sonilo_service.MAX_PROMPT_LENGTH,help=tr("Sonilo Music Prompt Help"),).strip()+ _set_runtime_config(+ "ui", "sonilo_bgm_prompt", params.video_music_prompt+ )if params.video_count > 1:st.warning(tr("Sonilo Multiple Videos Warning"))if st.button(@@ -3914,12 +4118,20 @@ def _render_background_music_settings(params, elevenlabs_api_key_rendered=False)else:st.success(tr("Sonilo Connection Test Succeeded"))elif params.bgm_type == "elevenlabs":+ if previous_bgm_type != "elevenlabs":+ st.session_state["elevenlabs_music_prompt_input"] = _saved_ui_text(+ "elevenlabs_music_prompt",+ max_length=elevenlabs_music_service.MAX_PROMPT_LENGTH,+ )params.video_music_prompt = st.text_input(tr("ElevenLabs Music Prompt"),key="elevenlabs_music_prompt_input",max_chars=elevenlabs_music_service.MAX_PROMPT_LENGTH,help=tr("ElevenLabs Music Prompt Help"),).strip()+ _set_runtime_config(+ "ui", "elevenlabs_music_prompt", params.video_music_prompt+ )if params.video_count > 1:st.warning(tr("ElevenLabs Multiple Videos Warning"))if st.button(@@ -3946,6 +4158,7 @@ def _render_background_music_settings(params, elevenlabs_api_key_rendered=False)and not elevenlabs_music_service.is_enabled()):st.warning(tr("ElevenLabs API Key Required"))+ st.session_state["last_rendered_bgm_type"] = params.bgm_typereturn uploaded_bgm_file@@ -4319,14 +4532,18 @@ def _render_audio_settings(panel, params):params.voice_volume = 1.0params.voice_rate = 1.0uploaded_audio_file = None+ voice_volume_options = [0.6, 0.8, 1.0, 1.2, 1.5, 2.0, 3.0, 4.0, 5.0]+ voice_rate_options = [0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.5, 1.8, 2.0]if tts_mode_enabled:voice_control_cols = st.columns(2)with voice_control_cols[0]:params.voice_volume = stable_selectbox(tr("Voiceover Volume"),- options=[0.6, 0.8, 1.0, 1.2, 1.5, 2.0, 3.0, 4.0, 5.0],- default_value=1.0,+ options=voice_volume_options,+ default_value=_saved_ui_choice(+ "voice_volume", voice_volume_options, 1.0+ ),key="voice_volume_select",format_func=lambda value: f"{int(value * 100)}%",help=tr("Voiceover Volume Help"),@@ -4335,12 +4552,16 @@ def _render_audio_settings(panel, params):with voice_control_cols[1]:params.voice_rate = stable_selectbox(tr("Voiceover Speed"),- options=[0.8, 0.9, 1.0, 1.1, 1.2, 1.3, 1.5, 1.8, 2.0],- default_value=1.0,+ options=voice_rate_options,+ default_value=_saved_ui_choice(+ "voice_rate", voice_rate_options, 1.0+ ),key="voice_rate_select",format_func=lambda value: f"{value:.1f}×",help=tr("Voiceover Speed Help"),)+ _set_runtime_config("ui", "voice_volume", params.voice_volume)+ _set_runtime_config("ui", "voice_rate", params.voice_rate)# 试听必须位于音量和语速控件之后,确保调用使用当前控件值。_render_voice_preview(@@ -4363,12 +4584,15 @@ def _render_audio_settings(panel, params):)params.voice_volume = stable_selectbox(tr("Voiceover Volume"),- options=[0.6, 0.8, 1.0, 1.2, 1.5, 2.0, 3.0, 4.0, 5.0],- default_value=1.0,+ options=voice_volume_options,+ default_value=_saved_ui_choice(+ "voice_volume", voice_volume_options, 1.0+ ),key="voice_volume_select",format_func=lambda value: f"{int(value * 100)}%",help=tr("Voiceover Volume Help"),)+ _set_runtime_config("ui", "voice_volume", params.voice_volume)if uploaded_audio_file:st.audio(uploaded_audio_file, format="audio/mp3")st.info(@@ -4390,12 +4614,16 @@ def _render_subtitle_settings(panel, params):st.write(tr("Subtitle Settings"))st.session_state.setdefault("subtitle_enabled_checkbox",- DEFAULT_SUBTITLE_SETTINGS["subtitle_enabled"],+ _saved_ui_bool(+ "subtitle_enabled",+ DEFAULT_SUBTITLE_SETTINGS["subtitle_enabled"],+ ),)params.subtitle_enabled = st.checkbox(tr("Enable Subtitles"),key="subtitle_enabled_checkbox",)+ _set_runtime_config("ui", "subtitle_enabled", params.subtitle_enabled)subtitle_settings_disabled = not params.subtitle_enabledfont_names = get_all_fonts()saved_font_name = config.ui.get(@@ -4495,16 +4723,26 @@ def _render_subtitle_settings(panel, params):stroke_cols = st.columns([0.42, 0.58])with stroke_cols[0]:st.session_state.setdefault(- "stroke_color_picker", DEFAULT_SUBTITLE_SETTINGS["stroke_color"]+ "stroke_color_picker",+ _saved_ui_color(+ "stroke_color", DEFAULT_SUBTITLE_SETTINGS["stroke_color"]+ ),)params.stroke_color = st.color_picker(tr("Stroke Color"),key="stroke_color_picker",disabled=subtitle_settings_disabled,)+ _set_runtime_config("ui", "stroke_color", params.stroke_color)with stroke_cols[1]:st.session_state.setdefault(- "stroke_width_slider", DEFAULT_SUBTITLE_SETTINGS["stroke_width"]+ "stroke_width_slider",+ _saved_ui_number(+ "stroke_width",+ DEFAULT_SUBTITLE_SETTINGS["stroke_width"],+ 0.0,+ 10.0,+ ),)params.stroke_width = st.slider(tr("Stroke Width"),@@ -4513,6 +4751,7 @@ def _render_subtitle_settings(panel, params):key="stroke_width_slider",disabled=subtitle_settings_disabled,)+ _set_runtime_config("ui", "stroke_width", params.stroke_width)# 背景开关的本地化名称普遍比颜色标签更长,因此让开关占据略多空间。subtitle_bg_cols = st.columns([0.55, 0.45])