利用 AI 大模型和自动化工作流,根据主题或关键词一键生成高清短视频。Generate HD short videos from a topic or keyword with an automated AI workflow.
Python ai-video-generatorcontent-creationffmpeginstagram-reelsllmpythonshort-videosubtitlestext-to-speechtiktokvideo-automationvideo-workflowworkflow-automationyoutube-shorts
feat(material): add OFox multi-model video provider
celeste1900ba49f3426da4
diff --git a/README-en.md b/README-en.mdindex 23175407..31c56267 100644--- a/README-en.md+++ b/README-en.md@@ -141,6 +141,7 @@ Thanks to [Kimi](https://platform.kimi.ai?track_id=track-f6b0a640d35c41deb03b247- [x] Supports your own **local assets** and free-to-use HD footage from **Pexels**, **Pixabay**, and **Coverr**- [x] Supports **AI-generated footage**: [WaveSpeed AI](https://wavespeed.ai) text-to-video models (Seedance by default) create brand-new visuals from your script keywords instead of relying on stock libraries- [x] Supports native **Volcano Engine Ark Seedance** text-to-video generation with configurable model/Endpoint ID, bounded polling, and paid-task confirmation+- [x] Supports native **OFox** multi-model text-to-video generation (Seedance, Wan, and more behind one API key) with bounded polling and paid-task confirmation- [x] Supports leading model providers including **Kimi / Moonshot AI**, **OpenAI**, **Anthropic Claude**, **Google Gemini**, **DeepSeek**, **Alibaba Cloud Qwen**, **Microsoft Azure OpenAI**, **ByteDance VolcEngine Ark**, **xAI Grok**, **MiniMax**, and **Xiaomi MiMo**, plus unified gateways, aggregators, and local runtimes such as **Cloudflare AI Gateway**, **Alibaba ModelScope**, **AIHubMix**, **AIML API**, **EvoLink**, **Ollama**, **OneAPI**, **LiteLLM**, **Groq**, and **Pollinations AI**- [x] Supports one-click **cross-platform publishing** to **TikTok**, **Instagram**, and **YouTube Shorts** after video generation- [x] Supports **exporting and importing generation settings** as a preset file, and backing up and restoring every **API key** from the settings dialog@@ -483,6 +484,24 @@ The first integration supports text-to-video only. Every submitted clip is a pai</details>+<details>+<summary>How do I use the OFox multi-model text-to-video provider?</summary>++Create an [OFox API key](https://ofox.ai), then configure under `[app]`:++```toml+[app]+ofox_api_key = "your-ofox-api-key"+ofox_text_to_video_model = "bytedance/seedance-2.0-fast"+ofox_base_url = "https://api.ofox.ai/v1"+```++When the dedicated config value is empty, the `OFOX_API_KEY` environment variable is used. Select **OFox AI Video** as the video source and explicitly confirm paid generation before starting. CLI users must add `--confirm-ofox-charge`. The model can be any text-to-video model from the OFox catalog (`GET /v1/models`), e.g. `alibaba/wan-2.7`; each model has its own supported duration range and resolutions, and out-of-range values are rejected by the API with a clear error before any task is created.++The first version supports text-to-video only. Each clip creates one asynchronous paid task; the program only polls the same task id, stops submitting new tasks whenever a paid task state is unknown, and generates just enough footage to cover the voiceover duration.++</details>+<details><summary>RuntimeError: No ffmpeg exe could be found</summary>diff --git a/README-ja.md b/README-ja.mdindex 558cf1f0..5a0fd873 100644--- a/README-ja.md+++ b/README-ja.md@@ -139,6 +139,7 @@- [x] ランダムまたはカスタムの **BGM** に対応し、音量も調整できます- [x] 手持ちの**ローカル素材**に加え、**Pexels**、**Pixabay**、**Coverr** の無料で使える高画質素材に対応- [x] ネイティブの **Volcano Engine Ark Seedance** テキスト動画生成に対応し、モデル/Endpoint ID、制限付きポーリング、有料タスク確認を設定できます+- [x] ネイティブの **OFox** マルチモデルテキスト動画生成に対応(1 つの API キーで Seedance や Wan などを利用可能)。制限付きポーリングと有料タスク確認も同様に提供します- [x] **Kimi / Moonshot AI**、**OpenAI**、**Google Gemini**、**DeepSeek**、**Alibaba Cloud Qwen**、**Microsoft Azure OpenAI**、**ByteDance VolcEngine Ark**、**xAI Grok**、**MiniMax**、**Xiaomi MiMo** といった主要なモデルプロバイダーに加え、**Cloudflare AI Gateway**、**Alibaba ModelScope**、**AIHubMix**、**AIML API**、**EvoLink**、**Ollama**、**OneAPI**、**LiteLLM**、**Groq**、**Pollinations AI** などの統合ゲートウェイ、アグリゲーター、ローカルランタイムに対応- [x] 動画生成後、**TikTok**、**Instagram**、**YouTube Shorts** へワンクリックで**クロスプラットフォーム投稿**が可能- [x] 生成設定をプリセットファイルとして**エクスポート/インポート**でき、設定画面から **API キー**のバックアップと復元も可能@@ -461,6 +462,24 @@ Seedance 専用設定が空の場合は、`VOLCENGINE_ARK_API_KEY` 環境変数</details>+<details>+<summary>OFox のマルチモデルテキスト動画素材ソースを使うには?</summary>++[OFox API キー](https://ofox.ai)を作成し、`[app]` 配下に設定します:++```toml+[app]+ofox_api_key = "your-ofox-api-key"+ofox_text_to_video_model = "bytedance/seedance-2.0-fast"+ofox_base_url = "https://api.ofox.ai/v1"+```++専用設定が空の場合は、`OFOX_API_KEY` 環境変数を使用します。動画ソースで **OFox AI Video** を選び、生成前に有料タスクを明示的に確認してください。CLI では `--confirm-ofox-charge` も必要です。モデルは OFox カタログ(`GET /v1/models`)の任意のテキスト動画モデル(例:`alibaba/wan-2.7`)に変更できます。モデルごとに対応する動画長と解像度が異なり、範囲外の値はタスク作成前に API が明確なエラーで拒否します。++初版はテキスト動画のみ対応です。各クリップは非同期の有料タスクを 1 つ作成します。プログラムは同じタスク ID のみをポーリングし、状態が不明な場合は新規タスクの送信を停止し、ナレーションの長さを満たす分だけ生成します。++</details>+<details><summary>RuntimeError: No ffmpeg exe could be found</summary>diff --git a/README.md b/README.mdindex 2ea2c965..91097bd7 100644--- a/README.md+++ b/README.md@@ -151,6 +151,7 @@- [x] 支持使用自己的 **本地素材**,也可从 **Pexels**、**Pixabay** 和 **Coverr** 获取可免费使用的高清素材- [x] 支持 **AI 生成素材**:接入 [WaveSpeed AI](https://wavespeed.ai) 文生视频模型(默认 Seedance),按脚本关键词直接生成全新画面,不再受限于库存素材- [x] 原生支持 **火山引擎方舟 Seedance** 文生视频,可配置模型或推理接入点 ID,并提供有限轮询与付费任务确认+- [x] 原生支持 **OFox** 多模型文生视频(一个 Key 可调 Seedance、Wan 等模型),同样提供有限轮询与付费任务确认- [x] 支持 **Kimi / Moonshot AI**、**OpenAI**、**Anthropic Claude**、**Google Gemini**、**DeepSeek**、**阿里云通义千问**、**Microsoft Azure OpenAI**、**火山引擎方舟**、**xAI Grok**、**MiniMax**、**小米 MiMo** 等主流模型服务,并兼容 **Cloudflare AI Gateway**、**魔搭 ModelScope**、**AIHubMix**、**AIML API**、**EvoLink**、**Ollama**、**OneAPI**、**LiteLLM**、**Groq**、**Pollinations AI** 等统一网关、聚合平台和本地运行环境- [x] 支持一键 **跨平台发布**,生成完成后可自动上传至 **TikTok**、**Instagram** 和 **YouTube Shorts**- [x] 支持将生成设置**导出和导入**为预设文件,并在设置弹窗中备份和恢复所有 **API Key**@@ -478,6 +479,24 @@ Seedance 专用配置为空时,会依次使用 `VOLCENGINE_ARK_API_KEY` 环境</details>+<details>+<summary>如何使用 OFox 多模型文生视频素材源?</summary>++创建 [OFox API Key](https://ofox.ai),然后在 `[app]` 下配置:++```toml+[app]+ofox_api_key = "your-ofox-api-key"+ofox_text_to_video_model = "bytedance/seedance-2.0-fast"+ofox_base_url = "https://api.ofox.ai/v1"+```++专用配置为空时,会使用 `OFOX_API_KEY` 环境变量。在视频源中选择"OFox AI 视频",并在生成前明确确认付费任务;CLI 还需要传入 `--confirm-ofox-charge`。模型可换成 OFox 目录(`GET /v1/models`)中任意文生视频模型(如 `alibaba/wan-2.7`),不同模型支持的时长区间与分辨率不同,超出范围会在创建任务前被 API 明确拒绝。++首版仅支持文生视频。每个片段都会创建一个异步付费任务;程序只轮询同一个任务 ID,状态不明时停止继续下单,并仅生成足够覆盖配音时长的素材。++</details>+<details><summary>RuntimeError: No ffmpeg exe could be found</summary>diff --git a/app/services/material.py b/app/services/material.pyindex 818ceb3b..a2a24568 100644--- a/app/services/material.py+++ b/app/services/material.py@@ -17,7 +17,13 @@ from PIL import Image, UnidentifiedImageErrorfrom app.config import configfrom app.models.schema import MaterialInfo, VideoAspect, VideoConcatMode-from app.services import material_cache, task_artifacts, video, volcengine_seedance+from app.services import (+ material_cache,+ ofox,+ task_artifacts,+ video,+ volcengine_seedance,+)from app.utils import utils# Thread-safe counter for API key rotation@@ -1710,6 +1716,18 @@ def download_videos(max_clip_duration=max_clip_duration,material_directory=material_directory,)+ if source == "ofox":+ # 与 WaveSpeed/方舟相同的按需付费语义:OFox 网关的 /v1/videos 会创建+ # 异步付费任务,必须逐段生成、凑够所需时长立即停止;产物地址是会过+ # 期的临时直链,也不参与 24 小时搜索缓存。+ return _download_videos_ofox_on_demand(+ task_id=task_id,+ search_terms=search_terms,+ video_aspect=video_aspect,+ audio_duration=audio_duration,+ max_clip_duration=max_clip_duration,+ material_directory=material_directory,+ )if source == "openai_image":# 与 WaveSpeed 相同的按需付费语义:文生图按张计费,逐段生成、凑够# 所需时长立即停止。生成结果是一次性的本地图片文件,也不参与 24@@ -1990,6 +2008,111 @@ def _download_videos_seedance_on_demand(return video_paths+def _download_videos_ofox_on_demand(+ *,+ task_id: str,+ search_terms: List[str],+ video_aspect: VideoAspect,+ audio_duration: float,+ max_clip_duration: int,+ material_directory: str,+) -> List[str]:+ """顺序生成 OFox 素材,覆盖配音时长后立即停止付费下单。"""+ video_paths: List[str] = []+ material_sources: list[dict[str, Any]] = []++ # 付费生成循环必须先验证控制循环次数的两个时长。NaN/Infinity 会让+ # ``total_duration >= audio_duration`` 永远不成立,而非正片段时长会让+ # 累计值无法增长,两者都可能为全部关键词创建无用的付费任务。+ try:+ required_duration = float(audio_duration)+ except (TypeError, ValueError) as exc:+ raise ofox.OFoxError("OFox audio duration must be a finite number") from exc+ if not math.isfinite(required_duration):+ raise ofox.OFoxError("OFox audio duration must be a finite number")+ if required_duration <= 0:+ logger.warning(+ "skip OFox paid generation because required audio duration is "+ f"not positive: duration={required_duration}"+ )+ _persist_material_sources(task_id, material_sources)+ return video_paths++ try:+ clip_duration = int(max_clip_duration)+ except (TypeError, ValueError, OverflowError) as exc:+ raise ofox.OFoxError("OFox clip duration must be a positive integer") from exc+ if clip_duration <= 0:+ raise ofox.OFoxError("OFox clip duration must be a positive integer")++ total_duration = 0.0+ for search_term in search_terms:+ try:+ video_items = ofox.generate_videos(+ search_term=search_term,+ minimum_duration=clip_duration,+ video_aspect=video_aspect,+ )+ except ofox.OFoxUnconfirmedTaskError as exc:+ # 远端付费任务仍可能成功。立即停止继续下单,并保留任务 ID,方便+ # 用户随后在 OFox 控制台确认或找回结果。+ logger.error(+ "stop submitting new OFox tasks because the last paid task "+ f"is unconfirmed: task_id={exc.task_id or 'unknown'}, detail={exc}"+ )+ _persist_material_sources(task_id, material_sources)+ raise+ except ofox.OFoxError as exc:+ logger.error(f"OFox generation failed before completion: {exc}")+ _persist_material_sources(task_id, material_sources)+ raise++ # 单个关键词被远端明确判失败(如触发内容审核)时返回空列表:任务已+ # 结束、无计费悬念,跳过该片段继续生成后续关键词。+ for item in video_items:+ saved_video_path = _save_generated_video_with_retry(+ item.url, material_directory, "ofox"+ )+ if not saved_video_path:+ # 远端任务已完成并产生费用,本地下载失败时必须把远端任务 ID+ # 带回任务状态,便于用户去 OFox 控制台找回结果。这里直接抛出+ # 专用错误,同时阻止后续关键词继续创建新的付费任务。+ source_info = (+ item.source_info if isinstance(item.source_info, dict) else {}+ )+ remote_task_id = str(source_info.get("asset_id") or "").strip()+ _persist_material_sources(task_id, material_sources)+ raise ofox.OFoxDownloadError(+ "OFox generated a paid video but the result could not be "+ f"downloaded: id={remote_task_id or 'unknown'}",+ task_id=remote_task_id,+ )+ logger.info(f"video saved: {saved_video_path}")+ video_paths.append(saved_video_path)+ try:+ material_sources.append(_material_source_record(item, saved_video_path))+ except Exception as source_error:+ logger.warning(+ "failed to prepare generated material source record: "+ f"provider=ofox, "+ f"error={type(source_error).__name__}, detail={source_error}"+ )+ total_duration += min(clip_duration, item.duration)+ if total_duration >= required_duration:+ break+ if total_duration >= required_duration:+ logger.info(+ "generated OFox materials cover the required duration; stop "+ f"submitting paid tasks: generated={total_duration:.1f}s, "+ f"required={required_duration:.1f}s"+ )+ break++ logger.success(f"generated and downloaded {len(video_paths)} OFox videos")+ _persist_material_sources(task_id, material_sources)+ return video_paths++def _download_videos_by_script_order(task_id: str,search_terms: List[str],diff --git a/app/services/ofox.py b/app/services/ofox.pynew file mode 100644index 00000000..3b0a2397--- /dev/null+++ b/app/services/ofox.py@@ -0,0 +1,441 @@+import math+import os+import time+from typing import Any, Mapping+from urllib.parse import quote_plus++import requests+from loguru import logger++from app.config import config+from app.models.schema import MaterialInfo, VideoAspect+++DEFAULT_BASE_URL = "https://api.ofox.ai/v1"+DEFAULT_MODEL_ID = "bytedance/seedance-2.0-fast"+DEFAULT_RESOLUTION = "720p"+# 默认模型 bytedance/seedance-2.0-fast 只接受 4-15 秒(服务端实测校验值)。+# 其它可选模型区间不同(如 alibaba/wan-2.7 为 2-15 秒),切换模型时应同步+# 调整配置里的区间;超出区间的请求会被 API 以明确的 400 拒绝,不会计费。+DEFAULT_MIN_DURATION_SECONDS = 4+DEFAULT_MAX_DURATION_SECONDS = 15+DEFAULT_POLL_INTERVAL_SECONDS = 5.0+DEFAULT_RUN_TIMEOUT_SECONDS = 1800.0+MAX_POLL_RETRIES = 5+RETRY_BASE_SECONDS = 1.0+MAX_ERROR_TEXT_LENGTH = 500+RETRYABLE_STATUS_CODES = frozenset({429, 500, 502, 503, 504})+TERMINAL_SUCCESS_STATUSES = frozenset({"completed", "succeeded"})+TERMINAL_FAILURE_STATUSES = frozenset(+ {"failed", "error", "cancelled", "canceled", "expired"}+)+ACTIVE_STATUSES = frozenset({"queued", "in_progress"})+++class OFoxError(RuntimeError):+ """确定性的配置、请求或响应错误。"""++ def __init__(self, message: str, task_id: str = ""):+ super().__init__(message)+ # 只要远端任务已经创建,所有错误类型都统一携带任务 ID。上层无需+ # 根据异常子类分别维护恢复逻辑,WebUI/API 也能稳定展示排障依据。+ self.task_id = task_id+++class OFoxUnconfirmedTaskError(OFoxError):+ """远端可能已创建付费任务,但本机无法确认其最终状态。"""++ def __init__(self, message: str, task_id: str = ""):+ super().__init__(message, task_id=task_id)+++class OFoxDownloadError(OFoxError):+ """远端付费任务已成功,但生成的视频未能下载到本机。"""++ def __init__(self, message: str, task_id: str):+ super().__init__(message, task_id=task_id)+++def get_api_key(settings: Mapping[str, Any] | None = None) -> str:+ """+ 按明确且唯一的优先级读取 OFox 凭据。++ 配置文件里的专用键优先级最高;唯一支持的运行时环境变量是语义明确的+ ``OFOX_API_KEY``。+ """+ settings = config.app if settings is None else settings+ configured = str(settings.get("ofox_api_key", "") or "").strip()+ environment_key = os.getenv("OFOX_API_KEY", "").strip()+ return configured or environment_key+++def is_enabled(settings: Mapping[str, Any] | None = None) -> bool:+ return bool(get_api_key(settings))+++def _base_url() -> str:+ return str(+ config.app.get("ofox_base_url", DEFAULT_BASE_URL) or DEFAULT_BASE_URL+ ).rstrip("/")+++def _model_id() -> str:+ return str(+ config.app.get("ofox_text_to_video_model", DEFAULT_MODEL_ID) or DEFAULT_MODEL_ID+ ).strip()+++def _resolution() -> str:+ """+ 读取生成分辨率。++ OFox 按模型在服务端校验分辨率(例如默认 Seedance fast 模型只接受+ 480p/720p),无效值会得到一个明确的 400 拒绝且不会创建付费任务,+ 因此这里只做去空白,不维护本地白名单——白名单会随远端模型目录+ 变化而过期。空值退回默认,避免把空字符串提交到远端。+ """+ value = str(config.app.get("ofox_resolution", DEFAULT_RESOLUTION) or "").strip()+ return value or DEFAULT_RESOLUTION+++def _config_bool(key: str, default: bool) -> bool:+ value = config.app.get(key, default)+ if isinstance(value, str):+ return value.strip().lower() not in {"0", "false", "no", "off", ""}+ return bool(value)+++def _bounded_float(key: str, default: float, minimum: float, maximum: float) -> float:+ try:+ value = float(config.app.get(key, default))+ except (TypeError, ValueError):+ return default+ if not math.isfinite(value):+ return default+ return min(max(value, minimum), maximum)+++def _duration_bounds() -> tuple[int, int]:+ def read(key: str, default: int) -> int:+ try:+ value = int(config.app.get(key, default))+ except (TypeError, ValueError):+ return default+ return value if value >= 1 else default++ minimum = read("ofox_min_duration", DEFAULT_MIN_DURATION_SECONDS)+ maximum = read("ofox_max_duration", DEFAULT_MAX_DURATION_SECONDS)+ return minimum, max(minimum, maximum)+++def _tls_verify() -> bool:+ return _config_bool("tls_verify", True)+++def _status_code(response: Any) -> int:+ try:+ return int(getattr(response, "status_code", 200))+ except (TypeError, ValueError):+ return 200+++def _redact_secret(value: Any, secret: str) -> str:+ text = str(value or "")+ if secret:+ text = text.replace(secret, "***")+ encoded = quote_plus(secret)+ if encoded != secret:+ text = text.replace(encoded, "***")+ for proxy_url in config.proxy.values():+ proxy_secret = str(proxy_url or "")+ if proxy_secret:+ text = text.replace(proxy_secret, "***")+ return text[:MAX_ERROR_TEXT_LENGTH]+++def _response_error(response: Any, api_key: str) -> str:+ try:+ payload = response.json()+ except Exception:+ return f"HTTP {_status_code(response)}"+ if not isinstance(payload, dict):+ return f"HTTP {_status_code(response)}"+ error = payload.get("error")+ if isinstance(error, dict):+ code = error.get("code") or payload.get("code")+ message = error.get("message") or payload.get("message")+ else:+ code = payload.get("code")+ message = payload.get("message") or error+ detail = ": ".join(str(item) for item in (code, message) if item not in (None, ""))+ return _redact_secret(detail or f"HTTP {_status_code(response)}", api_key)+++def _is_retryable_error(error: Exception) -> bool:+ if isinstance(+ error,+ (+ requests.exceptions.ConnectionError,+ requests.exceptions.Timeout,+ requests.exceptions.ChunkedEncodingError,+ ),+ ):+ return True+ response = getattr(error, "response", None)+ return response is not None and _status_code(response) in RETRYABLE_STATUS_CODES+++def generate_videos(+ search_term: str,+ minimum_duration: int,+ video_aspect: VideoAspect = VideoAspect.portrait,+) -> list[MaterialInfo]:+ """提交一个 OFox 文生视频任务,并等待可下载的结果地址。"""+ api_key = get_api_key()+ if not api_key:+ raise OFoxError("OFox video generation requires an OFox API key")++ term = str(search_term or "").strip()+ if not term:+ # 空提示词可能来自上游脚本拆分异常。付费生成源不能把它提交到远端,+ # 否则即使接口接受请求,也只会得到无法使用且已经计费的视频。+ raise OFoxError("OFox search term must not be empty")++ aspect = VideoAspect(video_aspect)+ video_width, video_height = aspect.to_resolution()+ requested_duration = max(int(minimum_duration), 1)+ minimum, maximum = _duration_bounds()+ duration = min(max(requested_duration, minimum), maximum)+ if duration != requested_duration:+ # 生成比请求更长不会影响成片:剪辑流程仍按片段时长裁剪;生成比请求+ # 更短只发生在请求超过模型上限时,此时也只能收敛到上限。+ logger.info(+ f"ofox clip duration clamped to the configured model range: "+ f"requested={requested_duration}s, using={duration}s "+ f"(configured {minimum}-{maximum}s)"+ )+ payload = {+ "model": _model_id(),+ "prompt": term,+ "duration": duration,+ "resolution": _resolution(),+ "aspect_ratio": aspect.value,+ }+ headers = {+ "Authorization": f"Bearer {api_key}",+ "Content-Type": "application/json",+ }+ videos_url = f"{_base_url()}/videos"+ logger.info(+ "generating video with OFox: "+ f"model={payload['model']}, term={term!r}, duration={duration}s"+ )++ # 提交接口不做自动重试:超时或 5xx 可能发生在付费任务已经创建之后,+ # 盲目重试会造成重复扣费。只有拿到明确拒绝响应时才判定为确定性失败。+ try:+ response = requests.post(+ videos_url,+ json=payload,+ headers=headers,+ proxies=config.proxy,+ verify=_tls_verify(),+ timeout=(30, 60),+ )+ except Exception as exc:+ raise OFoxUnconfirmedTaskError(+ "OFox submission returned no response; a paid task may already "+ "exist remotely: "+ f"error={type(exc).__name__}, detail={_redact_secret(exc, api_key)}"+ ) from exc++ status_code = _status_code(response)+ if status_code >= 500:+ raise OFoxUnconfirmedTaskError(+ f"OFox submission failed with HTTP {status_code}; a paid task may "+ "already exist remotely"+ )+ if not 200 <= status_code < 300:+ # 4xx 是明确拒绝(如 duration/resolution 超出模型支持范围),远端+ # 没有创建任务,不存在重复计费风险;错误信息里带着服务端给出的+ # 合法取值范围,直接抛给用户修配置。+ raise OFoxError(+ "OFox video generation request rejected: "+ f"HTTP {status_code}, {_response_error(response, api_key)}"+ )+ try:+ body = response.json()+ except Exception as exc:+ raise OFoxUnconfirmedTaskError(+ "OFox submission returned an unreadable response; a paid task may "+ f"already exist remotely: error={type(exc).__name__}"+ ) from exc+ task_id = str(body.get("id") or "").strip() if isinstance(body, dict) else ""+ if not task_id:+ raise OFoxUnconfirmedTaskError(+ "OFox accepted the submission without returning a task id"+ )+ logger.info(f"OFox video task created: id={task_id}")++ task = _wait_for_task(+ task_id=task_id,+ videos_url=videos_url,+ headers=headers,+ api_key=api_key,+ )+ if task is None:+ return []++ # 产物地址在 unsigned_urls 里,是会过期的临时直链,必须整体保留并+ # 立即用于下载,不能写入长期的 source_info。+ unsigned_urls = task.get("unsigned_urls")+ video_url = ""+ for candidate in unsigned_urls if isinstance(unsigned_urls, list) else []:+ if isinstance(candidate, str) and candidate.startswith(("http://", "https://")):+ video_url = candidate+ break+ if not video_url:+ raise OFoxError(+ f"OFox task completed without a downloadable video: id={task_id}",+ task_id=task_id,+ )++ return [+ MaterialInfo(+ provider="ofox",+ url=video_url,+ duration=duration,+ source_info={+ "provider": "ofox",+ "search_term": term,+ "asset_id": task_id,+ "rendition": {+ "id": task_id,+ "width": video_width,+ "height": video_height,+ },+ },+ )+ ]+++def _wait_for_task(+ *,+ task_id: str,+ videos_url: str,+ headers: dict[str, str],+ api_key: str,+) -> dict[str, Any] | None:+ deadline = time.monotonic() + _bounded_float(+ "ofox_run_timeout",+ DEFAULT_RUN_TIMEOUT_SECONDS,+ 60.0,+ 7200.0,+ )+ poll_interval = _bounded_float(+ "ofox_poll_interval",+ DEFAULT_POLL_INTERVAL_SECONDS,+ 0.5,+ 60.0,+ )+ consecutive_failures = 0+ while True:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise OFoxUnconfirmedTaskError(+ "OFox task is still running after the configured local wait "+ f"timeout: id={task_id}",+ task_id=task_id,+ )++ # requests 的 connect/read timeout 分别计时,因此各使用剩余总时间的+ # 一半。即使连接和读取都走到上限,单轮请求也不会有意超过总截止时间;+ # 网络库仍可能有极小调度误差,下一处 deadline 检查会阻止再次重试。+ phase_timeout = max(min(remaining / 2.0, 30.0), 0.001)+ try:+ response = requests.get(+ f"{videos_url}/{task_id}",+ headers=headers,+ proxies=config.proxy,+ verify=_tls_verify(),+ timeout=(phase_timeout, phase_timeout),+ )+ status_code = _status_code(response)+ if status_code in RETRYABLE_STATUS_CODES:+ raise requests.exceptions.HTTPError(+ f"HTTP {status_code}", response=response+ )+ if not 200 <= status_code < 300:+ raise OFoxUnconfirmedTaskError(+ "OFox task status is unknown: "+ f"http_status={status_code}, "+ f"detail={_response_error(response, api_key)}",+ task_id=task_id,+ )+ body = response.json()+ if not isinstance(body, dict):+ raise OFoxUnconfirmedTaskError(+ "OFox task status response is malformed", task_id=task_id+ )+ except OFoxUnconfirmedTaskError:+ raise+ except Exception as exc:+ if not _is_retryable_error(exc):+ raise OFoxUnconfirmedTaskError(+ "OFox polling failed and the paid task state is unknown: "+ f"error={type(exc).__name__}, "+ f"detail={_redact_secret(exc, api_key)}",+ task_id=task_id,+ ) from exc++ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise OFoxUnconfirmedTaskError(+ "OFox task is still running after the configured local wait "+ f"timeout: id={task_id}",+ task_id=task_id,+ ) from exc+ consecutive_failures += 1+ if consecutive_failures > MAX_POLL_RETRIES:+ raise OFoxUnconfirmedTaskError(+ "OFox polling failed after retries; the paid task may still "+ f"be running remotely: id={task_id}",+ task_id=task_id,+ ) from exc+ delay = min(RETRY_BASE_SECONDS * consecutive_failures, remaining)+ logger.warning(+ "OFox polling hit a transient error; retrying the same task: "+ f"id={task_id}, attempt={consecutive_failures}/{MAX_POLL_RETRIES}, "+ f"retry_in={delay:.1f}s"+ )+ time.sleep(delay)+ continue++ consecutive_failures = 0+ status = str(body.get("status") or "").strip().lower()+ if status in TERMINAL_SUCCESS_STATUSES:+ return body+ if status in TERMINAL_FAILURE_STATUSES:+ error_detail = body.get("error")+ logger.error(+ "OFox task did not produce a video: "+ f"id={task_id}, status={status}, "+ f"detail={_redact_secret(error_detail, api_key)}"+ )+ # 远端明确失败意味着任务已经结束,可以安全地继续后续片段;由+ # 调用方决定是否换一个关键词重试。+ return None+ if status not in ACTIVE_STATUSES:+ raise OFoxUnconfirmedTaskError(+ f"OFox returned an unknown task status: id={task_id}, "+ f"status={status!r}",+ task_id=task_id,+ )+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ raise OFoxUnconfirmedTaskError(+ "OFox task is still running after the configured local wait "+ f"timeout: id={task_id}",+ task_id=task_id,+ )+ time.sleep(min(poll_interval, remaining))diff --git a/app/services/task.py b/app/services/task.pyindex a310390d..05a543db 100644--- a/app/services/task.py+++ b/app/services/task.py@@ -20,6 +20,7 @@ from app.services import (llm,loomloom,material,+ ofox,sonilo,subtitle,task_artifacts,@@ -739,6 +740,20 @@ def get_video_materials(details=details,)return None+ except ofox.OFoxError as exc:+ # 与方舟同一恢复语义:未确认状态和已生成但下载失败都对应一个可在+ # OFox 控制台恢复的远端任务,统一从异常携带的 task_id 写入失败状态。+ remote_task_id = str(getattr(exc, "task_id", "") or "").strip()+ details = (+ {"ofox_task_id": remote_task_id} if remote_task_id else None+ )+ _mark_task_failed(+ task_id,+ "materials",+ str(exc),+ details=details,+ )+ return Noneif not downloaded_videos:_mark_task_failed(task_id,@@ -1262,6 +1277,17 @@ def _run_pipeline("Volcano Engine Seedance requires an Ark API key",)+ if (+ stop_at in {"materials", "video"}+ and params.video_source == "ofox"+ and not ofox.is_enabled()+ ):+ return _mark_task_failed(+ task_id,+ "preflight",+ "OFox video generation requires an OFox API key",+ )+if (stop_at in {"materials", "video"}and params.video_source == "openai_image"diff --git a/cli.py b/cli.pyindex 9ac602fd..e8b618fa 100644--- a/cli.py+++ b/cli.py@@ -268,6 +268,7 @@ Batch manifests:"pixabay","coverr","volcengine_seedance",+ "ofox","openai_image","local",],@@ -297,6 +298,14 @@ Batch manifests:"with --video-source volcengine_seedance for materials or video output"),)+ material_group.add_argument(+ "--confirm-ofox-charge",+ action="store_true",+ help=(+ "confirm that OFox video generation creates paid tasks; required "+ "with --video-source ofox for materials or video output"+ ),+ )video_group = parser.add_argument_group("video output")video_group.add_argument(@@ -595,6 +604,15 @@ Batch manifests:"--confirm-seedance-charge is required with ""--video-source volcengine_seedance")+ if (+ not args.batch_file+ and args.video_source == "ofox"+ and stage_requires_materials+ and not args.confirm_ofox_charge+ ):+ parser.error(+ "--confirm-ofox-charge is required with --video-source ofox"+ )if args.bgm_file:if args.bgm_type in (None, "custom"):@@ -971,6 +989,7 @@ def _validate_batch_task_params(stop_at: str,custom_position_is_explicit: bool,seedance_charge_confirmed: bool,+ ofox_charge_confirmed: bool,) -> None:if not params.video_subject.strip() and not params.video_script.strip():raise ValueError("one of video_subject or video_script is required")@@ -980,11 +999,12 @@ def _validate_batch_task_params("pixabay","coverr","volcengine_seedance",+ "ofox","local",}:raise ValueError("video_source must be one of: pexels, pixabay, coverr, "- "volcengine_seedance, local"+ "volcengine_seedance, ofox, local")for field_name, value in (("video_aspect", params.video_aspect),@@ -1018,6 +1038,12 @@ def _validate_batch_task_params(raise ValueError("--confirm-seedance-charge is required for Volcano Engine Seedance")+ if (+ params.video_source == "ofox"+ and stop_at in {"materials", "video"}+ and not ofox_charge_confirmed+ ):+ raise ValueError("--confirm-ofox-charge is required for OFox video generation")if stop_at == "subtitle" and not params.subtitle_enabled:raise ValueError("stop_at=subtitle cannot be combined with disabled subtitles")@@ -1118,6 +1144,7 @@ def _build_batch_tasks(args: argparse.Namespace) -> list[VideoParams]:or "custom_position" in override_fields),seedance_charge_confirmed=args.confirm_seedance_charge,+ ofox_charge_confirmed=args.confirm_ofox_charge,)except (TypeError, ValueError) as exc:raise ValueError(f"invalid batch task {index}: {exc}") from excdiff --git a/config.example.toml b/config.example.tomlindex ef53e49e..de0a5bb8 100644--- a/config.example.toml+++ b/config.example.toml@@ -63,11 +63,14 @@ tls_verify = true# -----------------------------------------------------------------------------# Available values: "pexels", "pixabay", "coverr", "wavespeed",-# "volcengine_seedance", "loomloom", "openai_image", "local".+# "volcengine_seedance", "ofox", "loomloom", "openai_image", "local".# "wavespeed" generates brand-new clips with WaveSpeed AI text-to-video models# instead of searching stock footage; generation is billed per request.# "loomloom" is a paid Shengsuan Cloud source and requires explicit# confirmation in the WebUI before each generation request.+# "ofox" generates brand-new clips through the OFox multi-model video API+# (Seedance / Wan and other text-to-video models behind one key); generation+# is billed per submitted clip.# "openai_image" generates one image per script keyword through any# OpenAI-compatible /images/generations endpoint (local ComfyUI/SD gateways# or cloud relays) and renders it into a video clip.@@ -118,6 +121,28 @@ volcengine_seedance_poll_interval = 5volcengine_seedance_run_timeout = 1800volcengine_seedance_watermark = false+# OFox (https://ofox.ai) exposes multiple text-to-video models (Seedance, Wan,+# and more) behind one API key using an asynchronous /v1/videos API.+# Create an API key at https://ofox.ai+# When empty, the OFOX_API_KEY environment variable is used.+# Generation is billed per submitted clip.+ofox_api_key = ""+ofox_base_url = "https://api.ofox.ai/v1"+# Any text-to-video model id from the OFox catalog (GET /v1/models) works here.+ofox_text_to_video_model = "bytedance/seedance-2.0-fast"+# Supported resolutions depend on the chosen model (the default model accepts+# "480p" and "720p"); invalid values are rejected by the API with a clear+# error before any task is created.+ofox_resolution = "720p"+# The default model only accepts durations of 4-15 seconds; other models have+# different ranges (for example alibaba/wan-2.7 accepts 2-15 seconds).+# Requested clip durations outside the range are clamped automatically before+# submission (extra footage is trimmed by the editing pipeline).+ofox_min_duration = 4+ofox_max_duration = 15+ofox_poll_interval = 5+ofox_run_timeout = 1800+# OpenAI-compatible text-to-image material source ("openai_image"). Point the# base URL at any endpoint that speaks the OpenAI /images/generations protocol:# a local ComfyUI/SD gateway, a self-hosted relay, or a cloud aggregator.diff --git a/docs/skill/SKILL.md b/docs/skill/SKILL.mdindex 9f007716..5452f41e 100644--- a/docs/skill/SKILL.md+++ b/docs/skill/SKILL.md@@ -110,12 +110,17 @@ MPT_LLM_BASE_URLMPT_LLM_MODEL_NAMEMPT_PEXELS_API_KEYMPT_VOLCENGINE_ARK_API_KEY+MPT_OFOX_API_KEY```When `SEEDANCE_CHARGE_CONFIRMATION_REQUIRED` is present, explain that everygenerated Seedance clip creates a paid Ark task. Only after the user explicitlyconfirms, rerun with `--confirm-seedance-charge`; never add this flag silently.+When `OFOX_CHARGE_CONFIRMATION_REQUIRED` is present, explain that every+generated OFox clip creates a paid task. Only after the user explicitly+confirms, rerun with `--confirm-ofox-charge`; never add this flag silently.+### Exit code 1: repair or reportUse `MPT_ERROR` and `LOG_FILE` to repair a recoverable problem and retry once. Ask the user only if the repair requires a new API key. If the retry fails, report the failed stage, a short error, and the log path.diff --git a/docs/skill/mpt_agent.py b/docs/skill/mpt_agent.pyindex 928a1e5c..d469fbb9 100644--- a/docs/skill/mpt_agent.py+++ b/docs/skill/mpt_agent.py@@ -30,11 +30,13 @@ SUPPORTED_SOURCES = {"pixabay","coverr","volcengine_seedance",+ "ofox","local",}VOLCENGINE_ARK_API_KEY_URL = ("https://console.volcengine.com/ark/region:ark+cn-beijing/apikey")+OFOX_API_KEY_URL = "https://ofox.ai"PEXELS_API_KEY_URL = "https://www.pexels.com/api/"PEXELS_VALIDATION_URL = "https://api.pexels.com/v1/collections?per_page=1"PEXELS_API_KEY_HELP_URL = (@@ -216,7 +218,10 @@ def apply_environment_config(config_path: Path) -> None:model_name = os.environ.get("MPT_LLM_MODEL_NAME", "").strip()pexels_key = os.environ.get("MPT_PEXELS_API_KEY", "").strip()seedance_key = os.environ.get("MPT_VOLCENGINE_ARK_API_KEY", "").strip()- if not any((provider, llm_key, base_url, model_name, pexels_key, seedance_key)):+ ofox_key = os.environ.get("MPT_OFOX_API_KEY", "").strip()+ if not any(+ (provider, llm_key, base_url, model_name, pexels_key, seedance_key, ofox_key)+ ):returntext = config_path.read_text(encoding="utf-8")@@ -243,6 +248,9 @@ def apply_environment_config(config_path: Path) -> None:text, "volcengine_seedance_api_key", seedance_key)changes.append("volcengine_seedance_api_key")+ if ofox_key:+ text = _replace_config_value(text, "ofox_api_key", ofox_key)+ changes.append("ofox_api_key")config_path.write_text(text, encoding="utf-8")log("updated configuration fields: " + ", ".join(changes))@@ -334,6 +342,17 @@ def missing_config(config_path: Path, cli_args: list[str]) -> tuple[str, list[stmissing.append("volcengine_seedance_api_key")if not has_cli_option(cli_args, "--confirm-seedance-charge"):missing.append("confirm_seedance_charge")+ elif source == "ofox":+ # 与运行时 Provider 保持完全一致的凭据优先级:配置键优先,其次是+ # 语义明确的 OFOX_API_KEY 环境变量。+ value = (+ _plain_config_value(text, "ofox_api_key")+ or os.environ.get("OFOX_API_KEY", "").strip()+ )+ if not _has_configured_value(value):+ missing.append("ofox_api_key")+ if not has_cli_option(cli_args, "--confirm-ofox-charge"):+ missing.append("confirm_ofox_charge")elif source != "local":value = _plain_config_value(text, f"{source}_api_keys")if not _has_configured_value(value):@@ -349,7 +368,7 @@ def report_missing_config(provider: str, missing: list[str]) -> int:print(f"MISSING={field}")if any(field.endswith("_api_key")- and field != "volcengine_seedance_api_key"+ and field not in {"volcengine_seedance_api_key", "ofox_api_key"}for field in missing):print("LLM_PROVIDER_OPTIONS_BEGIN")@@ -373,6 +392,11 @@ def report_missing_config(provider: str, missing: list[str]) -> int:print("VOLCENGINE_ARK_API_KEY_ENV=MPT_VOLCENGINE_ARK_API_KEY")if "confirm_seedance_charge" in missing:print("SEEDANCE_CHARGE_CONFIRMATION_REQUIRED=--confirm-seedance-charge")+ if "ofox_api_key" in missing:+ print(f"OFOX_API_KEY_URL={OFOX_API_KEY_URL}")+ print("OFOX_API_KEY_ENV=MPT_OFOX_API_KEY")+ if "confirm_ofox_charge" in missing:+ print("OFOX_CHARGE_CONFIRMATION_REQUIRED=--confirm-ofox-charge")print("Request only the listed values, set the environment variables, and rerun the same command.")return NEEDS_INPUT_EXIT_CODEdiff --git a/test/services/test_cli.py b/test/services/test_cli.pyindex 66014519..9f3a4987 100644--- a/test/services/test_cli.py+++ b/test/services/test_cli.py@@ -209,6 +209,79 @@ class TestCli(unittest.TestCase):cli.build_video_params(args).video_source, "volcengine_seedance")+ def test_ofox_video_source_requires_explicit_charge_confirmation(self):+ with self.assertRaises(SystemExit) as raised:+ cli.parse_args(+ ["--video-subject", "test", "--video-source", "ofox"]+ )+ self.assertEqual(raised.exception.code, 2)++ args = cli.parse_args(+ [+ "--video-subject",+ "test",+ "--video-source",+ "ofox",+ "--confirm-ofox-charge",+ ]+ )+ self.assertEqual(cli.build_video_params(args).video_source, "ofox")++ def test_ofox_confirmation_is_not_required_before_material_stage(self):+ args = cli.parse_args(+ [+ "--video-subject",+ "test",+ "--video-source",+ "ofox",+ "--stop-at",+ "script",+ ]+ )+ self.assertEqual(args.video_source, "ofox")++ def test_batch_ofox_source_uses_global_charge_confirmation(self):+ with tempfile.TemporaryDirectory() as temp_dir:+ manifest = Path(temp_dir) / "tasks.json"+ manifest.write_text(+ json.dumps(+ [+ {+ "video_subject": "OFox batch task",+ "video_source": "ofox",+ }+ ]+ ),+ encoding="utf-8",+ )+ with patch("app.services.task.start") as start:+ rejected = cli.run_cli(+ ["--batch-file", str(manifest), "--stop-at", "materials"]+ )+ self.assertEqual(rejected, 2)+ start.assert_not_called()++ with (+ patch(+ "app.services.task.start",+ return_value={"state": 1, "materials": ["ok"]},+ ) as start,+ patch("app.utils.utils.get_uuid", return_value="task-ofox"),+ redirect_stdout(io.StringIO()),+ ):+ accepted = cli.run_cli(+ [+ "--batch-file",+ str(manifest),+ "--stop-at",+ "materials",+ "--confirm-ofox-charge",+ ]+ )++ self.assertEqual(accepted, 0)+ start.assert_called_once()+def test_seedance_confirmation_is_not_required_before_material_stage(self):args = cli.parse_args([diff --git a/test/services/test_config.py b/test/services/test_config.pyindex 5729bc54..6ca3c8ac 100644--- a/test/services/test_config.py+++ b/test/services/test_config.py@@ -42,6 +42,7 @@ class TestConfigPersistence:"pixabay","coverr","volcengine_seedance",+ "ofox","loomloom","local",}@@ -52,6 +53,9 @@ class TestConfigPersistence:assert app_config["volcengine_seedance_api_key"] == ""assert app_config["volcengine_seedance_base_url"].startswith("https://")assert app_config["volcengine_seedance_model"]+ assert app_config["ofox_api_key"] == ""+ assert app_config["ofox_base_url"].startswith("https://")+ assert app_config["ofox_text_to_video_model"]assert "loomloom_market_listing_id" not in app_configassert "loomloom_video_market_listing_id" not in app_configassert app_config["shengsuanyun_api_key"] == ""diff --git a/test/services/test_mpt_agent_skill.py b/test/services/test_mpt_agent_skill.pyindex 58183bc9..af643dd6 100644--- a/test/services/test_mpt_agent_skill.py+++ b/test/services/test_mpt_agent_skill.py@@ -29,6 +29,7 @@ pexels_api_keys = []pixabay_api_keys = []coverr_api_keys = []volcengine_seedance_api_key = ""+ofox_api_key = ""oneapi_api_key = ""oneapi_base_url = ""oneapi_model_name = ""@@ -142,6 +143,91 @@ class TestMptAgentSkill(unittest.TestCase):self.assertEqual(default_missing, ["pexels_api_keys"])self.assertEqual(pixabay_missing, [])+ def test_ofox_source_requires_key_and_explicit_charge_confirmation(self):+ with tempfile.TemporaryDirectory() as temp_dir:+ config_path = Path(temp_dir) / "config.toml"+ config_path.write_text(+ MINIMAL_CONFIG.replace(+ 'moonshot_api_key = ""', 'moonshot_api_key = "configured"'+ ),+ encoding="utf-8",+ )++ with patch.dict(os.environ, {}, clear=True):+ _, missing = mpt_agent.missing_config(+ config_path, ["--video-source", "ofox"]+ )+ self.assertEqual(missing, ["ofox_api_key", "confirm_ofox_charge"])++ config_path.write_text(+ config_path.read_text(encoding="utf-8").replace(+ 'ofox_api_key = ""', 'ofox_api_key = "configured"'+ ),+ encoding="utf-8",+ )+ with patch.dict(os.environ, {}, clear=True):+ _, confirmed_missing = mpt_agent.missing_config(+ config_path,+ ["--video-source", "ofox", "--confirm-ofox-charge"],+ )+ self.assertEqual(confirmed_missing, [])++ def test_ofox_source_accepts_the_provider_specific_environment_key(self):+ with tempfile.TemporaryDirectory() as temp_dir:+ config_path = Path(temp_dir) / "config.toml"+ config_path.write_text(+ MINIMAL_CONFIG.replace(+ 'moonshot_api_key = ""', 'moonshot_api_key = "configured"'+ ),+ encoding="utf-8",+ )++ with patch.dict(+ os.environ,+ {"OFOX_API_KEY": "environment-ofox-key"},+ clear=True,+ ):+ _, missing = mpt_agent.missing_config(+ config_path,+ ["--video-source", "ofox", "--confirm-ofox-charge"],+ )++ self.assertEqual(missing, [])++ def test_ofox_environment_key_is_written_without_leaking_to_output(self):+ with tempfile.TemporaryDirectory() as temp_dir:+ config_path = Path(temp_dir) / "config.toml"+ config_path.write_text(MINIMAL_CONFIG, encoding="utf-8")+ ofox_key = "secret-ofox-key"+ output = io.StringIO()++ with patch.dict(+ os.environ,+ {"MPT_OFOX_API_KEY": ofox_key},+ clear=True,+ ), redirect_stdout(output):+ mpt_agent.apply_environment_config(config_path)++ config = config_path.read_text(encoding="utf-8")+ self.assertIn(f'ofox_api_key = "{ofox_key}"', config)+ self.assertNotIn(ofox_key, output.getvalue())++ def test_missing_ofox_inputs_report_signup_and_charge_flag(self):+ output = io.StringIO()+ with redirect_stdout(output):+ code = mpt_agent.report_missing_config(+ "deepseek",+ ["ofox_api_key", "confirm_ofox_charge"],+ )++ text = output.getvalue()+ self.assertEqual(code, mpt_agent.NEEDS_INPUT_EXIT_CODE)+ self.assertIn(f"OFOX_API_KEY_URL={mpt_agent.OFOX_API_KEY_URL}", text)+ self.assertIn(+ "OFOX_CHARGE_CONFIRMATION_REQUIRED=--confirm-ofox-charge", text+ )+ self.assertNotIn("LLM_PROVIDER_OPTIONS_BEGIN", text)+def test_seedance_source_requires_key_and_explicit_charge_confirmation(self):with tempfile.TemporaryDirectory() as temp_dir:config_path = Path(temp_dir) / "config.toml"diff --git a/test/services/test_ofox.py b/test/services/test_ofox.pynew file mode 100644index 00000000..57ab65cf--- /dev/null+++ b/test/services/test_ofox.py@@ -0,0 +1,808 @@+import os+import unittest+from types import SimpleNamespace+from unittest.mock import patch++import requests++from app.config import config+from app.models.schema import MaterialInfo, VideoAspect, VideoParams+from app.services import material, ofox, state as sm, task as task_service+++class TestOFoxService(unittest.TestCase):+ def setUp(self):+ self.original_app = dict(config.app)+ self.original_proxy = dict(config.proxy)+ config.app.update(+ {+ "ofox_api_key": "ofox-test-key",+ "ofox_text_to_video_model": ofox.DEFAULT_MODEL_ID,+ "ofox_base_url": ofox.DEFAULT_BASE_URL,+ }+ )+ config.proxy.clear()++ def tearDown(self):+ config.app.clear()+ config.app.update(self.original_app)+ config.proxy.clear()+ config.proxy.update(self.original_proxy)++ @staticmethod+ def _response(payload, status_code=200):+ return SimpleNamespace(status_code=status_code, json=lambda: payload)++ def test_api_key_prefers_config_then_provider_specific_environment_name(self):+ with patch.dict(+ os.environ,+ {"OFOX_API_KEY": "env-key"},+ clear=False,+ ):+ self.assertEqual(ofox.get_api_key(), "ofox-test-key")+ config.app["ofox_api_key"] = ""+ self.assertEqual(ofox.get_api_key(), "env-key")+ os.environ["OFOX_API_KEY"] = ""+ self.assertEqual(ofox.get_api_key(), "")++ def test_missing_api_key_fails_before_submission(self):+ config.app["ofox_api_key"] = ""+ with (+ patch.dict(os.environ, {"OFOX_API_KEY": ""}, clear=False),+ patch.object(ofox.requests, "post") as post,+ ):+ with self.assertRaises(ofox.OFoxError):+ ofox.generate_videos("sunrise", 5)+ post.assert_not_called()++ def test_empty_search_term_fails_before_paid_submission(self):+ for invalid in ("", " ", None, 0, False):+ with self.subTest(invalid=invalid):+ with patch.object(ofox.requests, "post") as post:+ with self.assertRaises(ofox.OFoxError) as raised:+ ofox.generate_videos(invalid, 5)++ self.assertIn("search term must not be empty", str(raised.exception))+ post.assert_not_called()++ def test_search_term_is_trimmed_consistently_in_request_and_source_record(self):+ submit = self._response({"id": "vid-trimmed", "status": "queued"}, 202)+ completed = self._response(+ {+ "id": "vid-trimmed",+ "status": "completed",+ "unsigned_urls": ["https://cdn.example.com/trimmed.mp4"],+ }+ )+ with (+ patch.object(ofox.requests, "post", return_value=submit) as post,+ patch.object(ofox.requests, "get", return_value=completed),+ ):+ result = ofox.generate_videos(" smart home ", 5)++ self.assertEqual(post.call_args.kwargs["json"]["prompt"], "smart home")+ self.assertEqual(result[0].source_info["search_term"], "smart home")++ def test_submit_poll_and_parse_successful_video(self):+ submit = self._response({"id": "vid-123", "status": "queued"}, 202)+ polls = [+ self._response({"id": "vid-123", "status": "in_progress"}),+ self._response(+ {+ "id": "vid-123",+ "status": "completed",+ "unsigned_urls": ["https://cdn.example.com/video.mp4?sig=abc"],+ "usage": {"video_seconds": 5, "video_cost": "0.5"},+ }+ ),+ ]++ with (+ patch.object(ofox.requests, "post", return_value=submit) as post,+ patch.object(ofox.requests, "get", side_effect=polls) as get,+ patch.object(ofox.time, "sleep") as sleep,+ ):+ result = ofox.generate_videos(+ "sunrise over mountains",+ minimum_duration=5,+ video_aspect=VideoAspect.portrait,+ )++ self.assertEqual(len(result), 1)+ item = result[0]+ self.assertEqual(item.provider, "ofox")+ self.assertEqual(item.url, "https://cdn.example.com/video.mp4?sig=abc")+ self.assertEqual(item.duration, 5)+ self.assertEqual(item.source_info["asset_id"], "vid-123")++ self.assertEqual(post.call_args.args[0], f"{ofox.DEFAULT_BASE_URL}/videos")+ self.assertEqual(+ post.call_args.kwargs["headers"]["Authorization"],+ "Bearer ofox-test-key",+ )+ self.assertEqual(+ post.call_args.kwargs["json"],+ {+ "model": ofox.DEFAULT_MODEL_ID,+ "prompt": "sunrise over mountains",+ "duration": 5,+ "resolution": "720p",+ "aspect_ratio": "9:16",+ },+ )+ self.assertEqual(get.call_count, 2)+ self.assertTrue(+ all("/videos/vid-123" in call.args[0] for call in get.call_args_list)+ )+ sleep.assert_called_once_with(ofox.DEFAULT_POLL_INTERVAL_SECONDS)++ def test_resolution_defaults_only_when_blank_and_passes_configured_value(self):+ config.app.pop("ofox_resolution", None)+ self.assertEqual(ofox._resolution(), ofox.DEFAULT_RESOLUTION)++ config.app["ofox_resolution"] = " "+ self.assertEqual(ofox._resolution(), ofox.DEFAULT_RESOLUTION)++ # 分辨率白名单随远端模型目录变化,本地不做校验;配置值原样提交,+ # 由服务端按模型给出明确的 400 拒绝(不创建付费任务)。+ config.app["ofox_resolution"] = " 480p "+ self.assertEqual(ofox._resolution(), "480p")++ def test_server_rejected_resolution_raises_clear_error_without_polling(self):+ config.app["ofox_resolution"] = "1080p"+ rejected = self._response(+ {+ "error": {+ "code": "unsupported_parameter",+ "message": 'resolution "1080p" not supported; allowed: [480p 720p]',+ }+ },+ status_code=400,+ )+ with (+ patch.object(ofox.requests, "post", return_value=rejected),+ patch.object(ofox.requests, "get") as get,+ ):+ with self.assertRaises(ofox.OFoxError) as raised:+ ofox.generate_videos("city", 5)++ get.assert_not_called()+ self.assertIn("not supported", str(raised.exception))++ def test_configured_model_base_url_and_duration_bounds_are_applied(self):+ config.app.update(+ {+ "ofox_text_to_video_model": "alibaba/wan-2.7",+ "ofox_base_url": "https://ofox.example.test/v1/",+ "ofox_min_duration": 2,+ "ofox_max_duration": 8,+ "ofox_resolution": "480p",+ }+ )+ submit = self._response({"id": "vid-bounds", "status": "queued"}, 202)+ completed = self._response(+ {+ "id": "vid-bounds",+ "status": "completed",+ "unsigned_urls": ["https://cdn.example.com/bounds.mp4"],+ }+ )+ with (+ patch.object(ofox.requests, "post", return_value=submit) as post,+ patch.object(ofox.requests, "get", return_value=completed),+ ):+ result = ofox.generate_videos("city", 99, VideoAspect.landscape)++ self.assertEqual(result[0].duration, 8)+ self.assertEqual(post.call_args.args[0], "https://ofox.example.test/v1/videos")+ payload = post.call_args.kwargs["json"]+ self.assertEqual(payload["model"], "alibaba/wan-2.7")+ self.assertEqual(payload["duration"], 8)+ self.assertEqual(payload["resolution"], "480p")+ self.assertEqual(payload["aspect_ratio"], "16:9")++ def test_rejected_submission_raises_clear_error_without_polling(self):+ rejected = self._response(+ {+ "error": {+ "code": "invalid_request",+ "message": "rejected ofox-test-key",+ }+ },+ status_code=400,+ )+ with (+ patch.object(ofox.requests, "post", return_value=rejected),+ patch.object(ofox.requests, "get") as get,+ ):+ with self.assertRaises(ofox.OFoxError) as raised:+ ofox.generate_videos("unsafe", 5)++ get.assert_not_called()+ self.assertNotIn("ofox-test-key", str(raised.exception))++ def test_submission_network_or_server_error_is_unconfirmed_and_not_retried(self):+ for side_effect, response in (+ (requests.exceptions.ConnectionError("offline"), None),+ (None, self._response({"message": "bad gateway"}, status_code=502)),+ ):+ with self.subTest(response=response):+ with patch.object(+ ofox.requests,+ "post",+ side_effect=side_effect,+ return_value=response,+ ) as post:+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError):+ ofox.generate_videos("sunrise", 5)+ self.assertEqual(post.call_count, 1)++ def test_poll_retries_transient_errors_on_same_task(self):+ submit = self._response({"id": "vid-retry", "status": "queued"}, 202)+ rate_limited = self._response({}, status_code=429)+ completed = self._response(+ {+ "id": "vid-retry",+ "status": "completed",+ "unsigned_urls": ["https://cdn.example.com/retry.mp4"],+ }+ )+ with (+ patch.object(ofox.requests, "post", return_value=submit) as post,+ patch.object(+ ofox.requests,+ "get",+ side_effect=[+ rate_limited,+ requests.exceptions.ConnectionError("offline"),+ completed,+ ],+ ) as get,+ patch.object(ofox.time, "sleep") as sleep,+ ):+ result = ofox.generate_videos("sunrise", 5)++ self.assertEqual(len(result), 1)+ self.assertEqual(post.call_count, 1)+ self.assertEqual(get.call_count, 3)+ self.assertEqual([call.args[0] for call in sleep.call_args_list], [1.0, 2.0])++ def test_poll_retry_exhaustion_preserves_remote_task_id(self):+ submit = self._response({"id": "vid-stuck", "status": "queued"}, 202)+ with (+ patch.object(ofox.requests, "post", return_value=submit),+ patch.object(+ ofox.requests,+ "get",+ side_effect=requests.exceptions.ConnectionError("offline"),+ ) as get,+ patch.object(ofox.time, "sleep"),+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError) as raised:+ ofox.generate_videos("sunrise", 5)++ self.assertEqual(raised.exception.task_id, "vid-stuck")+ self.assertEqual(get.call_count, ofox.MAX_POLL_RETRIES + 1)++ def test_running_task_timeout_preserves_remote_task_id(self):+ submit = self._response({"id": "vid-running", "status": "queued"}, 202)+ running = self._response({"id": "vid-running", "status": "in_progress"})+ clock = iter([0.0, 1.0, ofox.DEFAULT_RUN_TIMEOUT_SECONDS + 1])+ with (+ patch.object(ofox.requests, "post", return_value=submit),+ patch.object(ofox.requests, "get", return_value=running),+ patch.object(ofox.time, "monotonic", side_effect=lambda: next(clock)),+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError) as raised:+ ofox.generate_videos("sunrise", 5)++ self.assertEqual(raised.exception.task_id, "vid-running")++ def test_network_retry_stops_when_total_run_deadline_is_reached(self):+ # 第一次请求前仍有 59 秒;请求异常返回时总截止时间已经过去,不能继续+ # 执行其余五次网络重试,也不能再进入退避 sleep。+ config.app["ofox_run_timeout"] = 60+ clock = iter([0.0, 1.0, 61.0])+ with (+ patch.object(+ ofox.requests,+ "get",+ side_effect=requests.exceptions.Timeout("slow"),+ ) as get,+ patch.object(ofox.time, "monotonic", side_effect=lambda: next(clock)),+ patch.object(ofox.time, "sleep") as sleep,+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError) as raised:+ ofox._wait_for_task(+ task_id="vid-network-timeout",+ videos_url="https://ofox.example.test/v1/videos",+ headers={},+ api_key="ofox-test-key",+ )++ self.assertEqual(raised.exception.task_id, "vid-network-timeout")+ self.assertEqual(get.call_count, 1)+ self.assertEqual(get.call_args.kwargs["timeout"], (29.5, 29.5))+ sleep.assert_not_called()++ def test_expired_run_deadline_stops_before_remote_poll(self):+ config.app["ofox_run_timeout"] = 60+ clock = iter([0.0, 61.0])+ with (+ patch.object(ofox.requests, "get") as get,+ patch.object(ofox.time, "monotonic", side_effect=lambda: next(clock)),+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError) as raised:+ ofox._wait_for_task(+ task_id="vid-expired",+ videos_url="https://ofox.example.test/v1/videos",+ headers={},+ api_key="ofox-test-key",+ )++ self.assertEqual(raised.exception.task_id, "vid-expired")+ get.assert_not_called()++ def test_active_poll_sleep_is_capped_by_remaining_deadline(self):+ config.app.update(+ {+ "ofox_run_timeout": 60,+ "ofox_poll_interval": 5,+ }+ )+ running = self._response({"id": "vid-running", "status": "in_progress"})+ # 第一次响应完成时只剩 0.25 秒,应只休眠剩余时间;下一轮在发起+ # 网络请求前发现截止时间已过,避免额外一次远端请求。+ clock = iter([0.0, 59.0, 59.75, 60.1])+ with (+ patch.object(ofox.requests, "get", return_value=running) as get,+ patch.object(ofox.time, "monotonic", side_effect=lambda: next(clock)),+ patch.object(ofox.time, "sleep") as sleep,+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError):+ ofox._wait_for_task(+ task_id="vid-running",+ videos_url="https://ofox.example.test/v1/videos",+ headers={},+ api_key="ofox-test-key",+ )++ self.assertEqual(get.call_count, 1)+ sleep.assert_called_once_with(0.25)++ def test_retry_backoff_is_capped_by_remaining_deadline(self):+ config.app["ofox_run_timeout"] = 60+ clock = iter([0.0, 59.0, 59.75, 60.1])+ with (+ patch.object(+ ofox.requests,+ "get",+ side_effect=requests.exceptions.Timeout("slow"),+ ) as get,+ patch.object(ofox.time, "monotonic", side_effect=lambda: next(clock)),+ patch.object(ofox.time, "sleep") as sleep,+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError):+ ofox._wait_for_task(+ task_id="vid-retry-deadline",+ videos_url="https://ofox.example.test/v1/videos",+ headers={},+ api_key="ofox-test-key",+ )++ self.assertEqual(get.call_count, 1)+ self.assertEqual(get.call_args.kwargs["timeout"], (0.5, 0.5))+ sleep.assert_called_once_with(0.25)++ def test_non_retryable_poll_response_stops_and_redacts_secret(self):+ unauthorized = self._response(+ {"error": {"code": "unauthorized", "message": "ofox-test-key"}},+ status_code=401,+ )+ with (+ patch.object(ofox.requests, "get", return_value=unauthorized) as get,+ patch.object(ofox.time, "sleep") as sleep,+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError) as raised:+ ofox._wait_for_task(+ task_id="vid-unauthorized",+ videos_url="https://ofox.example.test/v1/videos",+ headers={},+ api_key="ofox-test-key",+ )++ self.assertEqual(raised.exception.task_id, "vid-unauthorized")+ self.assertNotIn("ofox-test-key", str(raised.exception))+ self.assertEqual(get.call_count, 1)+ sleep.assert_not_called()++ def test_malformed_poll_payload_preserves_remote_task_id(self):+ for payload in ([], None, "in_progress"):+ with self.subTest(payload=payload):+ with patch.object(+ ofox.requests, "get", return_value=self._response(payload)+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError) as raised:+ ofox._wait_for_task(+ task_id="vid-malformed",+ videos_url="https://ofox.example.test/v1/videos",+ headers={},+ api_key="ofox-test-key",+ )++ self.assertEqual(raised.exception.task_id, "vid-malformed")++ def test_all_terminal_failure_statuses_end_the_task_without_billing_doubt(self):+ # 远端明确失败(如触发内容审核)意味着任务已结束、无计费悬念。返回+ # None 让上层跳过该关键词继续生成,而不是中止整条视频。+ for status in ofox.TERMINAL_FAILURE_STATUSES:+ with self.subTest(status=status):+ terminal = self._response(+ {"id": "vid-terminal", "status": status, "error": {}}+ )+ with patch.object(ofox.requests, "get", return_value=terminal):+ result = ofox._wait_for_task(+ task_id="vid-terminal",+ videos_url="https://ofox.example.test/v1/videos",+ headers={},+ api_key="ofox-test-key",+ )++ self.assertIsNone(result)++ def test_terminal_failure_returns_empty_result_from_generate(self):+ submit = self._response({"id": "vid-failed", "status": "queued"}, 202)+ failed = self._response(+ {+ "id": "vid-failed",+ "status": "failed",+ "error": {"code": "content_policy", "message": "rejected"},+ }+ )+ with (+ patch.object(ofox.requests, "post", return_value=submit),+ patch.object(ofox.requests, "get", return_value=failed),+ ):+ result = ofox.generate_videos("sunrise", 5)++ self.assertEqual(result, [])++ def test_unknown_remote_status_is_unconfirmed_and_preserves_task_id(self):+ unknown = self._response({"id": "vid-unknown", "status": "pausing"})+ with patch.object(ofox.requests, "get", return_value=unknown):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError) as raised:+ ofox._wait_for_task(+ task_id="vid-unknown",+ videos_url="https://ofox.example.test/v1/videos",+ headers={},+ api_key="ofox-test-key",+ )++ self.assertEqual(raised.exception.task_id, "vid-unknown")++ def test_missing_task_id_is_treated_as_unconfirmed(self):+ for payload in ({}, {"id": " "}, [], None):+ with self.subTest(payload=payload):+ with (+ patch.object(+ ofox.requests,+ "post",+ return_value=self._response(payload, 202),+ ),+ patch.object(ofox.requests, "get") as get,+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError):+ ofox.generate_videos("sunrise", 5)+ get.assert_not_called()++ def test_completed_task_without_downloadable_url_stops_as_protocol_error(self):+ for urls in (None, [], ["not-a-url"], [123, {"url": "x"}]):+ with self.subTest(urls=urls):+ submit = self._response({"id": "vid-no-url", "status": "queued"}, 202)+ completed = self._response(+ {"id": "vid-no-url", "status": "completed", "unsigned_urls": urls}+ )+ with (+ patch.object(ofox.requests, "post", return_value=submit),+ patch.object(ofox.requests, "get", return_value=completed),+ ):+ with self.assertRaises(ofox.OFoxError) as raised:+ ofox.generate_videos("sunrise", 5)++ self.assertEqual(raised.exception.task_id, "vid-no-url")++ def test_first_valid_unsigned_url_is_selected(self):+ submit = self._response({"id": "vid-multi", "status": "queued"}, 202)+ completed = self._response(+ {+ "id": "vid-multi",+ "status": "completed",+ "unsigned_urls": [+ None,+ "ftp://invalid.example.com/a.mp4",+ "https://cdn.example.com/first-valid.mp4",+ "https://cdn.example.com/second.mp4",+ ],+ }+ )+ with (+ patch.object(ofox.requests, "post", return_value=submit),+ patch.object(ofox.requests, "get", return_value=completed),+ ):+ result = ofox.generate_videos("sunrise", 5)++ self.assertEqual(result[0].url, "https://cdn.example.com/first-valid.mp4")+++class TestOFoxMaterialIntegration(unittest.TestCase):+ @staticmethod+ def _item(term: str, url: str) -> MaterialInfo:+ return MaterialInfo(+ provider="ofox",+ url=url,+ duration=5,+ source_info={+ "provider": "ofox",+ "search_term": term,+ "asset_id": f"task-{term}",+ },+ )++ def test_on_demand_generation_stops_when_duration_is_covered(self):+ with (+ patch.object(+ ofox,+ "generate_videos",+ side_effect=[+ [self._item("one", "https://cdn.example.com/one.mp4")],+ [self._item("two", "https://cdn.example.com/two.mp4")],+ ],+ ) as generate,+ patch.object(+ material,+ "save_video",+ side_effect=["/tmp/one.mp4", "/tmp/two.mp4"],+ ),+ patch.object(material, "_persist_material_sources") as persist,+ ):+ result = material.download_videos(+ task_id="ofox-materials",+ search_terms=["one", "two", "three"],+ source="ofox",+ audio_duration=10,+ max_clip_duration=5,+ )++ self.assertEqual(result, ["/tmp/one.mp4", "/tmp/two.mp4"])+ self.assertEqual(generate.call_count, 2)+ self.assertEqual(persist.call_args.args[0], "ofox-materials")+ self.assertEqual(len(persist.call_args.args[1]), 2)++ def test_failed_keyword_is_skipped_and_generation_continues(self):+ # 单个关键词被远端明确判失败(generate_videos 返回空列表)时应跳过该+ # 片段继续下一个关键词,而不是中止整条视频。+ with (+ patch.object(+ ofox,+ "generate_videos",+ side_effect=[+ [],+ [self._item("two", "https://cdn.example.com/two.mp4")],+ [self._item("three", "https://cdn.example.com/three.mp4")],+ ],+ ) as generate,+ patch.object(+ material,+ "save_video",+ side_effect=["/tmp/two.mp4", "/tmp/three.mp4"],+ ),+ patch.object(material, "_persist_material_sources"),+ ):+ result = material.download_videos(+ task_id="ofox-skip-failed",+ search_terms=["one", "two", "three"],+ source="ofox",+ audio_duration=10,+ max_clip_duration=5,+ )++ self.assertEqual(result, ["/tmp/two.mp4", "/tmp/three.mp4"])+ self.assertEqual(generate.call_count, 3)++ def test_non_positive_audio_duration_avoids_paid_submission(self):+ for audio_duration in (0, -1, -0.1):+ with self.subTest(audio_duration=audio_duration):+ with (+ patch.object(ofox, "generate_videos") as generate,+ patch.object(material, "_persist_material_sources") as persist,+ ):+ result = material.download_videos(+ task_id="ofox-no-audio",+ search_terms=["one", "two"],+ source="ofox",+ audio_duration=audio_duration,+ max_clip_duration=5,+ )++ self.assertEqual(result, [])+ generate.assert_not_called()+ persist.assert_called_once_with("ofox-no-audio", [])++ def test_non_finite_or_invalid_audio_duration_fails_before_paid_submission(self):+ for audio_duration in (float("nan"), float("inf"), float("-inf"), None, "bad"):+ with self.subTest(audio_duration=audio_duration):+ with patch.object(ofox, "generate_videos") as generate:+ with self.assertRaises(ofox.OFoxError) as raised:+ material.download_videos(+ task_id="ofox-invalid-audio",+ search_terms=["one", "two"],+ source="ofox",+ audio_duration=audio_duration,+ max_clip_duration=5,+ )++ self.assertIn("audio duration", str(raised.exception))+ generate.assert_not_called()++ def test_invalid_clip_duration_fails_before_paid_submission(self):+ for clip_duration in (0, -1, None, "bad", float("nan"), float("inf")):+ with self.subTest(clip_duration=clip_duration):+ with patch.object(ofox, "generate_videos") as generate:+ with self.assertRaises(ofox.OFoxError) as raised:+ material.download_videos(+ task_id="ofox-invalid-clip",+ search_terms=["one", "two"],+ source="ofox",+ audio_duration=10,+ max_clip_duration=clip_duration,+ )++ self.assertIn("clip duration", str(raised.exception))+ generate.assert_not_called()++ def test_unconfirmed_task_stops_later_paid_submissions(self):+ with (+ patch.object(+ ofox,+ "generate_videos",+ side_effect=ofox.OFoxUnconfirmedTaskError(+ "unknown", task_id="vid-stuck"+ ),+ ) as generate,+ patch.object(material, "save_video") as save,+ ):+ with self.assertRaises(ofox.OFoxUnconfirmedTaskError):+ material.download_videos(+ task_id="ofox-unconfirmed",+ search_terms=["one", "two"],+ source="ofox",+ audio_duration=10,+ max_clip_duration=5,+ )++ self.assertEqual(generate.call_count, 1)+ save.assert_not_called()++ def test_download_failure_stops_later_paid_submissions(self):+ first_item = self._item("one", "https://cdn.example.com/one.mp4")+ with (+ patch.object(+ ofox, "generate_videos", return_value=[first_item]+ ) as generate,+ patch.object(material, "_save_generated_video_with_retry", return_value=""),+ ):+ with self.assertRaises(ofox.OFoxDownloadError) as raised:+ material.download_videos(+ task_id="ofox-download-failed",+ search_terms=["one", "two"],+ source="ofox",+ audio_duration=10,+ max_clip_duration=5,+ )++ self.assertEqual(raised.exception.task_id, "task-one")+ self.assertEqual(generate.call_count, 1)++ def test_later_download_failure_preserves_prior_material_sources(self):+ first_item = self._item("one", "https://cdn.example.com/one.mp4")+ second_item = self._item("two", "https://cdn.example.com/two.mp4")+ with (+ patch.object(+ ofox,+ "generate_videos",+ side_effect=[[first_item], [second_item]],+ ) as generate,+ patch.object(+ material,+ "_save_generated_video_with_retry",+ side_effect=["/tmp/one.mp4", ""],+ ),+ patch.object(material, "_persist_material_sources") as persist,+ ):+ with self.assertRaises(ofox.OFoxDownloadError) as raised:+ material.download_videos(+ task_id="ofox-partial-download",+ search_terms=["one", "two", "three"],+ source="ofox",+ audio_duration=15,+ max_clip_duration=5,+ )++ self.assertEqual(raised.exception.task_id, "task-two")+ self.assertEqual(generate.call_count, 2)+ persisted_task_id, persisted_sources = persist.call_args.args+ self.assertEqual(persisted_task_id, "ofox-partial-download")+ self.assertEqual(len(persisted_sources), 1)+ self.assertEqual(persisted_sources[0]["asset_id"], "task-one")++ def test_task_preflight_rejects_missing_ofox_key_before_script_generation(self):+ params = VideoParams(+ video_subject="OFox preflight",+ video_source="ofox",+ )+ memory_state = sm.MemoryState()+ with (+ patch.object(ofox, "is_enabled", return_value=False),+ patch.object(task_service.sm, "state", memory_state),+ patch.object(task_service, "generate_script") as generate_script,+ ):+ result = task_service.start("ofox-preflight", params, stop_at="materials")++ self.assertEqual(result["failed_stage"], "preflight")+ self.assertIn("OFox API key", result["error"])+ generate_script.assert_not_called()++ def test_task_records_ofox_material_error_and_remote_task_id(self):+ params = VideoParams(+ video_subject="OFox material failure",+ video_source="ofox",+ )+ memory_state = sm.MemoryState()+ error = ofox.OFoxUnconfirmedTaskError(+ "remote state unknown", task_id="vid-recover"+ )+ with (+ patch.object(task_service.sm, "state", memory_state),+ patch.object(task_service.material, "download_videos", side_effect=error),+ ):+ result = task_service.get_video_materials(+ task_id="ofox-material-error",+ params=params,+ video_terms=["scene"],+ audio_duration=5,+ )++ self.assertIsNone(result)+ failed = memory_state.get_task("ofox-material-error")+ self.assertEqual(failed["failed_stage"], "materials")+ self.assertEqual(failed["ofox_task_id"], "vid-recover")++ def test_task_records_paid_task_id_when_generated_video_download_fails(self):+ params = VideoParams(+ video_subject="OFox download failure",+ video_source="ofox",+ )+ memory_state = sm.MemoryState()+ error = ofox.OFoxDownloadError(+ "generated video download failed",+ task_id="vid-paid-result",+ )+ with (+ patch.object(task_service.sm, "state", memory_state),+ patch.object(task_service.material, "download_videos", side_effect=error),+ ):+ result = task_service.get_video_materials(+ task_id="ofox-download-error",+ params=params,+ video_terms=["scene"],+ audio_duration=5,+ )++ self.assertIsNone(result)+ failed = memory_state.get_task("ofox-download-error")+ self.assertEqual(failed["failed_stage"], "materials")+ self.assertEqual(failed["ofox_task_id"], "vid-paid-result")+++if __name__ == "__main__":+ unittest.main()diff --git a/test/services/test_webui_generation_defaults.py b/test/services/test_webui_generation_defaults.pyindex 2da6ac15..22955abd 100644--- a/test/services/test_webui_generation_defaults.py+++ b/test/services/test_webui_generation_defaults.py@@ -339,6 +339,29 @@ def test_invalid_saved_generation_settings_fall_back_without_breaking_webui():assert app.session_state["loomloom_video_scene_count"] == 1+def test_ofox_source_shows_unchecked_paid_task_confirmation():+ test_app_config = dict(+ config.app,+ video_source="ofox",+ ofox_api_key="",+ )+ test_ui_config = dict(+ config.ui,+ language="en",+ voice_mode="none",+ )++ with (+ patch.object(config, "app", test_app_config),+ patch.object(config, "ui", test_ui_config),+ patch.object(config, "save_config"),+ ):+ app = _new_app()++ assert _widget_by_key(app.selectbox, "video_source_select").value == "ofox"+ assert _widget_by_key(app.checkbox, "ofox_confirm_charge").value is False++def test_seedance_source_shows_unchecked_paid_task_confirmation():test_app_config = dict(config.app,diff --git a/test/services/test_webui_ofox.py b/test/services/test_webui_ofox.pynew file mode 100644index 00000000..b79846f5--- /dev/null+++ b/test/services/test_webui_ofox.py@@ -0,0 +1,58 @@+from pathlib import Path+from unittest.mock import patch++from streamlit.testing.v1 import AppTest++from app.config import config+++ROOT_DIR = Path(__file__).parent.parent.parent+WEBUI_MAIN = ROOT_DIR / "webui" / "Main.py"+++def _widget_by_key(elements, key):+ return next(+ item+ for item in elements+ if str(getattr(item, "key", "")) == key+ or str(getattr(item, "key", "")).startswith(f"{key}_")+ )+++def test_ofox_source_requires_confirmation_then_submits_without_secret_in_params():+ test_config = dict(+ config.app,+ llm_provider="openai",+ video_source="pexels",+ ofox_api_key="ofox-secret",+ )+ with (+ patch.object(config, "app", test_config),+ patch.object(config, "try_save_config", return_value=True),+ patch("app.services.webui_task.submit_generation") as submit_generation,+ ):+ app = AppTest.from_file(str(WEBUI_MAIN), default_timeout=60)+ 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"+ ).run()+ _widget_by_key(app.selectbox, "video_source_select").select("ofox").run()++ _widget_by_key(app.button, "generate_video_button").click().run()+ assert submit_generation.call_count == 0+ assert any("confirm" in str(item.value).lower() for item in app.error)++ _widget_by_key(app.checkbox, "ofox_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"]+ assert submitted_params.video_source == "ofox"+ assert "ofox-secret" not in submitted_params.model_dump_json()+ assert [str(item.value) for item in app.exception] == []diff --git a/test/services/test_webui_settings_transfer.py b/test/services/test_webui_settings_transfer.pyindex 2ac98078..5df80f26 100644--- a/test/services/test_webui_settings_transfer.py+++ b/test/services/test_webui_settings_transfer.py@@ -123,6 +123,7 @@ def _sample_config_sections():"upload_post_api_key": "api-key-123","upload_post_username": "my-username","volcengine_seedance_api_key": "ark-seedance-key",+ "ofox_api_key": "ofox-backup-key",},"azure": {"speech_key": "azure-key", "speech_region": "westeurope"},"elevenlabs": {"api_key": "eleven-key", "model_id": "eleven_v3"},@@ -225,11 +226,12 @@ def test_key_backup_collects_credentials_and_their_companion_settings():"upload_post_api_key": "api-key-123","upload_post_username": "my-username","volcengine_seedance_api_key": "ark-seedance-key",+ "ofox_api_key": "ofox-backup-key",},"azure": {"speech_key": "azure-key", "speech_region": "westeurope"},"elevenlabs": {"api_key": "eleven-key"},}- assert count_backup_keys(backup) == 11+ assert count_backup_keys(backup) == 12def test_key_backup_carries_llm_provider_extra_fields_with_the_key():@@ -284,6 +286,7 @@ def test_key_backup_round_trip_restores_every_saved_key():assert restored["app"]["upload_post_api_key"] == "api-key-123"assert restored["app"]["upload_post_username"] == "my-username"assert restored["app"]["volcengine_seedance_api_key"] == "ark-seedance-key"+ assert restored["app"]["ofox_api_key"] == "ofox-backup-key"def test_key_backup_import_ignores_unknown_sections_and_non_key_settings():@@ -333,6 +336,9 @@ def test_credential_widget_state_keys_match_settings_inputs():assert credential_widget_state_keys("app", "volcengine_seedance_api_key") == ("volcengine_seedance_api_key_input",)+ assert credential_widget_state_keys("app", "ofox_api_key") == (+ "ofox_api_key_input",+ )assert credential_widget_state_keys("azure", "speech_key") == ("azure_speech_key_input",)diff --git a/webui/Main.py b/webui/Main.pyindex ac7b0cfc..e03b3c5e 100644--- a/webui/Main.py+++ b/webui/Main.py@@ -50,6 +50,7 @@ from app.services import (loomloom,material,video,+ ofox,volcengine_seedance,voice,webui_task,@@ -106,7 +107,7 @@ LOOMLOOM_MAX_POLL_FAILURES = 5# config.toml、历史任务和 API 请求中的字段语义,旧用户升级后无需迁移配置。VIDEO_SOURCE_GROUPS = {"stock_video": ("pexels", "pixabay", "coverr"),- "ai_video": ("wavespeed", "volcengine_seedance", "loomloom"),+ "ai_video": ("wavespeed", "volcengine_seedance", "ofox", "loomloom"),"ai_image": ("openai_image",),"local": ("local",),}@@ -560,6 +561,7 @@ def _initialize_session_state():"loomloom_video_confirm_charge": False,"wavespeed_confirm_charge": False,"volcengine_seedance_confirm_charge": False,+ "ofox_confirm_charge": False,# AI 视频按素材段计费,默认只生成一段,用户确认效果后再主动增加数量。"loomloom_video_scene_count": _saved_ui_number("loomloom_video_scene_count",@@ -3385,6 +3387,48 @@ def _render_settings_dialog():seedance_base_url.strip() or volcengine_seedance.DEFAULT_BASE_URL,)+ st.markdown("**OFox**")+ ofox_api_key = st.text_input(+ tr("OFox API Key"),+ value=str(config.app.get("ofox_api_key", "") or ""),+ type="password",+ key="ofox_api_key_input",+ )+ _set_runtime_config("app", "ofox_api_key", ofox_api_key.strip())+ ofox_model = st.text_input(+ tr("OFox Text-to-Video Model"),+ value=str(+ config.app.get(+ "ofox_text_to_video_model",+ ofox.DEFAULT_MODEL_ID,+ )+ or ofox.DEFAULT_MODEL_ID+ ),+ key="ofox_text_to_video_model_input",+ )+ _set_runtime_config(+ "app", "ofox_text_to_video_model", ofox_model.strip()+ )+ configured_ofox_base_url = str(+ config.app.get("ofox_base_url", ofox.DEFAULT_BASE_URL)+ or ofox.DEFAULT_BASE_URL+ ).strip()+ ofox_base_url = st.text_input(+ tr("OFox Base URL"),+ value=(+ ""+ if configured_ofox_base_url == ofox.DEFAULT_BASE_URL+ else configured_ofox_base_url+ ),+ placeholder=ofox.DEFAULT_BASE_URL,+ key="ofox_base_url_input",+ )+ _set_runtime_config(+ "app",+ "ofox_base_url",+ ofox_base_url.strip() or ofox.DEFAULT_BASE_URL,+ )+with st.container(border=True):st.markdown(f"#### {tr('AI Image Generation APIs')}")st.caption(tr("AI Image Generation APIs Help"))@@ -4243,6 +4287,7 @@ def _render_video_settings(panel, params):"coverr": tr("Coverr"),"wavespeed": tr("WaveSpeed AI Video"),"volcengine_seedance": tr("Volcano Engine Seedance"),+ "ofox": tr("OFox AI Video"),"loomloom": tr("Shengsuan Cloud AI Video"),"openai_image": tr("OpenAI Compatible Text-to-Image"),"local": tr("Local file"),@@ -4270,6 +4315,8 @@ def _render_video_settings(panel, params):st.caption(tr("WaveSpeed AI Video Help"))if params.video_source == "volcengine_seedance":st.caption(tr("Volcano Engine Seedance Help"))+ if params.video_source == "ofox":+ st.caption(tr("OFox AI Video Help"))if params.video_source == "local":# Streamlit 的文件类型校验对扩展名大小写敏感,这里同时放行大小写两种形式。local_file_types = sorted(@@ -4491,6 +4538,8 @@ def _render_video_settings(panel, params):_render_wavespeed_video_settings(params)if params.video_source == "volcengine_seedance":_render_seedance_video_settings(params)+ if params.video_source == "ofox":+ _render_ofox_video_settings(params)return uploaded_files@@ -4552,6 +4601,30 @@ def _render_seedance_video_settings(params):)+def _render_ofox_video_settings(params):+ """展示预计付费任务数量,并要求用户明确确认 OFox 生成费用。"""+ clip_duration = max(int(params.video_clip_duration or 1), 1)+ video_count = max(int(params.video_count or 1), 1)+ estimated_range = _estimate_voiceover_duration_range(+ str(params.video_script or ""), params.voice_rate+ )+ if estimated_range:+ min_clips = max(math.ceil(estimated_range[0] * video_count / clip_duration), 1)+ max_clips = max(+ math.ceil(estimated_range[1] * video_count / clip_duration), min_clips+ )+ st.warning(+ tr("OFox Billing Notice").format(min=min_clips, max=max_clips)+ )+ else:+ st.warning(tr("OFox Billing Notice Without Script"))+ st.checkbox(+ tr("Confirm OFox Charge"),+ key="ofox_confirm_charge",+ help=tr("Confirm OFox Charge Help"),+ )++def _estimate_voiceover_duration_range(text: str, voice_rate: float) -> tuple[float, float] | None:@@ -6224,6 +6297,7 @@ def _render_generation_controls("coverr","wavespeed","volcengine_seedance",+ "ofox","loomloom","openai_image","local",@@ -6283,6 +6357,20 @@ def _render_generation_controls(st.error(tr("Confirm Volcano Engine Seedance Charge Required"))st.stop()+ if params.video_source == "ofox" and not (+ ofox.is_enabled(config.snapshot_config_with_pending(config.app))+ ):+ _remove_active_generation_task(task_id)+ st.error(tr("Please Enter the OFox API Key"))+ st.stop()++ if params.video_source == "ofox" and not st.session_state.get(+ "ofox_confirm_charge", False+ ):+ _remove_active_generation_task(task_id)+ st.error(tr("Confirm OFox Charge Required"))+ st.stop()+if params.video_source == "openai_image" and not material.is_openai_image_enabled(config.snapshot_config_with_pending(config.app)):diff --git a/webui/i18n/de.json b/webui/i18n/de.jsonindex 4d7ed1f4..e3cf829d 100644--- a/webui/i18n/de.json+++ b/webui/i18n/de.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Upload-Post Profil-Benutzername","Upload-Post Profile Username Help": "Geben Sie den unter [Manage Users]({manage_users_url}) angezeigten Benutzernamen ein, nicht die E-Mail-Adresse Ihres Upload-Post-Kontos. Dieser Veröffentlichungsbenutzer muss mit den ausgewählten Plattformen verbunden sein.","Upload-Post Setup Guide": "Bevor Sie die automatische Veröffentlichung aktivieren:\n1. Erstellen Sie unter [API Keys]({api_keys_url}) einen API-Schlüssel.\n2. Erstellen oder wählen Sie unter [Manage Users]({manage_users_url}) einen Veröffentlichungsbenutzer und verbinden Sie die Zielplattformen.\n\nGeben Sie unten dessen **Benutzernamen** ein, nicht die E-Mail-Adresse Ihres Upload-Post-Kontos.",- "YouTube Privacy Status": "YouTube-Datenschutzstatus"+ "YouTube Privacy Status": "YouTube-Datenschutzstatus",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Erzeugen Sie neue Clips über die offizielle OFox API. Jeder eingereichte Clip ist ein kostenpflichtiger OFox-Auftrag.",+ "OFox API Key": "OFox API-Schlüssel ([API-Schlüssel abrufen](https://ofox.ai))",+ "OFox Text-to-Video Model": "OFox Text-zu-Video-Modell",+ "OFox Base URL": "OFox Base-URL",+ "Please Enter the OFox API Key": "Bitte geben Sie den **OFox API-Schlüssel** ein",+ "OFox Billing Notice": "Jeder erzeugte Clip wird von OFox berechnet. Auf Grundlage der geschätzten Sprecher- und Clipdauer werden ungefähr {min}–{max} kostenpflichtige Aufträge übermittelt. Die Generierung endet, sobald genügend Material vorhanden ist.",+ "OFox Billing Notice Without Script": "Jeder erzeugte Clip wird von OFox berechnet. Geben Sie ein Videoskript ein oder erzeugen Sie eines, um die geschätzte Anzahl der Aufträge anzuzeigen.",+ "Confirm OFox Charge": "Ich verstehe, dass die OFox-Generierung kostenpflichtige OFox-Aufträge erstellt",+ "Confirm OFox Charge Help": "OFox-Clips werden einzeln übermittelt, bis sie die Dauer der Sprachausgabe abdecken. OFox berechnet jeden eingereichten Generierungsauftrag.",+ "Confirm OFox Charge Required": "Bitte bestätigen Sie die Kosten der OFox-Generierung, bevor Sie das Video erstellen."}}diff --git a/webui/i18n/en.json b/webui/i18n/en.jsonindex f9e7cd82..c155f8c5 100644--- a/webui/i18n/en.json+++ b/webui/i18n/en.json@@ -444,6 +444,17 @@"Upload-Post Profile Username": "Upload-Post Profile Username","Upload-Post Profile Username Help": "Enter the Username shown on [Manage Users]({manage_users_url}), not your Upload-Post account email. This publishing user must be connected to the selected platforms.","Upload-Post Setup Guide": "Before enabling auto-publish:\n1. Create an API key on [API Keys]({api_keys_url}).\n2. Create or select a publishing user on [Manage Users]({manage_users_url}), then connect the target platforms.\n\nEnter that publishing user's **Username** below, not your Upload-Post account email.",- "YouTube Privacy Status": "YouTube Privacy Status"+ "YouTube Privacy Status": "YouTube Privacy Status",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Generate brand-new clips through the OFox multi-model video API (Seedance, Wan, and more behind one key). Each submitted clip is a paid task.",+ "OFox API Key": "OFox API Key ([Get API Key](https://ofox.ai))",+ "OFox Text-to-Video Model": "OFox Text-to-Video Model",+ "OFox Base URL": "OFox Base URL",+ "Please Enter the OFox API Key": "Please enter the **OFox API Key**",+ "OFox Billing Notice": "Each generated clip is billed by OFox. Based on the estimated voiceover duration and clip duration, roughly {min}-{max} paid task(s) will be submitted. Generation stops as soon as enough footage is collected.",+ "OFox Billing Notice Without Script": "Each generated clip is billed by OFox. Enter or generate the video script to see an estimated task count.",+ "Confirm OFox Charge": "I understand OFox video generation creates paid tasks",+ "Confirm OFox Charge Help": "OFox clips are submitted one at a time and stop once they cover the voiceover duration. OFox bills each submitted generation task.",+ "Confirm OFox Charge Required": "Please confirm the OFox charge before generating the video."}}diff --git a/webui/i18n/es.json b/webui/i18n/es.jsonindex 984cfb9a..e1a93ba9 100644--- a/webui/i18n/es.json+++ b/webui/i18n/es.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Nombre de usuario del perfil de Upload-Post","Upload-Post Profile Username Help": "Introduce el nombre de usuario que aparece en [Manage Users]({manage_users_url}), no el correo de tu cuenta de Upload-Post. Este usuario de publicación debe estar conectado a las plataformas seleccionadas.","Upload-Post Setup Guide": "Antes de activar la publicación automática:\n1. Crea una clave API en [API Keys]({api_keys_url}).\n2. Crea o selecciona un usuario de publicación en [Manage Users]({manage_users_url}) y conecta las plataformas de destino.\n\nIntroduce abajo el **nombre de usuario** de publicación, no el correo de tu cuenta de Upload-Post.",- "YouTube Privacy Status": "Estado de privacidad de YouTube"+ "YouTube Privacy Status": "Estado de privacidad de YouTube",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Genera clips nuevos mediante la API oficial OFox. Cada clip enviado crea una tarea de pago en OFox.",+ "OFox API Key": "Clave API de OFox ([Obtener clave API](https://ofox.ai))",+ "OFox Text-to-Video Model": "Modelo de texto a vídeo de OFox",+ "OFox Base URL": "URL base de OFox",+ "Please Enter the OFox API Key": "Introduce la **clave API de OFox**",+ "OFox Billing Notice": "OFox cobra cada clip generado. Según la duración estimada de la narración y de los clips, se enviarán aproximadamente entre {min} y {max} tareas de pago. La generación se detiene en cuanto haya suficiente material.",+ "OFox Billing Notice Without Script": "OFox cobra cada clip generado. Introduce o genera el guion del vídeo para ver una estimación del número de tareas.",+ "Confirm OFox Charge": "Entiendo que la generación con OFox crea tareas de pago en OFox",+ "Confirm OFox Charge Help": "Los clips de OFox se envían uno a uno y se detienen cuando cubren la duración de la narración. OFox cobra cada tarea de generación enviada.",+ "Confirm OFox Charge Required": "Confirma el coste de generación de OFox antes de generar el vídeo."}}diff --git a/webui/i18n/fr.json b/webui/i18n/fr.jsonindex aa2286cd..9ecbdec3 100644--- a/webui/i18n/fr.json+++ b/webui/i18n/fr.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Nom d'utilisateur du profil Upload-Post","Upload-Post Profile Username Help": "Saisissez le nom d'utilisateur affiché dans [Manage Users]({manage_users_url}), et non l'adresse e-mail de votre compte Upload-Post. Cet utilisateur de publication doit être connecté aux plateformes sélectionnées.","Upload-Post Setup Guide": "Avant d'activer la publication automatique :\n1. Créez une clé API dans [API Keys]({api_keys_url}).\n2. Créez ou sélectionnez un utilisateur de publication dans [Manage Users]({manage_users_url}), puis connectez les plateformes cibles.\n\nSaisissez ci-dessous son **nom d'utilisateur**, et non l'adresse e-mail de votre compte Upload-Post.",- "YouTube Privacy Status": "Statut de confidentialité YouTube"+ "YouTube Privacy Status": "Statut de confidentialité YouTube",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Générez de nouveaux clips avec l’API officielle OFox. Chaque clip soumis crée une tâche OFox payante.",+ "OFox API Key": "Clé API OFox ([Obtenir une clé API](https://ofox.ai))",+ "OFox Text-to-Video Model": "Modèle texte-vidéo OFox",+ "OFox Base URL": "URL de base OFox",+ "Please Enter the OFox API Key": "Saisissez la **clé API OFox**",+ "OFox Billing Notice": "Chaque clip généré est facturé par OFox. D’après la durée estimée de la narration et des clips, environ {min} à {max} tâches payantes seront soumises. La génération s’arrête dès que suffisamment de séquences ont été obtenues.",+ "OFox Billing Notice Without Script": "Chaque clip généré est facturé par OFox. Saisissez ou générez le script vidéo pour afficher une estimation du nombre de tâches.",+ "Confirm OFox Charge": "Je comprends que la génération OFox crée des tâches OFox payantes",+ "Confirm OFox Charge Help": "Les clips OFox sont soumis un par un jusqu’à couvrir la durée de la narration. OFox facture chaque tâche de génération soumise.",+ "Confirm OFox Charge Required": "Veuillez confirmer les frais de génération OFox avant de créer la vidéo."}}diff --git a/webui/i18n/id.json b/webui/i18n/id.jsonindex 072e3300..6c11cb02 100644--- a/webui/i18n/id.json+++ b/webui/i18n/id.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Nama Pengguna Profil Upload-Post","Upload-Post Profile Username Help": "Masukkan Username yang ditampilkan di [Manage Users]({manage_users_url}), bukan email akun Upload-Post Anda. Pengguna penerbitan ini harus terhubung ke platform yang dipilih.","Upload-Post Setup Guide": "Sebelum mengaktifkan publikasi otomatis:\n1. Buat kunci API di [API Keys]({api_keys_url}).\n2. Buat atau pilih pengguna penerbitan di [Manage Users]({manage_users_url}), lalu hubungkan platform tujuan.\n\nMasukkan **Username** pengguna penerbitan tersebut di bawah, bukan email akun Upload-Post Anda.",- "YouTube Privacy Status": "Status Privasi YouTube"+ "YouTube Privacy Status": "Status Privasi YouTube",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Buat klip baru melalui API resmi OFox. Setiap klip yang dikirim merupakan tugas OFox berbayar.",+ "OFox API Key": "Kunci API OFox ([Dapatkan Kunci API](https://ofox.ai))",+ "OFox Text-to-Video Model": "Model teks-ke-video OFox",+ "OFox Base URL": "URL Dasar OFox",+ "Please Enter the OFox API Key": "Masukkan **Kunci API OFox**",+ "OFox Billing Notice": "Setiap klip yang dibuat dikenai biaya oleh OFox. Berdasarkan perkiraan durasi narasi dan klip, sekitar {min}–{max} tugas berbayar akan dikirim. Pembuatan berhenti segera setelah materi mencukupi.",+ "OFox Billing Notice Without Script": "Setiap klip yang dibuat dikenai biaya oleh OFox. Masukkan atau buat naskah video untuk melihat perkiraan jumlah tugas.",+ "Confirm OFox Charge": "Saya memahami bahwa pembuatan OFox menghasilkan tugas OFox berbayar",+ "Confirm OFox Charge Help": "Klip OFox dikirim satu per satu dan berhenti setelah mencakup durasi narasi. OFox mengenakan biaya untuk setiap tugas pembuatan yang dikirim.",+ "Confirm OFox Charge Required": "Konfirmasikan biaya pembuatan OFox sebelum membuat video."}}diff --git a/webui/i18n/it.json b/webui/i18n/it.jsonindex 182f20fd..d3ddd0de 100644--- a/webui/i18n/it.json+++ b/webui/i18n/it.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Nome utente del profilo Upload-Post","Upload-Post Profile Username Help": "Inserisci il nome utente mostrato in [Manage Users]({manage_users_url}), non l'email del tuo account Upload-Post. Questo utente di pubblicazione deve essere collegato alle piattaforme selezionate.","Upload-Post Setup Guide": "Prima di abilitare la pubblicazione automatica:\n1. Crea una chiave API in [API Keys]({api_keys_url}).\n2. Crea o seleziona un utente di pubblicazione in [Manage Users]({manage_users_url}), quindi collega le piattaforme di destinazione.\n\nInserisci qui sotto il suo **nome utente**, non l'email del tuo account Upload-Post.",- "YouTube Privacy Status": "Stato di privacy di YouTube"+ "YouTube Privacy Status": "Stato di privacy di YouTube",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Genera nuovi clip tramite l’API ufficiale OFox. Ogni clip inviato crea un’attività OFox a pagamento.",+ "OFox API Key": "Chiave API OFox ([Ottieni chiave API](https://ofox.ai))",+ "OFox Text-to-Video Model": "Modello testo-video OFox",+ "OFox Base URL": "URL di base OFox",+ "Please Enter the OFox API Key": "Inserisci la **chiave API OFox**",+ "OFox Billing Notice": "Ogni clip generato viene addebitato da OFox. In base alla durata stimata della narrazione e dei clip, verranno inviate circa {min}–{max} attività a pagamento. La generazione si arresta non appena il materiale è sufficiente.",+ "OFox Billing Notice Without Script": "Ogni clip generato viene addebitato da OFox. Inserisci o genera lo script del video per visualizzare una stima del numero di attività.",+ "Confirm OFox Charge": "Comprendo che la generazione OFox crea attività OFox a pagamento",+ "Confirm OFox Charge Help": "I clip OFox vengono inviati uno alla volta e si arrestano quando coprono la durata della narrazione. OFox addebita ogni attività di generazione inviata.",+ "Confirm OFox Charge Required": "Conferma il costo della generazione OFox prima di creare il video."}}diff --git a/webui/i18n/ko.json b/webui/i18n/ko.jsonindex 91e83d56..61f38802 100644--- a/webui/i18n/ko.json+++ b/webui/i18n/ko.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Upload-Post 게시 사용자 이름","Upload-Post Profile Username Help": "[사용자 관리]({manage_users_url})에 표시된 사용자 이름을 입력하세요. Upload-Post 계정 이메일이 아닙니다. 이 게시 사용자는 선택한 플랫폼에 연결되어 있어야 합니다.","Upload-Post Setup Guide": "자동 게시를 활성화하기 전에:\n1. [API 키]({api_keys_url})에서 API 키를 생성하세요.\n2. [사용자 관리]({manage_users_url})에서 게시 사용자를 생성하거나 선택한 다음 대상 플랫폼을 연결하세요.\n\n아래에 Upload-Post 계정 이메일이 아닌 해당 게시 사용자의 **사용자 이름**을 입력하세요.",- "YouTube Privacy Status": "YouTube 공개 상태"+ "YouTube Privacy Status": "YouTube 공개 상태",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "공식 OFox API로 새로운 클립을 생성합니다. 제출하는 각 클립은 유료 OFox 작업입니다.",+ "OFox API Key": "OFox API 키 ([API 키 발급](https://ofox.ai))",+ "OFox Text-to-Video Model": "OFox 텍스트-비디오 모델",+ "OFox Base URL": "OFox 기본 URL",+ "Please Enter the OFox API Key": "**OFox API 키**를 입력하세요",+ "OFox Billing Notice": "생성된 각 클립은 OFox에서 과금됩니다. 예상 내레이션 길이와 클립 길이에 따라 약 {min}~{max}개의 유료 작업이 제출됩니다. 필요한 영상이 확보되면 즉시 생성을 중단합니다.",+ "OFox Billing Notice Without Script": "생성된 각 클립은 OFox에서 과금됩니다. 예상 작업 수를 확인하려면 영상 대본을 입력하거나 생성하세요.",+ "Confirm OFox Charge": "OFox 생성이 유료 OFox 작업을 만든다는 것을 이해했습니다",+ "Confirm OFox Charge Help": "OFox 클립은 하나씩 제출되며 내레이션 길이를 채우면 중단됩니다. Ark는 제출된 각 생성 작업에 요금을 부과합니다.",+ "Confirm OFox Charge Required": "영상을 생성하기 전에 OFox 생성 요금을 확인해 주세요."}}diff --git a/webui/i18n/pt.json b/webui/i18n/pt.jsonindex 4f27d6ea..dd8e13b7 100644--- a/webui/i18n/pt.json+++ b/webui/i18n/pt.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Nome de Usuário do Perfil Upload-Post","Upload-Post Profile Username Help": "Informe o nome de usuário exibido em [Manage Users]({manage_users_url}), não o e-mail da sua conta Upload-Post. Esse usuário de publicação deve estar conectado às plataformas selecionadas.","Upload-Post Setup Guide": "Antes de ativar a publicação automática:\n1. Crie uma chave API em [API Keys]({api_keys_url}).\n2. Crie ou selecione um usuário de publicação em [Manage Users]({manage_users_url}) e conecte as plataformas de destino.\n\nInforme abaixo o **nome de usuário** de publicação, não o e-mail da sua conta Upload-Post.",- "YouTube Privacy Status": "Status de Privacidade do YouTube"+ "YouTube Privacy Status": "Status de Privacidade do YouTube",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Gere novos clipes pela API oficial OFox. Cada clipe enviado cria uma tarefa OFox paga.",+ "OFox API Key": "Chave de API do OFox ([Obter chave de API](https://ofox.ai))",+ "OFox Text-to-Video Model": "Modelo de texto para vídeo OFox",+ "OFox Base URL": "URL base do OFox",+ "Please Enter the OFox API Key": "Insira a **chave de API do OFox**",+ "OFox Billing Notice": "Cada clipe gerado é cobrado pelo OFox. Com base na duração estimada da narração e dos clipes, serão enviadas aproximadamente {min}–{max} tarefas pagas. A geração termina assim que houver material suficiente.",+ "OFox Billing Notice Without Script": "Cada clipe gerado é cobrado pelo OFox. Insira ou gere o roteiro do vídeo para ver uma estimativa do número de tarefas.",+ "Confirm OFox Charge": "Entendo que a geração OFox cria tarefas OFox pagas",+ "Confirm OFox Charge Help": "Os clipes OFox são enviados um por vez até cobrirem a duração da narração. O OFox cobra cada tarefa de geração enviada.",+ "Confirm OFox Charge Required": "Confirme o custo da geração OFox antes de criar o vídeo."}}diff --git a/webui/i18n/ru.json b/webui/i18n/ru.jsonindex 58a912c6..684665b6 100644--- a/webui/i18n/ru.json+++ b/webui/i18n/ru.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Имя пользователя профиля Upload-Post","Upload-Post Profile Username Help": "Введите имя пользователя со страницы [Manage Users]({manage_users_url}), а не адрес электронной почты аккаунта Upload-Post. Этот пользователь публикации должен быть подключён к выбранным платформам.","Upload-Post Setup Guide": "Перед включением автопубликации:\n1. Создайте API-ключ на странице [API Keys]({api_keys_url}).\n2. Создайте или выберите пользователя публикации на странице [Manage Users]({manage_users_url}) и подключите целевые платформы.\n\nНиже введите его **имя пользователя**, а не адрес электронной почты аккаунта Upload-Post.",- "YouTube Privacy Status": "Статус конфиденциальности YouTube"+ "YouTube Privacy Status": "Статус конфиденциальности YouTube",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Создавайте новые клипы через официальный API OFox. Каждый отправленный клип является платной задачей OFox.",+ "OFox API Key": "API-ключ OFox ([Получить API-ключ](https://ofox.ai))",+ "OFox Text-to-Video Model": "Модель текст-в-видео OFox",+ "OFox Base URL": "Базовый URL OFox",+ "Please Enter the OFox API Key": "Введите **API-ключ OFox**",+ "OFox Billing Notice": "Каждый созданный клип оплачивается в OFox. С учётом предполагаемой длительности озвучки и клипов будет отправлено примерно {min}–{max} платных задач. Генерация остановится, как только материала будет достаточно.",+ "OFox Billing Notice Without Script": "Каждый созданный клип оплачивается в OFox. Введите или создайте сценарий видео, чтобы увидеть примерное количество задач.",+ "Confirm OFox Charge": "Я понимаю, что генерация OFox создаёт платные задачи OFox",+ "Confirm OFox Charge Help": "Клипы OFox отправляются по одному, пока не покроют длительность озвучки. OFox взимает плату за каждую отправленную задачу генерации.",+ "Confirm OFox Charge Required": "Подтвердите стоимость генерации OFox перед созданием видео."}}diff --git a/webui/i18n/tr.json b/webui/i18n/tr.jsonindex b69e8147..b5dbe332 100644--- a/webui/i18n/tr.json+++ b/webui/i18n/tr.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Upload-Post Profil Kullanıcı Adı","Upload-Post Profile Username Help": "Upload-Post hesap e-postanız yerine [Manage Users]({manage_users_url}) sayfasında gösterilen kullanıcı adını girin. Bu yayın kullanıcısı seçilen platformlara bağlı olmalıdır.","Upload-Post Setup Guide": "Otomatik yayınlamayı etkinleştirmeden önce:\n1. [API Keys]({api_keys_url}) sayfasında bir API anahtarı oluşturun.\n2. [Manage Users]({manage_users_url}) sayfasında bir yayın kullanıcısı oluşturun veya seçin ve hedef platformları bağlayın.\n\nAşağıya Upload-Post hesap e-postanızı değil, bu yayın kullanıcısının **kullanıcı adını** girin.",- "YouTube Privacy Status": "YouTube Gizlilik Durumu"+ "YouTube Privacy Status": "YouTube Gizlilik Durumu",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Resmî OFox API’siyle yeni klipler oluşturun. Gönderilen her klip ücretli bir OFox görevidir.",+ "OFox API Key": "OFox API Anahtarı ([API Anahtarı Al](https://ofox.ai))",+ "OFox Text-to-Video Model": "OFox metinden videoya modeli",+ "OFox Base URL": "OFox Temel URL’si",+ "Please Enter the OFox API Key": "Lütfen **OFox API Anahtarını** girin",+ "OFox Billing Notice": "Oluşturulan her klip OFox tarafından ücretlendirilir. Tahmini seslendirme ve klip süresine göre yaklaşık {min}–{max} ücretli görev gönderilir. Yeterli görüntü elde edildiğinde üretim durur.",+ "OFox Billing Notice Without Script": "Oluşturulan her klip OFox tarafından ücretlendirilir. Tahmini görev sayısını görmek için video metnini girin veya oluşturun.",+ "Confirm OFox Charge": "OFox üretiminin ücretli OFox görevleri oluşturduğunu anlıyorum",+ "Confirm OFox Charge Help": "OFox klipleri tek tek gönderilir ve seslendirme süresini karşıladığında durur. OFox, gönderilen her üretim görevi için ücret alır.",+ "Confirm OFox Charge Required": "Videoyu oluşturmadan önce OFox üretim ücretini onaylayın."}}diff --git a/webui/i18n/vi.json b/webui/i18n/vi.jsonindex 43c9c943..ba97fdd2 100644--- a/webui/i18n/vi.json+++ b/webui/i18n/vi.json@@ -375,6 +375,17 @@"Upload-Post Profile Username": "Tên người dùng hồ sơ Upload-Post","Upload-Post Profile Username Help": "Nhập tên người dùng hiển thị tại [Manage Users]({manage_users_url}), không phải email tài khoản Upload-Post. Người dùng xuất bản này phải được kết nối với các nền tảng đã chọn.","Upload-Post Setup Guide": "Trước khi bật tự động xuất bản:\n1. Tạo khóa API tại [API Keys]({api_keys_url}).\n2. Tạo hoặc chọn người dùng xuất bản tại [Manage Users]({manage_users_url}), sau đó kết nối các nền tảng đích.\n\nNhập **tên người dùng** xuất bản đó bên dưới, không phải email tài khoản Upload-Post.",- "YouTube Privacy Status": "Trạng thái quyền riêng tư của YouTube"+ "YouTube Privacy Status": "Trạng thái quyền riêng tư của YouTube",+ "OFox AI Video": "OFox AI Video",+ "OFox AI Video Help": "Tạo clip mới qua API OFox chính thức. Mỗi clip được gửi là một tác vụ OFox có tính phí.",+ "OFox API Key": "Khóa API OFox ([Lấy khóa API](https://ofox.ai))",+ "OFox Text-to-Video Model": "Mô hình chuyển văn bản thành video OFox",+ "OFox Base URL": "URL cơ sở OFox",+ "Please Enter the OFox API Key": "Vui lòng nhập **Khóa API OFox**",+ "OFox Billing Notice": "Mỗi clip được tạo đều bị OFox tính phí. Dựa trên thời lượng lồng tiếng và thời lượng clip ước tính, khoảng {min}–{max} tác vụ có tính phí sẽ được gửi. Quá trình tạo dừng ngay khi đã có đủ cảnh quay.",+ "OFox Billing Notice Without Script": "Mỗi clip được tạo đều bị OFox tính phí. Nhập hoặc tạo kịch bản video để xem số tác vụ ước tính.",+ "Confirm OFox Charge": "Tôi hiểu rằng việc tạo bằng OFox sẽ tạo các tác vụ OFox có tính phí",+ "Confirm OFox Charge Help": "Các clip OFox được gửi lần lượt và dừng khi đã đủ thời lượng lồng tiếng. OFox tính phí cho từng tác vụ tạo được gửi.",+ "Confirm OFox Charge Required": "Vui lòng xác nhận chi phí tạo OFox trước khi tạo video."}}diff --git a/webui/i18n/zh.json b/webui/i18n/zh.jsonindex 5c81267e..fa212ea7 100644--- a/webui/i18n/zh.json+++ b/webui/i18n/zh.json@@ -444,6 +444,17 @@"Upload-Post Profile Username": "Upload-Post 发布用户名称","Upload-Post Profile Username Help": "填写 [Manage Users]({manage_users_url}) 页面显示的 Username,而不是 Upload-Post 登录邮箱;该发布用户需要已经连接所选平台。","Upload-Post Setup Guide": "启用自动发布前,请先:\n1. 在 [API Keys]({api_keys_url}) 页面创建 API Key。\n2. 在 [Manage Users]({manage_users_url}) 页面创建或选择发布用户,并连接目标平台。\n\n下方请填写该发布用户的 **Username**,而不是 Upload-Post 登录邮箱。",- "YouTube Privacy Status": "YouTube 隐私状态"+ "YouTube Privacy Status": "YouTube 隐私状态",+ "OFox AI Video": "OFox AI 视频",+ "OFox AI Video Help": "通过 OFox 多模型视频 API(一个 Key 可调 Seedance、Wan 等文生视频模型)按脚本关键词生成全新视频素材。每段素材都会创建一个付费任务。",+ "OFox API Key": "OFox API Key([获取 API Key](https://ofox.ai))",+ "OFox Text-to-Video Model": "OFox 文生视频模型",+ "OFox Base URL": "OFox Base URL",+ "Please Enter the OFox API Key": "请输入 **OFox API Key**",+ "OFox Billing Notice": "每段生成视频都会由 OFox 计费。根据预计配音时长和片段时长,将提交约 {min}-{max} 个付费任务;凑够所需素材后会立即停止。",+ "OFox Billing Notice Without Script": "每段生成视频都会由 OFox 计费。填写或生成视频文案后可查看预计任务数量。",+ "Confirm OFox Charge": "我已了解 OFox 视频生成会创建付费任务",+ "Confirm OFox Charge Help": "OFox 素材按脚本片段逐段提交,凑够配音所需时长后立即停止。OFox 按实际提交的生成任务计费。",+ "Confirm OFox Charge Required": "请确认 OFox 生成费用后再生成视频。"}}