利用 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(material): improve Shengsuan video workflow
harry07035ceffd02a267
diff --git a/app/services/loomloom.py b/app/services/loomloom.pyindex e17eb040..4c3a7d2b 100644--- a/app/services/loomloom.py+++ b/app/services/loomloom.py@@ -22,9 +22,10 @@ from loguru import loggerDEFAULT_RESULT_PORT_NAME = "output"DEFAULT_BASE_URL = "https://loomloom.shengsuanyun.com/loom/v1"DEFAULT_SCRIPT_MARKET_LISTING_ID = "019fd618-9baa-73d9-94f4-c9270b6f3025"+VIDEO_CAPABILITY_PROFILE_ID = "video.text-to-video.aspect-ratio.v1"# 文案与视频是两个输入、产物结构完全不同的已上架 SkillBot。两个 ID 都是# MoneyPrinterTurbo 集成的内部常量,用户只需提供 API Key,不应接触 Listing ID。-DEFAULT_VIDEO_MARKET_LISTING_ID = "019fd60d-5c26-78f7-bba0-5584f9ee7337"+DEFAULT_VIDEO_MARKET_LISTING_ID = "01a06563-7331-773a-b9b2-25989a0dd70e"DEFAULT_REQUEST_TIMEOUT_SECONDS = 30.0DEFAULT_POLL_INTERVAL_SECONDS = 2.0DEFAULT_RUN_TIMEOUT_SECONDS = 600.0@@ -162,6 +163,21 @@ class LoomLoomVideoBatch:input_rows: tuple[dict[str, str], ...]+@dataclass(frozen=True)+class LoomLoomVideoModel:+ model_id: str+ display_name: str+++@dataclass(frozen=True)+class LoomLoomVideoCapability:+ """当前账号可用于文本生成视频 Profile 的公开候选。"""++ models: tuple[LoomLoomVideoModel, ...]+ default_model_id: str+ aspect_ratios: tuple[str, ...]++@dataclass(frozen=True)class LoomLoomQuote:quote_id: str@@ -242,7 +258,7 @@ def video_settings_from_mapping(values: Mapping[str, Any]) -> LoomLoomSettings:return LoomLoomSettings(base_url=settings.base_url,api_token=settings.api_token,- # 视频 Listing 接收 scenePrompt/aspectRatio/sceneIndex 并返回 MP4;不能+ # 视频 Listing 接收 prompt/modelChoice/aspectRatio 并返回 MP4;不能# 复用文案 Listing,否则报价阶段就会因输入 schema 不匹配而失败。market_listing_id=DEFAULT_VIDEO_MARKET_LISTING_ID,listing_version_id=settings.listing_version_id,@@ -634,7 +650,9 @@ class LoomLoomScriptBackend:if isinstance(error_payload, dict):server_error = str(error_payload.get("error", "")).strip()if server_error:- message = server_error+ # 服务端错误偶尔会回显请求上下文。即使出现异常响应,也不能+ # 让 Bearer Token 进入页面错误、日志或任务状态。+ message = server_error.replace(api_token, "[redacted]")raise LoomLoomAPIError(f"LoomLoom API returned HTTP {response.status_code}: {message}",status_code=response.status_code,@@ -681,17 +699,120 @@ class LoomLoomScriptBackend:class LoomLoomVideoBackend(LoomLoomScriptBackend):"""通过默认 SkillBot 生成视频素材,并将 MP4 产物安全下载到任务目录。"""+ def resolve_video_capability(self) -> LoomLoomVideoCapability:+ """读取当前账号在固定视频 Profile 下的实时模型与比例候选。"""+ response = self._request(+ "GET",+ "/authoringCapabilities:resolve",+ params={"inputModality": "text", "outputModality": "video"},+ )+ matches = response.get("matches", [])+ if not isinstance(matches, list):+ raise LoomLoomAPIError("LoomLoom capability matches must be a list")++ profile_match = next(+ (+ match+ for match in matches+ if isinstance(match, dict)+ and isinstance(match.get("profile"), dict)+ and str(match["profile"].get("profileId", "")).strip()+ == VIDEO_CAPABILITY_PROFILE_ID+ ),+ None,+ )+ if profile_match is None:+ raise LoomLoomConfigurationError(+ f"LoomLoom capability profile {VIDEO_CAPABILITY_PROFILE_ID} is unavailable"+ )++ eligible_models = profile_match.get("eligibleModels", [])+ if not isinstance(eligible_models, list):+ raise LoomLoomAPIError("LoomLoom eligibleModels must be a list")++ models = []+ seen_model_ids = set()+ for candidate in eligible_models:+ if not isinstance(candidate, dict):+ raise LoomLoomAPIError("LoomLoom eligible model must be an object")+ # null/数值不能转成看似有效的 ID,否则会把坏目录继续传给付费接口。+ model_id = candidate.get("modelId")+ display_name = candidate.get("displayName")+ if not isinstance(model_id, str) or not isinstance(display_name, str):+ raise LoomLoomAPIError("LoomLoom modelId and displayName must be strings")+ model_id = model_id.strip()+ display_name = display_name.strip()+ if not model_id or not display_name:+ raise LoomLoomAPIError(+ "LoomLoom eligible model requires modelId and displayName"+ )+ if model_id in seen_model_ids:+ continue+ seen_model_ids.add(model_id)+ models.append(+ LoomLoomVideoModel(model_id=model_id, display_name=display_name)+ )+ if not models:+ raise LoomLoomConfigurationError(+ "LoomLoom video capability has no eligible models"+ )++ profile = profile_match["profile"]+ operations = profile.get("operations", {})+ if not isinstance(operations, dict):+ raise LoomLoomAPIError("LoomLoom profile operations must be an object")+ default_model_id = str(operations.get("defaultModelId", "")).strip()+ if default_model_id not in seen_model_ids:+ raise LoomLoomConfigurationError(+ "LoomLoom video capability default model is not eligible"+ )++ definition = profile.get("definition", {})+ constraints = (+ definition.get("constraints", {}) if isinstance(definition, dict) else {}+ )+ ports = constraints.get("ports", {}) if isinstance(constraints, dict) else {}+ aspect_ratio = ports.get("aspect_ratio", {}) if isinstance(ports, dict) else {}+ raw_aspect_ratios = (+ aspect_ratio.get("enum", []) if isinstance(aspect_ratio, dict) else []+ )+ if not isinstance(raw_aspect_ratios, list):+ raise LoomLoomAPIError(+ "LoomLoom video aspect ratio constraint must be a list"+ )+ aspect_ratios = tuple(+ dict.fromkeys(+ str(value).strip()+ for value in raw_aspect_ratios+ if str(value).strip() in {"9:16", "16:9"}+ )+ )+ if not aspect_ratios:+ raise LoomLoomConfigurationError(+ "LoomLoom video capability has no supported aspect ratios"+ )++ return LoomLoomVideoCapability(+ models=tuple(models),+ default_model_id=default_model_id,+ aspect_ratios=aspect_ratios,+ )+def prepare_video_batch(self,*,subject: str,scene_prompts: list[str] | tuple[str, ...],+ model_id: str,aspect_ratio: str,) -> LoomLoomVideoBatch:normalized_subject = str(subject or "").strip()+ normalized_model_id = str(model_id or "").strip()normalized_aspect_ratio = str(aspect_ratio or "").strip()if not normalized_subject:raise ValueError("subject is required")+ if not normalized_model_id:+ raise ValueError("model_id is required")if normalized_aspect_ratio not in {"9:16", "16:9"}:raise ValueError("aspect_ratio must be 9:16 or 16:9")@@ -707,13 +828,13 @@ class LoomLoomVideoBackend(LoomLoomScriptBackend):rows = tuple({- "scenePrompt": (+ "prompt": ("Create cinematic stock-footage-style video for a short video "- f"about {normalized_subject}. Scene focus: {scene}. "+ f"about {normalized_subject}. Scene {index} focus: {scene}. ""No text, subtitles, captions, watermarks, logos, or spoken audio."),+ "modelChoice": normalized_model_id,"aspectRatio": normalized_aspect_ratio,- "sceneIndex": str(index),}for index, scene in enumerate(scenes, start=1))diff --git a/test/services/test_loomloom.py b/test/services/test_loomloom.pyindex b56eddd5..ea8ef621 100644--- a/test/services/test_loomloom.py+++ b/test/services/test_loomloom.py@@ -23,6 +23,45 @@ from app.services.loomloom import ()+def _video_capability_payload(+ *, models=None, default_model_id="model-a", include_target_profile=True+):+ matches = [+ {+ "profile": {+ "profileId": "unrelated.profile",+ "operations": {"defaultModelId": "wrong-model"},+ },+ "eligibleModels": [+ {"modelId": "wrong-model", "displayName": "Wrong Model"}+ ],+ }+ ]+ if include_target_profile:+ matches.append(+ {+ "profile": {+ "profileId": "video.text-to-video.aspect-ratio.v1",+ "operations": {"defaultModelId": default_model_id},+ "definition": {+ "constraints": {+ "ports": {"aspect_ratio": {"enum": ["16:9", "9:16"]}}+ }+ },+ },+ "eligibleModels": (+ [+ {"modelId": "model-a", "displayName": "Model A"},+ {"modelId": "model-b", "displayName": "Model B"},+ ]+ if models is None+ else models+ ),+ }+ )+ return {"matches": matches}++class _Response:def __init__(self, status_code, payload):self.status_code = status_code@@ -103,6 +142,10 @@ class TestLoomLoomSettings(unittest.TestCase):)self.assertEqual(settings.market_listing_id, DEFAULT_VIDEO_MARKET_LISTING_ID)+ self.assertEqual(+ settings.market_listing_id,+ "01a06563-7331-773a-b9b2-25989a0dd70e",+ )self.assertEqual(settings.run_timeout_seconds, 1800)@@ -438,31 +481,164 @@ class TestLoomLoomScriptBackend(unittest.TestCase):self.assertNotIn("do-not-copy", str(captured.exception))+ def test_api_error_redacts_bearer_token_echoed_by_server(self):+ self.session.request.return_value = _Response(+ 400,+ {"error": "invalid credential test-token"},+ )+ batch = self.backend.prepare_script_batch(subject="主题", candidate_count=1)++ with self.assertRaises(LoomLoomAPIError) as captured:+ self.backend.quote(batch)++ self.assertNotIn("test-token", str(captured.exception))+ self.assertIn("[redacted]", str(captured.exception))+class TestLoomLoomVideoBackend(unittest.TestCase):def setUp(self):self.settings = LoomLoomSettings(base_url="https://example.test/loom/v1",api_token="test-token",- market_listing_id=DEFAULT_SCRIPT_MARKET_LISTING_ID,+ market_listing_id=DEFAULT_VIDEO_MARKET_LISTING_ID,result_port_name="output",)self.session = MagicMock()self.backend = LoomLoomVideoBackend(self.settings, session=self.session)+ def test_resolves_exact_video_profile_and_ignores_other_profiles(self):+ self.session.request.return_value = _Response(200, _video_capability_payload())++ capability = self.backend.resolve_video_capability()++ self.assertEqual(+ [(model.model_id, model.display_name) for model in capability.models],+ [("model-a", "Model A"), ("model-b", "Model B")],+ )+ self.assertEqual(capability.default_model_id, "model-a")+ self.assertEqual(capability.aspect_ratios, ("16:9", "9:16"))+ request = self.session.request.call_args+ self.assertEqual(+ request.args,+ (+ "GET",+ "https://example.test/loom/v1/authoringCapabilities:resolve",+ ),+ )+ self.assertEqual(+ request.kwargs["params"],+ {"inputModality": "text", "outputModality": "video"},+ )++ def test_resolver_rejects_missing_empty_or_invalid_default_profile(self):+ cases = (+ (+ _video_capability_payload(include_target_profile=False),+ "profile .* is unavailable",+ ),+ (_video_capability_payload(models=[]), "no eligible models"),+ (+ _video_capability_payload(default_model_id="removed-model"),+ "default model is not eligible",+ ),+ )+ for payload, error in cases:+ with self.subTest(error=error):+ self.session.request.return_value = _Response(200, payload)+ with self.assertRaisesRegex(LoomLoomConfigurationError, error):+ self.backend.resolve_video_capability()++ def test_resolver_rejects_non_string_model_fields(self):+ """服务返回 null/数值时应在目录阶段报错,不把伪 ID 传进付费请求。"""+ for field in ("modelId", "displayName"):+ for value in (None, 123, {}, []):+ with self.subTest(field=field, value=value):+ model = {"modelId": "model-a", "displayName": "Model A"}+ model[field] = value+ self.session.request.return_value = _Response(+ 200, _video_capability_payload(models=[model])+ )+ with self.assertRaisesRegex(LoomLoomAPIError, "must be strings"):+ self.backend.resolve_video_capability()+def test_prepares_one_video_row_per_scene(self):"""默认 SkillBot 必须按场景逐行报价,并携带固定的视频安全要求。"""batch = self.backend.prepare_video_batch(subject="AI 办公效率",scene_prompts=["office worker", "AI assistant"],+ model_id="google/veo3.1-fast-preview",aspect_ratio="9:16",)self.assertEqual(len(batch.input_rows), 2)self.assertEqual(batch.input_rows[0]["aspectRatio"], "9:16")- self.assertEqual(batch.input_rows[1]["sceneIndex"], "2")- self.assertIn("office worker", batch.input_rows[0]["scenePrompt"])- self.assertIn("No text", batch.input_rows[0]["scenePrompt"])+ self.assertEqual(+ {row["modelChoice"] for row in batch.input_rows},+ {"google/veo3.1-fast-preview"},+ )+ self.assertIn("office worker", batch.input_rows[0]["prompt"])+ self.assertIn("Scene 2", batch.input_rows[1]["prompt"])+ self.assertIn("No text", batch.input_rows[0]["prompt"])+ self.assertNotIn("scenePrompt", batch.input_rows[0])+ self.assertNotIn("sceneIndex", batch.input_rows[0])++ def test_video_batch_accepts_only_supported_aspect_ratios(self):+ for aspect_ratio in ("16:9", "9:16"):+ with self.subTest(aspect_ratio=aspect_ratio):+ batch = self.backend.prepare_video_batch(+ subject="subject",+ scene_prompts=["scene"],+ model_id="model-a",+ aspect_ratio=aspect_ratio,+ )+ self.assertEqual(batch.input_rows[0]["aspectRatio"], aspect_ratio)++ with self.assertRaisesRegex(ValueError, "aspect_ratio"):+ self.backend.prepare_video_batch(+ subject="subject",+ scene_prompts=["scene"],+ model_id="model-a",+ aspect_ratio="1:1",+ )++ def test_video_quote_uses_new_listing_and_public_input_contract(self):+ self.session.request.return_value = _Response(+ 200,+ {+ "quoteId": "quote-1",+ "listingVersionId": "listing-version-1",+ "currency": "CNY",+ "taskCount": 1,+ "estimatedBuyerPayableT": 0,+ },+ )+ batch = self.backend.prepare_video_batch(+ subject="subject",+ scene_prompts=["scene"],+ model_id="model-a",+ aspect_ratio="16:9",+ )++ self.backend.quote(batch)++ request = self.session.request.call_args+ self.assertEqual(+ request.args[1],+ "https://example.test/loom/v1/marketListings/"+ "01a06563-7331-773a-b9b2-25989a0dd70e:quote",+ )+ self.assertEqual(+ request.kwargs["json"],+ {+ "inputRows": [+ {+ "prompt": batch.input_rows[0]["prompt"],+ "modelChoice": "model-a",+ "aspectRatio": "16:9",+ }+ ]+ },+ )def test_downloads_video_artifact_without_forwarding_api_key(self):"""签名产物地址无需 Bearer Key,避免把账户凭证泄漏给对象存储。"""diff --git a/test/services/test_webui_i18n.py b/test/services/test_webui_i18n.pyindex c873f2eb..957d8b3d 100644--- a/test/services/test_webui_i18n.py+++ b/test/services/test_webui_i18n.py@@ -24,8 +24,15 @@ ENGLISH_FALLBACK_KEYS = frozenset({"AI Video Quote Required","AI Video Quote Retained For Retry",+ "AI Video Quote Estimate Incomplete","AI Video Quote Summary","AI Video Quote Summary Singular",+ "AI Video Model",+ "AI Video Model Reference Price",+ "AI Video Model List Load Failed",+ "AI Video Duration Basis Actual",+ "AI Video Duration Basis Estimated",+ "AI Video Material Coverage","AI Video Scene Count","Confirm AI Video Charge","Confirm AI Video Charge Help",@@ -44,6 +51,8 @@ ENGLISH_FALLBACK_KEYS = frozenset("LoomLoom Poll Retry Pending","LoomLoom Poll Retry Warning","Resume LoomLoom Status Check",+ "Refresh AI Video Models",+ "Retry AI Video Quote","LoomLoom Quote Summary Singular","LoomLoom Video Terms Reuse Help","Metaso MiniMax H3",@@ -68,12 +77,16 @@ ENGLISH_FALLBACK_KEYS = frozenset("Shengsuan Cloud AI Video Help","Shengsuan Cloud API Key","Shengsuan Cloud API Key Help",+ "Shengsuan Cloud API Key Link","Shengsuan Cloud API Key Placeholder","Shengsuan Cloud API Key Required","Shengsuan Cloud API Key Reused","Shengsuan Cloud Batch Script Generation",+ "Selected AI Video Model Unavailable",+ "Selected AI Video Ratio Unavailable","Stop Tracking LoomLoom Run","Stop Tracking LoomLoom Run Help",+ "Unavailable AI Video Model",})FORMAT_PLACEHOLDER_PATTERN = re.compile(r"(?<!\{)\{([a-zA-Z_][a-zA-Z0-9_]*)\}(?!\})")diff --git a/test/services/test_webui_loomloom.py b/test/services/test_webui_loomloom.pyindex b51f7764..f0fd865b 100644--- a/test/services/test_webui_loomloom.py+++ b/test/services/test_webui_loomloom.py@@ -2,18 +2,34 @@ import astimport hashlibimport jsonfrom pathlib import Path+from types import SimpleNamespacefrom unittest.mock import patchfrom streamlit.testing.v1 import AppTestfrom app.config import config-from app.services import loomloom+from app.services import llm, loomloomROOT_DIR = Path(__file__).parent.parent.parentWEBUI_MAIN = ROOT_DIR / "webui" / "Main.py"+def _video_capability(default_model_id="model-a", models=None):+ return loomloom.LoomLoomVideoCapability(+ models=(+ (+ loomloom.LoomLoomVideoModel("model-a", "Model A"),+ loomloom.LoomLoomVideoModel("model-b", "Model B"),+ )+ if models is None+ else tuple(models)+ ),+ default_model_id=default_model_id,+ aspect_ratios=("16:9", "9:16"),+ )++def _function(tree, name):return next(node@@ -120,6 +136,55 @@ def test_loomloom_quote_signature_changes_with_billable_inputs():assert original != changed_credential+def test_loomloom_model_reference_prices_match_known_models_and_ignore_new_ones():+ """价格仅是本地展示增强,未知后端模型不能因此变成不可选。"""+ tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))+ price_table = next(+ node+ for node in tree.body+ if isinstance(node, ast.Assign)+ and any(+ isinstance(target, ast.Name)+ and target.id == "LOOMLOOM_VIDEO_MODEL_PRICES"+ for target in node.targets+ )+ )+ module = ast.fix_missing_locations(+ ast.Module(+ body=[+ price_table,+ _function(tree, "_normalize_loomloom_model_identifier"),+ _function(tree, "_loomloom_video_model_price"),+ _function(tree, "_format_loomloom_video_model_option"),+ ],+ type_ignores=[],+ )+ )+ namespace = {"re": __import__("re")}+ exec(compile(module, str(WEBUI_MAIN), "exec"), namespace)++ known_models = (+ ("google/veo3.1-fast-preview", "Veo3.1-fast", "¥0.700/秒"),+ ("", "通义万相2.2-文生视频-Fast-Lora", "¥0.350–0.770/条"),+ ("", "即梦3.0-文生视频-720P", "¥0.230/秒"),+ ("", "即梦3.0Pro-视频", "¥1.000/秒"),+ ("", "Veo3", "¥1.400/秒"),+ ("", "Veo3.1", "¥1.400/秒"),+ ("", "KlingV2", "¥10.00–20.00/条"),+ ("", "Kling V2.1 Master", "¥10.00–20.00/条"),+ ("", "ViduQ3-Pro", "¥0.440–1.000/秒"),+ )+ unknown = SimpleNamespace(model_id="future/model", display_name="Future Model")++ for model_id, display_name, compact_price in known_models:+ model = SimpleNamespace(model_id=model_id, display_name=display_name)+ assert namespace["_format_loomloom_video_model_option"](model) == (+ f"{display_name} · {compact_price}"+ )+ assert namespace["_loomloom_video_model_price"](unknown) == ("", "")+ assert namespace["_format_loomloom_video_model_option"](unknown) == "Future Model"++def test_loomloom_webui_quotes_then_requires_confirmation_before_execute():test_config = dict(config.app,@@ -203,6 +268,61 @@ def test_loomloom_webui_quotes_then_requires_confirmation_before_execute():assert [str(item.value) for item in app.exception] == []+def test_generated_long_script_autofills_video_count_once_and_shows_shortfall():+ """推荐数受五段上限约束,且用户手动调整后不能被下一次 rerun 覆盖。"""+ long_script = " ".join(+ [+ "Robots cross the ruined city while alarms echo through every street"+ ]+ * 8+ )+ test_config = dict(+ config.app,+ llm_provider="openai",+ script_generation_backend="local",+ video_source="loomloom",+ loomloom_api_token="",+ )+ test_ui_config = dict(config.ui, video_clip_duration=3)++ with (+ patch.object(config, "app", test_config),+ patch.object(config, "ui", test_ui_config),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(llm, "generate_script", return_value=long_script),+ patch.object(llm, "generate_terms", return_value=["robot city"]),+ ):+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)+ app.session_state["ui_language"] = "en"+ app.run()++ _widget_by_key(app.text_area, "video_subject").set_value("Robot city").run()+ _widget_by_key(app.button, "auto_generate_script").click().run()++ scene_count = _widget_by_key(+ app.number_input, "loomloom_video_scene_count"+ )+ assert scene_count.value == loomloom.MAX_VIDEO_SCENES+ warning_text = " ".join(str(item.value) for item in app.warning).lower()+ assert "shortfall" in warning_text+ assert "black screen" not in warning_text+ assert "cover approximately 15.0 sec" in warning_text+ assert app.session_state["loomloom_video_scene_autofill_digest"] == ""++ scene_count.set_value(3).run()+ assert _widget_by_key(+ app.number_input, "loomloom_video_scene_count"+ ).value == 3+ # 任意普通 rerun 也应保留用户的手动选择,而不是再次跳回推荐值 5。+ _widget_by_key(app.text_area, "video_subject").set_value(+ "Robot city updated"+ ).run()+ assert _widget_by_key(+ app.number_input, "loomloom_video_scene_count"+ ).value == 3+ assert [str(item.value) for item in app.exception] == []++def test_loomloom_video_source_quotes_then_passes_secret_in_confirmed_request():test_config = dict(config.app,@@ -224,12 +344,19 @@ def test_loomloom_video_source_quotes_then_passes_secret_in_confirmed_request():with (patch.object(config, "app", test_config),+ # 显式从两段切到一段,不能依赖开发者 config.toml 中的历史值。+ patch.object(config, "ui", dict(config.ui, loomloom_video_scene_count=2)),patch.object(config, "try_save_config", return_value=True),patch.object(loomloom.LoomLoomVideoBackend,"quote",return_value=quote_result,) as quote_call,+ patch.object(+ loomloom.LoomLoomVideoBackend,+ "resolve_video_capability",+ return_value=_video_capability(),+ ) as resolve_call,patch("app.services.webui_task.submit_generation") as submit_generation,):app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)@@ -245,10 +372,31 @@ def test_loomloom_video_source_quotes_then_passes_secret_in_confirmed_request():).run()app.session_state["video_source_select_en"] = "loomloom"app.run()+ _widget_by_key(app.number_input, "loomloom_video_scene_count").set_value(+ 1+ ).run()+ model_select = _widget_by_key(app.selectbox, "loomloom_video_model_select_en")+ assert model_select.value == "model-a"+ assert model_select.options == ["Model A", "Model B"]+ assert resolve_call.call_count == 1assert all(item.key != "loomloom_user_api_token" for item in app.text_input)- assert _widget_by_key(app.number_input, "loomloom_video_scene_count").value == 1- _widget_by_key(app.button, "loomloom_quote_videos").click().run()- assert quote_call.call_count == 1+ # 切换来源后取得初始报价;场景数归一为 1 后再刷新一次。+ assert quote_call.call_count == 2+ assert all(item.key != "loomloom_quote_videos" for item in app.button)+ quoted_batch = quote_call.call_args.args[0]+ assert quoted_batch.input_rows[0]["modelChoice"] == "model-a"++ model_select = _widget_by_key(app.selectbox, "loomloom_video_model_select_en")+ model_select.select("model-b").run()+ assert quote_call.call_count == 3+ assert not _widget_by_key(+ app.checkbox, "loomloom_video_confirm_charge"+ ).value++ _widget_by_key(app.selectbox, "loomloom_video_model_select_en").select(+ "model-a"+ ).run()+ assert quote_call.call_count == 4_widget_by_key(app.checkbox, "loomloom_video_confirm_charge").check().run()_widget_by_key(app.button, "generate_video_button").click().run()@@ -264,13 +412,112 @@ def test_loomloom_video_source_quotes_then_passes_secret_in_confirmed_request():assert [str(item.value) for item in app.exception] == []-def test_generation_page_omits_shengsuan_key_input():+def test_loomloom_refresh_keeps_unavailable_selection_until_user_changes_it():+ test_config = dict(+ config.app,+ llm_provider="openai",+ script_generation_backend="local",+ video_source="pexels",+ loomloom_api_token="session-user-token",+ )+ refreshed_capability = _video_capability(+ models=(loomloom.LoomLoomVideoModel("model-a", "Model A"),)+ )++ with (+ patch.object(config, "app", test_config),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(+ loomloom.LoomLoomVideoBackend,+ "resolve_video_capability",+ side_effect=[_video_capability(), refreshed_capability],+ ),+ ):+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)+ app.session_state["ui_language"] = "en"+ app.run()++ app.session_state["video_source_select_en"] = "loomloom"+ app.run()+ _widget_by_key(app.selectbox, "loomloom_video_model_select_en").select(+ "model-b"+ ).run()+ _widget_by_key(app.button, "loomloom_refresh_video_models").click().run()++ selected = _widget_by_key(app.selectbox, "loomloom_video_model_select_en")+ assert selected.value == "model-b"+ assert selected.options[0] == "Unavailable: model-b"+ assert any(+ "no longer available" in str(item.value).lower() for item in app.error+ )+ assert all(item.key != "loomloom_quote_videos" for item in app.button)+ assert [str(item.value) for item in app.exception] == []+++def test_loomloom_zero_video_quote_warns_about_actual_charges():+ test_config = dict(+ config.app,+ llm_provider="openai",+ script_generation_backend="local",+ video_source="pexels",+ loomloom_base_url="https://example.test/loom/v1",+ loomloom_api_token="",+ )+ quote_result = loomloom.LoomLoomQuote(+ quote_id="video-quote-zero",+ listing_version_id="video-version-1",+ currency="CNY",+ task_count=1,+ estimated_buyer_payable_t=0,+ estimated_buyer_payable_amount="0",+ input_rows=(),+ )++ with (+ patch.object(config, "app", test_config),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(+ loomloom.LoomLoomVideoBackend,+ "resolve_video_capability",+ return_value=_video_capability(),+ ),+ patch.object(+ loomloom.LoomLoomVideoBackend,+ "quote",+ return_value=quote_result,+ ),+ ):+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)+ app.session_state["ui_language"] = "en"+ app.run()++ _widget_by_key(app.text_area, "video_subject").set_value("AI office").run()+ _widget_by_key(app.text_area, "video_script").set_value("AI at work").run()+ _widget_by_key(app.text_area, "video_terms").set_value("office").run()+ app.session_state["video_source_select_en"] = "loomloom"+ app.run()+ test_config["loomloom_api_token"] = "session-user-token"+ app.run()++ warnings = " ".join(str(item.value) for item in app.warning).lower()+ assert all(item.key != "loomloom_quote_videos" for item in app.button)+ assert "complete cost estimate" in warnings+ assert "final billing" in warnings+ assert "free" not in warnings+ assert not _widget_by_key(+ app.checkbox, "loomloom_video_confirm_charge"+ ).disabled+ assert [str(item.value) for item in app.exception] == []+++def test_selected_shengsuanyun_provider_hides_duplicate_loomloom_key_input():test_config = dict(config.app,llm_provider="shengsuanyun",shengsuanyun_api_key="provider-key",- script_generation_backend="loomloom",+ script_generation_backend="local",loomloom_api_token="standalone-key",+ video_source="pexels",)with (@@ -278,10 +525,35 @@ def test_generation_page_omits_shengsuan_key_input():patch.object(config, "try_save_config", return_value=True),):app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)- app.session_state["ui_language"] = "en"+ app.session_state["ui_language"] = "zh"app.run()assert all(item.key != "loomloom_user_api_token" for item in app.text_input)+ generation_method = _widget_by_key(+ app.selectbox, "script_generation_backend_select_zh"+ )+ assert generation_method.value == "local"+ assert "使用“设置”中当前选择的大模型 Provider 生成文案" in generation_method.help+ assert "LoomLoom" not in generation_method.help+ assert "https://console.shengsuanyun.com/user/keys" not in generation_method.help++ generation_method.select("loomloom").run()+ generation_method = _widget_by_key(+ app.selectbox, "script_generation_backend_select_zh"+ )+ assert generation_method.value == "loomloom"+ assert "LoomLoom 会批量生成多个独立文案候选" in generation_method.help+ assert "已复用“设置 → 大模型提供商”中的胜算云 API Key" in generation_method.help+ assert (+ "https://console.shengsuanyun.com/user/keys" in generation_method.help+ )+ assert _widget_by_key(app.button, "loomloom_quote_scripts")+ assert all(item.key != "auto_generate_script" for item in app.button)+ assert all(item.key != "loomloom_user_api_token" for item in app.text_input)+ assert all(+ "https://console.shengsuanyun.com/user/keys" not in str(item.value)+ for item in app.markdown+ )assert [str(item.value) for item in app.exception] == []diff --git a/test/services/test_webui_loomloom_regressions.py b/test/services/test_webui_loomloom_regressions.pynew file mode 100644index 00000000..c05bbdcd--- /dev/null+++ b/test/services/test_webui_loomloom_regressions.py@@ -0,0 +1,378 @@+"""胜算云吸收优化的回归:隔离状态、准确试听时长和既有文案路由。"""++import ast+import hashlib+import json+import math+from contextlib import ExitStack+from pathlib import Path+from types import SimpleNamespace+from unittest.mock import patch++import pytest+from streamlit.testing.v1 import AppTest++from app.config import config+from app.services import llm, loomloom++MAIN = Path(__file__).parents[2] / "webui" / "Main.py"+++def helpers(state):+ """只执行待测 helper,避免为了验证缓存语义启动整页或访问外部服务。"""+ names = {+ "_loomloom_video_account_signature",+ "_load_loomloom_video_capability",+ "_matching_full_voice_preview_duration",+ }+ tree = ast.parse(MAIN.read_text(encoding="utf-8"))+ module = ast.fix_missing_locations(+ ast.Module(+ body=[+ n+ for n in tree.body+ if isinstance(n, ast.FunctionDef) and n.name in names+ ],+ type_ignores=[],+ )+ )+ env = {+ "st": SimpleNamespace(session_state=state),+ "config": config,+ "loomloom": loomloom,+ "hashlib": hashlib,+ "json": json,+ "math": math,+ "localized_widget_key": lambda key: key,+ "logger": SimpleNamespace(warning=lambda message: None),+ }+ exec(compile(module, str(MAIN), "exec"), env)+ return env+++def test_capability_cache_isolated_by_endpoint_and_key_and_recovers():+ state = {}+ env = helpers(state)+ capability = loomloom.LoomLoomVideoCapability(+ (loomloom.LoomLoomVideoModel("m", "Model"),), "m", ("9:16",)+ )+ from unittest.mock import Mock++ backend = Mock()+ backend.resolve_video_capability.return_value = capability+ env["_create_loomloom_video_backend"] = lambda: backend+ values = {"loomloom_base_url": "https://example.test/v1"}+ with patch.object(config, "snapshot_config_with_pending", return_value=values):+ load = env["_load_loomloom_video_capability"]+ assert load("key-a") == capability+ assert load("key-a") == capability+ assert backend.resolve_video_capability.call_count == 1+ backend.resolve_video_capability.side_effect = loomloom.LoomLoomAPIError(+ "offline"+ )+ assert load("key-a", force=True) == capability+ assert state["loomloom_video_capability_error"] == "offline"+ # 换 Key/端点后失败必须清空旧目录,不能把其他账户的目录误认为有效。+ assert load("key-b") is None+ backend.resolve_video_capability.side_effect = None+ assert load("key-b", force=True) == capability+ assert not state["loomloom_video_capability_error"]+ values["loomloom_base_url"] = "https://second.test/v1"+ backend.resolve_video_capability.side_effect = loomloom.LoomLoomAPIError(+ "offline"+ )+ assert load("key-b") is None+ assert load("") is None+++ "field,value",+ [+ ("preview_type", "sample"),+ ("content_digest", "old"),+ ("tts_server", "other"),+ ("voice_name", "other"),+ ("voice_rate", 1.2),+ ("voice_rate", "invalid"),+ ("duration", 0),+ ("duration", float("nan")),+ ("duration", float("inf")),+ ],+)+def test_old_or_invalid_preview_never_changes_recommendation(field, value):+ preview = {+ "preview_type": "full",+ "content_digest": hashlib.sha256(b"script").hexdigest(),+ "tts_server": "kokoro",+ "voice_name": "kokoro:af_heart",+ "voice_rate": 1.0,+ "duration": 12.0,+ }+ state = {+ "voice_preview_audio": preview,+ "tts_server_select": "kokoro",+ "speech_synthesis_select_kokoro": "kokoro:af_heart",+ }+ match = helpers(state)["_matching_full_voice_preview_duration"]+ assert match("script", 1.0) == 12.0+ preview[field] = value+ assert match("script", 1.0) is None+++def test_batch_script_and_video_use_settings_key_without_local_llm():+ values = dict(+ config.app,+ llm_provider="openai",+ script_generation_backend="loomloom",+ video_source="loomloom",+ loomloom_api_token="",+ )+ capability = loomloom.LoomLoomVideoCapability(+ (loomloom.LoomLoomVideoModel("m", "Model"),), "m", ("9:16",)+ )+ quote = loomloom.LoomLoomQuote("q", "v", "CNY", 1, 1, "0.1", ())+ with (+ patch.object(config, "app", values),+ patch.object(config, "ui", {}),+ patch.object(config, "try_save_config", return_value=True),+ patch.object(+ loomloom.LoomLoomVideoBackend,+ "resolve_video_capability",+ return_value=capability,+ ),+ patch.object(loomloom.LoomLoomVideoBackend, "quote", return_value=quote),+ patch.object(llm, "generate_script") as generate,+ ):+ app = AppTest.from_file(str(MAIN), default_timeout=30)+ app.session_state["ui_language"] = "en"+ app.run()+ fields = [x for x in app.text_input if x.key == "loomloom_user_api_token"]+ assert len(fields) == 0+ # 设置是唯一凭据入口;配置更新后两个功能都读取最新快照。+ values["loomloom_api_token"] = "test-key"+ app.run()+ assert not app.exception+ assert app.session_state["loomloom_video_capability"] == capability+ assert any(x.key == "loomloom_quote_scripts" for x in app.button)+ assert not any(x.key == "auto_generate_script" for x in app.button)+ generate.assert_not_called()+++def widget(items, key):+ return next(item for item in items if item.key == key)+++def quote_page():+ """用真实 Streamlit 控件运行失败路径,模拟网络且禁止写配置和提交任务。"""+ values = dict(+ config.app,+ video_source="loomloom",+ script_generation_backend="local",+ loomloom_api_token="test-key",+ loomloom_base_url="https://example.test/v1",+ )+ capability = loomloom.LoomLoomVideoCapability(+ (+ loomloom.LoomLoomVideoModel("a", "Model A"),+ loomloom.LoomLoomVideoModel("b", "Model B"),+ ),+ "a",+ ("16:9", "9:16"),+ )+ with ExitStack() as stack:+ stack.enter_context(patch.object(config, "app", values))+ stack.enter_context(patch.object(config, "ui", {}))+ stack.enter_context(patch.object(config, "try_save_config", return_value=True))+ stack.enter_context(+ patch.object(+ loomloom.LoomLoomVideoBackend,+ "resolve_video_capability",+ return_value=capability,+ )+ )+ quote = stack.enter_context(+ patch.object(loomloom.LoomLoomVideoBackend, "quote")+ )+ submit = stack.enter_context(patch("app.services.webui_task.submit_generation"))+ app = AppTest.from_file(str(MAIN), default_timeout=30)+ app.session_state["ui_language"] = "en"+ app.session_state["video_subject"] = "AI daily life"+ app.session_state["video_script"] = "AI helps people every day."+ app.session_state["video_terms"] = "robot, office"+ yield app, values, quote, submit+ assert not app.exception+ submit.assert_not_called()+++ "error",+ [+ loomloom.LoomLoomAPIError("timeout", retryable=True),+ loomloom.LoomLoomAPIError("unauthorized", status_code=401),+ loomloom.LoomLoomAPIError("rate limited", status_code=429, retryable=True),+ ValueError("invalid quote"),+ ValueError(""),+ ],+)+def test_failed_quote_pauses_until_manual_retry_and_recovers(quote_page, error):+ app, _, quote, _ = quote_page+ quote.side_effect = error+ app.run()+ assert quote.call_count == 1+ for _ in range(3):+ app.run()+ assert quote.call_count == 1+ assert app.session_state["loomloom_video_quote_error"]+ widget(app.button, "loomloom_retry_video_quote").click().run()+ assert quote.call_count == 2+ app.run()+ assert quote.call_count == 2+ quote.side_effect = None+ quote.return_value = loomloom.LoomLoomQuote("q", "v", "CNY", 1, 0, "0", ())+ widget(app.button, "loomloom_retry_video_quote").click().run()+ assert quote.call_count == 3+ assert not app.session_state["loomloom_video_quote_error"]+ assert not app.session_state["loomloom_video_confirm_charge"]+ request_id = app.session_state["loomloom_video_client_request_id"]+ app.run()+ assert quote.call_count == 3+ assert app.session_state["loomloom_video_client_request_id"] == request_id+ assert not any(item.key == "loomloom_retry_video_quote" for item in app.button)+++ "field", ["subject", "terms", "model", "ratio", "count", "key", "endpoint"]+)+def test_changed_billable_inputs_allow_one_new_quote_attempt(quote_page, field):+ app, values, quote, _ = quote_page+ quote.side_effect = loomloom.LoomLoomAPIError("offline", retryable=True)+ app.run()+ signature = app.session_state["loomloom_video_quote_error_signature"]+ if field == "subject":+ widget(app.text_area, "video_subject").set_value("New topic")+ elif field == "terms":+ widget(app.text_area, "video_terms").set_value("new scene")+ elif field == "model":+ widget(app.selectbox, "loomloom_video_model_select_en").select("b")+ elif field == "ratio":+ widget(app.selectbox, "video_aspect_for_loomloom_en").select("9:16")+ elif field == "count":+ widget(app.number_input, "loomloom_video_scene_count").set_value(2)+ elif field == "key":+ values["loomloom_api_token"] = "second-key"+ else:+ values["loomloom_base_url"] = "https://second.test/v1"+ app.run()+ assert quote.call_count == 2+ assert app.session_state["loomloom_video_quote_error_signature"] != signature+ app.run()+ assert quote.call_count == 2+++def test_missing_key_clears_error_and_never_retries(quote_page):+ app, values, quote, _ = quote_page+ quote.side_effect = loomloom.LoomLoomAPIError("offline")+ app.run()+ values["loomloom_api_token"] = ""+ app.run()+ app.run()+ assert quote.call_count == 1+ assert not app.session_state["loomloom_video_quote_error"]+ assert not any(item.key == "loomloom_retry_video_quote" for item in app.button)++[email protected]("change", ["script", "source"])+def test_unrelated_edits_do_not_retry_failed_quote(quote_page, change):+ """文案正文不改变已有主题/关键词报价;切到其它来源也不能触发胜算云请求。"""+ app, _, quote, _ = quote_page+ quote.side_effect = loomloom.LoomLoomAPIError("offline")+ app.run()+ if change == "script":+ widget(app.text_area, "video_script").set_value("A different narration.").run()+ else:+ # 来源使用自定义分组控件,AppTest 无 selectbox 适配器;模拟其回传状态。+ app.session_state["video_source_select_en"] = "pexels"+ app.run()+ app.run()+ assert not any(item.key == "loomloom_retry_video_quote" for item in app.button)+ app.session_state["video_source_select_en"] = "loomloom"+ app.run()+ assert quote.call_count == 1+++def test_incomplete_input_clears_failed_quote_without_network(quote_page):+ app, _, quote, _ = quote_page+ quote.side_effect = loomloom.LoomLoomAPIError("offline")+ app.run()+ widget(app.text_area, "video_subject").set_value("")+ widget(app.text_area, "video_script").set_value("")+ widget(app.text_area, "video_terms").set_value("")+ app.run()+ assert quote.call_count == 1+ assert not app.session_state["loomloom_video_quote_error"]+ assert not any(item.key == "loomloom_retry_video_quote" for item in app.button)+++def test_new_quote_failure_disables_old_confirmation(quote_page):+ app, _, quote, _ = quote_page+ quote.return_value = loomloom.LoomLoomQuote("q", "v", "CNY", 1, 1, "0.1", ())+ app.run()+ widget(app.checkbox, "loomloom_video_confirm_charge").check().run()+ old_id = app.session_state["loomloom_video_client_request_id"]+ quote.side_effect = loomloom.LoomLoomAPIError("offline")+ widget(app.selectbox, "loomloom_video_model_select_en").select("b").run()+ assert not app.session_state["loomloom_video_confirm_charge"]+ assert widget(app.checkbox, "loomloom_video_confirm_charge").disabled+ widget(app.button, "generate_video_button").click().run()+ assert quote.call_count == 2+ quote.side_effect = None+ widget(app.button, "loomloom_retry_video_quote").click().run()+ assert app.session_state["loomloom_video_client_request_id"] != old_id+ assert not widget(app.checkbox, "loomloom_video_confirm_charge").value+++ "script",+ [+ "AI helps us.",+ "人工智能帮助人们改善生活。" * 40,+ " " + "AI improves daily life. " * 50 + "\n",+ ],+)+def test_batch_candidate_autofill_once_preserves_manual_count(script):+ values = dict(+ config.app,+ video_source="loomloom",+ script_generation_backend="loomloom",+ loomloom_api_token="",+ llm_provider="openai",+ )+ candidate = SimpleNamespace(+ row_index=0, script=script, video_terms=("robot", "home")+ )+ with (+ patch.object(config, "app", values),+ patch.object(config, "ui", {"video_clip_duration": 3}),+ patch.object(config, "try_save_config", return_value=True),+ ):+ app = AppTest.from_file(str(MAIN), default_timeout=30)+ app.session_state["ui_language"] = "en"+ app.session_state["loomloom_script_candidates"] = (candidate,)+ app.run()+ widget(app.button, "loomloom_apply_candidate").click().run()+ assert not app.exception+ expected = 1 if script == "AI helps us." else loomloom.MAX_VIDEO_SCENES+ assert widget(app.number_input, "loomloom_video_scene_count").value == expected+ assert app.session_state["loomloom_video_scene_autofill_digest"] == ""+ widget(app.number_input, "loomloom_video_scene_count").set_value(3).run()+ app.run()+ assert widget(app.number_input, "loomloom_video_scene_count").value == 3+++def test_reference_price_copy_does_not_promise_quote_is_final():+ for locale in ("zh", "en"):+ messages = json.loads((MAIN.parent / "i18n" / f"{locale}.json").read_text())+ # 价格仅作选择参考,避免与“不完整估算仍可能扣费”的警告矛盾。+ text = messages["Translation"]["AI Video Model Reference Price"]+ assert ("实际模型调用" if locale == "zh" else "actual model usage") in textdiff --git a/webui/Main.py b/webui/Main.pyindex 684d98e2..a827d033 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -132,6 +132,43 @@ UPLOAD_POST_MANAGE_USERS_URL = "https://app.upload-post.com/manage-users"# 后端在 video_codec 未配置时继续采用稳定的 libx264;单独保留该哨兵可以区分# “跟随项目默认策略”和“用户明确固定 libx264”,便于未来安全调整默认策略。DEFAULT_VIDEO_CODEC_OPTION = "__default__"+# LoomLoom 的能力接口只返回模型 ID 和展示名,不提供价格。这里仅维护用户确认过+# 的参考价,用于帮助选择模型;最终费用按实际模型调用结算。别名同时覆盖+# 当前展示名和常见模型 ID,未收录的新模型会自然返回空价格,不影响选择或报价。+LOOMLOOM_VIDEO_MODEL_PRICES = (+ (("veo31fast", "googleveo31fastpreview"), "¥0.700/秒", "¥0.700/秒"),+ (+ (+ "通义万相22图生视频fastlora",+ "通义万相22文生视频fastlora",+ "tongyiwanxiang22i2vfastlora",+ "tongyiwanxiang22t2vfastlora",+ "wanx22i2vfastlora",+ "wanx22t2vfastlora",+ ),+ "¥0.350–0.770/条",+ "¥0.350/条(480P);¥0.770/条(720P)",+ ),+ (("即梦30文生视频720p", "jimeng30t2v720p"), "¥0.230/秒", "¥0.230/秒"),+ (("即梦30pro视频", "jimeng30pro视频", "jimeng30provideo"), "¥1.000/秒", "¥1.000/秒"),+ (("veo3", "googleveo3"), "¥1.400/秒", "¥1.400/秒"),+ (("veo31", "googleveo31"), "¥1.400/秒", "¥1.400/秒"),+ (+ ("klingv2", "可灵v2"),+ "¥10.00–20.00/条",+ "¥10.00/条(5 秒);¥20.00/条(10 秒)",+ ),+ (+ ("klingv21master", "可灵v21master"),+ "¥10.00–20.00/条",+ "¥10.00/条(5 秒);¥20.00/条(10 秒)",+ ),+ (+ ("viduq3pro",),+ "¥0.440–1.000/秒",+ "¥0.440/秒(540P);¥0.940/秒(720P);¥1.000/秒(1080P)",+ ),+)DEFAULT_SUBTITLE_SETTINGS = {"subtitle_enabled": True,"font_name": "MicrosoftYaHeiBold.ttc",@@ -649,6 +686,16 @@ def _initialize_session_state():"loomloom_video_input_signature": "","loomloom_video_client_request_id": "","loomloom_video_confirm_charge": False,+ "loomloom_video_quote_error_signature": "",+ "loomloom_video_quote_error": "",+ "loomloom_video_capability": None,+ "loomloom_video_capability_fingerprint": "",+ "loomloom_video_capability_load_attempt": "",+ "loomloom_video_capability_error": "",+ "loomloom_video_model_id": "",+ # 文案或完整配音刚生成时,在视频数量控件创建前消费这个摘要并自动+ # 填入推荐素材数;消费后即清空,避免覆盖用户后续手动调整。+ "loomloom_video_scene_autofill_digest": "","wavespeed_confirm_charge": False,"volcengine_seedance_confirm_charge": False,"ofox_confirm_charge": False,@@ -3807,6 +3854,24 @@ def _effective_script_generation_backend():return backend if backend in {"local", "loomloom"} else "local"+++def _script_generation_method_help(selected_backend):+ """让“文案生成方式”的问号内容严格跟随当前选择。"""+ if selected_backend != "loomloom":+ return tr("Script Generation Method Help")++ app_config_snapshot = config.snapshot_config_with_pending(config.app)+ guidance = [tr("LoomLoom Batch Script Generation Help")]+ if (+ str(app_config_snapshot.get("llm_provider", "") or "").strip().lower()+ == "shengsuanyun"+ ):+ guidance.append(tr("Shengsuan Cloud API Key Reused"))+ guidance.append(tr("Shengsuan Cloud API Key Link"))+ return "\n\n".join(guidance)++def _loomloom_video_scene_prompts(video_terms, subject, scene_count):"""按素材关键词生成有限数量的场景描述,供视频模型逐段生成素材。"""if isinstance(video_terms, str):@@ -3846,33 +3911,221 @@ def _loomloom_video_signature(batch, credential_fingerprint):return hashlib.sha256(serialized.encode("utf-8")).hexdigest()+def _loomloom_video_account_signature(token):+ """服务地址和凭据共同隔离模型目录及报价,不能跨端点复用已确认状态。"""+ values = config.snapshot_config_with_pending(config.app)+ base_url = str(values.get("loomloom_base_url") or loomloom.DEFAULT_BASE_URL).strip().rstrip("/")+ payload = json.dumps([base_url, str(token or "").strip()])+ return hashlib.sha256(payload.encode("utf-8")).hexdigest()+++def _load_loomloom_video_capability(token, *, force=False):+ """按当前凭证缓存 Profile;刷新失败时保留同一凭证最近的成功结果。"""+ normalized_token = str(token or "").strip()+ if not normalized_token:+ return None++ fingerprint = _loomloom_video_account_signature(normalized_token)+ if st.session_state.get("loomloom_video_capability_fingerprint") != fingerprint:+ st.session_state["loomloom_video_capability"] = None+ st.session_state["loomloom_video_capability_fingerprint"] = fingerprint+ st.session_state["loomloom_video_capability_load_attempt"] = ""+ st.session_state["loomloom_video_capability_error"] = ""++ should_load = force or (+ st.session_state.get("loomloom_video_capability_load_attempt") != fingerprint+ )+ if should_load:+ st.session_state["loomloom_video_capability_load_attempt"] = fingerprint+ try:+ capability = _create_loomloom_video_backend().resolve_video_capability()+ except (loomloom.LoomLoomError, ValueError) as exc:+ logger.warning(+ f"failed to load LoomLoom video capability: error={type(exc).__name__}"+ )+ st.session_state["loomloom_video_capability_error"] = str(exc)+ else:+ st.session_state["loomloom_video_capability"] = capability+ st.session_state["loomloom_video_capability_error"] = ""++ capability = st.session_state.get("loomloom_video_capability")+ return (+ capability if isinstance(capability, loomloom.LoomLoomVideoCapability) else None+ )+++def _normalize_loomloom_model_identifier(value):+ """统一展示名和模型 ID 的分隔符、大小写,供本地价格表安全匹配。"""+ return re.sub(r"[^a-z0-9\u4e00-\u9fff]+", "", str(value or "").lower())+++def _loomloom_video_model_price(model):+ """返回已知模型的(下拉框短价、选中后完整参考价);未知模型返回空值。"""+ identifiers = {+ _normalize_loomloom_model_identifier(model.model_id),+ _normalize_loomloom_model_identifier(model.display_name),+ }+ for aliases, compact_price, detailed_price in LOOMLOOM_VIDEO_MODEL_PRICES:+ if identifiers.intersection(aliases):+ return compact_price, detailed_price+ return "", ""+++def _format_loomloom_video_model_option(model):+ """在模型名右侧展示短价格,避免多档分辨率价格把下拉框撑得过宽。"""+ compact_price, _ = _loomloom_video_model_price(model)+ return f"{model.display_name} · {compact_price}" if compact_price else model.display_name+++def _effective_voice_rate_before_audio_panel():+ """视频面板位于音频面板之前,需从现有控件状态或配置读取当前语速。"""+ raw_rate = st.session_state.get(+ localized_widget_key("voice_rate_select"),+ config.ui.get("voice_rate", 1.0),+ )+ try:+ rate = float(raw_rate)+ except (TypeError, ValueError, OverflowError):+ return 1.0+ return rate if math.isfinite(rate) and rate > 0 else 1.0+++def _matching_full_voice_preview_duration(script, voice_rate):+ """仅在文案、Provider、音色和语速均未变化时采用完整试听的真实时长。"""+ cached = st.session_state.get("voice_preview_audio")+ if not isinstance(cached, dict) or cached.get("preview_type") != "full":+ return None+ script_digest = hashlib.sha256(str(script or "").encode("utf-8")).hexdigest()+ if cached.get("content_digest") != script_digest:+ return None++ current_tts_server = st.session_state.get(+ localized_widget_key("tts_server_select"),+ config.ui.get("tts_server", "azure-tts-v1"),+ )+ current_voice_name = st.session_state.get(+ localized_widget_key(f"speech_synthesis_select_{current_tts_server}"),+ config.ui.get("voice_name", ""),+ )+ try:+ cached_voice_rate = float(cached.get("voice_rate", 0))+ except (TypeError, ValueError, OverflowError):+ return None+ if (+ cached.get("tts_server") != current_tts_server+ or cached.get("voice_name") != current_voice_name+ or not math.isfinite(cached_voice_rate)+ or not math.isclose(cached_voice_rate, voice_rate)+ ):+ return None++ duration = cached.get("duration")+ if (+ not isinstance(duration, (int, float))+ or not math.isfinite(duration)+ or duration <= 0+ ):+ return None+ return float(duration)+++def _loomloom_video_coverage_plan(params):+ """按真实或估算旁白时长推荐素材数;不足部分仍由原有循环逻辑补齐。"""+ script = str(params.video_script or "").strip()+ if not script:+ return None++ voice_rate = _effective_voice_rate_before_audio_panel()+ actual_duration = _matching_full_voice_preview_duration(script, voice_rate)+ if actual_duration is not None:+ duration_min = duration_max = actual_duration+ basis_key = "AI Video Duration Basis Actual"+ else:+ estimated = _estimate_voiceover_duration_range(script, voice_rate)+ if not estimated:+ return None+ duration_min, duration_max = estimated+ basis_key = "AI Video Duration Basis Estimated"++ clip_duration = max(float(params.video_clip_duration or 1), 1.0)+ needed_min = max(math.ceil(duration_min / clip_duration), 1)+ needed_max = max(math.ceil(duration_max / clip_duration), needed_min)+ return {+ "script_digest": hashlib.sha256(script.encode("utf-8")).hexdigest(),+ "basis_key": basis_key,+ "duration_min": float(duration_min),+ "duration_max": float(duration_max),+ "clip_duration": clip_duration,+ "needed_min": needed_min,+ "needed_max": needed_max,+ # 推荐值优先覆盖保守上界,但绝不突破服务端允许的付费任务上限。+ "recommended_count": min(needed_max, loomloom.MAX_VIDEO_SCENES),+ }+++def _format_numeric_range(minimum, maximum, digits=1):+ if math.isclose(float(minimum), float(maximum)):+ return f"{float(maximum):.{digits}f}"+ return f"{float(minimum):.{digits}f}–{float(maximum):.{digits}f}"+++def _selected_loomloom_video_model(capability):+ """返回仍在当前 Profile 候选中的用户选择,不做静默回退。"""+ selected_model_id = str(+ st.session_state.get("loomloom_video_model_id", "") or ""+ ).strip()+ eligible_model_ids = {model.model_id for model in capability.models}+ return selected_model_id if selected_model_id in eligible_model_ids else ""++def _current_loomloom_video_quote_context(params):"""根据当前页面参数构建默认 SkillBot 的视频报价批次。"""token = _effective_loomloom_api_token()+ fingerprint = _loomloom_video_account_signature(token) if token else ""+ capability = st.session_state.get("loomloom_video_capability")+ if (+ not isinstance(capability, loomloom.LoomLoomVideoCapability)+ or st.session_state.get("loomloom_video_capability_fingerprint") != fingerprint+ ):+ return None, ""+ model_id = _selected_loomloom_video_model(capability)scene_count = int(st.session_state.get("loomloom_video_scene_count", 1) or 1)prompts = _loomloom_video_scene_prompts(params.video_terms,params.video_subject or params.video_script,scene_count,)- if not token or not prompts:+ aspect_ratio = str(+ params.video_aspect.value+ if isinstance(params.video_aspect, VideoAspect)+ else params.video_aspect+ )+ if (+ not token+ or not model_id+ or not prompts+ or aspect_ratio not in capability.aspect_ratios+ ):return None, ""try:batch = _create_loomloom_video_backend().prepare_video_batch(subject=params.video_subject or params.video_script,scene_prompts=prompts,- aspect_ratio=str(- params.video_aspect.value- if isinstance(params.video_aspect, VideoAspect)- else params.video_aspect- ),+ model_id=model_id,+ aspect_ratio=aspect_ratio,)except (loomloom.LoomLoomError, ValueError):return None, ""- fingerprint = hashlib.sha256(token.encode("utf-8")).hexdigest()return batch, _loomloom_video_signature(batch, fingerprint)+def _retry_loomloom_video_quote():+ """用户主动重试时解除失败锁;不沿用之前的付费确认。"""+ st.session_state["loomloom_video_quote_error_signature"] = ""+ st.session_state["loomloom_video_quote_error"] = ""+ st.session_state["loomloom_video_confirm_charge"] = False++def _render_loomloom_video_settings(params):"""渲染默认视频 SkillBot 的报价、报价失效和付费确认流程。"""st.caption(tr("Shengsuan Cloud AI Video Help"))@@ -3887,6 +4140,80 @@ def _render_loomloom_video_settings(params):token = _effective_loomloom_api_token()+ refresh_models = st.button(+ tr("Refresh AI Video Models"),+ key="loomloom_refresh_video_models",+ use_container_width=True,+ disabled=not token,+ )+ capability = _load_loomloom_video_capability(token, force=refresh_models)+ capability_error = str(+ st.session_state.get("loomloom_video_capability_error", "") or ""+ ).strip()+ if capability_error:+ st.warning(tr("AI Video Model List Load Failed").format(error=capability_error))++ if capability is not None:+ models_by_id = {model.model_id: model for model in capability.models}+ selected_model_id = str(+ st.session_state.get("loomloom_video_model_id", "") or ""+ ).strip()+ if not selected_model_id:+ selected_model_id = capability.default_model_id+ st.session_state["loomloom_video_model_id"] = selected_model_id++ model_options = list(models_by_id)+ if selected_model_id not in models_by_id:+ # 保留已失效的原选择,让用户明确看到状态并主动重选。直接把控件+ # 改成新的默认模型会让旧报价与用户认知不一致。+ model_options.insert(0, selected_model_id)++ selected_model_id = stable_selectbox(+ tr("AI Video Model"),+ options=model_options,+ default_value=selected_model_id,+ key="loomloom_video_model_select",+ format_func=lambda model_id: (+ _format_loomloom_video_model_option(models_by_id[model_id])+ if model_id in models_by_id+ else tr("Unavailable AI Video Model").format(model=model_id)+ ),+ )+ st.session_state["loomloom_video_model_id"] = selected_model_id+ if selected_model_id not in models_by_id:+ st.error(tr("Selected AI Video Model Unavailable"))+ else:+ _, detailed_price = _loomloom_video_model_price(+ models_by_id[selected_model_id]+ )+ if detailed_price:+ st.caption(+ tr("AI Video Model Reference Price").format(price=detailed_price)+ )++ current_aspect_ratio = str(+ params.video_aspect.value+ if isinstance(params.video_aspect, VideoAspect)+ else params.video_aspect+ )+ if current_aspect_ratio not in capability.aspect_ratios:+ st.error(tr("Selected AI Video Ratio Unavailable"))++ coverage_plan = _loomloom_video_coverage_plan(params)+ pending_autofill_digest = str(+ st.session_state.get("loomloom_video_scene_autofill_digest", "") or ""+ )+ if (+ coverage_plan is not None+ and pending_autofill_digest == coverage_plan["script_digest"]+ ):+ # 只在“刚生成文案”或“刚取得完整试听真实时长”时推荐一次。+ # 消费标记后不再覆盖,用户随后手动调整段数会被完整保留。+ st.session_state["loomloom_video_scene_count"] = coverage_plan[+ "recommended_count"+ ]+ st.session_state["loomloom_video_scene_autofill_digest"] = ""+scene_count = st.number_input(tr("AI Video Scene Count"),min_value=1,@@ -3895,23 +4222,62 @@ def _render_loomloom_video_settings(params):key="loomloom_video_scene_count",)_set_runtime_config("ui", "loomloom_video_scene_count", int(scene_count))+ if coverage_plan is not None:+ coverage_seconds = int(scene_count) * coverage_plan["clip_duration"]+ shortfall_min = max(+ coverage_plan["duration_min"] - coverage_seconds, 0.0+ )+ shortfall_max = max(+ coverage_plan["duration_max"] - coverage_seconds, 0.0+ )+ duration_basis = tr(coverage_plan["basis_key"]).format(+ duration=_format_numeric_range(+ coverage_plan["duration_min"], coverage_plan["duration_max"]+ )+ )+ coverage_message = tr("AI Video Material Coverage").format(+ basis=duration_basis,+ clip=_format_numeric_range(+ coverage_plan["clip_duration"], coverage_plan["clip_duration"]+ ),+ needed=_format_numeric_range(+ coverage_plan["needed_min"], coverage_plan["needed_max"], digits=0+ ),+ count=int(scene_count),+ coverage=_format_numeric_range(coverage_seconds, coverage_seconds),+ shortfall=_format_numeric_range(shortfall_min, shortfall_max),+ )+ if shortfall_max > 0:+ st.warning(coverage_message)+ else:+ st.caption(coverage_message)+batch, input_signature = _current_loomloom_video_quote_context(params)if not token:st.warning(tr("Shengsuan Cloud API Key Required"))- if st.button(- tr("Get LoomLoom Quote"),- key="loomloom_quote_videos",- use_container_width=True,- type="secondary",- icon=":material/request_quote:",- disabled=not token or batch is None,- ):+ quote_result = st.session_state.get("loomloom_video_quote")+ quoted_batch = st.session_state.get("loomloom_video_batch")+ quote_is_current = bool(+ quote_result is not None+ and quoted_batch is not None+ and st.session_state.get("loomloom_video_input_signature") == input_signature+ )+ # 同一组参数失败后暂停自动请求,避免普通页面交互反复等待服务超时。+ # 签名包含账号、端点与全部计费输入;参数变化或用户主动重试后再询价。+ if st.session_state.get("loomloom_video_quote_error_signature") != input_signature:+ st.session_state["loomloom_video_quote_error_signature"] = ""+ st.session_state["loomloom_video_quote_error"] = ""+ quote_failed = bool(st.session_state.get("loomloom_video_quote_error"))+ # Quote 不创建付费任务,真正执行仍需用户明确勾选确认。+ if token and batch is not None and not quote_is_current and not quote_failed:+ st.session_state["loomloom_video_confirm_charge"] = Falsetry:quote_result = _create_loomloom_video_backend().quote(batch)except (loomloom.LoomLoomError, ValueError) as exc:logger.warning(f"failed to quote LoomLoom videos: error={exc}")- st.error(str(exc))+ st.session_state["loomloom_video_quote_error_signature"] = input_signature+ st.session_state["loomloom_video_quote_error"] = str(exc) or type(exc).__name__else:st.session_state["loomloom_video_batch"] = batchst.session_state["loomloom_video_quote"] = quote_result@@ -3926,6 +4292,14 @@ def _render_loomloom_video_settings(params):f"estimated_payable_t={quote_result.estimated_buyer_payable_t}")+ if st.session_state.get("loomloom_video_quote_error"):+ st.error(st.session_state["loomloom_video_quote_error"])+ st.button(+ tr("Retry AI Video Quote"),+ key="loomloom_retry_video_quote",+ on_click=_retry_loomloom_video_quote,+ )+quote_result = st.session_state.get("loomloom_video_quote")quoted_batch = st.session_state.get("loomloom_video_batch")if quote_result is not None and quoted_batch is not None:@@ -3933,17 +4307,20 @@ def _render_loomloom_video_settings(params):quote_result.estimated_buyer_payable_amountor f"{quote_result.estimated_buyer_payable_t} T")- st.success(- tr(- "AI Video Quote Summary Singular"- if quote_result.task_count == 1- else "AI Video Quote Summary"- ).format(- tasks=quote_result.task_count,- amount=display_amount,- currency=quote_result.currency,+ if quote_result.estimated_buyer_payable_t == 0:+ st.warning(tr("AI Video Quote Estimate Incomplete"))+ else:+ st.success(+ tr(+ "AI Video Quote Summary Singular"+ if quote_result.task_count == 1+ else "AI Video Quote Summary"+ ).format(+ tasks=quote_result.task_count,+ amount=display_amount,+ currency=quote_result.currency,+ ))- )quote_is_current = (st.session_state.get("loomloom_video_input_signature") == input_signature)@@ -4027,6 +4404,9 @@ def _render_local_script_generation(params):else:st.session_state["video_script"] = scriptst.session_state["video_terms"] = ", ".join(terms)+ st.session_state["loomloom_video_scene_autofill_digest"] = (+ hashlib.sha256(script.strip().encode("utf-8")).hexdigest()+ )def _render_loomloom_candidates():@@ -4063,6 +4443,10 @@ def _render_loomloom_candidates():):st.session_state["video_script"] = selected.scriptst.session_state["video_terms"] = ", ".join(selected.video_terms)+ # 与普通大模型生成文案保持一致:应用新候选后仅推荐一次素材数量。+ st.session_state["loomloom_video_scene_autofill_digest"] = (+ hashlib.sha256(selected.script.strip().encode("utf-8")).hexdigest()+ )st.toast(tr("LoomLoom Candidate Applied"))@@ -4394,13 +4778,20 @@ def _render_script_settings(panel, params):"local": tr("Local LLM Script Generation"),"loomloom": tr("Shengsuan Cloud Batch Script Generation"),}+ script_backend_widget_key = localized_widget_key(+ "script_generation_backend_select"+ )+ current_script_backend = st.session_state.get(+ script_backend_widget_key,+ _effective_script_generation_backend(),+ )script_generation_backend = stable_selectbox(tr("Script Generation Method"),options=script_backend_options,default_value=_effective_script_generation_backend(),key="script_generation_backend_select",format_func=lambda value: script_backend_labels[value],- help=tr("Script Generation Method Help"),+ help=_script_generation_method_help(current_script_backend),)_set_runtime_config("app", "script_generation_backend", script_generation_backend@@ -4468,6 +4859,7 @@ def _render_script_settings(panel, params):))+ # 模型发现只增强视频素材,不改变用户明确选择的文案 Provider。if _effective_script_generation_backend() == "loomloom":_render_loomloom_script_generation(params)else:@@ -4478,10 +4870,7 @@ def _render_script_settings(panel, params):height=180,key="video_script",)- using_loomloom_scripts = (- _effective_script_generation_backend() == "loomloom"- )- if using_loomloom_scripts:+ if _effective_script_generation_backend() == "loomloom":st.caption(tr("LoomLoom Video Terms Reuse Help"))elif st.button(tr("Generate Video Keywords"),@@ -4559,6 +4948,14 @@ def _render_video_settings(panel, params):)_set_runtime_config("app", "video_source", params.video_source)+ loomloom_video_capability = None+ if params.video_source == "loomloom":+ # 尽早读取缓存,使下方画面比例控件直接受当前 Profile 约束。+ # 首次输入 Key 后 Streamlit 会 rerun,此处随即加载一次。+ loomloom_video_capability = _load_loomloom_video_capability(+ _effective_loomloom_api_token()+ )+if params.video_source == "wavespeed":st.caption(tr("WaveSpeed AI Video Help"))if params.video_source == "volcengine_seedance":@@ -4654,6 +5051,12 @@ def _render_video_settings(panel, params):(tr("Portrait"), VideoAspect.portrait.value),(tr("Landscape"), VideoAspect.landscape.value),]+ if loomloom_video_capability is not None:+ ratio_labels = {value: label for label, value in video_aspect_ratios}+ video_aspect_ratios = [+ (ratio_labels[value], value)+ for value in loomloom_video_capability.aspect_ratios+ ]# Coverr 库 99% 是 16:9 横屏,默认竖屏会让画面被大量黑边包围。# 用 source-specific widget key 让每个 source 各自记忆 aspect 选择:# - 首次切到 coverr → 默认 Landscape(index=1)@@ -5147,6 +5550,12 @@ def _synthesize_voice_preview("duration": duration,"preview_type": preview_type,"sub_maker": sub_maker,+ # 让位于音频面板之前的视频面板只采用与当前设置完全匹配的+ # 完整试听时长;短试听或旧文案绝不能改变推荐素材数。+ "content_digest": hashlib.sha256(content.encode("utf-8")).hexdigest(),+ "tts_server": selected_tts_server,+ "voice_name": voice_name,+ "voice_rate": float(voice_rate),}finally:# 浏览器播放器使用内存字节,文件读取完即可清理,避免频繁试听积累临时文件。@@ -5260,6 +5669,19 @@ def _render_voice_preview(params, friendly_names, selected_tts_server, voice_namelif preview_result:preview_result["fingerprint"] = requested_fingerprintst.session_state["voice_preview_audio"] = preview_result+ if (+ preview_type == "full"+ and params.video_source == "loomloom"+ and isinstance(preview_result.get("duration"), (int, float))+ and math.isfinite(preview_result["duration"])+ and preview_result["duration"] > 0+ ):+ # 视频设置先于音频设置渲染。完整试听成功后触发一次 rerun,+ # 让上方素材数立刻按真实旁白时长重新推荐并刷新覆盖提示。+ st.session_state["loomloom_video_scene_autofill_digest"] = (+ preview_result["content_digest"]+ )+ st.rerun()else:st.error(tr("Voice Preview No Audio"))diff --git a/webui/i18n/en.json b/webui/i18n/en.jsonindex 11d25d29..f0815a80 100644--- a/webui/i18n/en.json+++ b/webui/i18n/en.json@@ -28,11 +28,12 @@"LoomLoom Batch Script Generation Help": "LoomLoom generates multiple independent script candidates. Get a quote first; execution and billing start only after confirmation.","Shengsuan Cloud API Key": "Shengsuan Cloud API Key","Shengsuan Cloud API Key Help": "Create an API Key in the [Shengsuan Cloud console](https://console.shengsuanyun.com/user/keys). The key is saved to config.toml, and usage is billed to your account.",+ "Shengsuan Cloud API Key Link": "[Get an API Key from the Shengsuan Cloud console](https://console.shengsuanyun.com/user/keys)","Shengsuan Cloud API Key Placeholder": "Enter an API Key","Shengsuan Cloud API Key Required": "Configure your Shengsuan Cloud API Key in Settings before using Shengsuan Cloud script or AI video generation.","Shengsuan Cloud API Key Reused": "The Shengsuan Cloud API Key from Settings is reused here; no duplicate entry is needed.","Script Generation Method": "Script Generation Method",- "Script Generation Method Help": "Local LLM uses the Provider configured in Settings. Shengsuan Cloud generates several paid candidates after you review and confirm a quote.",+ "Script Generation Method Help": "Generate the script with the current LLM Provider configured in Settings.","Local LLM Script Generation": "Current LLM Provider","Shengsuan Cloud Batch Script Generation": "Shengsuan Cloud Batch (Paid)","Script Candidate Count": "Script Candidates",@@ -251,6 +252,9 @@"Voiceover Script Required": "Add a video script to estimate and preview the full voiceover.","Full Voiceover Preview Cost Hint": "A full preview calls the selected TTS service and may use API credits.","Actual Voiceover Duration": "Actual voiceover duration: {duration} sec",+ "AI Video Duration Basis Actual": "Actual voiceover: {duration} sec",+ "AI Video Duration Basis Estimated": "Estimated voiceover: {duration} sec",+ "AI Video Material Coverage": "{basis}. At {clip} sec per clip, about {needed} clips are recommended. The current {count} clip(s) cover approximately {coverage} sec, with a possible shortfall of {shortfall} sec. Actual coverage depends on the generated footage and editing settings; existing clips are looped if needed, without additional generation charges.","Voice Preview Failed": "Voice preview failed: {error}","Voice Preview No Audio": "The TTS service did not return preview audio. Check its settings and the application logs.","Voice Preview Busy": "A video task is currently using the voice settings. Try again shortly.",@@ -456,12 +460,21 @@"llm_provider_tips.pollinations": "##### Pollinations AI Configuration\n- **API Key**: create one on [Pollinations]({api_key_url})\n- **Base Url**: defaults to `{default_base_url}`\n- **Model Name**: defaults to `{default_model}`; you can also enter another model ID from the [model catalog](https://gen.pollinations.ai/v1/models) that supports Chat Completions","LoomLoom Video Terms Reuse Help": "LoomLoom script candidates already include video terms. Select a candidate or edit the terms below; no separate local LLM call is needed.","Shengsuan Cloud AI Video": "Shengsuan Cloud AI Video",- "Shengsuan Cloud AI Video Help": "Generate 1–5 paid AI video clips through the default LoomLoom SkillBot. Review and confirm the quote before using the existing narration, subtitle, and editing pipeline.",+ "Shengsuan Cloud AI Video Help": "Generate 1–5 paid AI video clips through the current LoomLoom video Listing. Models are loaded from the authenticated capability profile. Review and confirm the quote before using the existing narration, subtitle, and editing pipeline.",+ "AI Video Model": "Video Model",+ "AI Video Model Reference Price": "Reference price: {price}, for guidance only. Final charges are based on actual model usage.",+ "Retry AI Video Quote": "Retry Quote",+ "Refresh AI Video Models": "Refresh Model List",+ "AI Video Model List Load Failed": "Could not load the video model list: {error}",+ "Unavailable AI Video Model": "Unavailable: {model}",+ "Selected AI Video Model Unavailable": "The selected model is no longer available. Refresh the model list, choose another model, and get a new quote.",+ "Selected AI Video Ratio Unavailable": "The selected aspect ratio is not supported by the current video capability profile.","AI Video Scene Count": "AI Video Scene Count","AI Video Quote Summary": "{tasks} AI video clips; estimated charge: {amount} {currency}","AI Video Quote Summary Singular": "1 AI video clip; estimated charge: {amount} {currency}",+ "AI Video Quote Estimate Incomplete": "A complete cost estimate is not currently available. Charges may still apply; final billing is based on actual model usage.","Confirm AI Video Charge": "I understand that AI video generation is a paid service",- "Confirm AI Video Charge Help": "Execution uses the SkillBot version returned by this quote and a stable idempotency key. The charge follows the LoomLoom quote shown above.",+ "Confirm AI Video Charge Help": "Execution uses the Listing version returned by this quote and a stable idempotency key. The final charge is based on actual model usage and may be nonzero even when the estimate is incomplete.","AI Video Quote Required": "Get a current Shengsuan Cloud AI video quote before generating the video.","Confirm AI Video Charge Required": "Confirm the Shengsuan Cloud AI video charge before generating the video.","AI Video Quote Retained For Retry": "Generation failed, but the confirmed quote was retained. You can retry safely with the same request or request a new quote.",diff --git a/webui/i18n/zh.json b/webui/i18n/zh.jsonindex 1f4c1440..d86b7b17 100644--- a/webui/i18n/zh.json+++ b/webui/i18n/zh.json@@ -28,11 +28,12 @@"LoomLoom Batch Script Generation Help": "LoomLoom 会批量生成多个独立文案候选。请先获取报价,确认费用后才会执行和扣费。","Shengsuan Cloud API Key": "胜算云 API Key","Shengsuan Cloud API Key Help": "请前往[胜算云控制台](https://console.shengsuanyun.com/user/keys)创建 API Key。密钥会保存到 config.toml,调用费用将从您的账户扣除。",+ "Shengsuan Cloud API Key Link": "[前往胜算云控制台获取 API Key](https://console.shengsuanyun.com/user/keys)","Shengsuan Cloud API Key Placeholder": "输入 API Key","Shengsuan Cloud API Key Required": "请先在“设置”中配置胜算云 API Key,再使用胜算云脚本或 AI 视频生成。","Shengsuan Cloud API Key Reused": "已复用“设置 → 大模型提供商”中的胜算云 API Key,无需重复填写。","Script Generation Method": "文案生成方式",- "Script Generation Method Help": "当前大模型使用“设置”中的 Provider;胜算云批量生成会在确认报价后付费生成多个候选。",+ "Script Generation Method Help": "使用“设置”中当前选择的大模型 Provider 生成文案。","Local LLM Script Generation": "当前大模型 Provider","Shengsuan Cloud Batch Script Generation": "胜算云批量生成(付费)","Script Candidate Count": "文案候选数量",@@ -251,6 +252,9 @@"Voiceover Script Required": "填写视频文案后,可估算并预览完整配音。","Full Voiceover Preview Cost Hint": "完整预览会调用当前配音服务,并可能消耗 API 额度。","Actual Voiceover Duration": "实际配音时长:{duration} 秒",+ "AI Video Duration Basis Actual": "实际旁白 {duration} 秒",+ "AI Video Duration Basis Estimated": "旁白预计 {duration} 秒",+ "AI Video Material Coverage": "{basis};按每段 {clip} 秒估算,建议约 {needed} 段。当前 {count} 段预计覆盖 {coverage} 秒,可能缺少 {shortfall} 秒。实际覆盖取决于生成素材和剪辑设置;时长不足会循环已有素材,不会自动追加付费生成。","Voice Preview Failed": "配音预览失败:{error}","Voice Preview No Audio": "配音服务未返回试听音频,请检查相关设置和应用日志。","Voice Preview Busy": "当前有视频任务正在使用配音配置,请稍后重试。",@@ -455,13 +459,22 @@"llm_provider_tips.minimax": "##### MiniMax 配置说明\n- **API Key**: 在 [中国站](https://platform.minimaxi.com/) 或 [国际站](https://platform.minimax.io/) 创建\n- **Base Url**: 中国站使用 `https://api.minimaxi.com/v1`;国际站使用 `{default_base_url}`(默认)\n- **Model Name**: 默认 `{default_model}`;也可以填写当前账号支持的其它模型 ID\n\n请确保 API Key 与 Base Url 来自同一平台,否则可能出现鉴权失败。","llm_provider_tips.pollinations": "##### Pollinations AI 配置说明\n- **API Key**: 在 [Pollinations]({api_key_url}) 创建\n- **Base Url**: 默认 `{default_base_url}`\n- **Model Name**: 默认 `{default_model}`;也可以填写 [模型目录](https://gen.pollinations.ai/v1/models) 中支持 Chat Completions 的其它模型 ID","LoomLoom Video Terms Reuse Help": "LoomLoom 文案候选已包含素材关键词。选择候选或在下方编辑关键词即可,不再调用本地大模型。",- "Shengsuan Cloud AI Video": "胜算云 AI 视频",- "Shengsuan Cloud AI Video Help": "通过默认 LoomLoom SkillBot 付费生成 1~5 段 AI 视频素材。请先获取报价并确认费用,再使用现有配音、字幕和剪辑流程合成成片。",+ "Shengsuan Cloud AI Video": "胜算云 AI 生成",+ "Shengsuan Cloud AI Video Help": "通过当前 LoomLoom 视频 Listing 付费生成 1~5 段 AI 视频素材。模型来自当前账号的能力 Profile。请先获取报价并确认费用,再使用现有配音、字幕和剪辑流程合成成片。",+ "AI Video Model": "视频模型",+ "AI Video Model Reference Price": "参考价:{price};仅供参考,最终费用按实际模型调用结算。",+ "Retry AI Video Quote": "重试报价",+ "Refresh AI Video Models": "刷新模型列表",+ "AI Video Model List Load Failed": "模型列表加载失败:{error}",+ "Unavailable AI Video Model": "已不可用:{model}",+ "Selected AI Video Model Unavailable": "所选模型已不可用。请刷新模型列表、重新选择并重新获取报价。",+ "Selected AI Video Ratio Unavailable": "当前视频能力 Profile 不支持所选画面比例。","AI Video Scene Count": "AI 视频素材段数","AI Video Quote Summary": "共 {tasks} 段 AI 视频素材,预计扣费:{amount} {currency}","AI Video Quote Summary Singular": "共 1 段 AI 视频素材,预计扣费:{amount} {currency}",+ "AI Video Quote Estimate Incomplete": "暂未获得完整费用估算,并非免费;最终按实际模型调用结算。","Confirm AI Video Charge": "我已了解 AI 视频生成为付费服务",- "Confirm AI Video Charge Help": "执行将严格使用当前报价返回的 SkillBot 版本和幂等请求 ID,费用以页面展示的 LoomLoom 报价为准。",+ "Confirm AI Video Charge Help": "执行将严格使用当前报价返回的 Listing 版本和幂等请求 ID。即使估算不完整也可能产生实际费用,最终按实际模型调用结算。","AI Video Quote Required": "请先获取与当前参数一致的胜算云 AI 视频报价。","Confirm AI Video Charge Required": "请确认胜算云 AI 视频生成费用后再生成视频。","AI Video Quote Retained For Retry": "生成失败,但本次报价和请求记录已保留。你可以安全重试同一请求,或重新获取报价。",