Skip to content

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

feat(video): add Shengsuan AI video generation

LewisZhou9377b24837d8
diff --git a/README.md b/README.md
index 08b2a2b8..947e4f19 100644
--- a/README.md
+++ b/README.md
@@ -57,7 +57,7 @@
<a href="https://www.ccsub.net/register?ref=VCVDAWWY"><strong>CCSub</strong></a>
</td>
<td align="left">
- 感谢 <a href="https://www.ccsub.net/register?ref=VCVDAWWY">CCSub</a> 赞助本项目!CCSub 是稳定、实惠的 AI API 中转平台,是 Claude Code 官方订阅的超强平替。一个 API Key 即可调用 Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini 等模型,价格约为官方直连的 1/3,全球直连无需梯子。兼容 Claude Code、Codex、Cursor、Cline、Continue、Windsurf 等所有主流 AI 编程工具。前往 <a href="https://www.ccsub.net/register?ref=VCVDAWWY">www.ccsub.net</a> 注册即送 $5 体验额度。
+ 感谢 <a href="https://www.ccsub.net/register?ref=VCVDAWWY">CCSub</a> 赞助本项目!<strong>CCSub 是稳定、实惠的 AI API 中转平台,是 Claude Code 官方订阅的超强平替。</strong>一个 API Key 即可调用 Claude Opus 4.8、Sonnet 4.6、Haiku 4.5、GPT-5、Gemini 等模型,价格约为官方直连的 1/3,全球直连无需梯子。兼容 Claude Code、Codex、Cursor、Cline、Continue、Windsurf 等所有主流 AI 编程工具。前往 <a href="https://www.ccsub.net/register?ref=VCVDAWWY">www.ccsub.net</a> 注册即送 $5 体验额度。
</td>
</tr>
<tr>
@@ -73,6 +73,17 @@
🎁 MoneyPrinterTurbo 用户专属福利:通过 <a href="https://infistar.ai/register?aff=6T4EYXP2&amp;ref_source=link">专属推广链接</a> 注册即享 [专属赠送额度 / 首充特惠],开箱即用!
</td>
</tr>
+ <tr>
+ <td align="center" width="120">
+ <a href="https://www.shengsuanyun.com/?from=CH_XUQ4OTSK"><img src="docs/sponsors/shengsuanyun-logo.jpg" alt="胜算云" height="56"></a><br>
+ <a href="https://www.shengsuanyun.com/?from=CH_XUQ4OTSK"><strong>胜算云</strong></a>
+ </td>
+ <td align="left">
+ 感谢<a href="https://www.shengsuanyun.com/?from=CH_XUQ4OTSK">胜算云</a>对本项目的赞助!胜算云是面向 AI 原生团队的模型 API 聚合平台,汇集 Claude、ChatGPT、Gemini 等海内外大语言模型及多媒体模型,支持统一接入与按量调用。<br>
+ 平台坚持合规 API 服务,杜绝逆向工程和资源稀释。此外平台提供企业级定制网关,包括团队成本与权限管理、智能路由、安全防护及 BYOK 密钥托管,并提供发票服务。<br>
+ 🎁新用户通过<a href="https://www.shengsuanyun.com/?from=CH_XUQ4OTSK">此链接</a>注册,即可领取 10 元 Token 体验额度。
+ </td>
+ </tr>
<tr>
<td align="center" width="120">
<a href="https://reccloud.cn"><img src="docs/sponsors/reccloud-logo.svg" alt="录咖" height="36"></a><br>
diff --git a/app/models/llm_provider.py b/app/models/llm_provider.py
index 6f1e78df..3a29a44f 100644
--- a/app/models/llm_provider.py
+++ b/app/models/llm_provider.py
@@ -168,6 +168,13 @@ LLM_PROVIDER_REGISTRY = (
default_base_url="https://api.xiaomimimo.com/v1",
),
# 聚合与统一接入平台
+ LLMProviderSpec(
+ "shengsuanyun",
+ "Shengsuan Cloud",
+ api_key_url="https://www.shengsuanyun.com/?from=CH_XUQ4OTSK",
+ default_model="deepseek/deepseek-v4-flash",
+ default_base_url="https://router.shengsuanyun.com/api/v1",
+ ),
LLMProviderSpec(
"cloudflare",
"Cloudflare AI Gateway",
diff --git a/app/services/loomloom.py b/app/services/loomloom.py
new file mode 100644
index 00000000..e17eb040
--- /dev/null
+++ b/app/services/loomloom.py
@@ -0,0 +1,830 @@
+"""LoomLoom Market clients for MoneyPrinterTurbo batch generation.
+
+This module deliberately lives outside ``llm_provider``. LoomLoom executes a
+versioned Market SkillBot with quote, confirmation, run lifecycle, and result
+rows; it is not a chat-completions provider.
+"""
+
+from __future__ import annotations
+
+import json
+import os
+import time
+from collections.abc import Callable, Mapping
+from dataclasses import dataclass, field
+from typing import Any
+from urllib.parse import quote, urlsplit
+
+import requests
+from loguru import logger
+
+
+DEFAULT_RESULT_PORT_NAME = "output"
+DEFAULT_BASE_URL = "https://loomloom.shengsuanyun.com/loom/v1"
+DEFAULT_SCRIPT_MARKET_LISTING_ID = "019fd618-9baa-73d9-94f4-c9270b6f3025"
+# 文案与视频是两个输入、产物结构完全不同的已上架 SkillBot。两个 ID 都是
+# MoneyPrinterTurbo 集成的内部常量,用户只需提供 API Key,不应接触 Listing ID。
+DEFAULT_VIDEO_MARKET_LISTING_ID = "019fd60d-5c26-78f7-bba0-5584f9ee7337"
+DEFAULT_REQUEST_TIMEOUT_SECONDS = 30.0
+DEFAULT_POLL_INTERVAL_SECONDS = 2.0
+DEFAULT_RUN_TIMEOUT_SECONDS = 600.0
+DEFAULT_VIDEO_RUN_TIMEOUT_SECONDS = 1800.0
+MAX_EXECUTE_ATTEMPTS = 3
+MAX_POLL_RETRY_DELAY_SECONDS = 30.0
+MAX_SCRIPT_CANDIDATES = 10
+MAX_VIDEO_SCENES = 5
+MAX_VIDEO_ARTIFACT_BYTES = 512 * 1024 * 1024
+TERMINAL_RUN_STATUSES = frozenset({"completed", "failed", "cancelled", "canceled"})
+
+
+class LoomLoomError(RuntimeError):
+ """Base error for the LoomLoom integration."""
+
+
+class LoomLoomConfigurationError(LoomLoomError):
+ """Raised when the integration is enabled without complete settings."""
+
+
+class LoomLoomAPIError(LoomLoomError):
+ """Raised when the Public API rejects a request or returns invalid JSON."""
+
+ def __init__(
+ self,
+ message: str,
+ *,
+ status_code: int | None = None,
+ retryable: bool = False,
+ ):
+ super().__init__(message)
+ self.status_code = status_code
+ self.retryable = retryable
+
+
+class LoomLoomRunError(LoomLoomError):
+ """Raised when a submitted run fails or exceeds its wait timeout."""
+
+
+def resolve_api_token(values: Mapping[str, Any]) -> str:
+ """
+ 解析当前功能应使用的胜算云 API Key。
+
+ 当大模型 Provider 已选择胜算云时,文案和视频必须复用设置页中的 Key;
+ 其它 Provider 则继续使用 LoomLoom 独立 Key,避免改变既有用户配置。
+ """
+ if str(values.get("llm_provider", "") or "").strip().lower() == "shengsuanyun":
+ return str(values.get("shengsuanyun_api_key", "") or "").strip()
+ return str(values.get("loomloom_api_token", "") or "").strip()
+
+
+@dataclass(frozen=True)
+class LoomLoomSettings:
+ base_url: str
+ api_token: str = field(repr=False)
+ market_listing_id: str
+ listing_version_id: str = ""
+ result_port_name: str = DEFAULT_RESULT_PORT_NAME
+ request_timeout_seconds: float = DEFAULT_REQUEST_TIMEOUT_SECONDS
+ poll_interval_seconds: float = DEFAULT_POLL_INTERVAL_SECONDS
+ run_timeout_seconds: float = DEFAULT_RUN_TIMEOUT_SECONDS
+
+ @classmethod
+ def from_mapping(
+ cls,
+ values: Mapping[str, Any],
+ ) -> "LoomLoomSettings":
+ settings = cls(
+ base_url=str(values.get("loomloom_base_url", "") or DEFAULT_BASE_URL)
+ .strip()
+ .rstrip("/"),
+ api_token=resolve_api_token(values),
+ # MoneyPrinterTurbo 固定调用项目已经上架的默认 SkillBot。Listing ID
+ # 属于集成实现细节,不能要求普通用户在 config.toml 中重复配置。
+ market_listing_id=DEFAULT_SCRIPT_MARKET_LISTING_ID,
+ listing_version_id="",
+ result_port_name=DEFAULT_RESULT_PORT_NAME,
+ request_timeout_seconds=float(
+ values.get(
+ "loomloom_request_timeout_seconds",
+ DEFAULT_REQUEST_TIMEOUT_SECONDS,
+ )
+ ),
+ poll_interval_seconds=float(
+ values.get(
+ "loomloom_poll_interval_seconds",
+ DEFAULT_POLL_INTERVAL_SECONDS,
+ )
+ ),
+ run_timeout_seconds=float(
+ values.get("loomloom_run_timeout_seconds", DEFAULT_RUN_TIMEOUT_SECONDS)
+ ),
+ )
+ settings.validate(require_api_token=True)
+ return settings
+
+ def validate(self, *, require_api_token: bool = True) -> None:
+ missing = []
+ if not self.base_url:
+ missing.append("loomloom_base_url")
+ if require_api_token and not self.api_token:
+ missing.append("loomloom_api_token")
+ if not self.market_listing_id:
+ missing.append("loomloom_market_listing_id")
+ if not self.result_port_name:
+ missing.append("loomloom_result_port_name")
+ if missing:
+ raise LoomLoomConfigurationError(
+ "missing LoomLoom settings: " + ", ".join(missing)
+ )
+
+ parsed = urlsplit(self.base_url)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ raise LoomLoomConfigurationError(
+ "loomloom_base_url must be an absolute HTTP(S) URL"
+ )
+ for name, value in (
+ ("loomloom_request_timeout_seconds", self.request_timeout_seconds),
+ ("loomloom_poll_interval_seconds", self.poll_interval_seconds),
+ ("loomloom_run_timeout_seconds", self.run_timeout_seconds),
+ ):
+ if value <= 0:
+ raise LoomLoomConfigurationError(f"{name} must be greater than zero")
+
+
+@dataclass(frozen=True)
+class LoomLoomScriptBatch:
+ input_rows: tuple[dict[str, str], ...]
+
+
+@dataclass(frozen=True)
+class LoomLoomVideoBatch:
+ """默认 SkillBot 一次视频素材报价所包含的输入行。"""
+
+ input_rows: tuple[dict[str, str], ...]
+
+
+@dataclass(frozen=True)
+class LoomLoomQuote:
+ quote_id: str
+ listing_version_id: str
+ currency: str
+ task_count: int
+ estimated_buyer_payable_t: int
+ estimated_buyer_payable_amount: str
+ input_rows: tuple[dict[str, str], ...]
+
+
+@dataclass(frozen=True)
+class LoomLoomExecution:
+ run_id: str
+ transaction_id: str
+ transaction_status: str
+ listing_version_id: str
+
+
+@dataclass(frozen=True)
+class LoomLoomRun:
+ run_id: str
+ status: str
+ total_tasks: int
+ completed_tasks: int
+ failed_tasks: int
+ cancelled_tasks: int
+ first_error_message: str
+
+
+@dataclass(frozen=True)
+class LoomLoomScriptCandidate:
+ row_index: int
+ script: str
+ video_terms: tuple[str, ...]
+
+
+@dataclass(frozen=True)
+class LoomLoomCandidateError:
+ row_index: int
+ message: str
+
+
+@dataclass(frozen=True)
+class LoomLoomScriptBatchResult:
+ candidates: tuple[LoomLoomScriptCandidate, ...]
+ errors: tuple[LoomLoomCandidateError, ...]
+
+
+@dataclass(frozen=True)
+class LoomLoomConfirmedVideoRequest:
+ """
+ 已由用户确认过报价的视频请求快照。
+
+ API Key 通过 `LoomLoomSettings` 的隐藏字段仅在当前进程内传递,不进入
+ VideoParams、任务状态或日志;报价版本和幂等请求 ID 确保后台执行与用户
+ 看到的报价一致,并避免网络重试造成重复扣费。
+ """
+
+ settings: LoomLoomSettings
+ batch: LoomLoomVideoBatch
+ listing_version_id: str
+ client_request_id: str
+
+ def validate(self) -> None:
+ self.settings.validate(require_api_token=True)
+ if not self.batch.input_rows:
+ raise LoomLoomConfigurationError("LoomLoom video batch is empty")
+ if not str(self.listing_version_id or "").strip():
+ raise LoomLoomConfigurationError("quoted listing version is required")
+ if not str(self.client_request_id or "").strip():
+ raise LoomLoomConfigurationError("video client request id is required")
+
+
+def video_settings_from_mapping(values: Mapping[str, Any]) -> LoomLoomSettings:
+ """使用项目内置的视频 SkillBot 创建客户端,并放宽视频任务等待时间。"""
+ settings = LoomLoomSettings.from_mapping(values)
+ return LoomLoomSettings(
+ base_url=settings.base_url,
+ api_token=settings.api_token,
+ # 视频 Listing 接收 scenePrompt/aspectRatio/sceneIndex 并返回 MP4;不能
+ # 复用文案 Listing,否则报价阶段就会因输入 schema 不匹配而失败。
+ market_listing_id=DEFAULT_VIDEO_MARKET_LISTING_ID,
+ listing_version_id=settings.listing_version_id,
+ result_port_name=settings.result_port_name,
+ request_timeout_seconds=settings.request_timeout_seconds,
+ poll_interval_seconds=settings.poll_interval_seconds,
+ run_timeout_seconds=float(
+ values.get(
+ "loomloom_video_run_timeout_seconds",
+ DEFAULT_VIDEO_RUN_TIMEOUT_SECONDS,
+ )
+ ),
+ )
+
+
+class LoomLoomScriptBackend:
+ """Execute one configured LoomLoom Market Listing for script candidates."""
+
+ def __init__(
+ self,
+ settings: LoomLoomSettings,
+ *,
+ session: requests.Session | Any | None = None,
+ credential_provider: Callable[[], str] | None = None,
+ sleep: Callable[[float], None] = time.sleep,
+ clock: Callable[[], float] = time.monotonic,
+ ):
+ settings.validate(require_api_token=credential_provider is None)
+ self.settings = settings
+ self._session = session or requests.Session()
+ self._credential_provider = credential_provider or (lambda: settings.api_token)
+ self._sleep = sleep
+ self._clock = clock
+
+ def prepare_script_batch(
+ self,
+ *,
+ subject: str,
+ candidate_count: int,
+ language: str = "auto",
+ duration_seconds: int = 60,
+ style: str = "",
+ ) -> LoomLoomScriptBatch:
+ normalized_subject = str(subject or "").strip()
+ if not normalized_subject:
+ raise ValueError("subject is required")
+ if not 1 <= candidate_count <= MAX_SCRIPT_CANDIDATES:
+ raise ValueError(
+ f"candidate_count must be between 1 and {MAX_SCRIPT_CANDIDATES}"
+ )
+ if duration_seconds <= 0:
+ raise ValueError("duration_seconds must be greater than zero")
+
+ requirements = (
+ f"输出语言:{str(language or 'auto').strip() or 'auto'}\n"
+ f"目标时长(秒):{duration_seconds}"
+ )
+ normalized_style = str(style or "").strip()
+ if normalized_style:
+ requirements += f"\n风格或附加要求:{normalized_style}"
+
+ rows = tuple(
+ {
+ "subject": normalized_subject,
+ "requirements": requirements,
+ "candidateIndex": str(index),
+ }
+ for index in range(1, candidate_count + 1)
+ )
+ return LoomLoomScriptBatch(input_rows=rows)
+
+ def quote(self, batch: LoomLoomScriptBatch | LoomLoomVideoBatch) -> LoomLoomQuote:
+ payload = self._listing_payload(batch)
+ response = self._request(
+ "POST",
+ f"/marketListings/{quote(self.settings.market_listing_id, safe='')}:quote",
+ json_body=payload,
+ )
+ estimated_buyer_payable = response.get("estimatedBuyerPayable", {})
+ if not isinstance(estimated_buyer_payable, dict):
+ estimated_buyer_payable = {}
+ return LoomLoomQuote(
+ quote_id=self._required_string(response, "quoteId"),
+ listing_version_id=self._required_string(response, "listingVersionId"),
+ currency=str(response.get("currency", "")).strip(),
+ task_count=self._integer(response, "taskCount"),
+ estimated_buyer_payable_t=self._integer(response, "estimatedBuyerPayableT"),
+ estimated_buyer_payable_amount=str(
+ estimated_buyer_payable.get("amount", "")
+ ).strip(),
+ input_rows=batch.input_rows,
+ )
+
+ def execute(
+ self,
+ batch: LoomLoomScriptBatch | LoomLoomVideoBatch,
+ *,
+ client_request_id: str,
+ listing_version_id: str,
+ confirm: bool,
+ ) -> LoomLoomExecution:
+ if confirm is not True:
+ raise ValueError("confirm=True is required before a paid LoomLoom run")
+ normalized_request_id = str(client_request_id or "").strip()
+ if not normalized_request_id:
+ raise ValueError("client_request_id is required")
+ normalized_listing_version_id = str(listing_version_id or "").strip()
+ if not normalized_listing_version_id:
+ raise ValueError("listing_version_id from the quote is required")
+
+ payload = self._listing_payload(
+ batch, listing_version_id=normalized_listing_version_id
+ )
+ payload.update(
+ {
+ "clientRequestId": normalized_request_id,
+ "confirm": True,
+ }
+ )
+ response = None
+ for attempt in range(1, MAX_EXECUTE_ATTEMPTS + 1):
+ try:
+ response = self._request(
+ "POST",
+ f"/marketListings/{quote(self.settings.market_listing_id, safe='')}:execute",
+ json_body=payload,
+ )
+ break
+ except LoomLoomAPIError as exc:
+ if not exc.retryable or attempt >= MAX_EXECUTE_ATTEMPTS:
+ raise
+ # execute 是付费操作,不能生成新的请求 ID 后盲目重试。服务端以
+ # clientRequestId 保证幂等,因此这里只复用完全相同的载荷做有限
+ # 重试,用于恢复“服务端已接受、客户端未收到响应”的网络故障。
+ retry_delay = min(float(attempt), MAX_POLL_RETRY_DELAY_SECONDS)
+ logger.warning(
+ "retry LoomLoom execute with the same client request id: "
+ f"attempt={attempt + 1}/{MAX_EXECUTE_ATTEMPTS}, "
+ f"error={type(exc).__name__}"
+ )
+ self._sleep(retry_delay)
+
+ if response is None: # pragma: no cover - 循环的成功或异常分支已覆盖
+ raise LoomLoomAPIError("LoomLoom execute returned no response")
+ return LoomLoomExecution(
+ run_id=self._required_string(response, "runId"),
+ transaction_id=str(response.get("runTransactionId", "")).strip(),
+ transaction_status=str(response.get("transactionStatus", "")).strip(),
+ listing_version_id=str(response.get("listingVersionId", "")).strip(),
+ )
+
+ def get_run(self, run_id: str) -> LoomLoomRun:
+ normalized_run_id = self._required_identifier(run_id, "run_id")
+ response = self._request(
+ "GET", f"/users/me/runs/{quote(normalized_run_id, safe='')}"
+ )
+ run = response.get("run")
+ if not isinstance(run, dict):
+ raise LoomLoomAPIError("LoomLoom run response is missing run")
+ return LoomLoomRun(
+ run_id=self._required_string(run, "runId"),
+ status=self._required_string(run, "status").lower(),
+ total_tasks=self._integer(run, "totalTasks"),
+ completed_tasks=self._integer(run, "completedTasks"),
+ failed_tasks=self._integer(run, "failedTasks"),
+ cancelled_tasks=self._integer(run, "cancelledTasks"),
+ first_error_message=str(run.get("firstErrorMessage", "")).strip(),
+ )
+
+ def wait_for_run(self, run_id: str) -> LoomLoomRun:
+ deadline = self._clock() + self.settings.run_timeout_seconds
+ started_at = self._clock()
+ last_logged_status = None
+ last_progress_log_at = started_at
+ consecutive_poll_errors = 0
+ while True:
+ try:
+ run = self.get_run(run_id)
+ consecutive_poll_errors = 0
+ except LoomLoomAPIError as exc:
+ if not exc.retryable:
+ raise
+ now = self._clock()
+ if now >= deadline:
+ raise LoomLoomRunError(
+ f"LoomLoom run {run_id} could not be queried within "
+ f"{self.settings.run_timeout_seconds:g} seconds"
+ ) from exc
+ consecutive_poll_errors += 1
+ retry_delay = min(
+ self.settings.poll_interval_seconds
+ * (2 ** min(consecutive_poll_errors - 1, 4)),
+ MAX_POLL_RETRY_DELAY_SECONDS,
+ max(deadline - now, 0),
+ )
+ logger.warning(
+ "retry LoomLoom run polling after a transient error: "
+ f"run_id={run_id}, attempt={consecutive_poll_errors}, "
+ f"delay={retry_delay:g}s, error={type(exc).__name__}"
+ )
+ self._sleep(retry_delay)
+ continue
+ now = self._clock()
+ progress = run.completed_tasks + run.failed_tasks + run.cancelled_tasks
+ # 远端视频任务可能持续数分钟。状态变化时立即记录,状态不变时每
+ # 30 秒记录一次心跳,既能帮助定位卡住位置,也避免两秒一次刷屏。
+ if run.status != last_logged_status or now - last_progress_log_at >= 30:
+ logger.info(
+ "LoomLoom run progress: "
+ f"run_id={run.run_id}, status={run.status}, "
+ f"finished={progress}/{run.total_tasks}"
+ )
+ last_logged_status = run.status
+ last_progress_log_at = now
+ if run.status in TERMINAL_RUN_STATUSES:
+ if run.status != "completed":
+ detail = run.first_error_message or run.status
+ raise LoomLoomRunError(
+ f"LoomLoom run {run.run_id} ended with {detail}"
+ )
+ return run
+ if now >= deadline:
+ raise LoomLoomRunError(
+ f"LoomLoom run {run.run_id} did not complete within "
+ f"{self.settings.run_timeout_seconds:g} seconds"
+ )
+ self._sleep(self.settings.poll_interval_seconds)
+
+ def get_script_results(self, run_id: str) -> LoomLoomScriptBatchResult:
+ normalized_run_id = self._required_identifier(run_id, "run_id")
+ rows = self._list_all_result_rows(normalized_run_id)
+ candidates = []
+ errors = []
+ for row in rows:
+ row_index = self._integer(row, "rowIndex")
+ status = str(row.get("status", "")).strip().lower()
+ if status != "completed":
+ errors.append(
+ LoomLoomCandidateError(
+ row_index=row_index,
+ message=str(row.get("errorMessage", "")).strip()
+ or f"row ended with status {status or 'unknown'}",
+ )
+ )
+ continue
+ try:
+ candidates.append(self._parse_candidate(row_index, row))
+ except (LoomLoomAPIError, ValueError) as exc:
+ errors.append(
+ LoomLoomCandidateError(row_index=row_index, message=str(exc))
+ )
+ return LoomLoomScriptBatchResult(
+ candidates=tuple(candidates), errors=tuple(errors)
+ )
+
+ def _listing_payload(
+ self,
+ batch: LoomLoomScriptBatch | LoomLoomVideoBatch,
+ *,
+ listing_version_id: str | None = None,
+ ) -> dict[str, Any]:
+ if not batch.input_rows:
+ raise ValueError("input_rows is required")
+ payload: dict[str, Any] = {"inputRows": [dict(row) for row in batch.input_rows]}
+ resolved_listing_version_id = (
+ self.settings.listing_version_id
+ if listing_version_id is None
+ else listing_version_id
+ )
+ if resolved_listing_version_id:
+ payload["listingVersionId"] = resolved_listing_version_id
+ return payload
+
+ def _list_all_result_rows(self, run_id: str) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ page_token = ""
+ while True:
+ params: dict[str, Any] = {"pageSize": 200}
+ if page_token:
+ params["pageToken"] = page_token
+ response = self._request(
+ "GET",
+ f"/users/me/runs/{quote(run_id, safe='')}/resultRows",
+ params=params,
+ )
+ items = response.get("items", [])
+ if not isinstance(items, list) or not all(
+ isinstance(item, dict) for item in items
+ ):
+ raise LoomLoomAPIError("LoomLoom resultRows items must be objects")
+ rows.extend(items)
+ page_token = str(response.get("nextPageToken", "")).strip()
+ if not page_token:
+ return rows
+
+ def _parse_candidate(
+ self, row_index: int, row: Mapping[str, Any]
+ ) -> LoomLoomScriptCandidate:
+ artifacts = row.get("artifacts", [])
+ if not isinstance(artifacts, list):
+ raise LoomLoomAPIError("row artifacts must be a list")
+ matching = [
+ artifact
+ for artifact in artifacts
+ if isinstance(artifact, dict)
+ and str(artifact.get("portName", "")).strip()
+ == self.settings.result_port_name
+ ]
+ if len(matching) != 1:
+ raise LoomLoomAPIError(
+ f"expected one {self.settings.result_port_name!r} result artifact, "
+ f"got {len(matching)}"
+ )
+ inline_text = str(matching[0].get("inlineText", "")).strip()
+ if not inline_text:
+ raise LoomLoomAPIError("result artifact does not contain inlineText")
+ lines = inline_text.splitlines()
+ if (
+ len(lines) >= 3
+ and lines[0].strip().lower() in {"```", "```json"}
+ and lines[-1].strip() == "```"
+ ):
+ inline_text = "\n".join(lines[1:-1]).strip()
+ try:
+ value = json.loads(inline_text)
+ except json.JSONDecodeError as exc:
+ raise LoomLoomAPIError("result artifact is not valid JSON") from exc
+ if not isinstance(value, dict):
+ raise LoomLoomAPIError("result artifact JSON must be an object")
+
+ script = str(value.get("script", "")).strip()
+ if not script:
+ raise LoomLoomAPIError("result artifact script is required")
+ video_terms = value.get("videoTerms")
+ if not isinstance(video_terms, list) or not video_terms:
+ raise LoomLoomAPIError(
+ "result artifact videoTerms must be a non-empty list"
+ )
+ normalized_terms = tuple(
+ str(term).strip() for term in video_terms if str(term).strip()
+ )
+ if not normalized_terms:
+ raise LoomLoomAPIError("result artifact videoTerms must not be empty")
+ return LoomLoomScriptCandidate(
+ row_index=row_index,
+ script=script,
+ video_terms=normalized_terms,
+ )
+
+ def _request(
+ self,
+ method: str,
+ path: str,
+ *,
+ json_body: Mapping[str, Any] | None = None,
+ params: Mapping[str, Any] | None = None,
+ ) -> dict[str, Any]:
+ url = f"{self.settings.base_url}{path}"
+ api_token = str(self._credential_provider() or "").strip()
+ if not api_token:
+ raise LoomLoomConfigurationError(
+ "a LoomLoom credential is required for this request"
+ )
+ try:
+ response = self._session.request(
+ method,
+ url,
+ headers={
+ "Accept": "application/json",
+ "Authorization": f"Bearer {api_token}",
+ "Content-Type": "application/json",
+ },
+ json=dict(json_body) if json_body is not None else None,
+ params=dict(params) if params is not None else None,
+ timeout=(5.0, self.settings.request_timeout_seconds),
+ )
+ except requests.RequestException as exc:
+ raise LoomLoomAPIError(
+ f"LoomLoom request failed: {type(exc).__name__}",
+ retryable=True,
+ ) from exc
+
+ if not 200 <= response.status_code < 300:
+ message = "request rejected"
+ try:
+ error_payload = response.json()
+ except ValueError:
+ error_payload = None
+ if isinstance(error_payload, dict):
+ server_error = str(error_payload.get("error", "")).strip()
+ if server_error:
+ message = server_error
+ raise LoomLoomAPIError(
+ f"LoomLoom API returned HTTP {response.status_code}: {message}",
+ status_code=response.status_code,
+ retryable=(
+ response.status_code in {408, 425, 429}
+ or response.status_code >= 500
+ ),
+ )
+ try:
+ payload = response.json()
+ except ValueError as exc:
+ raise LoomLoomAPIError("LoomLoom API returned invalid JSON") from exc
+ if not isinstance(payload, dict):
+ raise LoomLoomAPIError("LoomLoom API response must be a JSON object")
+ return payload
+
+ @staticmethod
+ def _required_identifier(value: str, name: str) -> str:
+ normalized = str(value or "").strip()
+ if not normalized:
+ raise ValueError(f"{name} is required")
+ return normalized
+
+ @staticmethod
+ def _required_string(values: Mapping[str, Any], name: str) -> str:
+ value = str(values.get(name, "")).strip()
+ if not value:
+ raise LoomLoomAPIError(f"LoomLoom response is missing {name}")
+ return value
+
+ @staticmethod
+ def _integer(values: Mapping[str, Any], name: str) -> int:
+ value = values.get(name, 0)
+ if isinstance(value, bool):
+ raise LoomLoomAPIError(f"LoomLoom response {name} must be an integer")
+ try:
+ return int(value)
+ except (TypeError, ValueError) as exc:
+ raise LoomLoomAPIError(
+ f"LoomLoom response {name} must be an integer"
+ ) from exc
+
+
+class LoomLoomVideoBackend(LoomLoomScriptBackend):
+ """通过默认 SkillBot 生成视频素材,并将 MP4 产物安全下载到任务目录。"""
+
+ def prepare_video_batch(
+ self,
+ *,
+ subject: str,
+ scene_prompts: list[str] | tuple[str, ...],
+ aspect_ratio: str,
+ ) -> LoomLoomVideoBatch:
+ normalized_subject = str(subject or "").strip()
+ normalized_aspect_ratio = str(aspect_ratio or "").strip()
+ if not normalized_subject:
+ raise ValueError("subject is required")
+ if normalized_aspect_ratio not in {"9:16", "16:9"}:
+ raise ValueError("aspect_ratio must be 9:16 or 16:9")
+
+ scenes = tuple(
+ str(prompt or "").strip()
+ for prompt in scene_prompts
+ if str(prompt or "").strip()
+ )
+ if not 1 <= len(scenes) <= MAX_VIDEO_SCENES:
+ raise ValueError(
+ f"scene_prompts must contain between 1 and {MAX_VIDEO_SCENES} items"
+ )
+
+ rows = tuple(
+ {
+ "scenePrompt": (
+ "Create cinematic stock-footage-style video for a short video "
+ f"about {normalized_subject}. Scene focus: {scene}. "
+ "No text, subtitles, captions, watermarks, logos, or spoken audio."
+ ),
+ "aspectRatio": normalized_aspect_ratio,
+ "sceneIndex": str(index),
+ }
+ for index, scene in enumerate(scenes, start=1)
+ )
+ return LoomLoomVideoBatch(input_rows=rows)
+
+ def download_video_results(
+ self, run_id: str, destination_dir: str
+ ) -> tuple[str, ...]:
+ normalized_run_id = self._required_identifier(run_id, "run_id")
+ raw_destination = str(destination_dir or "").strip()
+ if not raw_destination:
+ raise ValueError("destination_dir is required")
+ normalized_destination = os.path.realpath(raw_destination)
+ os.makedirs(normalized_destination, exist_ok=True)
+
+ rows = sorted(
+ self._list_all_result_rows(normalized_run_id),
+ key=lambda row: self._integer(row, "rowIndex"),
+ )
+ if not rows:
+ raise LoomLoomRunError("LoomLoom video run returned no result rows")
+
+ downloaded = []
+ for row in rows:
+ row_index = self._integer(row, "rowIndex")
+ status = str(row.get("status", "")).strip().lower()
+ if status != "completed":
+ detail = str(row.get("errorMessage", "")).strip() or status
+ raise LoomLoomRunError(
+ f"LoomLoom video row {row_index + 1} ended with {detail}"
+ )
+ artifact = self._video_artifact(row)
+ destination = os.path.join(
+ normalized_destination, f"loomloom-video-{row_index + 1:02d}.mp4"
+ )
+ self._download_video_artifact(artifact["accessUrl"], destination)
+ downloaded.append(destination)
+ logger.info(
+ "downloaded LoomLoom video artifact: "
+ f"run_id={normalized_run_id}, row={row_index + 1}, "
+ f"filename={os.path.basename(destination)}"
+ )
+ return tuple(downloaded)
+
+ def _video_artifact(self, row: Mapping[str, Any]) -> dict[str, Any]:
+ artifacts = row.get("artifacts", [])
+ if not isinstance(artifacts, list):
+ raise LoomLoomAPIError("row artifacts must be a list")
+ matching = [
+ artifact
+ for artifact in artifacts
+ if isinstance(artifact, dict)
+ and str(artifact.get("portName", "")).strip()
+ == self.settings.result_port_name
+ and str(artifact.get("mimeType", "")).strip().lower() == "video/mp4"
+ ]
+ if len(matching) != 1:
+ raise LoomLoomAPIError(
+ f"expected one {self.settings.result_port_name!r} video/mp4 artifact, "
+ f"got {len(matching)}"
+ )
+ access_url = str(matching[0].get("accessUrl", "")).strip()
+ parsed = urlsplit(access_url)
+ if parsed.scheme not in {"http", "https"} or not parsed.netloc:
+ raise LoomLoomAPIError("video artifact accessUrl must be HTTP(S)")
+ return {**matching[0], "accessUrl": access_url}
+
+ def _download_video_artifact(self, access_url: str, destination: str) -> None:
+ temporary = destination + ".part"
+ downloaded_bytes = 0
+ response = None
+ try:
+ response = self._session.get(
+ access_url,
+ stream=True,
+ timeout=(5.0, self.settings.request_timeout_seconds),
+ )
+ response.raise_for_status()
+ content_length = int(response.headers.get("content-length", 0) or 0)
+ if content_length > MAX_VIDEO_ARTIFACT_BYTES:
+ raise LoomLoomAPIError("video artifact exceeds the download limit")
+ with open(temporary, "wb") as output:
+ for chunk in response.iter_content(chunk_size=1024 * 1024):
+ if not chunk:
+ continue
+ downloaded_bytes += len(chunk)
+ if downloaded_bytes > MAX_VIDEO_ARTIFACT_BYTES:
+ raise LoomLoomAPIError(
+ "video artifact exceeds the download limit"
+ )
+ output.write(chunk)
+ if downloaded_bytes == 0:
+ raise LoomLoomAPIError("video artifact download was empty")
+ os.replace(temporary, destination)
+ except LoomLoomError:
+ raise
+ except (requests.RequestException, OSError, ValueError) as exc:
+ raise LoomLoomAPIError(
+ f"video artifact download failed: {type(exc).__name__}"
+ ) from exc
+ finally:
+ if response is not None:
+ try:
+ # stream=True 在大小校验失败或写盘异常时不会保证消费完整响应体。
+ # 显式关闭可以立即归还或释放底层连接,避免连续失败逐步耗尽
+ # Session 连接池;关闭失败只记录告警,不能覆盖原始下载异常。
+ response.close()
+ except Exception as exc:
+ logger.warning(
+ "failed to close LoomLoom video download response: "
+ f"error={type(exc).__name__}"
+ )
+ if os.path.exists(temporary):
+ os.remove(temporary)
diff --git a/app/services/task.py b/app/services/task.py
index 5ea42ac5..4cb290b8 100644
--- a/app/services/task.py
+++ b/app/services/task.py
@@ -18,6 +18,7 @@ from app.services import bgm as bgm_service
from app.services import (
elevenlabs_music,
llm,
+ loomloom,
material,
sonilo,
subtitle,
@@ -52,6 +53,8 @@ _ACTIVE_CROSS_POST_STATES = {
}
_CROSS_POST_STATE_WRITE_ATTEMPTS = 3
_CROSS_POST_STATE_RETRY_DELAY_SECONDS = 0.1
+_LOOMLOOM_STATE_WRITE_ATTEMPTS = 3
+_LOOMLOOM_STATE_RETRY_DELAY_SECONDS = 0.1
_INTERRUPTED_CROSS_POST_ERROR = (
"cross-posting was interrupted before the process completed"
)
@@ -226,7 +229,12 @@ def _is_cross_post_owner_alive(owner: str | None) -> bool:
return True
-def _mark_task_failed(task_id: str, stage: str, error: str) -> dict:
+def _mark_task_failed(
+ task_id: str,
+ stage: str,
+ error: str,
+ details: dict | None = None,
+) -> dict:
"""记录结构化失败信息,并保留任务失败前已经到达的进度。"""
existing_task = None
try:
@@ -245,9 +253,7 @@ def _mark_task_failed(task_id: str, stage: str, error: str) -> dict:
message = str(error or "unknown task error").strip()
progress = int((existing_task or {}).get("progress", 0) or 0)
- logger.error(
- f"task failed, task_id: {task_id}, stage: {stage}, error: {message}"
- )
+ logger.error(f"task failed, task_id: {task_id}, stage: {stage}, error: {message}")
failure = {
"task_id": task_id,
"state": const.TASK_STATE_FAILED,
@@ -255,12 +261,19 @@ def _mark_task_failed(task_id: str, stage: str, error: str) -> dict:
"failed_stage": stage,
"error": message,
}
+ # 某些外部任务已经创建了可用于恢复或排障的远端 ID。失败状态需要保留
+ # 这些非敏感字段,但不能允许调用方覆盖统一的状态、进度和错误结构。
+ failure_details = {
+ key: value for key, value in dict(details or {}).items() if key not in failure
+ }
+ failure.update(failure_details)
sm.state.update_task(
task_id,
state=failure["state"],
progress=failure["progress"],
failed_stage=failure["failed_stage"],
error=failure["error"],
+ **failure_details,
)
return failure
@@ -505,14 +518,15 @@ def generate_audio(task_id, params, video_script, voice_preview=None):
return None, None, None
return custom_audio_file, audio_duration, None
+
def generate_subtitle(task_id, params, video_script, sub_maker, audio_file):
- '''
+ """
Generate subtitle for the video script.
If subtitle generation is disabled or no subtitle maker is provided, it will return an empty string.
Otherwise, it will generate the subtitle using the specified provider.
Returns:
- subtitle_path: path to the generated subtitle file
- '''
+ """
logger.info("\n\n## generating subtitle")
if not params.subtitle_enabled:
return ""
@@ -563,7 +577,13 @@ def generate_subtitle(task_id, params, video_script, sub_maker, audio_file):
return subtitle_path
-def get_video_materials(task_id, params, video_terms, audio_duration):
+def get_video_materials(
+ task_id,
+ params,
+ video_terms,
+ audio_duration,
+ loomloom_video_request: loomloom.LoomLoomConfirmedVideoRequest | None = None,
+):
if params.video_source == "local":
logger.info("\n\n## preprocess local materials")
materials = video.preprocess_video(
@@ -577,6 +597,67 @@ def get_video_materials(task_id, params, video_terms, audio_duration):
)
return None
return [material_info.url for material_info in materials]
+ elif params.video_source == "loomloom":
+ if not isinstance(
+ loomloom_video_request, loomloom.LoomLoomConfirmedVideoRequest
+ ):
+ _mark_task_failed(
+ task_id,
+ "materials",
+ "LoomLoom video generation requires a confirmed quote",
+ )
+ return None
+
+ request = loomloom_video_request
+ logger.info(
+ "\n\n## generating "
+ f"{len(request.batch.input_rows)} video materials with LoomLoom"
+ )
+ run_id = ""
+ try:
+ request.validate()
+ backend = loomloom.LoomLoomVideoBackend(request.settings)
+ execution = backend.execute(
+ request.batch,
+ client_request_id=request.client_request_id,
+ listing_version_id=request.listing_version_id,
+ confirm=True,
+ )
+ run_id = execution.run_id
+ # execute 返回即表示付费任务已经由远端接受。必须先把 run ID 写入
+ # 进程日志,即使 Redis 等状态后端随后不可用,运维人员仍能凭日志
+ # 在胜算云侧定位任务,不能让唯一标识只存在于局部变量中。
+ logger.info(
+ "LoomLoom paid video run created: "
+ f"task_id={task_id}, run_id={run_id}, "
+ f"listing_version_id={request.listing_version_id}"
+ )
+ # 付费任务一旦创建就立即记录远端 ID。即使后续轮询超时,日志和任务
+ # 状态仍能帮助用户或平台支持人员定位并找回已经生成的产物。状态后端
+ # 故障只能降低可观测性,不能中断已经开始计费的远端任务和产物下载。
+ _record_loomloom_run_reference(
+ task_id=task_id,
+ run_id=run_id,
+ listing_version_id=request.listing_version_id,
+ )
+ backend.wait_for_run(run_id)
+ return list(
+ backend.download_video_results(
+ run_id,
+ utils.task_dir(task_id),
+ )
+ )
+ except (loomloom.LoomLoomError, ValueError) as exc:
+ _mark_task_failed(
+ task_id,
+ "materials",
+ str(exc),
+ details={
+ "loomloom_run_id": run_id,
+ "loomloom_listing_version_id": request.listing_version_id,
+ },
+ )
+ return None
else:
logger.info(f"\n\n## downloading videos from {params.video_source}")
# 顺序匹配模式只在用户显式开启时生效。这里强制素材下载按关键词顺序
@@ -605,6 +686,49 @@ def get_video_materials(task_id, params, video_terms, audio_duration):
return downloaded_videos
+def _record_loomloom_run_reference(
+ *, task_id: str, run_id: str, listing_version_id: str
+) -> bool | None:
+ """
+ 尽最大努力保存已创建的付费 LoomLoom Run,不让状态故障中断远端任务。
+
+ 返回 True 表示保存成功,False 表示任务记录已经不存在,None 表示状态后端
+ 在有限重试后仍不可用。调用方无论得到哪种结果都应继续轮询和下载,因为
+ execute 已经产生外部付费副作用,停止本地流程只会让产物更难找回。
+ """
+ fields = {
+ "loomloom_run_id": run_id,
+ "loomloom_listing_version_id": listing_version_id,
+ }
+ for attempt in range(1, _LOOMLOOM_STATE_WRITE_ATTEMPTS + 1):
+ try:
+ updated = sm.state.patch_task(task_id, **fields)
+ except Exception as exc:
+ if attempt >= _LOOMLOOM_STATE_WRITE_ATTEMPTS:
+ logger.exception(
+ "failed to persist LoomLoom paid run after retries: "
+ f"task_id={task_id}, run_id={run_id}, attempts={attempt}, "
+ f"error={exc}"
+ )
+ return None
+ logger.warning(
+ "retry LoomLoom paid run state update: "
+ f"task_id={task_id}, run_id={run_id}, attempt={attempt}, "
+ f"error={exc}"
+ )
+ time.sleep(_LOOMLOOM_STATE_RETRY_DELAY_SECONDS)
+ continue
+
+ if updated is False:
+ logger.warning(
+ "could not persist LoomLoom paid run because task is missing: "
+ f"task_id={task_id}, run_id={run_id}"
+ )
+ return updated
+
+ return None
+
+
def generate_final_videos(
task_id, params, downloaded_videos, audio_file, subtitle_path, audio_duration
):
@@ -946,9 +1070,7 @@ def _run_cross_post_with_slot(*args) -> None:
# _run_cross_post 已处理预期异常;这里是最后一道保护,避免未来新增
# 逻辑抛出的异常只保存在无人读取的 Future 中。
task_id = str(args[0]) if args else "unknown"
- logger.exception(
- f"cross-post worker crashed, task_id: {task_id}, error: {exc}"
- )
+ logger.exception(f"cross-post worker crashed, task_id: {task_id}, error: {exc}")
if args:
_record_cross_post_failure(task_id, exc)
finally:
@@ -1045,6 +1167,7 @@ def _run_pipeline(
params: VideoParams,
stop_at: str = "video",
voice_preview: dict | None = None,
+ loomloom_video_request: loomloom.LoomLoomConfirmedVideoRequest | None = None,
):
logger.info(f"start task: {task_id}, stop_at: {stop_at}")
sm.state.update_task(task_id, state=const.TASK_STATE_PROCESSING, progress=5)
@@ -1170,7 +1293,11 @@ def _run_pipeline(
# 5. Get video materials
downloaded_videos = get_video_materials(
- task_id, params, video_terms, audio_duration
+ task_id,
+ params,
+ video_terms,
+ audio_duration,
+ loomloom_video_request=loomloom_video_request,
)
if not downloaded_videos:
return _mark_task_failed(
@@ -1196,13 +1323,15 @@ def _run_pipeline(
params.video_concat_mode = VideoConcatMode(params.video_concat_mode)
# 6. Generate final videos
- final_video_paths, combined_video_paths, generation_warnings = generate_final_videos(
- task_id,
- params,
- downloaded_videos,
- audio_file,
- subtitle_path,
- audio_duration,
+ final_video_paths, combined_video_paths, generation_warnings = (
+ generate_final_videos(
+ task_id,
+ params,
+ downloaded_videos,
+ audio_file,
+ subtitle_path,
+ audio_duration,
+ )
)
if not final_video_paths:
@@ -1223,9 +1352,7 @@ def _run_pipeline(
and upload_post.upload_post_service.auto_upload
)
platforms = (
- list(upload_post.upload_post_service.platforms)
- if cross_post_enabled
- else []
+ list(upload_post.upload_post_service.platforms) if cross_post_enabled else []
)
should_cross_post = cross_post_enabled and bool(platforms)
if cross_post_enabled and not platforms:
@@ -1279,6 +1406,7 @@ def start(
params: VideoParams,
stop_at: str = "video",
voice_preview: dict | None = None,
+ loomloom_video_request: loomloom.LoomLoomConfirmedVideoRequest | None = None,
):
"""执行任务流水线,并确保未预期异常也会转换成可查询的失败状态。"""
try:
@@ -1287,6 +1415,7 @@ def start(
params,
stop_at=stop_at,
voice_preview=voice_preview,
+ loomloom_video_request=loomloom_video_request,
)
except Exception as exc:
logger.exception(
diff --git a/app/services/webui_task.py b/app/services/webui_task.py
index 8cec972e..498ddb4e 100644
--- a/app/services/webui_task.py
+++ b/app/services/webui_task.py
@@ -9,6 +9,7 @@ from app.models import const
from app.models.schema import VideoParams
from app.services import state as sm
from app.services import task as tm
+from app.services.loomloom import LoomLoomConfirmedVideoRequest
from app.utils.logging_utils import format_log_record
@@ -54,6 +55,7 @@ def _run_generation(
params: VideoParams,
capture_logs: bool,
voice_preview: dict | None = None,
+ loomloom_video_request: LoomLoomConfirmedVideoRequest | None = None,
) -> dict:
"""
在后台线程中执行现有视频流水线。
@@ -81,6 +83,7 @@ def _run_generation(
task_id=task_id,
params=params,
voice_preview=voice_preview,
+ loomloom_video_request=loomloom_video_request,
)
except Exception as exc:
# tm.start 已负责把流水线异常转换成失败状态;这里额外保护日志 sink、
@@ -121,6 +124,7 @@ def submit_generation(
params: VideoParams,
capture_logs: bool = True,
voice_preview: dict | None = None,
+ loomloom_video_request: LoomLoomConfirmedVideoRequest | None = None,
) -> None:
"""
登记并提交 WebUI 视频生成任务,调用后立即返回。
@@ -132,6 +136,9 @@ def submit_generation(
# 预览载荷只包含不可变音频路径、参数快照和只读字幕时间轴。复制外层字典,
# 避免页面后续 rerun 替换缓存字段时影响已经提交到后台队列的任务。
voice_preview_snapshot = dict(voice_preview) if voice_preview else None
+ # 已确认请求是冻结的数据对象,只在当前进程内传递。API Key 不会进入
+ # VideoParams、任务状态、日志或落盘历史,也不会受后续页面 rerun 影响。
+ loomloom_request_snapshot = loomloom_video_request
sm.state.update_task(
task_id,
state=const.TASK_STATE_PROCESSING,
@@ -145,6 +152,7 @@ def submit_generation(
params=task_params,
capture_logs=capture_logs,
voice_preview=voice_preview_snapshot,
+ loomloom_video_request=loomloom_request_snapshot,
)
except Exception as exc:
# 调度失败与流水线失败一样必须成为可查询状态,避免任务管理器永久显示
diff --git a/config.example.toml b/config.example.toml
index 9d452c40..14ced7f9 100644
--- a/config.example.toml
+++ b/config.example.toml
@@ -21,6 +21,23 @@ listen_port = 8080
# 是否隐藏 WebUI 基础配置面板。
hide_config = false
+# Script generation backend. "local" keeps the existing LLM workflow.
+# "loomloom" uses a configured LoomLoom Market SkillBot to return multiple
+# independently generated script candidates. The WebUI integration is optional.
+script_generation_backend = "local"
+
+# LoomLoom Public API settings. The WebUI supports the public MoneyPrinterTurbo
+# SkillBot below out of the box. Configure the key in the WebUI or a private
+# config.toml, and never commit a real key. The fixed SkillBot accepts subject,
+# requirements, and candidateIndex for each row
+# and returns inline JSON {script, videoTerms} on port "output".
+loomloom_base_url = "https://loomloom.shengsuanyun.com/loom/v1"
+loomloom_api_token = ""
+loomloom_request_timeout_seconds = 30
+loomloom_poll_interval_seconds = 2
+loomloom_run_timeout_seconds = 600
+loomloom_video_run_timeout_seconds = 1800
+
# Timeout in seconds for a single Edge TTS streaming request.
# 单次 Edge TTS 流式请求超时时间。慢网络可适当调大,设置为 0 表示禁用超时。
edge_tts_timeout = 30
@@ -33,7 +50,9 @@ tls_verify = true
# Video Materials / 视频素材
# -----------------------------------------------------------------------------
-# Available values: "pexels", "pixabay", "coverr", "local".
+# Available values: "pexels", "pixabay", "coverr", "loomloom", "local".
+# "loomloom" is a paid Shengsuan Cloud source and requires explicit
+# confirmation in the WebUI before each generation request.
video_source = "pexels"
# API key lists support key rotation. Use straight ASCII double quotes and
@@ -87,6 +106,12 @@ moonshot_api_key = ""
moonshot_base_url = ""
moonshot_model_name = ""
+# Shengsuan Cloud, OpenAI-compatible multi-model API.
+# API docs: https://lean.shengsuanyun.com/apidocs/api/openai-api
+shengsuanyun_api_key = ""
+shengsuanyun_base_url = ""
+shengsuanyun_model_name = ""
+
# OpenAI or another OpenAI Chat Completions-compatible provider.
# API key: https://platform.openai.com/api-keys
openai_api_key = ""
diff --git a/docs/loomloom/moneyprinterturbo-ai-video-materials.template.json b/docs/loomloom/moneyprinterturbo-ai-video-materials.template.json
new file mode 100644
index 00000000..b2f39eda
--- /dev/null
+++ b/docs/loomloom/moneyprinterturbo-ai-video-materials.template.json
@@ -0,0 +1,108 @@
+{
+ "meta": {
+ "name": "MoneyPrinterTurbo AI 视频素材",
+ "description": "为 MoneyPrinterTurbo 批量生成无字幕、无配音的短视频素材片段。",
+ "scenario": "short-video-material-generation",
+ "inputSummary": "场景描述、画面比例和场景编号",
+ "primaryOutputType": "video",
+ "tags": [
+ "MoneyPrinterTurbo",
+ "短视频",
+ "AI 视频素材"
+ ]
+ },
+ "steps": [
+ {
+ "stepId": "stp_video01",
+ "displayName": "生成视频素材",
+ "executionUnit": "video-generate",
+ "instruction": "生成可用于短视频剪辑的独立视频素材片段。不要生成字幕、文字、标题、水印、Logo 或口播音频。保持主体运动和镜头运动自然,避免突然切镜。",
+ "defaultModelRef": {
+ "modelKey": "google/veo3.1-fast-preview"
+ },
+ "staticParams": {
+ "generate_audio": "false",
+ "sample_count": "1"
+ }
+ }
+ ],
+ "inputSchema": {
+ "instructions": [
+ "每一行生成一段独立 MP4 视频素材。",
+ "场景编号用于让同一主题的多个素材保持镜头差异。"
+ ],
+ "fields": [
+ {
+ "key": "scenePrompt",
+ "label": "场景描述",
+ "description": "需要生成的视频画面、主体、动作和镜头要求",
+ "valueType": "string",
+ "required": true,
+ "order": 1,
+ "presentation": {
+ "widget": "textarea",
+ "placeholder": "例如:现代办公室中的工作人员使用 AI 助手,自然光,缓慢推进镜头"
+ }
+ },
+ {
+ "key": "aspectRatio",
+ "label": "画面比例",
+ "description": "MoneyPrinterTurbo 最终成片使用的画面比例",
+ "valueType": "enum",
+ "enumValues": [
+ "9:16",
+ "16:9"
+ ],
+ "required": true,
+ "order": 2
+ },
+ {
+ "key": "sceneIndex",
+ "label": "场景编号",
+ "description": "同一批次中从 1 开始的场景序号",
+ "valueType": "string",
+ "required": true,
+ "order": 3
+ }
+ ],
+ "sampleRows": [
+ {
+ "values": {
+ "scenePrompt": "现代办公室中的工作人员使用 AI 助手,自然光,缓慢推进镜头,无文字无水印",
+ "aspectRatio": "9:16",
+ "sceneIndex": "1"
+ }
+ }
+ ]
+ },
+ "fieldBindings": [
+ {
+ "fieldKey": "aspectRatio",
+ "stepId": "stp_video01",
+ "paramKey": "aspect_ratio",
+ "bindMode": "shared"
+ }
+ ],
+ "paramBindings": [
+ {
+ "stepId": "stp_video01",
+ "paramKey": "prompt",
+ "bindMode": "shared",
+ "separator": "\n",
+ "sources": [
+ {
+ "kind": "field_ref",
+ "fieldKey": "scenePrompt"
+ },
+ {
+ "kind": "literal",
+ "literal": "场景编号:"
+ },
+ {
+ "kind": "field_ref",
+ "fieldKey": "sceneIndex"
+ }
+ ]
+ }
+ ]
+}
diff --git a/docs/loomloom/moneyprinterturbo-script-candidates.template.json b/docs/loomloom/moneyprinterturbo-script-candidates.template.json
new file mode 100644
index 00000000..90e2dd65
--- /dev/null
+++ b/docs/loomloom/moneyprinterturbo-script-candidates.template.json
@@ -0,0 +1,86 @@
+{
+ "meta": {
+ "name": "MoneyPrinterTurbo 批量文案候选",
+ "description": "根据视频主题批量生成可直接用于 MoneyPrinterTurbo 的文案与素材搜索词。",
+ "scenario": "short-video-script",
+ "inputSummary": "视频主题、生成要求和候选编号",
+ "primaryOutputType": "text",
+ "tags": ["MoneyPrinterTurbo", "短视频", "批量文案"]
+ },
+ "steps": [
+ {
+ "stepId": "stp_script01",
+ "displayName": "生成短视频文案与素材词",
+ "executionUnit": "text-generate",
+ "instruction": "你是短视频文案策划。根据输入生成一份适合目标时长的完整口播文案,并给出 5 到 10 个用于搜索视频素材的简短英文关键词。不同候选编号应采用不同的切入角度。只输出一个合法 JSON 对象,不要输出 Markdown、代码围栏、解释或 JSON 以外的文字。JSON 必须严格使用这个结构:{\"script\":\"完整文案\",\"videoTerms\":[\"keyword one\",\"keyword two\"]}。script 和 videoTerms 均不能为空。",
+ "defaultModelRef": {
+ "modelKey": "google/gemini-2.5-flash"
+ }
+ }
+ ],
+ "inputSchema": {
+ "instructions": [
+ "每一行生成一个独立文案候选。",
+ "candidateIndex 用于让同一主题的多个候选保持差异。"
+ ],
+ "fields": [
+ {
+ "key": "subject",
+ "label": "视频主题",
+ "description": "视频需要讲述的主题或核心观点",
+ "valueType": "string",
+ "required": true,
+ "order": 1,
+ "presentation": {
+ "widget": "textarea",
+ "placeholder": "例如:普通人如何用 AI 提高工作效率"
+ }
+ },
+ {
+ "key": "requirements",
+ "label": "生成要求",
+ "description": "输出语言、目标时长、风格以及其他附加要求",
+ "valueType": "string",
+ "required": true,
+ "order": 2,
+ "presentation": {
+ "widget": "textarea",
+ "placeholder": "输出语言:zh-CN\n目标时长(秒):60\n风格或附加要求:开头制造反差"
+ }
+ },
+ {
+ "key": "candidateIndex",
+ "label": "候选编号",
+ "description": "同一批次中从 1 开始的候选序号",
+ "valueType": "string",
+ "required": true,
+ "order": 3
+ }
+ ],
+ "sampleRows": [
+ {
+ "values": {
+ "subject": "普通人如何用 AI 提高工作效率",
+ "requirements": "输出语言:zh-CN\n目标时长(秒):60\n风格或附加要求:开头制造反差,结尾给出行动建议",
+ "candidateIndex": "1"
+ }
+ }
+ ]
+ },
+ "paramBindings": [
+ {
+ "stepId": "stp_script01",
+ "paramKey": "prompt",
+ "bindMode": "shared",
+ "separator": "\n",
+ "sources": [
+ {"kind": "literal", "literal": "视频主题:"},
+ {"kind": "field_ref", "fieldKey": "subject"},
+ {"kind": "literal", "literal": "生成要求:"},
+ {"kind": "field_ref", "fieldKey": "requirements"},
+ {"kind": "literal", "literal": "候选编号:"},
+ {"kind": "field_ref", "fieldKey": "candidateIndex"}
+ ]
+ }
+ ]
+}
diff --git a/docs/sponsors/shengsuanyun-logo.jpg b/docs/sponsors/shengsuanyun-logo.jpg
new file mode 100644
index 00000000..43058d42
Binary files /dev/null and b/docs/sponsors/shengsuanyun-logo.jpg differ
diff --git a/test/services/test_config.py b/test/services/test_config.py
index a213e62a..2397cf52 100644
--- a/test/services/test_config.py
+++ b/test/services/test_config.py
@@ -35,8 +35,20 @@ class TestConfigPersistence:
assert example_config["listen_host"] == "0.0.0.0"
assert example_config["listen_port"] == 8080
assert example_config["log_level"] == "DEBUG"
- assert app_config["video_source"] in {"pexels", "pixabay", "coverr", "local"}
+ assert app_config["video_source"] in {
+ "pexels",
+ "pixabay",
+ "coverr",
+ "loomloom",
+ "local",
+ }
assert "match_materials_to_script" in app_config
+ assert app_config["script_generation_backend"] == "local"
+ assert app_config["loomloom_api_token"] == ""
+ assert app_config["loomloom_video_run_timeout_seconds"] == 1800
+ assert "loomloom_market_listing_id" not in app_config
+ assert "loomloom_video_market_listing_id" not in app_config
+ assert app_config["shengsuanyun_api_key"] == ""
assert example_config["whisper"]["device"] == "cpu"
def test_example_config_covers_llm_provider_registry(self):
@@ -438,9 +450,7 @@ class TestConfigPersistence:
"pending-provider_api_key": "pending-key",
"pending-provider_model_name": "pending-model",
}
- original_values = {
- key: config.app.get(key, config._MISSING) for key in keys
- }
+ original_values = {key: config.app.get(key, config._MISSING) for key in keys}
updates_finished = threading.Event()
def queue_updates():
diff --git a/test/services/test_llm.py b/test/services/test_llm.py
index 065905c9..d377ed79 100644
--- a/test/services/test_llm.py
+++ b/test/services/test_llm.py
@@ -306,6 +306,7 @@ class TestLiteLLMProvider(unittest.TestCase):
"grok",
"minimax",
"mimo",
+ "shengsuanyun",
"cloudflare",
"modelscope",
"aihubmix",
@@ -326,6 +327,15 @@ class TestLiteLLMProvider(unittest.TestCase):
get_llm_provider("azure").default_label,
"Microsoft Azure OpenAI",
)
+ shengsuanyun = get_llm_provider("shengsuanyun")
+ self.assertEqual(
+ shengsuanyun.api_key_url,
+ "https://www.shengsuanyun.com/?from=CH_XUQ4OTSK",
+ )
+ self.assertEqual(
+ shengsuanyun.default_model,
+ "deepseek/deepseek-v4-flash",
+ )
def test_provider_registry_uses_conventional_locale_and_config_keys(self):
"""统一命名规则可避免 WebUI 为每个 Provider 增加硬编码映射。"""
diff --git a/test/services/test_loomloom.py b/test/services/test_loomloom.py
new file mode 100644
index 00000000..b56eddd5
--- /dev/null
+++ b/test/services/test_loomloom.py
@@ -0,0 +1,554 @@
+import json
+import os
+import tempfile
+import unittest
+from dataclasses import replace
+from pathlib import Path
+from unittest.mock import MagicMock, patch
+
+from app.services.loomloom import (
+ DEFAULT_BASE_URL,
+ DEFAULT_SCRIPT_MARKET_LISTING_ID,
+ DEFAULT_VIDEO_MARKET_LISTING_ID,
+ MAX_VIDEO_ARTIFACT_BYTES,
+ LoomLoomAPIError,
+ LoomLoomConfigurationError,
+ LoomLoomRun,
+ LoomLoomRunError,
+ LoomLoomScriptBackend,
+ LoomLoomSettings,
+ LoomLoomVideoBackend,
+ resolve_api_token,
+ video_settings_from_mapping,
+)
+
+
+class _Response:
+ def __init__(self, status_code, payload):
+ self.status_code = status_code
+ self._payload = payload
+
+ def json(self):
+ if isinstance(self._payload, Exception):
+ raise self._payload
+ return self._payload
+
+
+class _DownloadResponse:
+ status_code = 200
+
+ def __init__(self, *, headers=None):
+ self.headers = headers or {"content-length": "11"}
+ self.closed = False
+
+ def raise_for_status(self):
+ return None
+
+ def iter_content(self, chunk_size):
+ del chunk_size
+ return iter((b"video-bytes",))
+
+ def close(self):
+ self.closed = True
+
+
+class TestLoomLoomSettings(unittest.TestCase):
+ def test_requires_api_key_when_config_is_empty(self):
+ with self.assertRaisesRegex(
+ LoomLoomConfigurationError,
+ "loomloom_api_token",
+ ):
+ LoomLoomSettings.from_mapping({})
+
+ def test_does_not_read_api_key_from_process_environment(self):
+ with patch.dict(os.environ, {"SHENGSUANYUN_API_KEY": "environment-key"}):
+ self.assertEqual(resolve_api_token({}), "")
+
+ def test_selected_shengsuanyun_provider_reuses_its_api_key(self):
+ values = {
+ "llm_provider": "shengsuanyun",
+ "shengsuanyun_api_key": "provider-key",
+ "loomloom_api_token": "standalone-key",
+ }
+
+ self.assertEqual(resolve_api_token(values), "provider-key")
+
+ def test_uses_public_defaults_with_configured_api_key(self):
+ settings = LoomLoomSettings.from_mapping(
+ {"loomloom_api_token": "configured-key"},
+ )
+
+ self.assertEqual(settings.base_url, DEFAULT_BASE_URL)
+ self.assertEqual(settings.api_token, "configured-key")
+ self.assertEqual(settings.market_listing_id, DEFAULT_SCRIPT_MARKET_LISTING_ID)
+
+ def test_normalizes_settings_without_exposing_token(self):
+ settings = LoomLoomSettings.from_mapping(
+ {
+ "loomloom_base_url": "https://example.test/loom/v1/",
+ "loomloom_api_token": "secret-token",
+ "loomloom_market_listing_id": "listing-1",
+ }
+ )
+
+ self.assertEqual(settings.base_url, "https://example.test/loom/v1")
+ self.assertNotIn("secret-token", repr(settings))
+
+ def test_video_settings_use_fixed_default_skillbot(self):
+ settings = video_settings_from_mapping(
+ {
+ "loomloom_api_token": "secret-token",
+ "loomloom_market_listing_id": "ignored-user-listing",
+ }
+ )
+
+ self.assertEqual(settings.market_listing_id, DEFAULT_VIDEO_MARKET_LISTING_ID)
+ self.assertEqual(settings.run_timeout_seconds, 1800)
+
+
+class TestLoomLoomScriptBackend(unittest.TestCase):
+ def setUp(self):
+ self.settings = LoomLoomSettings(
+ base_url="https://example.test/loom/v1",
+ api_token="test-token",
+ market_listing_id="listing/1",
+ listing_version_id="version-1",
+ result_port_name="result",
+ poll_interval_seconds=0.01,
+ run_timeout_seconds=1,
+ )
+ self.session = MagicMock()
+ self.backend = LoomLoomScriptBackend(
+ self.settings,
+ session=self.session,
+ )
+
+ def test_prepares_one_independent_input_row_per_candidate(self):
+ batch = self.backend.prepare_script_batch(
+ subject="人工智能改变生活",
+ candidate_count=3,
+ language="zh-CN",
+ duration_seconds=45,
+ style="知识类",
+ )
+
+ self.assertEqual(len(batch.input_rows), 3)
+ self.assertEqual(batch.input_rows[0]["candidateIndex"], "1")
+ self.assertEqual(batch.input_rows[2]["candidateIndex"], "3")
+ self.assertEqual(
+ batch.input_rows[0]["requirements"],
+ "输出语言:zh-CN\n目标时长(秒):45\n风格或附加要求:知识类",
+ )
+ self.assertEqual(batch.input_rows[0]["subject"], "人工智能改变生活")
+
+ def test_quote_uses_market_listing_public_contract(self):
+ self.session.request.return_value = _Response(
+ 200,
+ {
+ "quoteId": "quote-1",
+ "listingVersionId": "version-1",
+ "currency": "CNY",
+ "taskCount": 2,
+ "estimatedBuyerPayableT": 12345,
+ "estimatedBuyerPayable": {"amount": "0.0012345", "currency": "CNY"},
+ },
+ )
+ batch = self.backend.prepare_script_batch(subject="主题", candidate_count=2)
+
+ result = self.backend.quote(batch)
+
+ self.assertEqual(result.quote_id, "quote-1")
+ self.assertEqual(result.task_count, 2)
+ self.assertEqual(result.estimated_buyer_payable_amount, "0.0012345")
+ request = self.session.request.call_args
+ self.assertEqual(request.args[0], "POST")
+ self.assertEqual(
+ request.args[1],
+ "https://example.test/loom/v1/marketListings/listing%2F1:quote",
+ )
+ self.assertEqual(
+ request.kwargs["headers"]["Authorization"], "Bearer test-token"
+ )
+ self.assertEqual(request.kwargs["json"]["listingVersionId"], "version-1")
+ self.assertEqual(len(request.kwargs["json"]["inputRows"]), 2)
+
+ def test_execute_requires_explicit_confirmation_before_network(self):
+ batch = self.backend.prepare_script_batch(subject="主题", candidate_count=1)
+
+ with self.assertRaisesRegex(ValueError, "confirm=True"):
+ self.backend.execute(
+ batch,
+ client_request_id="request-1",
+ listing_version_id="version-1",
+ confirm=False,
+ )
+
+ self.session.request.assert_not_called()
+
+ def test_execute_sends_stable_request_id_and_returns_run(self):
+ self.session.request.return_value = _Response(
+ 201,
+ {
+ "runId": "run-1",
+ "runTransactionId": "transaction-1",
+ "transactionStatus": "running",
+ "listingVersionId": "version-1",
+ },
+ )
+ batch = self.backend.prepare_script_batch(subject="主题", candidate_count=1)
+
+ result = self.backend.execute(
+ batch,
+ client_request_id="request-1",
+ listing_version_id="quoted-version-1",
+ confirm=True,
+ )
+
+ self.assertEqual(result.run_id, "run-1")
+ payload = self.session.request.call_args.kwargs["json"]
+ self.assertEqual(payload["clientRequestId"], "request-1")
+ self.assertEqual(payload["listingVersionId"], "quoted-version-1")
+ self.assertIs(payload["confirm"], True)
+
+ def test_execute_retries_transient_failure_with_same_idempotency_key(self):
+ self.session.request.side_effect = [
+ _Response(503, {"error": "temporarily unavailable"}),
+ _Response(
+ 201,
+ {
+ "runId": "run-1",
+ "runTransactionId": "transaction-1",
+ "transactionStatus": "running",
+ "listingVersionId": "version-1",
+ },
+ ),
+ ]
+ self.backend._sleep = MagicMock()
+ batch = self.backend.prepare_script_batch(subject="主题", candidate_count=1)
+
+ result = self.backend.execute(
+ batch,
+ client_request_id="stable-request-id",
+ listing_version_id="quoted-version-1",
+ confirm=True,
+ )
+
+ self.assertEqual(result.run_id, "run-1")
+ self.assertEqual(self.session.request.call_count, 2)
+ request_ids = [
+ call.kwargs["json"]["clientRequestId"]
+ for call in self.session.request.call_args_list
+ ]
+ self.assertEqual(request_ids, ["stable-request-id", "stable-request-id"])
+ self.backend._sleep.assert_called_once_with(1.0)
+
+ def test_request_can_use_a_per_user_credential_provider(self):
+ settings = LoomLoomSettings(
+ base_url="https://example.test/loom/v1",
+ api_token="",
+ market_listing_id="listing-1",
+ )
+ session = MagicMock()
+ session.request.return_value = _Response(
+ 200,
+ {
+ "quoteId": "quote-1",
+ "listingVersionId": "version-1",
+ "taskCount": 1,
+ "estimatedBuyerPayableT": 0,
+ },
+ )
+ backend = LoomLoomScriptBackend(
+ settings,
+ session=session,
+ credential_provider=lambda: "current-user-token",
+ )
+ batch = backend.prepare_script_batch(subject="主题", candidate_count=1)
+
+ backend.quote(batch)
+
+ self.assertEqual(
+ session.request.call_args.kwargs["headers"]["Authorization"],
+ "Bearer current-user-token",
+ )
+
+ def test_wait_for_run_polls_until_completed(self):
+ running = LoomLoomRun("run-1", "running", 1, 0, 0, 0, "")
+ completed = LoomLoomRun("run-1", "completed", 1, 1, 0, 0, "")
+ self.backend.get_run = MagicMock(side_effect=[running, completed])
+ self.backend._sleep = MagicMock()
+
+ result = self.backend.wait_for_run("run-1")
+
+ self.assertEqual(result.status, "completed")
+ self.backend._sleep.assert_called_once_with(0.01)
+
+ def test_wait_for_run_surfaces_terminal_failure(self):
+ failed = LoomLoomRun("run-1", "failed", 1, 0, 1, 0, "model timeout")
+ self.backend.get_run = MagicMock(return_value=failed)
+
+ with self.assertRaisesRegex(LoomLoomRunError, "model timeout"):
+ self.backend.wait_for_run("run-1")
+
+ def test_wait_for_run_recovers_from_transient_poll_failure(self):
+ completed = LoomLoomRun("run-1", "completed", 1, 1, 0, 0, "")
+ self.backend.get_run = MagicMock(
+ side_effect=[
+ LoomLoomAPIError("temporary", retryable=True),
+ completed,
+ ]
+ )
+ self.backend._clock = MagicMock(side_effect=[0, 0, 0, 0.1])
+ self.backend._sleep = MagicMock()
+
+ result = self.backend.wait_for_run("run-1")
+
+ self.assertEqual(result.status, "completed")
+ self.backend._sleep.assert_called_once_with(0.01)
+
+ def test_wait_for_run_logs_a_heartbeat_for_long_running_jobs(self):
+ running = LoomLoomRun("run-1", "running", 1, 0, 0, 0, "")
+ completed = LoomLoomRun("run-1", "completed", 1, 1, 0, 0, "")
+ self.backend.get_run = MagicMock(side_effect=[running, running, completed])
+ self.backend.settings = replace(self.backend.settings, run_timeout_seconds=100)
+ self.backend._clock = MagicMock(side_effect=[0, 0, 0, 31, 32])
+ self.backend._sleep = MagicMock()
+
+ with patch("app.services.loomloom.logger.info") as log_info:
+ result = self.backend.wait_for_run("run-1")
+
+ self.assertEqual(result.status, "completed")
+ self.assertEqual(log_info.call_count, 3)
+ self.assertIn("status=running", log_info.call_args_list[0].args[0])
+ self.assertIn("finished=1/1", log_info.call_args_list[-1].args[0])
+
+ def test_get_script_results_follows_pagination_and_ignores_step_id(self):
+ successful_artifact = {
+ "stepId": "internal-step-that-may-change",
+ "portName": "result",
+ "inlineText": json.dumps(
+ {
+ "script": "第一条脚本",
+ "videoTerms": ["人工智能", "日常生活"],
+ },
+ ensure_ascii=False,
+ ),
+ }
+ self.session.request.side_effect = [
+ _Response(
+ 200,
+ {
+ "items": [
+ {
+ "rowIndex": 0,
+ "status": "completed",
+ "artifacts": [successful_artifact],
+ }
+ ],
+ "nextPageToken": "page-2",
+ },
+ ),
+ _Response(
+ 200,
+ {
+ "items": [
+ {
+ "rowIndex": 1,
+ "status": "failed",
+ "errorMessage": "model timeout",
+ "artifacts": [],
+ }
+ ]
+ },
+ ),
+ ]
+
+ result = self.backend.get_script_results("run-1")
+
+ self.assertEqual(len(result.candidates), 1)
+ self.assertEqual(result.candidates[0].script, "第一条脚本")
+ self.assertEqual(result.candidates[0].video_terms, ("人工智能", "日常生活"))
+ self.assertEqual(result.errors[0].message, "model timeout")
+ second_request = self.session.request.call_args_list[1]
+ self.assertEqual(second_request.kwargs["params"]["pageToken"], "page-2")
+
+ def test_get_script_results_accepts_json_code_fence_from_model(self):
+ self.session.request.return_value = _Response(
+ 200,
+ {
+ "items": [
+ {
+ "rowIndex": 0,
+ "status": "completed",
+ "artifacts": [
+ {
+ "portName": "result",
+ "inlineText": (
+ "```json\n"
+ '{"script":"第一条脚本","videoTerms":["AI"]}\n'
+ "```"
+ ),
+ }
+ ],
+ }
+ ]
+ },
+ )
+
+ result = self.backend.get_script_results("run-1")
+
+ self.assertEqual(result.candidates[0].script, "第一条脚本")
+ self.assertEqual(result.candidates[0].video_terms, ("AI",))
+
+ def test_result_contract_requires_one_inline_json_result_artifact(self):
+ self.session.request.return_value = _Response(
+ 200,
+ {
+ "items": [
+ {
+ "rowIndex": 0,
+ "status": "completed",
+ "artifacts": [
+ {
+ "portName": "result",
+ "inlineText": '{"script":"missing terms"}',
+ }
+ ],
+ }
+ ]
+ },
+ )
+
+ result = self.backend.get_script_results("run-1")
+
+ self.assertEqual(result.candidates, ())
+ self.assertIn("videoTerms", result.errors[0].message)
+
+ def test_api_error_exposes_status_but_not_arbitrary_response_body(self):
+ self.session.request.return_value = _Response(
+ 402,
+ {"error": "insufficient balance", "sensitive": "do-not-copy"},
+ )
+ batch = self.backend.prepare_script_batch(subject="主题", candidate_count=1)
+
+ with self.assertRaisesRegex(
+ LoomLoomAPIError, "HTTP 402: insufficient balance"
+ ) as captured:
+ self.backend.quote(batch)
+
+ self.assertNotIn("do-not-copy", 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,
+ result_port_name="output",
+ )
+ self.session = MagicMock()
+ self.backend = LoomLoomVideoBackend(self.settings, session=self.session)
+
+ def test_prepares_one_video_row_per_scene(self):
+ """默认 SkillBot 必须按场景逐行报价,并携带固定的视频安全要求。"""
+ batch = self.backend.prepare_video_batch(
+ subject="AI 办公效率",
+ scene_prompts=["office worker", "AI assistant"],
+ 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"])
+
+ def test_downloads_video_artifact_without_forwarding_api_key(self):
+ """签名产物地址无需 Bearer Key,避免把账户凭证泄漏给对象存储。"""
+ self.session.request.return_value = _Response(
+ 200,
+ {
+ "items": [
+ {
+ "rowIndex": 0,
+ "status": "completed",
+ "artifacts": [
+ {
+ "portName": "output",
+ "mimeType": "video/mp4",
+ "accessUrl": "https://objects.test/video.mp4?signature=x",
+ }
+ ],
+ }
+ ]
+ },
+ )
+ response = _DownloadResponse()
+ self.session.get.return_value = response
+
+ with tempfile.TemporaryDirectory() as directory:
+ paths = self.backend.download_video_results("run-1", directory)
+ self.assertEqual(Path(paths[0]).read_bytes(), b"video-bytes")
+
+ self.session.get.assert_called_once_with(
+ "https://objects.test/video.mp4?signature=x",
+ stream=True,
+ timeout=(5.0, self.settings.request_timeout_seconds),
+ )
+ self.assertTrue(response.closed)
+
+ def test_closes_download_response_when_artifact_is_too_large(self):
+ """大小预检拒绝下载时也必须立即释放流式 HTTP 连接。"""
+ self.session.request.return_value = _Response(
+ 200,
+ {
+ "items": [
+ {
+ "rowIndex": 0,
+ "status": "completed",
+ "artifacts": [
+ {
+ "portName": "output",
+ "mimeType": "video/mp4",
+ "accessUrl": "https://objects.test/large.mp4",
+ }
+ ],
+ }
+ ]
+ },
+ )
+ response = _DownloadResponse(
+ headers={"content-length": str(MAX_VIDEO_ARTIFACT_BYTES + 1)}
+ )
+ self.session.get.return_value = response
+
+ with tempfile.TemporaryDirectory() as directory:
+ with self.assertRaisesRegex(LoomLoomAPIError, "download limit"):
+ self.backend.download_video_results("run-1", directory)
+
+ self.assertTrue(response.closed)
+
+ def test_rejects_non_video_result_artifact(self):
+ self.session.request.return_value = _Response(
+ 200,
+ {
+ "items": [
+ {
+ "rowIndex": 0,
+ "status": "completed",
+ "artifacts": [
+ {
+ "portName": "output",
+ "mimeType": "text/plain",
+ "accessUrl": "https://objects.test/result.txt",
+ }
+ ],
+ }
+ ]
+ },
+ )
+
+ with tempfile.TemporaryDirectory() as directory:
+ with self.assertRaisesRegex(LoomLoomAPIError, "video/mp4"):
+ self.backend.download_video_results("run-1", directory)
diff --git a/test/services/test_task.py b/test/services/test_task.py
index bb4f4e5f..5964563d 100644
--- a/test/services/test_task.py
+++ b/test/services/test_task.py
@@ -23,13 +23,14 @@ RUN_INTEGRATION_TESTS = os.environ.get("MPT_RUN_INTEGRATION_TESTS", "").lower()
"yes",
}
+
class TestTaskService(unittest.TestCase):
def setUp(self):
# 发布 Future 注册表是进程级状态。测试间清理可以避免某个模拟 Future
# 影响后续恢复测试,同时不会触碰真正线程池中的生产任务。
with tm._cross_post_registry_lock:
tm._cross_post_futures.clear()
-
+
def tearDown(self):
with tm._cross_post_registry_lock:
tm._cross_post_futures.clear()
@@ -75,7 +76,9 @@ class TestTaskService(unittest.TestCase):
custom_system_prompt="Only write short narration.",
)
- with patch.object(tm.llm, "generate_script", return_value="生成的文案") as generate:
+ with patch.object(
+ tm.llm, "generate_script", return_value="生成的文案"
+ ) as generate:
result = tm.generate_script("task-id", params)
self.assertEqual(result, "生成的文案")
@@ -178,9 +181,7 @@ class TestTaskService(unittest.TestCase):
self.assertEqual(warnings, [])
self.assertEqual(generate_bgm.call_args.kwargs["video_duration"], 5)
- self.assertEqual(
- generate_bgm.call_args.kwargs["prompt"], "gentle documentary"
- )
+ self.assertEqual(generate_bgm.call_args.kwargs["prompt"], "gentle documentary")
self.assertTrue(
generate_video.call_args.kwargs["bgm_file_override"].endswith(
"elevenlabs-bgm-1.mp3"
@@ -243,9 +244,7 @@ class TestTaskService(unittest.TestCase):
)
self.assertEqual(len(final_paths), 1)
- self.assertEqual(
- warnings, [{"code": "sonilo_bgm_failed", "video_index": 1}]
- )
+ self.assertEqual(warnings, [{"code": "sonilo_bgm_failed", "video_index": 1}])
self.assertEqual(generate_video.call_args.kwargs["bgm_file_override"], "")
def test_generate_final_videos_skips_sonilo_when_volume_is_zero(self):
@@ -301,12 +300,8 @@ class TestTaskService(unittest.TestCase):
)
self.assertEqual(len(final_paths), 1)
- self.assertEqual(
- warnings, [{"code": "sonilo_bgm_failed", "video_index": 1}]
- )
- self.assertTrue(
- generate.call_args.kwargs["bgm_file_override"].endswith(".m4a")
- )
+ self.assertEqual(warnings, [{"code": "sonilo_bgm_failed", "video_index": 1}])
+ self.assertTrue(generate.call_args.kwargs["bgm_file_override"].endswith(".m4a"))
def test_start_rejects_missing_sonilo_key_before_costly_pipeline_steps(self):
"""完整任务缺少 Sonilo Key 时不能先调用 LLM、TTS 或素材服务。"""
@@ -348,14 +343,159 @@ class TestTaskService(unittest.TestCase):
generate_script.assert_called_once_with("zero-volume-without-key", params)
self.assertEqual(result["failed_stage"], "script")
+ def test_loomloom_material_failure_keeps_remote_run_id(self):
+ """远端运行已创建后失败,任务状态必须保留 LoomLoom run ID。"""
+ params = VideoParams(video_subject="AI 办公", video_source="loomloom")
+ settings = tm.loomloom.LoomLoomSettings(
+ base_url="https://example.test/loom/v1",
+ api_token="test-token",
+ market_listing_id=tm.loomloom.DEFAULT_SCRIPT_MARKET_LISTING_ID,
+ )
+ batch = tm.loomloom.LoomLoomVideoBatch(
+ input_rows=(
+ {
+ "scenePrompt": "office worker",
+ "aspectRatio": "9:16",
+ "sceneIndex": "1",
+ },
+ ),
+ )
+ request = tm.loomloom.LoomLoomConfirmedVideoRequest(
+ settings=settings,
+ batch=batch,
+ listing_version_id="version-1",
+ client_request_id="mpt-video-1",
+ )
+ backend = MagicMock()
+ backend.execute.return_value = tm.loomloom.LoomLoomExecution(
+ run_id="run-1",
+ transaction_id="transaction-1",
+ transaction_status="running",
+ listing_version_id="version-1",
+ )
+ backend.wait_for_run.side_effect = tm.loomloom.LoomLoomRunError(
+ "remote run timeout"
+ )
+ state = MemoryState()
+ state.update_task(
+ "loomloom-material-timeout",
+ state=tm.const.TASK_STATE_PROCESSING,
+ progress=40,
+ )
+
+ with (
+ patch.object(tm.sm, "state", state),
+ patch.object(
+ tm.loomloom,
+ "LoomLoomVideoBackend",
+ return_value=backend,
+ ),
+ ):
+ result = tm.get_video_materials(
+ "loomloom-material-timeout",
+ params,
+ ["office worker"],
+ 10,
+ loomloom_video_request=request,
+ )
+
+ self.assertIsNone(result)
+ failed_task = state.get_task("loomloom-material-timeout")
+ self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
+ self.assertEqual(failed_task["failed_stage"], "materials")
+ self.assertEqual(failed_task["loomloom_run_id"], "run-1")
+ self.assertEqual(failed_task["loomloom_listing_version_id"], "version-1")
+
+ def test_loomloom_state_failure_does_not_abandon_paid_remote_run(self):
+ """状态后端不可用时仍需等待并下载已经开始计费的远端任务。"""
+ params = VideoParams(video_subject="AI 办公", video_source="loomloom")
+ settings = tm.loomloom.LoomLoomSettings(
+ base_url="https://example.test/loom/v1",
+ api_token="test-token",
+ market_listing_id=tm.loomloom.DEFAULT_VIDEO_MARKET_LISTING_ID,
+ )
+ request = tm.loomloom.LoomLoomConfirmedVideoRequest(
+ settings=settings,
+ batch=tm.loomloom.LoomLoomVideoBatch(
+ input_rows=(
+ {
+ "scenePrompt": "office worker",
+ "aspectRatio": "9:16",
+ "sceneIndex": "1",
+ },
+ )
+ ),
+ listing_version_id="version-1",
+ client_request_id="mpt-video-state-failure",
+ )
+ backend = MagicMock()
+ backend.execute.return_value = tm.loomloom.LoomLoomExecution(
+ run_id="paid-run-1",
+ transaction_id="transaction-1",
+ transaction_status="running",
+ listing_version_id="version-1",
+ )
+ backend.download_video_results.return_value = ("clip.mp4",)
+ unavailable_state = MagicMock()
+ unavailable_state.patch_task.side_effect = RuntimeError("Redis unavailable")
+
+ with (
+ patch.object(tm.sm, "state", unavailable_state),
+ patch.object(
+ tm.loomloom,
+ "LoomLoomVideoBackend",
+ return_value=backend,
+ ),
+ patch.object(tm.time, "sleep") as sleep,
+ ):
+ result = tm.get_video_materials(
+ "loomloom-state-failure",
+ params,
+ ["office worker"],
+ 10,
+ loomloom_video_request=request,
+ )
+
+ self.assertEqual(result, ["clip.mp4"])
+ self.assertEqual(
+ unavailable_state.patch_task.call_count,
+ tm._LOOMLOOM_STATE_WRITE_ATTEMPTS,
+ )
+ self.assertEqual(
+ sleep.call_count,
+ tm._LOOMLOOM_STATE_WRITE_ATTEMPTS - 1,
+ )
+ backend.wait_for_run.assert_called_once_with("paid-run-1")
+ backend.download_video_results.assert_called_once()
+
+ def test_mark_task_failed_preserves_a_specific_service_failure(self):
+ """服务层已记录具体错误时,编排层不能再用通用错误覆盖它。"""
+ state = MemoryState()
+ state.update_task(
+ "specific-service-failure",
+ state=tm.const.TASK_STATE_FAILED,
+ progress=40,
+ failed_stage="materials",
+ error="remote run timed out",
+ loomloom_run_id="run-1",
+ )
+
+ with patch.object(tm.sm, "state", state):
+ result = tm._mark_task_failed(
+ "specific-service-failure",
+ "materials",
+ "failed to prepare video materials",
+ )
+
+ self.assertEqual(result["error"], "remote run timed out")
+ self.assertEqual(result["loomloom_run_id"], "run-1")
+
def test_start_rejects_missing_elevenlabs_key_before_pipeline_steps(self):
"""完整任务缺少 ElevenLabs Key 时必须在任何付费步骤前失败。"""
params = VideoParams(video_subject="test", bgm_type="elevenlabs")
state = MemoryState()
with (
- patch.object(
- tm.elevenlabs_music, "is_enabled", return_value=False
- ),
+ patch.object(tm.elevenlabs_music, "is_enabled", return_value=False),
patch.object(tm, "generate_script") as generate_script,
patch.object(tm, "generate_audio") as generate_audio,
patch.object(tm.sm, "state", state),
@@ -373,9 +513,7 @@ class TestTaskService(unittest.TestCase):
params = VideoParams(video_subject="test", bgm_type="elevenlabs")
state = MemoryState()
with (
- patch.object(
- tm.elevenlabs_music, "is_enabled", return_value=True
- ),
+ patch.object(tm.elevenlabs_music, "is_enabled", return_value=True),
patch.object(
tm.elevenlabs_music,
"validate_generation_access",
@@ -406,9 +544,7 @@ class TestTaskService(unittest.TestCase):
)
state = MemoryState()
with (
- patch.object(
- tm.elevenlabs_music, "is_enabled", return_value=True
- ),
+ patch.object(tm.elevenlabs_music, "is_enabled", return_value=True),
patch.object(
tm.elevenlabs_music, "validate_generation_access"
) as validate_access,
@@ -433,7 +569,9 @@ class TestTaskService(unittest.TestCase):
match_materials_to_script=True,
)
- with patch.object(tm.llm, "generate_terms", return_value=["city", "train"]) as generate:
+ with patch.object(
+ tm.llm, "generate_terms", return_value=["city", "train"]
+ ) as generate:
result = tm.generate_terms("task-id", params, "先城市,再地铁")
self.assertEqual(result, ["city", "train"])
@@ -476,7 +614,7 @@ class TestTaskService(unittest.TestCase):
self.assertEqual(failed_task["state"], tm.const.TASK_STATE_FAILED)
self.assertEqual(failed_task["failed_stage"], "terms")
self.assertTrue(failed_task["error"])
-
+
def test_generate_audio_uses_custom_file_inside_task_directory(self):
task_id = "test-custom-audio-safe"
task_dir = utils.task_dir(task_id)
@@ -612,7 +750,9 @@ class TestTaskService(unittest.TestCase):
shutil.rmtree(task_dir, ignore_errors=True)
self.assertTrue(subtitle_path.endswith("subtitle.srt"))
- create.assert_called_once_with(audio_file=audio_file, subtitle_file=subtitle_path)
+ create.assert_called_once_with(
+ audio_file=audio_file, subtitle_file=subtitle_path
+ )
correct.assert_called_once_with(
subtitle_file=subtitle_path, video_script="Hello world."
)
@@ -718,7 +858,9 @@ class TestTaskService(unittest.TestCase):
with self.subTest(stop_at=stop_at):
params = VideoParams(video_subject="Coffee")
with (
- patch.object(tm, "generate_script", return_value="generated script"),
+ patch.object(
+ tm, "generate_script", return_value="generated script"
+ ),
patch.object(
tm,
"generate_terms",
@@ -825,7 +967,9 @@ class TestTaskService(unittest.TestCase):
params = VideoParams(video_subject="Coffee")
state = MemoryState()
with (
- patch.object(tm, "generate_script", return_value="generated script"),
+ patch.object(
+ tm, "generate_script", return_value="generated script"
+ ),
patch.object(tm, "generate_terms", return_value=["coffee"]),
patch.object(tm, "save_script_data"),
patch.object(tm, "generate_audio", return_value=audio_result),
@@ -970,9 +1114,7 @@ class TestTaskService(unittest.TestCase):
self.assertEqual(call.kwargs["platforms"], ["youtube"])
# start() 返回的是视频完成时的稳定快照;后台发布结果通过任务查询获取。
- self.assertEqual(
- result["cross_post_state"], tm.const.CROSS_POST_STATE_PENDING
- )
+ self.assertEqual(result["cross_post_state"], tm.const.CROSS_POST_STATE_PENDING)
self.assertIsNone(result["cross_post_results"])
published_task = state.get_task("youtube-cross-post")
self.assertEqual(published_task["state"], tm.const.TASK_STATE_COMPLETE)
@@ -1124,9 +1266,7 @@ class TestTaskService(unittest.TestCase):
result = tm.start("cross-post-queue-full-result", params)
submit.assert_not_called()
- self.assertEqual(
- result["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
- )
+ self.assertEqual(result["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
self.assertIn("queue is full", result["cross_post_error"])
persisted_task = state.get_task("cross-post-queue-full-result")
self.assertEqual(
@@ -1229,7 +1369,10 @@ class TestTaskService(unittest.TestCase):
self.assertEqual(sleep.call_count, 4)
self.assertEqual(log_exception.call_count, 2)
self.assertTrue(
- all("redis unavailable" in call.args[0] for call in log_exception.call_args_list)
+ all(
+ "redis unavailable" in call.args[0]
+ for call in log_exception.call_args_list
+ )
)
def test_cross_post_state_update_retries_transient_backend_failure(self):
@@ -1321,8 +1464,12 @@ class TestTaskService(unittest.TestCase):
self.assertEqual(recovered, 2)
stale_task = state.get_task("stale-pending")
- self.assertEqual(stale_task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
- self.assertEqual(stale_task["cross_post_error"], tm._INTERRUPTED_CROSS_POST_ERROR)
+ self.assertEqual(
+ stale_task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
+ )
+ self.assertEqual(
+ stale_task["cross_post_error"], tm._INTERRUPTED_CROSS_POST_ERROR
+ )
self.assertEqual(
state.get_task("active-processing")["cross_post_state"],
tm.const.CROSS_POST_STATE_PROCESSING,
@@ -1375,18 +1522,14 @@ class TestTaskService(unittest.TestCase):
patch.object(tm.os, "kill", side_effect=OSError("inspection failed")),
patch.object(tm.logger, "warning") as log_warning,
):
- self.assertTrue(
- tm._is_cross_post_owner_alive(f"{hostname}:987654:unknown")
- )
+ self.assertTrue(tm._is_cross_post_owner_alive(f"{hostname}:987654:unknown"))
self.assertIn("inspection failed", log_warning.call_args.args[0])
with (
patch.object(tm.os, "name", "nt"),
patch.object(tm, "_is_windows_process_alive", return_value=True) as probe,
):
- self.assertTrue(
- tm._is_cross_post_owner_alive(f"{hostname}:987654:windows")
- )
+ self.assertTrue(tm._is_cross_post_owner_alive(f"{hostname}:987654:windows"))
probe.assert_called_once_with(987654)
@unittest.skipUnless(os.name == "nt", "Windows process API test")
@@ -1482,9 +1625,7 @@ class TestTaskService(unittest.TestCase):
self.assertGreaterEqual(recovered, 1)
task = state.get_task(task_id)
self.assertEqual(task["videos"], ["final.mp4"])
- self.assertEqual(
- task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED
- )
+ self.assertEqual(task["cross_post_state"], tm.const.CROSS_POST_STATE_FAILED)
self.assertEqual(task["cross_post_error"], tm._INTERRUPTED_CROSS_POST_ERROR)
finally:
state.delete_task(task_id)
@@ -1543,13 +1684,15 @@ class TestTaskService(unittest.TestCase):
)
def test_task_local_materials(self):
task_id = "00000000-0000-0000-0000-000000000000"
- video_materials=[]
+ video_materials = []
for i in range(1, 4):
- video_materials.append(MaterialInfo(
- provider="local",
- url=os.path.join(resources_dir, f"{i}.png"),
- duration=0
- ))
+ video_materials.append(
+ MaterialInfo(
+ provider="local",
+ url=os.path.join(resources_dir, f"{i}.png"),
+ duration=0,
+ )
+ )
params = VideoParams(
video_subject="金钱的作用",
@@ -1579,11 +1722,11 @@ class TestTaskService(unittest.TestCase):
stroke_color="#000000",
stroke_width=1.5,
n_threads=2,
- paragraph_number=1
+ paragraph_number=1,
)
result = tm.start(task_id=task_id, params=params)
print(result)
-
+
if __name__ == "__main__":
unittest.main()
diff --git a/test/services/test_webui_i18n.py b/test/services/test_webui_i18n.py
index 35d358ea..34d34870 100644
--- a/test/services/test_webui_i18n.py
+++ b/test/services/test_webui_i18n.py
@@ -4,6 +4,7 @@ import re
import unittest
from pathlib import Path
+from app.models.llm_provider import get_llm_provider
from app.utils import utils
@@ -17,6 +18,39 @@ PROVIDER_TIPS_PREFIXES = (
LLM_PROVIDER_TIPS_PREFIX,
TTS_PROVIDER_TIPS_PREFIX,
)
+# Shengsuan Cloud 目前只提供中英文界面。次要语言统一回退英文,避免在七个
+# locale 中复制同一份英文后长期不同步;其它普通界面文案仍必须完整翻译。
+ENGLISH_FALLBACK_KEYS = frozenset(
+ {
+ "AI Video Quote Required",
+ "AI Video Quote Retained For Retry",
+ "AI Video Quote Summary",
+ "AI Video Quote Summary Singular",
+ "AI Video Scene Count",
+ "Confirm AI Video Charge",
+ "Confirm AI Video Charge Help",
+ "Confirm AI Video Charge Required",
+ "Local LLM Script Generation",
+ "llm_provider_label.shengsuanyun",
+ "LoomLoom Poll Retry Pending",
+ "LoomLoom Poll Retry Warning",
+ "Resume LoomLoom Status Check",
+ "LoomLoom Quote Summary Singular",
+ "LoomLoom Video Terms Reuse Help",
+ "Script Generation Method",
+ "Script Generation Method Help",
+ "Shengsuan Cloud AI Video",
+ "Shengsuan Cloud AI Video Help",
+ "Shengsuan Cloud API Key",
+ "Shengsuan Cloud API Key Help",
+ "Shengsuan Cloud API Key Placeholder",
+ "Shengsuan Cloud API Key Required",
+ "Shengsuan Cloud API Key Reused",
+ "Shengsuan Cloud Batch Script Generation",
+ "Stop Tracking LoomLoom Run",
+ "Stop Tracking LoomLoom Run Help",
+ }
+)
FORMAT_PLACEHOLDER_PATTERN = re.compile(r"(?<!\{)\{([a-zA-Z_][a-zA-Z0-9_]*)\}(?!\})")
MARKDOWN_URL_PATTERN = re.compile(r"\[[^\]]+\]\((https?://[^)]+)\)")
@@ -44,7 +78,12 @@ def _load_translation(locale):
def _required_translation_keys(translations):
"""返回二级语言必须维护的 key,Provider 长说明统一回退英文。"""
- return {key for key in translations if not key.startswith(PROVIDER_TIPS_PREFIXES)}
+ return {
+ key
+ for key in translations
+ if key not in ENGLISH_FALLBACK_KEYS
+ and not key.startswith(PROVIDER_TIPS_PREFIXES)
+ }
def _format_placeholders(value):
@@ -95,6 +134,24 @@ class TestWebuiI18n(unittest.TestCase):
self.assertEqual(sorted(visitor.keys - en_keys), [])
+ def test_shengsuanyun_provider_tips_keep_registration_and_model_links(self):
+ """合作入口和模型目录属于产品配置,避免后续改文案时误删追踪链接。"""
+ expected_urls = {
+ "https://www.shengsuanyun.com/?from=CH_XUQ4OTSK",
+ "https://global.modelmesh.info/model",
+ }
+
+ for locale in ("zh", "en"):
+ with self.subTest(locale=locale):
+ tips = _load_translation(locale)["llm_provider_tips.shengsuanyun"]
+ provider = get_llm_provider("shengsuanyun")
+ rendered = tips.format(
+ api_key_url=provider.api_key_url,
+ default_base_url=provider.default_base_url,
+ default_model=provider.default_model,
+ )
+ self.assertEqual(_markdown_urls(rendered), expected_urls)
+
def test_secondary_locales_cover_english_locale(self):
en_translations = _load_translation("en")
required_en_keys = _required_translation_keys(en_translations)
@@ -115,6 +172,12 @@ class TestWebuiI18n(unittest.TestCase):
)
self.assertEqual(duplicated_keys, [])
+ def test_secondary_locales_do_not_duplicate_english_fallback_keys(self):
+ for locale in SECONDARY_LOCALES:
+ with self.subTest(locale=locale):
+ locale_keys = set(_load_translation(locale))
+ self.assertEqual(sorted(ENGLISH_FALLBACK_KEYS & locale_keys), [])
+
def test_secondary_locales_cover_static_webui_labels(self):
tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))
visitor = _TrKeyVisitor()
@@ -123,7 +186,10 @@ class TestWebuiI18n(unittest.TestCase):
for locale in SECONDARY_LOCALES:
with self.subTest(locale=locale):
locale_keys = set(_load_translation(locale))
- self.assertEqual(sorted(visitor.keys - locale_keys), [])
+ self.assertEqual(
+ sorted(visitor.keys - locale_keys - ENGLISH_FALLBACK_KEYS),
+ [],
+ )
def test_secondary_locales_preserve_format_placeholders(self):
en_translations = _load_translation("en")
diff --git a/test/services/test_webui_loomloom.py b/test/services/test_webui_loomloom.py
new file mode 100644
index 00000000..9490c311
--- /dev/null
+++ b/test/services/test_webui_loomloom.py
@@ -0,0 +1,321 @@
+import ast
+import hashlib
+import json
+from pathlib import Path
+from unittest.mock import patch
+
+from streamlit.testing.v1 import AppTest
+
+from app.config import config
+from app.services import loomloom
+
+
+ROOT_DIR = Path(__file__).parent.parent.parent
+WEBUI_MAIN = ROOT_DIR / "webui" / "Main.py"
+
+
+def _function(tree, name):
+ return next(
+ node
+ for node in tree.body
+ if isinstance(node, ast.FunctionDef) and node.name == name
+ )
+
+
+def _widget_by_key(elements, key):
+ return next(item for item in elements if str(getattr(item, "key", "")) == key)
+
+
+def test_loomloom_execution_requires_confirmation_and_quoted_version():
+ tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))
+ function = _function(tree, "_render_loomloom_script_generation")
+ execute_calls = [
+ node
+ for node in ast.walk(function)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and node.func.attr == "execute"
+ ]
+
+ assert len(execute_calls) == 1
+ keywords = {keyword.arg: keyword.value for keyword in execute_calls[0].keywords}
+ assert isinstance(keywords["confirm"], ast.Constant)
+ assert keywords["confirm"].value is True
+ assert "client_request_id" in keywords
+ assert "listing_version_id" in keywords
+ assert any(
+ isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == "st"
+ and node.func.attr == "checkbox"
+ for node in ast.walk(function)
+ )
+
+
+def test_loomloom_path_does_not_fall_back_to_local_llm_calls():
+ tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))
+ loomloom_function = _function(tree, "_render_loomloom_script_generation")
+ local_function = _function(tree, "_render_local_script_generation")
+
+ def llm_calls(function):
+ return {
+ node.func.attr
+ for node in ast.walk(function)
+ if isinstance(node, ast.Call)
+ and isinstance(node.func, ast.Attribute)
+ and isinstance(node.func.value, ast.Name)
+ and node.func.value.id == "llm"
+ }
+
+ assert llm_calls(loomloom_function) == set()
+ assert {"generate_script", "generate_terms"} <= llm_calls(local_function)
+
+
+def test_loomloom_quote_signature_changes_with_billable_inputs():
+ tree = ast.parse(WEBUI_MAIN.read_text(encoding="utf-8"))
+ signature_function = _function(tree, "_loomloom_script_signature")
+ module = ast.fix_missing_locations(
+ ast.Module(body=[signature_function], type_ignores=[])
+ )
+ namespace = {"hashlib": hashlib, "json": json}
+ exec(compile(module, str(WEBUI_MAIN), "exec"), namespace)
+ signature = namespace["_loomloom_script_signature"]
+
+ original = signature(
+ subject="主题",
+ language="zh-CN",
+ candidate_count=3,
+ duration_seconds=60,
+ style="轻松",
+ credential_fingerprint="account-a",
+ )
+ repeated = signature(
+ subject="主题",
+ language="zh-CN",
+ candidate_count=3,
+ duration_seconds=60,
+ style="轻松",
+ credential_fingerprint="account-a",
+ )
+ changed = signature(
+ subject="主题",
+ language="zh-CN",
+ candidate_count=4,
+ duration_seconds=60,
+ style="轻松",
+ credential_fingerprint="account-a",
+ )
+ changed_credential = signature(
+ subject="主题",
+ language="zh-CN",
+ candidate_count=3,
+ duration_seconds=60,
+ style="轻松",
+ credential_fingerprint="account-b",
+ )
+
+ assert original == repeated
+ assert original != changed
+ assert original != changed_credential
+
+
+def test_loomloom_webui_quotes_then_requires_confirmation_before_execute():
+ test_config = dict(
+ config.app,
+ llm_provider="openai",
+ script_generation_backend="loomloom",
+ loomloom_base_url="https://example.test/loom/v1",
+ loomloom_api_token="test-token",
+ loomloom_market_listing_id="listing-1",
+ )
+ quote_result = loomloom.LoomLoomQuote(
+ quote_id="quote-1",
+ listing_version_id="listing-version-1",
+ currency="CNY",
+ task_count=3,
+ estimated_buyer_payable_t=12345,
+ estimated_buyer_payable_amount="0.0012345",
+ input_rows=(),
+ )
+ execution = loomloom.LoomLoomExecution(
+ run_id="run-1",
+ transaction_id="transaction-1",
+ transaction_status="running",
+ listing_version_id="listing-version-1",
+ )
+ running = loomloom.LoomLoomRun("run-1", "running", 3, 0, 0, 0, "")
+
+ with (
+ patch.object(config, "app", test_config),
+ patch.object(config, "try_save_config", return_value=True),
+ patch.object(
+ loomloom.LoomLoomScriptBackend,
+ "quote",
+ return_value=quote_result,
+ ) as quote_call,
+ patch.object(
+ loomloom.LoomLoomScriptBackend,
+ "execute",
+ return_value=execution,
+ ) as execute_call,
+ patch.object(
+ loomloom.LoomLoomScriptBackend,
+ "get_run",
+ return_value=running,
+ ),
+ ):
+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=30)
+ app.session_state["ui_language"] = "en"
+ app.run()
+
+ assert quote_call.call_count == 0
+ assert execute_call.call_count == 0
+
+ _widget_by_key(app.text_area, "video_subject").set_value("AI daily life").run()
+ _widget_by_key(app.text_input, "loomloom_user_api_token").set_value(
+ "user-token-1"
+ ).run()
+ _widget_by_key(app.button, "loomloom_quote_scripts").click().run()
+
+ assert quote_call.call_count == 1
+ execute_button = _widget_by_key(app.button, "loomloom_execute_scripts")
+ assert execute_button.disabled
+ assert execute_call.call_count == 0
+
+ _widget_by_key(app.text_input, "loomloom_user_api_token").set_value(
+ "user-token-2"
+ ).run()
+ assert _widget_by_key(app.button, "loomloom_execute_scripts").disabled
+
+ _widget_by_key(app.text_input, "loomloom_user_api_token").set_value(
+ "user-token-1"
+ ).run()
+ _widget_by_key(app.checkbox, "loomloom_confirm_charge").check().run()
+ execute_button = _widget_by_key(app.button, "loomloom_execute_scripts")
+ assert not execute_button.disabled
+ execute_button.click().run()
+
+ assert execute_call.call_count == 1
+ assert execute_call.call_args.kwargs["confirm"] is True
+ assert (
+ execute_call.call_args.kwargs["listing_version_id"] == "listing-version-1"
+ )
+ assert execute_call.call_args.kwargs["client_request_id"].startswith("mpt-")
+ assert app.session_state["loomloom_script_quote"] is None
+ assert app.session_state["loomloom_script_batch"] is None
+ 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,
+ 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-1",
+ listing_version_id="video-version-1",
+ currency="CNY",
+ task_count=1,
+ estimated_buyer_payable_t=1230000,
+ estimated_buyer_payable_amount="0.123",
+ input_rows=(),
+ )
+
+ with (
+ patch.object(config, "app", test_config),
+ patch.object(config, "try_save_config", return_value=True),
+ patch.object(
+ loomloom.LoomLoomVideoBackend,
+ "quote",
+ return_value=quote_result,
+ ) as quote_call,
+ patch("app.services.webui_task.submit_generation") as submit_generation,
+ ):
+ 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 helps people work faster."
+ ).run()
+ _widget_by_key(app.text_area, "video_terms").set_value(
+ "office worker, AI assistant, productive team"
+ ).run()
+ _widget_by_key(app.selectbox, "video_source_select_en").select("loomloom").run()
+ _widget_by_key(app.text_input, "loomloom_user_api_token").set_value(
+ "session-user-token"
+ ).run()
+ 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
+ _widget_by_key(app.checkbox, "loomloom_video_confirm_charge").check().run()
+ _widget_by_key(app.button, "generate_video_button").click().run()
+
+ assert submit_generation.call_count == 1
+ submitted_params = submit_generation.call_args.kwargs["params"]
+ video_request = submit_generation.call_args.kwargs["loomloom_video_request"]
+ assert "session-user-token" not in submitted_params.model_dump_json()
+ assert video_request.settings.api_token == "session-user-token"
+ assert "session-user-token" not in repr(video_request)
+ assert video_request.listing_version_id == "video-version-1"
+ assert video_request.client_request_id.startswith("mpt-video-")
+ assert app.session_state["loomloom_video_quote"] is None
+ 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",
+ loomloom_api_token="standalone-key",
+ )
+
+ with (
+ patch.object(config, "app", test_config),
+ 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.run()
+
+ assert all(item.key != "loomloom_user_api_token" for item in app.text_input)
+ assert any("reused" in str(item.value).lower() for item in app.caption)
+ assert [str(item.value) for item in app.exception] == []
+
+
+def test_paused_script_run_keeps_remote_id_until_user_stops_tracking():
+ test_config = dict(
+ config.app,
+ llm_provider="openai",
+ script_generation_backend="loomloom",
+ loomloom_base_url="https://example.test/loom/v1",
+ loomloom_api_token="configured-token",
+ loomloom_market_listing_id="script-listing",
+ )
+
+ with (
+ patch.object(config, "app", test_config),
+ 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["loomloom_run_id"] = "paid-run-1"
+ app.session_state["loomloom_run_error"] = "temporary network failure"
+ app.session_state["loomloom_poll_paused"] = True
+ app.run()
+
+ assert _widget_by_key(app.button, "loomloom_quote_scripts").disabled
+ assert _widget_by_key(app.button, "loomloom_resume_status_check")
+ _widget_by_key(app.button, "loomloom_stop_tracking_run").click().run()
+
+ assert app.session_state["loomloom_run_id"] == ""
+ assert not app.session_state["loomloom_poll_paused"]
+ assert [str(item.value) for item in app.exception] == []
diff --git a/webui/Main.py b/webui/Main.py
index dd7bef8e..50e154bf 100644
--- a/webui/Main.py
+++ b/webui/Main.py
@@ -8,6 +8,7 @@ import re
import shutil
import subprocess
import sys
+import time
import webbrowser
from collections.abc import Mapping
from datetime import datetime
@@ -42,7 +43,14 @@ from app.models.schema import (
VideoTransitionMode,
)
from app.services import bgm as bgm_service
-from app.services import cache_manager, llm, video, voice, webui_task
+from app.services import (
+ cache_manager,
+ llm,
+ loomloom,
+ video,
+ voice,
+ webui_task,
+)
from app.services import elevenlabs_music as elevenlabs_music_service
from app.services import sonilo as sonilo_service
from app.services import state as sm
@@ -88,6 +96,7 @@ ONBOARDING_TOUR_KEY = "mpt-onboarding-v1"
VOICE_MODE_TTS = "tts"
VOICE_MODE_UPLOAD = "upload"
VOICE_MODE_NONE = "none"
+LOOMLOOM_MAX_POLL_FAILURES = 5
# “默认”是 WebUI 专用哨兵,不会写入 config.toml,也不会传给 FFmpeg。
# 后端在 video_codec 未配置时继续采用稳定的 libx264;单独保留该哨兵可以区分
# “跟随项目默认策略”和“用户明确固定 libx264”,便于未来安全调整默认策略。
@@ -329,6 +338,28 @@ def _initialize_session_state():
# 最近一次从当前页面提交的任务。生成改为后台执行后,页面 Fragment
# 通过这个 ID 查询状态;刷新时不再依赖正在执行的旧页面脚本。
"current_generation_task_id": "",
+ # LoomLoom 询价与执行必须跨 Streamlit rerun 保留完全相同的输入和
+ # clientRequestId,避免网络重试产生重复付费任务。
+ "loomloom_script_batch": None,
+ "loomloom_script_quote": None,
+ "loomloom_script_input_signature": "",
+ "loomloom_client_request_id": "",
+ "loomloom_run_id": "",
+ "loomloom_run_status": "",
+ "loomloom_run_error": "",
+ "loomloom_poll_failure_count": 0,
+ "loomloom_poll_retry_after": 0.0,
+ "loomloom_poll_paused": False,
+ "loomloom_script_candidates": (),
+ "loomloom_candidate_errors": (),
+ "loomloom_selected_candidate": 0,
+ "loomloom_video_batch": None,
+ "loomloom_video_quote": None,
+ "loomloom_video_input_signature": "",
+ "loomloom_video_client_request_id": "",
+ "loomloom_video_confirm_charge": False,
+ # AI 视频按素材段计费,默认只生成一段,用户确认效果后再主动增加数量。
+ "loomloom_video_scene_count": 1,
}
for key, value in defaults.items():
st.session_state.setdefault(key, value)
@@ -339,7 +370,12 @@ _initialize_session_state()
def tr(key):
loc = locales.get(st.session_state["ui_language"], {})
- return loc.get("Translation", {}).get(key, key)
+ value = loc.get("Translation", {}).get(key)
+ if value is not None:
+ return value
+ # 新功能优先维护中英文。其它语言缺少单项翻译时统一回退英文,避免在多个
+ # locale 中复制相同英文后长期失去同步;英文也没有该键时才显示原始 key。
+ return locales.get("en", {}).get("Translation", {}).get(key, key)
# -----------------------------------------------------------------------------
@@ -2205,6 +2241,575 @@ def _render_settings_dialog():
# -----------------------------------------------------------------------------
+def _create_loomloom_script_backend():
+ """从当前 WebUI/config.toml 配置创建批量文案客户端。"""
+ app_config_snapshot = config.snapshot_config_with_pending(config.app)
+ settings = loomloom.LoomLoomSettings.from_mapping(app_config_snapshot)
+ return loomloom.LoomLoomScriptBackend(settings)
+
+
+def _create_loomloom_video_backend():
+ """使用项目默认 SkillBot 和当前有效凭证创建视频客户端。"""
+ app_config_snapshot = config.snapshot_config_with_pending(config.app)
+ settings = loomloom.video_settings_from_mapping(app_config_snapshot)
+ return loomloom.LoomLoomVideoBackend(settings)
+
+
+def _effective_loomloom_api_token():
+ """读取 WebUI 尚未落盘或 config.toml 中的胜算云 API Key。"""
+ app_config_snapshot = config.snapshot_config_with_pending(config.app)
+ return loomloom.resolve_api_token(app_config_snapshot)
+
+
+def _effective_script_generation_backend():
+ """读取包含 WebUI 待保存修改的文案生成方式。"""
+ app_config_snapshot = config.snapshot_config_with_pending(config.app)
+ backend = str(
+ app_config_snapshot.get("script_generation_backend", "local") or "local"
+ ).strip()
+ return backend if backend in {"local", "loomloom"} else "local"
+
+
+def _render_loomloom_api_token_input():
+ """仅在未选择胜算云 Provider 时显示独立 LoomLoom 密钥输入。"""
+ app_config_snapshot = config.snapshot_config_with_pending(config.app)
+ if str(app_config_snapshot.get("llm_provider", "") or "").lower() == "shengsuanyun":
+ st.caption(tr("Shengsuan Cloud API Key Reused"))
+ return loomloom.resolve_api_token(app_config_snapshot)
+
+ configured_token = loomloom.resolve_api_token(app_config_snapshot)
+ st.session_state.setdefault("loomloom_user_api_token", configured_token)
+ api_token = st.text_input(
+ tr("Shengsuan Cloud API Key"),
+ type="password",
+ key="loomloom_user_api_token",
+ help=tr("Shengsuan Cloud API Key Help"),
+ placeholder=tr("Shengsuan Cloud API Key Placeholder"),
+ ).strip()
+ _set_runtime_config("app", "loomloom_api_token", api_token)
+ return _effective_loomloom_api_token()
+
+
+def _loomloom_video_scene_prompts(video_terms, subject, scene_count):
+ """按素材关键词生成有限数量的场景描述,供视频模型逐段生成素材。"""
+ if isinstance(video_terms, str):
+ terms = [
+ term.strip() for term in re.split(r"[,,\n]", video_terms) if term.strip()
+ ]
+ elif isinstance(video_terms, list):
+ terms = [
+ str(term or "").strip() for term in video_terms if str(term or "").strip()
+ ]
+ else:
+ terms = []
+ fallback = str(subject or "").strip()
+ if not terms and fallback:
+ terms = [fallback]
+ if not terms:
+ return ()
+ return tuple(
+ (
+ terms[index % len(terms)]
+ if index < len(terms)
+ else f"{terms[index % len(terms)]}; alternative camera angle {index + 1}"
+ )
+ for index in range(int(scene_count))
+ )
+
+
+def _loomloom_video_signature(batch, credential_fingerprint):
+ """将全部计费输入和凭证摘要纳入签名,参数变化后强制重新报价。"""
+ payload = {
+ "inputRows": [dict(row) for row in batch.input_rows],
+ "credentialFingerprint": str(credential_fingerprint or "").strip(),
+ }
+ serialized = json.dumps(
+ payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")
+ )
+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
+
+
+def _current_loomloom_video_quote_context(params):
+ """根据当前页面参数构建默认 SkillBot 的视频报价批次。"""
+ token = _effective_loomloom_api_token()
+ 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:
+ 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
+ ),
+ )
+ except (loomloom.LoomLoomError, ValueError):
+ return None, ""
+ fingerprint = hashlib.sha256(token.encode("utf-8")).hexdigest()
+ return batch, _loomloom_video_signature(batch, fingerprint)
+
+
+def _render_loomloom_video_settings(params):
+ """渲染默认视频 SkillBot 的报价、报价失效和付费确认流程。"""
+ st.caption(tr("Shengsuan Cloud AI Video Help"))
+ if _effective_script_generation_backend() != "loomloom":
+ _render_loomloom_api_token_input()
+ elif (
+ str(
+ config.snapshot_config_with_pending(config.app).get("llm_provider", "")
+ or ""
+ ).lower()
+ == "shengsuanyun"
+ ):
+ st.caption(tr("Shengsuan Cloud API Key Reused"))
+
+ token = _effective_loomloom_api_token()
+
+ st.number_input(
+ tr("AI Video Scene Count"),
+ min_value=1,
+ max_value=loomloom.MAX_VIDEO_SCENES,
+ step=1,
+ key="loomloom_video_scene_count",
+ )
+ 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,
+ ):
+ try:
+ 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))
+ else:
+ st.session_state["loomloom_video_batch"] = batch
+ st.session_state["loomloom_video_quote"] = quote_result
+ st.session_state["loomloom_video_input_signature"] = input_signature
+ st.session_state["loomloom_video_client_request_id"] = (
+ f"mpt-video-{uuid4()}"
+ )
+ st.session_state["loomloom_video_confirm_charge"] = False
+ logger.info(
+ "LoomLoom video quote ready: "
+ f"tasks={quote_result.task_count}, currency={quote_result.currency}, "
+ f"estimated_payable_t={quote_result.estimated_buyer_payable_t}"
+ )
+
+ 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:
+ display_amount = (
+ quote_result.estimated_buyer_payable_amount
+ or 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,
+ )
+ )
+ quote_is_current = (
+ st.session_state.get("loomloom_video_input_signature") == input_signature
+ )
+ if not quote_is_current:
+ st.warning(tr("LoomLoom Quote Changed Warning"))
+ st.checkbox(
+ tr("Confirm AI Video Charge"),
+ key="loomloom_video_confirm_charge",
+ help=tr("Confirm AI Video Charge Help"),
+ disabled=not quote_is_current,
+ )
+
+
+def _loomloom_script_signature(
+ *,
+ subject,
+ language,
+ candidate_count,
+ duration_seconds,
+ style,
+ credential_fingerprint,
+):
+ payload = {
+ "subject": str(subject or "").strip(),
+ "language": str(language or "auto").strip() or "auto",
+ "candidateCount": int(candidate_count),
+ "durationSeconds": int(duration_seconds),
+ "style": str(style or "").strip(),
+ "credentialFingerprint": str(credential_fingerprint or "").strip(),
+ }
+ serialized = json.dumps(
+ payload, ensure_ascii=False, sort_keys=True, separators=(",", ":")
+ )
+ return hashlib.sha256(serialized.encode("utf-8")).hexdigest()
+
+
+def _render_local_script_generation(params):
+ """保留 MoneyPrinterTurbo 原有的本地 LLM 脚本生成路径。"""
+ if not st.button(
+ tr("Generate Video Script and Keywords"),
+ key="auto_generate_script",
+ use_container_width=True,
+ type="secondary",
+ icon=":material/auto_awesome:",
+ ):
+ return
+
+ if not params.video_subject:
+ st.toast(tr("Please Enter the Video Subject First"))
+ st.warning(tr("Please Enter the Video Subject First"))
+ return
+
+ with st.spinner(tr("Generating Video Script and Keywords")):
+
+ def generate_script_and_terms(app_config_snapshot):
+ script = llm.generate_script(
+ video_subject=params.video_subject,
+ language=params.video_language,
+ paragraph_number=params.paragraph_number,
+ video_script_prompt=params.video_script_prompt,
+ custom_system_prompt=params.custom_system_prompt,
+ app_config=app_config_snapshot,
+ )
+ terms = llm.generate_terms(
+ params.video_subject,
+ script,
+ amount=8 if params.match_materials_to_script else 5,
+ match_script_order=params.match_materials_to_script,
+ app_config=app_config_snapshot,
+ )
+ return script, terms
+
+ script, terms = _run_llm_read_operation(
+ "generate_script_and_terms",
+ generate_script_and_terms,
+ )
+ if "Error: " in script:
+ st.error(tr(script))
+ elif "Error: " in terms:
+ st.error(tr(terms))
+ else:
+ st.session_state["video_script"] = script
+ st.session_state["video_terms"] = ", ".join(terms)
+
+
+def _render_loomloom_candidates():
+ candidates = tuple(st.session_state.get("loomloom_script_candidates") or ())
+ errors = tuple(st.session_state.get("loomloom_candidate_errors") or ())
+ if errors:
+ st.warning(
+ tr("LoomLoom Candidate Errors").format(
+ count=len(errors),
+ details="; ".join(
+ f"#{error.row_index + 1}: {error.message}" for error in errors
+ ),
+ )
+ )
+ if not candidates:
+ return
+
+ selected_index = st.radio(
+ tr("Choose Script Candidate"),
+ options=list(range(len(candidates))),
+ key="loomloom_selected_candidate",
+ format_func=lambda index: (
+ f"#{candidates[index].row_index + 1} {candidates[index].script[:80]}"
+ ),
+ )
+ selected = candidates[selected_index]
+ st.code(selected.script, language=None, wrap_lines=True)
+ st.caption(", ".join(selected.video_terms))
+ if st.button(
+ tr("Use Selected Candidate"),
+ key="loomloom_apply_candidate",
+ type="primary",
+ use_container_width=True,
+ ):
+ st.session_state["video_script"] = selected.script
+ st.session_state["video_terms"] = ", ".join(selected.video_terms)
+ st.toast(tr("LoomLoom Candidate Applied"))
+
+
+def _handle_loomloom_poll_error(run_id, exc):
+ """对脚本任务轮询错误做有限退避,确定性错误立即停止轮询。"""
+ logger.warning(f"failed to poll LoomLoom run: run_id={run_id}, error={exc}")
+ failure_count = int(st.session_state.get("loomloom_poll_failure_count", 0) or 0) + 1
+ retryable = isinstance(exc, loomloom.LoomLoomAPIError) and exc.retryable
+ if not retryable or failure_count >= LOOMLOOM_MAX_POLL_FAILURES:
+ st.session_state["loomloom_run_error"] = str(exc)
+ st.session_state["loomloom_poll_failure_count"] = 0
+ st.session_state["loomloom_poll_retry_after"] = 0.0
+ # 查询失败不等于远端付费任务失败。保留 run_id 并暂停自动轮询,让用户
+ # 可以继续查询同一个任务;如果直接丢弃 ID 后重新提交,可能重复付费。
+ st.session_state["loomloom_poll_paused"] = True
+ st.rerun(scope="app")
+ return
+
+ retry_delay = min(2**failure_count, 30)
+ st.session_state["loomloom_poll_failure_count"] = failure_count
+ st.session_state["loomloom_poll_retry_after"] = time.monotonic() + retry_delay
+ st.warning(
+ tr("LoomLoom Poll Retry Warning").format(
+ attempt=failure_count,
+ max_attempts=LOOMLOOM_MAX_POLL_FAILURES,
+ )
+ )
+
+
[email protected](run_every="2s")
+def _render_loomloom_run_progress():
+ run_id = str(st.session_state.get("loomloom_run_id", "") or "").strip()
+ if not run_id or st.session_state.get("loomloom_poll_paused", False):
+ return
+ retry_after = float(st.session_state.get("loomloom_poll_retry_after", 0.0) or 0.0)
+ retry_wait_seconds = max(0, int(math.ceil(retry_after - time.monotonic())))
+ if retry_wait_seconds > 0:
+ st.info(
+ tr("LoomLoom Poll Retry Pending").format(
+ seconds=retry_wait_seconds,
+ )
+ )
+ return
+ try:
+ backend = _create_loomloom_script_backend()
+ run = backend.get_run(run_id)
+ except loomloom.LoomLoomError as exc:
+ _handle_loomloom_poll_error(run_id, exc)
+ return
+
+ st.session_state["loomloom_run_status"] = run.status
+ if run.status == "completed":
+ try:
+ result = backend.get_script_results(run_id)
+ except loomloom.LoomLoomError as exc:
+ _handle_loomloom_poll_error(run_id, exc)
+ return
+ st.session_state["loomloom_poll_failure_count"] = 0
+ st.session_state["loomloom_poll_retry_after"] = 0.0
+ st.session_state["loomloom_poll_paused"] = False
+ st.session_state["loomloom_script_candidates"] = result.candidates
+ st.session_state["loomloom_candidate_errors"] = result.errors
+ st.session_state["loomloom_selected_candidate"] = 0
+ st.session_state["loomloom_run_id"] = ""
+ st.rerun(scope="app")
+ return
+ if run.status in {"failed", "cancelled", "canceled"}:
+ st.session_state["loomloom_run_error"] = run.first_error_message or run.status
+ st.session_state["loomloom_run_id"] = ""
+ st.session_state["loomloom_poll_paused"] = False
+ st.rerun(scope="app")
+ return
+
+ st.session_state["loomloom_poll_failure_count"] = 0
+ st.session_state["loomloom_poll_retry_after"] = 0.0
+ st.info(
+ tr("LoomLoom Run Progress").format(
+ completed=run.completed_tasks,
+ total=run.total_tasks,
+ )
+ )
+
+
+def _render_loomloom_script_generation(params):
+ st.caption(tr("LoomLoom Batch Script Generation Help"))
+ effective_token = _render_loomloom_api_token_input()
+ if not effective_token:
+ st.warning(tr("Shengsuan Cloud API Key Required"))
+
+ candidate_col, duration_col = st.columns(2)
+ candidate_count = candidate_col.number_input(
+ tr("Script Candidate Count"),
+ min_value=1,
+ max_value=loomloom.MAX_SCRIPT_CANDIDATES,
+ value=3,
+ step=1,
+ key="loomloom_candidate_count",
+ )
+ duration_seconds = duration_col.number_input(
+ tr("Target Script Duration Seconds"),
+ min_value=10,
+ max_value=600,
+ value=60,
+ step=10,
+ key="loomloom_script_duration_seconds",
+ )
+ input_signature = _loomloom_script_signature(
+ subject=params.video_subject,
+ language=params.video_language,
+ candidate_count=candidate_count,
+ duration_seconds=duration_seconds,
+ style=params.video_script_prompt,
+ credential_fingerprint=(
+ hashlib.sha256(effective_token.encode("utf-8")).hexdigest()
+ if effective_token
+ else ""
+ ),
+ )
+
+ if st.button(
+ tr("Get LoomLoom Quote"),
+ key="loomloom_quote_scripts",
+ use_container_width=True,
+ type="secondary",
+ icon=":material/request_quote:",
+ disabled=not effective_token or bool(st.session_state.get("loomloom_run_id")),
+ ):
+ if not params.video_subject:
+ st.toast(tr("Please Enter the Video Subject First"))
+ st.warning(tr("Please Enter the Video Subject First"))
+ else:
+ try:
+ backend = _create_loomloom_script_backend()
+ batch = backend.prepare_script_batch(
+ subject=params.video_subject,
+ candidate_count=int(candidate_count),
+ language=params.video_language,
+ duration_seconds=int(duration_seconds),
+ style=params.video_script_prompt,
+ )
+ quote_result = backend.quote(batch)
+ except (loomloom.LoomLoomError, ValueError) as exc:
+ logger.warning(f"failed to quote LoomLoom scripts: error={exc}")
+ st.error(str(exc))
+ else:
+ st.session_state["loomloom_script_batch"] = batch
+ st.session_state["loomloom_script_quote"] = quote_result
+ st.session_state["loomloom_script_input_signature"] = input_signature
+ st.session_state["loomloom_client_request_id"] = f"mpt-{uuid4()}"
+ st.session_state["loomloom_run_id"] = ""
+ st.session_state["loomloom_run_status"] = "quoted"
+ st.session_state["loomloom_run_error"] = ""
+ st.session_state["loomloom_poll_failure_count"] = 0
+ st.session_state["loomloom_poll_retry_after"] = 0.0
+ st.session_state["loomloom_poll_paused"] = False
+ st.session_state["loomloom_script_candidates"] = ()
+ st.session_state["loomloom_candidate_errors"] = ()
+ st.session_state["loomloom_confirm_charge"] = False
+ logger.info(
+ "LoomLoom script quote ready: "
+ f"tasks={quote_result.task_count}, currency={quote_result.currency}, "
+ f"estimated_payable_t={quote_result.estimated_buyer_payable_t}"
+ )
+
+ quote_result = st.session_state.get("loomloom_script_quote")
+ batch = st.session_state.get("loomloom_script_batch")
+ if quote_result is not None and batch is not None:
+ display_amount = (
+ quote_result.estimated_buyer_payable_amount
+ or f"{quote_result.estimated_buyer_payable_t} T"
+ )
+ st.success(
+ tr(
+ "LoomLoom Quote Summary Singular"
+ if quote_result.task_count == 1
+ else "LoomLoom Quote Summary"
+ ).format(
+ tasks=quote_result.task_count,
+ amount=display_amount,
+ currency=quote_result.currency,
+ )
+ )
+ quote_is_current = (
+ st.session_state.get("loomloom_script_input_signature") == input_signature
+ )
+ if not quote_is_current:
+ st.warning(tr("LoomLoom Quote Changed Warning"))
+ confirm_charge = st.checkbox(
+ tr("Confirm LoomLoom Charge"),
+ key="loomloom_confirm_charge",
+ disabled=not quote_is_current,
+ )
+ run_in_progress = bool(st.session_state.get("loomloom_run_id"))
+ if st.button(
+ tr("Run LoomLoom Batch"),
+ key="loomloom_execute_scripts",
+ use_container_width=True,
+ type="primary",
+ disabled=(not quote_is_current or not confirm_charge or run_in_progress),
+ ):
+ try:
+ execution = _create_loomloom_script_backend().execute(
+ batch,
+ client_request_id=st.session_state["loomloom_client_request_id"],
+ listing_version_id=quote_result.listing_version_id,
+ confirm=True,
+ )
+ except (loomloom.LoomLoomError, ValueError) as exc:
+ logger.warning(f"failed to execute LoomLoom scripts: error={exc}")
+ st.error(str(exc))
+ else:
+ st.session_state["loomloom_run_id"] = execution.run_id
+ st.session_state["loomloom_run_status"] = "running"
+ st.session_state["loomloom_poll_paused"] = False
+ # 一次报价只允许启动一次付费批次。后台状态只依赖 run_id,提交
+ # 后即可丢弃报价与幂等请求 ID;失败后用户需要重新报价再重试。
+ st.session_state["loomloom_script_batch"] = None
+ st.session_state["loomloom_script_quote"] = None
+ st.session_state["loomloom_script_input_signature"] = ""
+ st.session_state["loomloom_client_request_id"] = ""
+ logger.info(
+ f"LoomLoom script run submitted: run_id={execution.run_id}, "
+ f"tasks={len(batch.input_rows)}"
+ )
+ st.toast(tr("LoomLoom Run Submitted"))
+
+ run_error = str(st.session_state.get("loomloom_run_error", "") or "").strip()
+ if run_error:
+ st.error(tr("LoomLoom Run Failed").format(error=run_error))
+ run_id = str(st.session_state.get("loomloom_run_id", "") or "").strip()
+ if run_id and st.session_state.get("loomloom_poll_paused", False):
+ retry_col, stop_col = st.columns(2)
+ if retry_col.button(
+ tr("Resume LoomLoom Status Check"),
+ key="loomloom_resume_status_check",
+ use_container_width=True,
+ type="secondary",
+ ):
+ st.session_state["loomloom_run_error"] = ""
+ st.session_state["loomloom_poll_failure_count"] = 0
+ st.session_state["loomloom_poll_retry_after"] = 0.0
+ st.session_state["loomloom_poll_paused"] = False
+ st.rerun(scope="app")
+ if stop_col.button(
+ tr("Stop Tracking LoomLoom Run"),
+ key="loomloom_stop_tracking_run",
+ use_container_width=True,
+ type="secondary",
+ help=tr("Stop Tracking LoomLoom Run Help"),
+ ):
+ # 这里只停止本地状态查询,不声称取消远端执行。用户确认放弃跟踪后
+ # 才清理 run_id,下一次付费运行仍需重新报价和确认。
+ st.session_state["loomloom_run_id"] = ""
+ st.session_state["loomloom_run_error"] = ""
+ st.session_state["loomloom_poll_paused"] = False
+ st.rerun(scope="app")
+ # 只有真实运行中的批次才启动两秒轮询,报价阶段和结果展示阶段不创建
+ # 定时 fragment,避免用户停留在页面时产生无意义的网络请求和 rerun。
+ if run_id and not st.session_state.get("loomloom_poll_paused", False):
+ _render_loomloom_run_progress()
+ _render_loomloom_candidates()
+
+
def _render_script_settings(panel, params):
"""渲染文案设置并更新生成参数。"""
with panel:
@@ -2238,6 +2843,23 @@ def _render_script_settings(panel, params):
# 同时避免样式误伤页面顶部的“基础设置”等其他折叠区域。
with st.container(key="advanced_settings_script"):
with st.expander(tr("Advanced Script Settings"), expanded=False):
+ script_backend_options = ["local", "loomloom"]
+ script_backend_labels = {
+ "local": tr("Local LLM Script Generation"),
+ "loomloom": tr("Shengsuan Cloud Batch Script Generation"),
+ }
+ 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"),
+ )
+ _set_runtime_config(
+ "app", "script_generation_backend", script_generation_backend
+ )
+
st.session_state.setdefault("paragraph_number_input", 1)
params.paragraph_number = st.slider(
tr("Script Paragraph Number"),
@@ -2292,56 +2914,22 @@ def _render_script_settings(panel, params):
)
)
- if st.button(
- tr("Generate Video Script and Keywords"),
- key="auto_generate_script",
- use_container_width=True,
- type="secondary",
- icon=":material/auto_awesome:",
- ):
- if not params.video_subject:
- # 视频主题是脚本生成的必要输入,提前拦截可以避免无意义的模型调用。
- st.toast(tr("Please Enter the Video Subject First"))
- st.warning(tr("Please Enter the Video Subject First"))
- else:
- with st.spinner(tr("Generating Video Script and Keywords")):
-
- def generate_script_and_terms(app_config_snapshot):
- script = llm.generate_script(
- video_subject=params.video_subject,
- language=params.video_language,
- paragraph_number=params.paragraph_number,
- video_script_prompt=params.video_script_prompt,
- custom_system_prompt=params.custom_system_prompt,
- app_config=app_config_snapshot,
- )
- terms = llm.generate_terms(
- params.video_subject,
- script,
- amount=8 if params.match_materials_to_script else 5,
- match_script_order=params.match_materials_to_script,
- app_config=app_config_snapshot,
- )
- return script, terms
-
- script, terms = _run_llm_read_operation(
- "generate_script_and_terms",
- generate_script_and_terms,
- )
- if "Error: " in script:
- st.error(tr(script))
- elif "Error: " in terms:
- st.error(tr(terms))
- else:
- st.session_state["video_script"] = script
- st.session_state["video_terms"] = ", ".join(terms)
+ if _effective_script_generation_backend() == "loomloom":
+ _render_loomloom_script_generation(params)
+ else:
+ _render_local_script_generation(params)
params.video_script = st.text_area(
tr("Video Script"),
help=tr("Video Script Help"),
height=180,
key="video_script",
)
- if st.button(
+ using_loomloom_scripts = (
+ _effective_script_generation_backend() == "loomloom"
+ )
+ if using_loomloom_scripts:
+ st.caption(tr("LoomLoom Video Terms Reuse Help"))
+ elif st.button(
tr("Generate Video Keywords"),
key="auto_generate_terms",
use_container_width=True,
@@ -2390,6 +2978,7 @@ def _render_video_settings(panel, params):
(tr("Pexels"), "pexels"),
(tr("Pixabay"), "pixabay"),
(tr("Coverr"), "coverr"),
+ (tr("Shengsuan Cloud AI Video"), "loomloom"),
(tr("Local file"), "local"),
]
@@ -2554,6 +3143,9 @@ def _render_video_settings(panel, params):
_delete_runtime_config("app", "video_codec")
else:
_set_runtime_config("app", "video_codec", selected_video_codec)
+
+ if params.video_source == "loomloom":
+ _render_loomloom_video_settings(params)
return uploaded_files
@@ -2961,9 +3553,7 @@ def _sync_minimax_tts_api_key_input():
widget_key = "minimax_tts_api_key_input"
configured_key = str(config.minimax_tts.get("api_key", "") or "").strip()
shared_key = str(
- config.app.get("minimax_api_key", "")
- or os.getenv("MINIMAX_API_KEY", "")
- or ""
+ config.app.get("minimax_api_key", "") or os.getenv("MINIMAX_API_KEY", "") or ""
).strip()
effective_key = configured_key or shared_key
had_widget_state = widget_key in st.session_state
@@ -3031,7 +3621,9 @@ def _render_minimax_tts_settings() -> tuple[list[str], dict[str, str]]:
if dedicated_key:
_set_runtime_config("minimax_tts", "base_url", minimax_tts_base_url)
- configured_model = config.minimax_tts.get("model_id", voice.MINIMAX_TTS_DEFAULT_MODEL)
+ configured_model = config.minimax_tts.get(
+ "model_id", voice.MINIMAX_TTS_DEFAULT_MODEL
+ )
if configured_model not in voice.MINIMAX_TTS_MODELS:
configured_model = voice.MINIMAX_TTS_DEFAULT_MODEL
minimax_tts_model = stable_selectbox(
@@ -3065,9 +3657,7 @@ def _render_minimax_tts_settings() -> tuple[list[str], dict[str, str]]:
minimax_tts_base_url,
available_voices,
)
- st.success(
- tr("MiniMax Voices Loaded").format(count=len(available_voices))
- )
+ st.success(tr("MiniMax Voices Loaded").format(count=len(available_voices)))
available_voices = _get_cached_minimax_voices(
effective_api_key,
@@ -3441,9 +4031,7 @@ def _render_audio_settings(panel, params):
minimax_voices = []
minimax_voice_labels = {}
if tts_mode_enabled and selected_tts_server == "minimax-tts":
- minimax_voices, minimax_voice_labels = (
- _render_minimax_tts_settings()
- )
+ minimax_voices, minimax_voice_labels = _render_minimax_tts_settings()
# 根据选择的TTS服务器获取声音列表
filtered_voices = []
@@ -4089,7 +4677,13 @@ def _render_generation_controls(
st.error(tr("Video Script and Subject Cannot Both Be Empty"))
st.stop()
- if params.video_source not in ["pexels", "pixabay", "coverr", "local"]:
+ if params.video_source not in [
+ "pexels",
+ "pixabay",
+ "coverr",
+ "loomloom",
+ "local",
+ ]:
_remove_active_generation_task(task_id)
st.error(tr("Please Select a Valid Video Source"))
st.stop()
@@ -4115,6 +4709,44 @@ def _render_generation_controls(
st.error(tr("Please Enter the Coverr API Key"))
st.stop()
+ loomloom_video_request = None
+ if params.video_source == "loomloom":
+ current_batch, current_signature = _current_loomloom_video_quote_context(
+ params
+ )
+ quoted_batch = st.session_state.get("loomloom_video_batch")
+ quote_result = st.session_state.get("loomloom_video_quote")
+ quote_is_current = bool(
+ current_batch is not None
+ and isinstance(quoted_batch, loomloom.LoomLoomVideoBatch)
+ and quote_result is not None
+ and st.session_state.get("loomloom_video_input_signature")
+ == current_signature
+ )
+ if not quote_is_current:
+ _remove_active_generation_task(task_id)
+ st.error(tr("AI Video Quote Required"))
+ st.stop()
+ if not st.session_state.get("loomloom_video_confirm_charge", False):
+ _remove_active_generation_task(task_id)
+ st.error(tr("Confirm AI Video Charge Required"))
+ st.stop()
+ try:
+ video_backend = _create_loomloom_video_backend()
+ loomloom_video_request = loomloom.LoomLoomConfirmedVideoRequest(
+ settings=video_backend.settings,
+ batch=current_batch,
+ listing_version_id=quote_result.listing_version_id,
+ client_request_id=st.session_state[
+ "loomloom_video_client_request_id"
+ ],
+ )
+ loomloom_video_request.validate()
+ except (loomloom.LoomLoomError, ValueError) as exc:
+ _remove_active_generation_task(task_id)
+ st.error(str(exc))
+ st.stop()
+
if (
params.bgm_type == "sonilo"
and bgm_service.should_use_bgm(params.bgm_type, params.bgm_volume)
@@ -4270,7 +4902,15 @@ def _render_generation_controls(
params=params,
capture_logs=not config.ui.get("hide_log", False),
voice_preview=reusable_voice_preview,
+ loomloom_video_request=loomloom_video_request,
)
+ if loomloom_video_request is not None:
+ # 一个报价只允许提交一次。后台请求自带稳定幂等 ID;提交成功后
+ # 清除页面报价,下一次生成必须重新询价和确认。
+ st.session_state["loomloom_video_batch"] = None
+ st.session_state["loomloom_video_quote"] = None
+ st.session_state["loomloom_video_input_signature"] = ""
+ st.session_state["loomloom_video_client_request_id"] = ""
except Exception:
_remove_active_generation_task(task_id)
st.error(tr("Video Generation Failed"))
diff --git a/webui/i18n/de.json b/webui/i18n/de.json
index d15ff339..4ce17622 100644
--- a/webui/i18n/de.json
+++ b/webui/i18n/de.json
@@ -23,6 +23,21 @@
"Preview Final Prompt": "Finalen Prompt anzeigen",
"Final Prompt Preview": "Vorschau des finalen Prompts",
"Generate Video Script and Keywords": "Skript & Keywords mit KI erstellen",
+ "LoomLoom Batch Script Generation Help": "LoomLoom erstellt mehrere unabhängige Skriptvarianten. Holen Sie zuerst ein Angebot ein; Ausführung und Abrechnung beginnen erst nach Bestätigung.",
+ "Script Candidate Count": "Anzahl der Skriptvarianten",
+ "Target Script Duration Seconds": "Zieldauer des Skripts (Sekunden)",
+ "Get LoomLoom Quote": "LoomLoom-Angebot abrufen",
+ "LoomLoom Quote Summary": "Dieser Lauf erstellt {tasks} Varianten für voraussichtlich {amount} {currency}.",
+ "LoomLoom Quote Changed Warning": "Thema oder Einstellungen wurden geändert. Bitte holen Sie ein neues Angebot ein.",
+ "Confirm LoomLoom Charge": "Ich bestätige das Angebot und die Belastung des aktuellen Guthabens",
+ "Run LoomLoom Batch": "Bestätigen und erstellen",
+ "LoomLoom Run Submitted": "LoomLoom-Stapellauf wurde gestartet",
+ "LoomLoom Run Progress": "LoomLoom erstellt: {completed}/{total} abgeschlossen",
+ "LoomLoom Run Failed": "LoomLoom-Stapellauf fehlgeschlagen: {error}",
+ "LoomLoom Candidate Errors": "{count} Varianten fehlgeschlagen: {details}",
+ "Choose Script Candidate": "Skriptvariante auswählen",
+ "Use Selected Candidate": "Dieses Skript und die Keywords verwenden",
+ "LoomLoom Candidate Applied": "Ausgewähltes Skript und Keywords übernommen",
"Auto Detect": "Automatisch erkennen",
"Video Script": "Videoskript (optional)",
"Video Script Help": "Leer lassen, um es per KI aus dem Videothema zu erstellen. Sinnvolle Zeichensetzung verbessert die Untertitel.",
diff --git a/webui/i18n/en.json b/webui/i18n/en.json
index e1b492d5..d4ad5e99 100644
--- a/webui/i18n/en.json
+++ b/webui/i18n/en.json
@@ -23,6 +23,31 @@
"Preview Final Prompt": "Preview Final Prompt",
"Final Prompt Preview": "Final Prompt Preview",
"Generate Video Script and Keywords": "Generate Script & Keywords with AI",
+ "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 Placeholder": "Enter an API Key",
+ "Shengsuan Cloud API Key Required": "Enter your Shengsuan Cloud API Key before generating AI video materials.",
+ "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.",
+ "Local LLM Script Generation": "Current LLM Provider",
+ "Shengsuan Cloud Batch Script Generation": "Shengsuan Cloud Batch (Paid)",
+ "Script Candidate Count": "Script Candidates",
+ "Target Script Duration Seconds": "Target Script Duration (seconds)",
+ "Get LoomLoom Quote": "Get LoomLoom Quote",
+ "LoomLoom Quote Summary": "This run will generate {tasks} candidates for an estimated {amount} {currency}.",
+ "LoomLoom Quote Summary Singular": "This run will generate 1 candidate for an estimated {amount} {currency}.",
+ "LoomLoom Quote Changed Warning": "The subject or generation settings changed. Get a new quote before running.",
+ "Confirm LoomLoom Charge": "I confirm this quote and authorize charging the current user's balance",
+ "Run LoomLoom Batch": "Confirm and Generate",
+ "LoomLoom Run Submitted": "LoomLoom batch run submitted",
+ "LoomLoom Run Progress": "LoomLoom is generating: {completed}/{total} completed",
+ "LoomLoom Run Failed": "LoomLoom batch run failed: {error}",
+ "LoomLoom Candidate Errors": "{count} candidates failed: {details}",
+ "Choose Script Candidate": "Choose a Script Candidate",
+ "Use Selected Candidate": "Use This Script and Keywords",
+ "LoomLoom Candidate Applied": "Selected script and keywords applied",
"Auto Detect": "Auto Detect",
"Video Script": "Video Script (Optional)",
"Video Script Help": "Leave blank to generate it with AI from the video subject. Proper punctuation helps generate subtitles.",
@@ -177,6 +202,7 @@
"LLM Provider": "LLM Provider",
"Recommended": "Recommended",
"llm_provider_label.moonshot": "Kimi / Moonshot AI (Recommended)",
+ "llm_provider_label.shengsuanyun": "Shengsuan Cloud",
"API Key": "API Key",
"Base Url": "Base Url",
"Account ID": "Account ID",
@@ -292,6 +318,7 @@
"llm_provider_tips.ollama": "##### Ollama Configuration\n- **API Key**: not required\n- **Base Url**: usually `http://localhost:11434/v1` for local runs or `http://host.docker.internal:11434/v1` for Docker{docker_hint}\n- **Model Name**: required; run `ollama list` and enter an installed model, such as `qwen:7b`",
"llm_provider_tips.ollama.docker_hint": "\n > Container environment detected. If Base Url is empty, `http://host.docker.internal:11434/v1` is used by default.\n",
"llm_provider_tips.openai": "##### OpenAI Configuration\n- **API Key**: create one on the [OpenAI Platform]({api_key_url})\n- **Base Url**: defaults to `{default_base_url}`; enter another endpoint when using a compatible service\n- **Model Name**: defaults to `{default_model}`; you can also enter another model ID available to your account\n> Accessing the official service may require a network proxy in some regions",
+ "llm_provider_tips.shengsuanyun": "##### Shengsuan Cloud Configuration\n- **API Key**: register and create one through the [Shengsuan Cloud API Key page]({api_key_url}); new MoneyPrinterTurbo users can receive a CNY 10 token voucher\n- **Base Url**: defaults to `{default_base_url}`\n- **Model Name**: defaults to `{default_model}`; [view the model list](https://global.modelmesh.info/model)\n\nWhen selected, LoomLoom script and video generation automatically reuse this API Key.",
"llm_provider_tips.aihubmix": "##### AIHubMix Configuration\n- **API Key**: create one in the [AIHubMix console]({api_key_url})\n- **Base Url**: defaults to `{default_base_url}`\n- **Model Name**: defaults to `{default_model}`; you can also enter another supported model ID",
"llm_provider_tips.aimlapi": "##### AIML API Configuration\n- **API Key**: create one at [AIML API]({api_key_url})\n- **Base Url**: defaults to `{default_base_url}`\n- **Model Name**: defaults to `{default_model}`; you can also enter another supported model ID",
"llm_provider_tips.evolink": "##### EvoLink Configuration\n- **API Key**: create one on [EvoLink]({api_key_url})\n- **Base Url**: defaults to `{default_base_url}`\n- **Model Name**: defaults to `{default_model}`; you can also enter another supported model ID",
@@ -309,6 +336,22 @@
"llm_provider_tips.cloudflare": "##### Cloudflare AI Gateway Configuration\n- **API Key**: create a token in the [Cloudflare dashboard]({api_key_url}) with `AI Gateway - Read`, `AI Gateway - Edit`, and `Workers AI - Read` permissions\n- **Account ID**: enter your Cloudflare account ID\n- **Gateway ID**: defaults to `{default_gateway_id}`; you can also enter an existing Gateway ID\n- **Base Url**: not required; the REST API endpoint is generated from the Account ID\n- **Model Name**: defaults to `{default_model}`; use the `provider/model` format for another model supported by AI Gateway",
"llm_provider_tips.minimax": "##### MiniMax Configuration\n- **API Key**: create one on the [China platform](https://platform.minimaxi.com/) or [international platform](https://platform.minimax.io/)\n- **Base Url**: use `https://api.minimaxi.com/v1` for China or `{default_base_url}` for international access (default)\n- **Model Name**: defaults to `{default_model}`; you can also enter another model ID available to your account\n\nMake sure the API Key and Base Url belong to the same platform, or authentication may fail.",
"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.",
+ "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}",
+ "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.",
+ "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.",
+ "LoomLoom Poll Retry Pending": "The service is temporarily unavailable. Retrying in {seconds} seconds...",
+ "LoomLoom Poll Retry Warning": "The service is temporarily unavailable. Status check {attempt}/{max_attempts} failed and will retry automatically.",
+ "Resume LoomLoom Status Check": "Resume Status Check",
+ "Stop Tracking LoomLoom Run": "Stop Tracking",
+ "Stop Tracking LoomLoom Run Help": "Stops local status checks only. It does not cancel a paid run that may still be active on Shengsuan Cloud.",
"llm_provider_tips.litellm": "##### LiteLLM Configuration\n- **API Key**: not entered here; configure the target Provider key through environment variables\n- **Base Url**: not required\n- **Model Name**: defaults to `{default_model}`; use the `provider/model` format and see the [Provider list](https://docs.litellm.ai/docs/providers)"
}
}
diff --git a/webui/i18n/es.json b/webui/i18n/es.json
index ed5260c0..3dedf085 100644
--- a/webui/i18n/es.json
+++ b/webui/i18n/es.json
@@ -23,6 +23,21 @@
"Preview Final Prompt": "Vista previa del prompt final",
"Final Prompt Preview": "Vista previa del prompt final",
"Generate Video Script and Keywords": "Generar guion y palabras clave con IA",
+ "LoomLoom Batch Script Generation Help": "LoomLoom genera varios guiones independientes. Obtén primero un presupuesto; la ejecución y el cobro comienzan solo tras confirmarlo.",
+ "Script Candidate Count": "Número de guiones candidatos",
+ "Target Script Duration Seconds": "Duración objetivo del guion (segundos)",
+ "Get LoomLoom Quote": "Obtener presupuesto de LoomLoom",
+ "LoomLoom Quote Summary": "Esta ejecución generará {tasks} candidatos por un coste estimado de {amount} {currency}.",
+ "LoomLoom Quote Changed Warning": "El tema o la configuración cambiaron. Obtén un nuevo presupuesto antes de ejecutar.",
+ "Confirm LoomLoom Charge": "Confirmo el presupuesto y autorizo el cargo al saldo del usuario actual",
+ "Run LoomLoom Batch": "Confirmar y generar",
+ "LoomLoom Run Submitted": "Tarea por lotes de LoomLoom enviada",
+ "LoomLoom Run Progress": "LoomLoom está generando: {completed}/{total} completados",
+ "LoomLoom Run Failed": "La tarea por lotes de LoomLoom falló: {error}",
+ "LoomLoom Candidate Errors": "Fallaron {count} candidatos: {details}",
+ "Choose Script Candidate": "Elegir un guion candidato",
+ "Use Selected Candidate": "Usar este guion y palabras clave",
+ "LoomLoom Candidate Applied": "Guion y palabras clave seleccionados aplicados",
"Auto Detect": "Detección automática",
"Video Script": "Guion del vídeo (opcional)",
"Video Script Help": "Déjalo vacío para generarlo con IA a partir del tema del vídeo. Una puntuación adecuada ayuda a generar los subtítulos.",
diff --git a/webui/i18n/id.json b/webui/i18n/id.json
index 804e7b99..9a3f503e 100644
--- a/webui/i18n/id.json
+++ b/webui/i18n/id.json
@@ -23,6 +23,21 @@
"Preview Final Prompt": "Pratinjau Prompt Akhir",
"Final Prompt Preview": "Pratinjau Prompt Akhir",
"Generate Video Script and Keywords": "Buat Skrip & Kata Kunci dengan AI",
+ "LoomLoom Batch Script Generation Help": "LoomLoom membuat beberapa kandidat skrip independen. Minta penawaran terlebih dahulu; eksekusi dan penagihan dimulai hanya setelah konfirmasi.",
+ "Script Candidate Count": "Jumlah Kandidat Skrip",
+ "Target Script Duration Seconds": "Durasi Target Skrip (detik)",
+ "Get LoomLoom Quote": "Dapatkan Penawaran LoomLoom",
+ "LoomLoom Quote Summary": "Proses ini akan membuat {tasks} kandidat dengan perkiraan biaya {amount} {currency}.",
+ "LoomLoom Quote Changed Warning": "Topik atau pengaturan berubah. Dapatkan penawaran baru sebelum menjalankan.",
+ "Confirm LoomLoom Charge": "Saya mengonfirmasi penawaran dan mengizinkan pemotongan saldo pengguna saat ini",
+ "Run LoomLoom Batch": "Konfirmasi dan Buat",
+ "LoomLoom Run Submitted": "Proses batch LoomLoom telah dikirim",
+ "LoomLoom Run Progress": "LoomLoom sedang membuat: {completed}/{total} selesai",
+ "LoomLoom Run Failed": "Proses batch LoomLoom gagal: {error}",
+ "LoomLoom Candidate Errors": "{count} kandidat gagal: {details}",
+ "Choose Script Candidate": "Pilih Kandidat Skrip",
+ "Use Selected Candidate": "Gunakan Skrip dan Kata Kunci Ini",
+ "LoomLoom Candidate Applied": "Skrip dan kata kunci terpilih diterapkan",
"Auto Detect": "Deteksi Otomatis",
"Video Script": "Skrip Video (Opsional)",
"Video Script Help": "Kosongkan untuk membuatnya dengan AI dari topik video. Tanda baca yang tepat membantu pembuatan subtitle.",
diff --git a/webui/i18n/pt.json b/webui/i18n/pt.json
index 96315886..7a3c9b57 100644
--- a/webui/i18n/pt.json
+++ b/webui/i18n/pt.json
@@ -23,6 +23,21 @@
"Preview Final Prompt": "Pré-visualizar prompt final",
"Final Prompt Preview": "Pré-visualização do prompt final",
"Generate Video Script and Keywords": "Gerar roteiro e palavras-chave com IA",
+ "LoomLoom Batch Script Generation Help": "O LoomLoom gera vários roteiros independentes. Obtenha primeiro uma cotação; a execução e a cobrança começam somente após a confirmação.",
+ "Script Candidate Count": "Quantidade de roteiros candidatos",
+ "Target Script Duration Seconds": "Duração alvo do roteiro (segundos)",
+ "Get LoomLoom Quote": "Obter cotação do LoomLoom",
+ "LoomLoom Quote Summary": "Esta execução gerará {tasks} candidatos por um custo estimado de {amount} {currency}.",
+ "LoomLoom Quote Changed Warning": "O tema ou as configurações mudaram. Obtenha uma nova cotação antes de executar.",
+ "Confirm LoomLoom Charge": "Confirmo a cotação e autorizo a cobrança no saldo do usuário atual",
+ "Run LoomLoom Batch": "Confirmar e gerar",
+ "LoomLoom Run Submitted": "Execução em lote do LoomLoom enviada",
+ "LoomLoom Run Progress": "O LoomLoom está gerando: {completed}/{total} concluídos",
+ "LoomLoom Run Failed": "A execução em lote do LoomLoom falhou: {error}",
+ "LoomLoom Candidate Errors": "{count} candidatos falharam: {details}",
+ "Choose Script Candidate": "Escolher um roteiro candidato",
+ "Use Selected Candidate": "Usar este roteiro e palavras-chave",
+ "LoomLoom Candidate Applied": "Roteiro e palavras-chave selecionados aplicados",
"Auto Detect": "Detectar Automaticamente",
"Video Script": "Roteiro do vídeo (opcional)",
"Video Script Help": "Deixe em branco para gerá-lo com IA a partir do tema do vídeo. Uma pontuação adequada ajuda a gerar as legendas.",
diff --git a/webui/i18n/ru.json b/webui/i18n/ru.json
index 2f88a7e9..27ef8877 100644
--- a/webui/i18n/ru.json
+++ b/webui/i18n/ru.json
@@ -23,6 +23,21 @@
"Preview Final Prompt": "Показать итоговый промпт",
"Final Prompt Preview": "Предпросмотр итогового промпта",
"Generate Video Script and Keywords": "Создать сценарий и ключевые слова с ИИ",
+ "LoomLoom Batch Script Generation Help": "LoomLoom создаёт несколько независимых вариантов сценария. Сначала получите расчёт; выполнение и списание начнутся только после подтверждения.",
+ "Script Candidate Count": "Количество вариантов сценария",
+ "Target Script Duration Seconds": "Целевая длительность сценария (секунды)",
+ "Get LoomLoom Quote": "Получить расчёт LoomLoom",
+ "LoomLoom Quote Summary": "Будет создано {tasks} вариантов, ориентировочная стоимость — {amount} {currency}.",
+ "LoomLoom Quote Changed Warning": "Тема или настройки изменились. Перед запуском получите новый расчёт.",
+ "Confirm LoomLoom Charge": "Я подтверждаю расчёт и разрешаю списание с баланса текущего пользователя",
+ "Run LoomLoom Batch": "Подтвердить и создать",
+ "LoomLoom Run Submitted": "Пакетная задача LoomLoom отправлена",
+ "LoomLoom Run Progress": "LoomLoom создаёт варианты: завершено {completed}/{total}",
+ "LoomLoom Run Failed": "Пакетная задача LoomLoom завершилась ошибкой: {error}",
+ "LoomLoom Candidate Errors": "Не удалось создать {count} вариантов: {details}",
+ "Choose Script Candidate": "Выберите вариант сценария",
+ "Use Selected Candidate": "Использовать этот сценарий и ключевые слова",
+ "LoomLoom Candidate Applied": "Выбранные сценарий и ключевые слова применены",
"Auto Detect": "Определить автоматически",
"Video Script": "Сценарий (необязательно)",
"Video Script Help": "Оставьте поле пустым, чтобы создать сценарий с помощью ИИ по теме видео. Правильная пунктуация помогает создавать субтитры.",
diff --git a/webui/i18n/tr.json b/webui/i18n/tr.json
index dabd3aeb..291520e4 100644
--- a/webui/i18n/tr.json
+++ b/webui/i18n/tr.json
@@ -23,6 +23,21 @@
"Preview Final Prompt": "Son Promptu Önizle",
"Final Prompt Preview": "Son Prompt Önizlemesi",
"Generate Video Script and Keywords": "AI ile Senaryo ve Anahtar Kelime Oluştur",
+ "LoomLoom Batch Script Generation Help": "LoomLoom birden fazla bağımsız senaryo adayı oluşturur. Önce fiyat teklifi alın; çalıştırma ve ücretlendirme yalnızca onaydan sonra başlar.",
+ "Script Candidate Count": "Senaryo Adayı Sayısı",
+ "Target Script Duration Seconds": "Hedef Senaryo Süresi (saniye)",
+ "Get LoomLoom Quote": "LoomLoom Fiyat Teklifi Al",
+ "LoomLoom Quote Summary": "Bu çalışma tahmini {amount} {currency} karşılığında {tasks} aday oluşturacak.",
+ "LoomLoom Quote Changed Warning": "Konu veya ayarlar değişti. Çalıştırmadan önce yeni bir teklif alın.",
+ "Confirm LoomLoom Charge": "Teklifi onaylıyor ve mevcut kullanıcı bakiyesinden ücret alınmasına izin veriyorum",
+ "Run LoomLoom Batch": "Onayla ve Oluştur",
+ "LoomLoom Run Submitted": "LoomLoom toplu çalışması gönderildi",
+ "LoomLoom Run Progress": "LoomLoom oluşturuyor: {completed}/{total} tamamlandı",
+ "LoomLoom Run Failed": "LoomLoom toplu çalışması başarısız: {error}",
+ "LoomLoom Candidate Errors": "{count} aday başarısız oldu: {details}",
+ "Choose Script Candidate": "Bir Senaryo Adayı Seçin",
+ "Use Selected Candidate": "Bu Senaryo ve Anahtar Kelimeleri Kullan",
+ "LoomLoom Candidate Applied": "Seçilen senaryo ve anahtar kelimeler uygulandı",
"Auto Detect": "Otomatik Algılama",
"Video Script": "Video Senaryosu (İsteğe Bağlı)",
"Video Script Help": "Video konusundan AI ile oluşturmak için boş bırakın. Doğru noktalama, altyazı oluşturmayı kolaylaştırır.",
diff --git a/webui/i18n/vi.json b/webui/i18n/vi.json
index e4769781..b0c2381f 100644
--- a/webui/i18n/vi.json
+++ b/webui/i18n/vi.json
@@ -23,6 +23,21 @@
"Preview Final Prompt": "Xem trước Prompt cuối",
"Final Prompt Preview": "Xem trước Prompt cuối",
"Generate Video Script and Keywords": "Tạo Kịch Bản & Từ Khóa Bằng AI",
+ "LoomLoom Batch Script Generation Help": "LoomLoom tạo nhiều phương án kịch bản độc lập. Hãy lấy báo giá trước; việc chạy và tính phí chỉ bắt đầu sau khi xác nhận.",
+ "Script Candidate Count": "Số phương án kịch bản",
+ "Target Script Duration Seconds": "Thời lượng kịch bản mục tiêu (giây)",
+ "Get LoomLoom Quote": "Lấy báo giá LoomLoom",
+ "LoomLoom Quote Summary": "Lần chạy này sẽ tạo {tasks} phương án với chi phí ước tính {amount} {currency}.",
+ "LoomLoom Quote Changed Warning": "Chủ đề hoặc cài đặt đã thay đổi. Hãy lấy báo giá mới trước khi chạy.",
+ "Confirm LoomLoom Charge": "Tôi xác nhận báo giá và cho phép trừ số dư của người dùng hiện tại",
+ "Run LoomLoom Batch": "Xác nhận và tạo",
+ "LoomLoom Run Submitted": "Đã gửi tác vụ hàng loạt LoomLoom",
+ "LoomLoom Run Progress": "LoomLoom đang tạo: hoàn tất {completed}/{total}",
+ "LoomLoom Run Failed": "Tác vụ hàng loạt LoomLoom thất bại: {error}",
+ "LoomLoom Candidate Errors": "Có {count} phương án thất bại: {details}",
+ "Choose Script Candidate": "Chọn một phương án kịch bản",
+ "Use Selected Candidate": "Dùng kịch bản và từ khóa này",
+ "LoomLoom Candidate Applied": "Đã áp dụng kịch bản và từ khóa đã chọn",
"Auto Detect": "Tự Động Phát Hiện",
"Video Script": "Kịch Bản Video (Không Bắt Buộc)",
"Video Script Help": "Để trống để AI tạo từ chủ đề video. Dấu câu hợp lý giúp tạo phụ đề chính xác hơn.",
diff --git a/webui/i18n/zh.json b/webui/i18n/zh.json
index bd601797..df2a0fce 100644
--- a/webui/i18n/zh.json
+++ b/webui/i18n/zh.json
@@ -23,6 +23,31 @@
"Preview Final Prompt": "预览最终提示词",
"Final Prompt Preview": "最终提示词预览",
"Generate Video Script and Keywords": "点击使用AI生成视频文案和关键词",
+ "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 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;胜算云批量生成会在确认报价后付费生成多个候选。",
+ "Local LLM Script Generation": "当前大模型 Provider",
+ "Shengsuan Cloud Batch Script Generation": "胜算云批量生成(付费)",
+ "Script Candidate Count": "文案候选数量",
+ "Target Script Duration Seconds": "目标文案时长(秒)",
+ "Get LoomLoom Quote": "获取 LoomLoom 报价",
+ "LoomLoom Quote Summary": "本次将生成 {tasks} 个候选,预计费用 {amount} {currency}。",
+ "LoomLoom Quote Summary Singular": "本次将生成 1 个候选,预计费用 {amount} {currency}。",
+ "LoomLoom Quote Changed Warning": "主题或生成设置已变化,请重新获取报价。",
+ "Confirm LoomLoom Charge": "我确认按上述报价执行并从当前用户余额扣费",
+ "Run LoomLoom Batch": "确认并批量生成",
+ "LoomLoom Run Submitted": "LoomLoom 批量任务已提交",
+ "LoomLoom Run Progress": "LoomLoom 正在生成:已完成 {completed}/{total}",
+ "LoomLoom Run Failed": "LoomLoom 批量任务失败:{error}",
+ "LoomLoom Candidate Errors": "有 {count} 个候选生成失败:{details}",
+ "Choose Script Candidate": "选择一个文案候选",
+ "Use Selected Candidate": "使用这个文案和关键词",
+ "LoomLoom Candidate Applied": "已应用选中的文案和关键词",
"Auto Detect": "自动检测",
"Video Script": "视频文案(可选)",
"Video Script Help": "可留空,由 AI 根据视频主题生成。合理使用标点断句有助于生成字幕。",
@@ -177,6 +202,7 @@
"LLM Provider": "大模型提供商",
"Recommended": "推荐",
"llm_provider_label.moonshot": "Kimi / Moonshot AI(推荐)",
+ "llm_provider_label.shengsuanyun": "胜算云",
"API Key": "API Key",
"Base Url": "Base Url",
"Account ID": "Account ID",
@@ -292,6 +318,7 @@
"llm_provider_tips.ollama": "##### Ollama 配置说明\n- **API Key**: 无需填写\n- **Base Url**: 本机运行时通常为 `http://localhost:11434/v1`;Docker 部署时通常为 `http://host.docker.internal:11434/v1`{docker_hint}\n- **Model Name**: 必填;运行 `ollama list` 查看本机已安装的模型,例如 `qwen:7b`",
"llm_provider_tips.ollama.docker_hint": "\n > 检测到容器环境,未配置 Base Url 时会默认使用 `http://host.docker.internal:11434/v1`\n",
"llm_provider_tips.openai": "##### OpenAI 配置说明\n- **API Key**: 在 [OpenAI Platform]({api_key_url}) 创建\n- **Base Url**: 默认 `{default_base_url}`;使用兼容服务时可填写对应地址\n- **Model Name**: 默认 `{default_model}`;也可以填写当前账号支持的其它模型 ID\n> 部分地区访问官方服务时可能需要配置网络代理",
+ "llm_provider_tips.shengsuanyun": "##### 胜算云配置说明\n- **API Key**: 通过 [胜算云 API Key 获取入口]({api_key_url}) 注册并创建;MoneyPrinterTurbo 新用户可领取 10 元 Token 券\n- **Base Url**: 默认 `{default_base_url}`\n- **Model Name**: 默认 `{default_model}`;[查看模型列表](https://global.modelmesh.info/model)\n\n选择胜算云后,文案和视频设置中的 LoomLoom 功能会自动复用此 API Key。",
"llm_provider_tips.aihubmix": "##### AIHubMix 配置说明\n- **API Key**: 在 [AIHubMix 控制台]({api_key_url}) 创建\n- **Base Url**: 默认 `{default_base_url}`\n- **Model Name**: 默认 `{default_model}`;也可以填写平台支持的其它模型 ID",
"llm_provider_tips.aimlapi": "##### AIML API 配置说明\n- **API Key**: 在 [AIML API]({api_key_url}) 创建\n- **Base Url**: 默认 `{default_base_url}`\n- **Model Name**: 默认 `{default_model}`;也可以填写平台支持的其它模型 ID",
"llm_provider_tips.evolink": "##### EvoLink 配置说明\n- **API Key**: 在 [EvoLink]({api_key_url}) 创建\n- **Base Url**: 默认 `{default_base_url}`\n- **Model Name**: 默认 `{default_model}`;也可以填写平台支持的其它模型 ID",
@@ -309,6 +336,22 @@
"llm_provider_tips.cloudflare": "##### Cloudflare AI Gateway 配置说明\n- **API Key**: 在 [Cloudflare 控制台]({api_key_url}) 创建 API Token,需要 `AI Gateway - Read`、`AI Gateway - Edit` 和 `Workers AI - Read` 权限\n- **Account ID**: 填写 Cloudflare 账号 ID\n- **Gateway ID**: 默认 `{default_gateway_id}`;也可以填写已创建的 Gateway ID\n- **Base Url**: 无需填写,程序会根据 Account ID 自动构造 REST API 地址\n- **Model Name**: 默认 `{default_model}`;使用 `provider/model` 格式填写 AI Gateway 支持的模型 ID",
"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 视频素材。请先获取报价并确认费用,再使用现有配音、字幕和剪辑流程合成成片。",
+ "AI Video Scene Count": "AI 视频素材段数",
+ "AI Video Quote Summary": "共 {tasks} 段 AI 视频素材,预计扣费:{amount} {currency}",
+ "AI Video Quote Summary Singular": "共 1 段 AI 视频素材,预计扣费:{amount} {currency}",
+ "Confirm AI Video Charge": "我已了解 AI 视频生成为付费服务",
+ "Confirm AI Video Charge Help": "执行将严格使用当前报价返回的 SkillBot 版本和幂等请求 ID,费用以页面展示的 LoomLoom 报价为准。",
+ "AI Video Quote Required": "请先获取与当前参数一致的胜算云 AI 视频报价。",
+ "Confirm AI Video Charge Required": "请确认胜算云 AI 视频生成费用后再生成视频。",
+ "AI Video Quote Retained For Retry": "生成失败,但本次报价和请求记录已保留。你可以安全重试同一请求,或重新获取报价。",
+ "LoomLoom Poll Retry Pending": "服务暂时不可用,将在 {seconds} 秒后重试...",
+ "LoomLoom Poll Retry Warning": "服务暂时不可用,第 {attempt}/{max_attempts} 次状态查询失败,稍后会自动重试。",
+ "Resume LoomLoom Status Check": "继续查询状态",
+ "Stop Tracking LoomLoom Run": "停止跟踪",
+ "Stop Tracking LoomLoom Run Help": "只停止本地状态查询,不会取消胜算云中可能仍在执行的付费任务。",
"llm_provider_tips.litellm": "##### LiteLLM 配置说明\n- **API Key**: 无需在此处填写;请通过环境变量配置目标 Provider 的密钥\n- **Base Url**: 无需填写\n- **Model Name**: 默认 `{default_model}`;使用 `provider/model` 格式,[查看 Provider 列表](https://docs.litellm.ai/docs/providers)"
}
}