Skip to content

PRINTFILM: AI short-video marketing and AI short-drama creation platform

fix(kepu): 合入前修正 TokenFree 预扣低估、误迁密钥与审核兜底

yi5c14d0e7dc10
diff --git a/admin/src/lib/tokenfreeRecommendedModels.ts b/admin/src/lib/tokenfreeRecommendedModels.ts
index 9beaaac..bbe114c 100644
--- a/admin/src/lib/tokenfreeRecommendedModels.ts
+++ b/admin/src/lib/tokenfreeRecommendedModels.ts
@@ -2,11 +2,11 @@ export type ModelCapability = "text" | "image" | "video" | "audio";
export type UpstreamModelOption = { id: string; label: string; capability: string };
-/** 勾选推荐时留下的 TokenFree id;视频只留 2.5 与 2.0 Mini */
+/** 勾选推荐时补上的 TokenFree id;视频含 2.5 / 2.0 / Mini */
export const RECOMMENDED_MODEL_IDS: Record<ModelCapability, string[]> = {
text: ["kimi-k2.6"],
image: ["gpt-image-2-5"],
- video: ["seedance-2-5", "seedance-2-0-mini"],
+ video: ["seedance-2-5", "seedance-2-0", "seedance-2-0-mini"],
audio: ["seed-tts-2.0"],
};
@@ -85,13 +85,8 @@ export function pickRecommendedDefaults(models: UpstreamModelOption[]): Record<M
return out;
}
-// 勾选推荐:补上短名单,Seedance 只留 2.5 / 2.0 Mini
+// 勾选推荐:canonicalize 后补上短名单,不删已选的 Seedance 2.0
export function mergeRecommendedSelection(selected: string[], catalog: UpstreamModelOption[]): string[] {
const recommended = pickRecommendedModelIds(catalog);
- const preferredVideo = new Set(RECOMMENDED_MODEL_IDS.video);
- const kept = canonicalizeChannelModels(selected).filter((id) => {
- if (!id.toLowerCase().includes("seedance")) return true;
- return preferredVideo.has(id);
- });
- return canonicalizeChannelModels([...kept, ...recommended]);
+ return canonicalizeChannelModels([...selected, ...recommended]);
}
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 7a5eb8e..37d36e8 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -30,6 +30,7 @@ from app.services.tokenfree_image import (
build_tokenfree_image_body,
extract_tokenfree_image_url,
is_tokenfree_image_url,
+ is_tokenfree_input_text_sensitive,
is_tokenfree_retryable_image_error,
post_until_not_rate_limited,
tokenfree_image_channel_dead,
@@ -83,6 +84,12 @@ def _raise_seedream_http_error(
snippet[:200],
)
if tokenfree:
+ if is_tokenfree_input_text_sensitive(status_code=status_code, body=snippet):
+ raise RuntimeError(
+ "生图文案未通过内容审核(可能含敏感或历史名人相关表述),"
+ "请修改提示词后重试。"
+ f" 详情:{snippet[:240]}"
+ )
raise RuntimeError(tokenfree_image_user_error(model=model, status_code=status_code, body=snippet))
if "InputTextSensitive" in snippet or "InputTextSensitiveContentDetected" in snippet:
raise RuntimeError(
@@ -442,10 +449,10 @@ class ArkGateway:
return result
async def download_result_media(self, url: str, dest: Path) -> None:
- """下载生成媒体;TokenFree /videos/:id/content 带 Bearer,读超时放宽。"""
+ """下载生成媒体;TokenFree 任务/content URL 带 Bearer,读超时放宽。"""
headers = None
timeout: float | httpx.Timeout = 300.0
- if is_tokenfree_content_url(url):
+ if is_tokenfree_content_url(url) or is_tokenfree_image_url(url):
headers = {"Authorization": f"Bearer {self._ark_api_key()}"}
timeout = httpx.Timeout(connect=30.0, read=600.0, write=60.0, pool=30.0)
await storage.download_to(url, dest, headers=headers, timeout=timeout)
@@ -1492,7 +1499,7 @@ class ArkGateway:
storage.project_dir(project_id)
/ f"shot_{shot_no:03d}_{stamp}_last.jpg"
)
- await storage.download_to(result.last_frame_url, frame_dest)
+ await self.download_result_media(result.last_frame_url, frame_dest)
last_local = storage.publish_local(frame_dest)
except Exception: # noqa: BLE001
logger.warning("failed to save last frame project=%s shot=%s", project_id, shot_no)
diff --git a/backend/app/services/billing/estimates.py b/backend/app/services/billing/estimates.py
index 35c3882..48ad071 100644
--- a/backend/app/services/billing/estimates.py
+++ b/backend/app/services/billing/estimates.py
@@ -33,6 +33,22 @@ __all__ = [
]
+def _kepu_video_resolution(project: Project | None, settings: Settings) -> str:
+ """科普成片清晰度:设置项;HD 且配置为 480p 时升到 720p(与 pipeline 一致)。"""
+ raw = str(getattr(settings, "ark_video_resolution", "") or "480p")
+ mode = str(getattr(project, "resolution_mode", "") or "")
+ if mode == "hd" and raw.strip().lower() == "480p":
+ return "720p"
+ return raw
+
+
+def _drama_video_resolution(payload: dict) -> str:
+ """漫剧成片默认 720p,与前端与 asset_video 缺省一致。"""
+ prepared = payload.get("prepared") if isinstance(payload.get("prepared"), dict) else {}
+ raw = str((prepared or {}).get("resolution") or payload.get("resolution") or "").strip()
+ return raw or "720p"
+
+
def _estimate_assets_fen(project: Project, settings: Settings) -> int:
"""只估尚未完成的出图 + 整片配音(不含镜头视频)。"""
buf = float(settings.billing_estimate_buffer or 1.2)
@@ -65,7 +81,9 @@ def _estimate_videos_fen(project: Project, settings: Settings) -> int:
total = 0
for sh in shots:
secs = max(float(sh.duration or 4), 2.0)
- total += charge_fen_official_video(secs, settings)
+ total += charge_fen_official_video(
+ secs, settings, resolution=_kepu_video_resolution(project, settings)
+ )
return max(math.ceil(total * buf), 1)
@@ -121,7 +139,11 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
return max(1, math.ceil(c * buf))
if task_type in {"shot_regen_video"}:
dur = float(payload.get("duration") or 5)
- c = charge_fen_official_video(max(dur, 2.0), s)
+ project_id = task.project_id or payload.get("project_id")
+ project = await db.get(Project, int(project_id)) if project_id else None
+ c = charge_fen_official_video(
+ max(dur, 2.0), s, resolution=_kepu_video_resolution(project, s)
+ )
return max(1, math.ceil(c * buf))
if task_type in {"shot_regen_audio", "project_regen_audio"}:
_, c = charge_fen_for_tokens(s.billing_est_tts_tokens * 3, "tts", settings=s)
@@ -169,7 +191,9 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
)
if dur <= 0:
dur = 8.0
- c = charge_fen_official_video(max(dur, 2.0), s)
+ c = charge_fen_official_video(
+ max(dur, 2.0), s, resolution=_drama_video_resolution(payload)
+ )
if task_type == "fragment_video":
c += max(1, charge_fen_official_image(s) // 2)
return max(1, math.ceil(c * buf))
@@ -190,7 +214,11 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
return max(1, math.ceil(c * buf))
if task_type in {"v1_video", "v1_seedance", "tool_video"}:
dur = float(payload.get("duration") or 5)
- c = charge_fen_official_video(max(dur, 2.0), s)
+ c = charge_fen_official_video(
+ max(dur, 2.0),
+ s,
+ resolution=str(payload.get("resolution") or "").strip() or "480p",
+ )
return max(1, math.ceil(c * buf))
c = charge_fen_official_llm(s.billing_est_llm_tokens, s)
diff --git a/backend/app/services/billing/pricing.py b/backend/app/services/billing/pricing.py
index e5c051f..dfa0c08 100644
--- a/backend/app/services/billing/pricing.py
+++ b/backend/app/services/billing/pricing.py
@@ -119,12 +119,6 @@ def parse_upstream_cost_fen(
return max(0, int(usage[key]))
except (TypeError, ValueError):
pass
- for key in ("cost", "total_cost", "amount", "cost_yuan", "total_cost_yuan"):
- if usage.get(key) is not None:
- try:
- return max(0, int(math.ceil(float(usage[key]) * 100)))
- except (TypeError, ValueError):
- pass
from app.services.tokenfree_usage import quota_to_cost_fen
newapi_quota = _extract_newapi_quota(data, usage)
@@ -132,6 +126,20 @@ def parse_upstream_cost_fen(
converted = quota_to_cost_fen(newapi_quota, settings)
if converted > 0:
return converted
+ # 明确人民币字段;无 New API quota 时才把火山 cost 当人民币元
+ has_quota_field = any(
+ usage.get(key) is not None or data.get(key) is not None
+ for key in ("quota", "quota_consumed", "consumed_quota")
+ )
+ yuan_keys = ("cost_yuan", "total_cost_yuan")
+ if not has_quota_field:
+ yuan_keys = yuan_keys + ("cost", "total_cost", "amount")
+ for key in yuan_keys:
+ if usage.get(key) is not None:
+ try:
+ return max(0, int(math.ceil(float(usage[key]) * 100)))
+ except (TypeError, ValueError):
+ pass
# Kie:任务级 creditsConsumed(usage 内或顶层)
credits = usage.get("creditsConsumed")
if credits is None:
diff --git a/backend/app/services/kepu_continuity.py b/backend/app/services/kepu_continuity.py
index 8b61d2d..88eb0c1 100644
--- a/backend/app/services/kepu_continuity.py
+++ b/backend/app/services/kepu_continuity.py
@@ -67,24 +67,37 @@ def shot_image_ref(shot: Any | None) -> str | None:
def _any_shot_image(shot: Any) -> str | None:
- """静帧任意可用地址(含本地 /static,交给下游 resolve)。"""
- for raw in (getattr(shot, "image_ark_url", None), getattr(shot, "image_url", None)):
- url = str(raw or "").strip()
+ """静帧任意可用地址(含本地 /static);TokenFree 产物跳过。优先本地路径。"""
+ for raw in (getattr(shot, "image_url", None), getattr(shot, "image_ark_url", None)):
+ url = _usable_video_ref(raw)
if url:
return url
return None
def shot_last_frame_ref(shot: Any | None) -> str | None:
- """上一镜尾帧;没有则退回该镜静帧。本地路径由 Seedance resolve 再上公网。"""
+ """上一镜尾帧;TokenFree 任务 URL 跳过,避免下游无鉴权拉不到。"""
if shot is None:
return None
last = str(getattr(shot, "last_frame_url", None) or "").strip()
- if last:
+ if last and _usable_video_ref(last):
return last
return shot_image_ref(shot) or _any_shot_image(shot)
+def _usable_video_ref(raw: str | None) -> str | None:
+ """本地路径或公网图可作下一镜参考;TokenFree 产物地址不行。"""
+ url = str(raw or "").strip()
+ if not url:
+ return None
+ from app.services.tokenfree_image import is_tokenfree_image_url
+ from app.services.tokenfree_video import is_tokenfree_content_url
+
+ if is_tokenfree_image_url(url) or is_tokenfree_content_url(url):
+ return None
+ return url
+
+
def image_refs_for_shot(prev: Any | None, base_refs: list[str] | None = None) -> list[str]:
"""本镜 Seedream 参考:上一镜静帧 + 模板底图。"""
bases = list(base_refs or [])
@@ -106,21 +119,21 @@ def persist_last_frame_from_video(
video_url: str,
preferred_url: str | None = None,
) -> str | None:
- """优先落盘/公网尾帧;没有再用 ffmpeg 从成片抽。"""
+ """优先已落盘/公网尾帧;TokenFree 任务 URL 不当公网尾帧,改从成片抽。"""
from app.services import storage
from app.services.ffmpeg_compose import extract_video_last_frame
pref = str(preferred_url or "").strip()
if pref:
- from app.services.tokenfree_image import is_tokenfree_image_url
-
- if (pref.startswith("http://") or pref.startswith("https://")) and not is_tokenfree_image_url(pref):
- return pref
- https = storage.republish_url(pref, sync=True)
- if https and str(https).startswith("http") and not is_tokenfree_image_url(str(https)):
- return str(https)
- if pref.startswith("/static/"):
+ if (pref.startswith("http://") or pref.startswith("https://")) and _usable_video_ref(pref):
return pref
+ if _usable_video_ref(pref):
+ https = storage.republish_url(pref, sync=True)
+ published = _usable_video_ref(str(https or ""))
+ if published and published.startswith("http"):
+ return published
+ if pref.startswith("/static/"):
+ return pref
path = storage.local_path_from_url(video_url)
if path and path.exists():
dest = storage.project_dir(int(project_id)) / f"shot_{int(shot_no):03d}_{int(time.time())}_last.jpg"
diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.py
index c7d9bca..72da1b8 100644
--- a/backend/app/services/model_settings.py
+++ b/backend/app/services/model_settings.py
@@ -9,7 +9,7 @@ from dataclasses import dataclass
from typing import Any
from cryptography.fernet import Fernet
-from sqlalchemy import delete, select
+from sqlalchemy import select
from sqlalchemy.ext.asyncio import AsyncSession
from app.config import Settings, get_settings, reload_settings
@@ -708,9 +708,12 @@ async def patch_admin_routing_settings(
row.sort_order = 0
row.advanced_config = None
db.add(row)
- stale_ids = [cid for cid in existing_rows if cid != TOKENFREE_CHANNEL_ID]
- if stale_ids:
- await db.execute(delete(SystemModelChannelRow).where(SystemModelChannelRow.id.in_(stale_ids)))
+ for cid, stale in existing_rows.items():
+ if cid == TOKENFREE_CHANNEL_ID:
+ continue
+ stale.enabled = False
+ db.add(stale)
+ await db.flush()
applied.append("system_channels")
config = dict(app_row.config_json or {})
diff --git a/backend/app/services/tokenfree_gateway.py b/backend/app/services/tokenfree_gateway.py
index 167b126..e105a76 100644
--- a/backend/app/services/tokenfree_gateway.py
+++ b/backend/app/services/tokenfree_gateway.py
@@ -64,17 +64,15 @@ def locked_tokenfree_channel(
def pick_migratable_api_key(channels: list[SystemModelChannel]) -> str:
- """从旧多渠道里挑一条已有 Key,迁移到 TokenFree。"""
+ """只迁 TokenFree 渠道或 base_url 含 tokenfree.com 的 Key,避免把 Moonshot/方舟 Key 写进去。"""
for channel in channels:
if channel.id == TOKENFREE_CHANNEL_ID and (channel.api_key or "").strip():
return (channel.api_key or "").strip()
- for prefer_id in ("openai-default", "ark-default", "ark-volc-media", "kie-default"):
- for channel in channels:
- if channel.id == prefer_id and (channel.api_key or "").strip():
- return (channel.api_key or "").strip()
for channel in channels:
- if (channel.api_key or "").strip():
- return (channel.api_key or "").strip()
+ key = (channel.api_key or "").strip()
+ base = (channel.base_url or "").strip().lower()
+ if key and "tokenfree.com" in base:
+ return key
return ""
diff --git a/backend/app/services/tokenfree_image.py b/backend/app/services/tokenfree_image.py
index e6695e1..448ecf7 100644
--- a/backend/app/services/tokenfree_image.py
+++ b/backend/app/services/tokenfree_image.py
@@ -150,6 +150,21 @@ def tokenfree_image_channel_dead(*, status_code: int = 0, body: str = "") -> boo
)
+def is_tokenfree_input_text_sensitive(*, status_code: int = 0, body: str = "") -> bool:
+ """文案审核拦截;协议失败、限流、无线路不算,才能走 compact/style_only。"""
+ if is_tokenfree_rate_limit(status_code=status_code, body=body):
+ return False
+ if tokenfree_image_channel_dead(status_code=status_code, body=body):
+ return False
+ text = body or ""
+ if "InputTextSensitive" in text or "InputTextSensitiveContentDetected" in text:
+ return True
+ lowered = text.lower()
+ if any(token in lowered for token in ("content_filter", "content_policy", "text sensitive", "sensitive content")):
+ return True
+ return "内容审核" in text or "敏感内容" in text
+
+
def tokenfree_image_user_error(*, model: str = "", status_code: int = 0, body: str = "") -> str:
"""用户可见的 TokenFree 出图失败文案;通道挂了不再误导改模型。"""
if is_tokenfree_rate_limit(status_code=status_code, body=body):
diff --git a/backend/app/services/tokenfree_pricing.py b/backend/app/services/tokenfree_pricing.py
index d1cd6f5..7db4c7f 100644
--- a/backend/app/services/tokenfree_pricing.py
+++ b/backend/app/services/tokenfree_pricing.py
@@ -34,6 +34,14 @@ VENDOR_VIDEO_YUAN_PER_SEC_480P = {
"seedance-2-0": 2.31 / 5.0,
"seedance-2-0-mini": 2.31 / 5.0,
}
+# 相对 480P 的预估倍率(宁多冻、少结算超扣)
+VIDEO_RESOLUTION_MULT = {
+ "480p": 1.0,
+ "720p": 2.0,
+ "1080p": 4.0,
+}
+# 价目失败时按 gpt-image-2-5 现价保底,避免退回 8 元/百万 token 低估约 10 倍
+GPT_IMAGE_USD_PER_CALL_FLOOR = 0.625
# 产品里好用、目录有、方便去 TokenFree 核对的短名单
RECOMMENDED_MODELS: tuple[dict[str, Any], ...] = (
@@ -62,16 +70,9 @@ RECOMMENDED_MODELS: tuple[dict[str, Any], ...] = (
"id": "gpt-image-2-5",
"capability": "image",
"label": "GPT Image 2.5",
- "note": "TokenFree 实测可通;Seedream 会改走此模型",
+ "note": "TokenFree 实测可通;Seedream 在此上游会改走此模型,按张计价",
"recommended": True,
},
- {
- "id": "seedream-5-0-pro",
- "capability": "image",
- "label": "Seedream 5.0 Pro",
- "note": "便宜,但 TokenFree /responses 可能不通",
- "recommended": False,
- },
{
"id": "nano-banana-2",
"capability": "image",
@@ -86,6 +87,13 @@ RECOMMENDED_MODELS: tuple[dict[str, Any], ...] = (
"note": "默认成片,最长约 30 秒",
"recommended": True,
},
+ {
+ "id": "seedance-2-0",
+ "capability": "video",
+ "label": "Seedance 2.0",
+ "note": "标准 2.0,与 Mini 不同价档",
+ "recommended": False,
+ },
{
"id": "seedance-2-0-mini",
"capability": "video",
@@ -269,16 +277,15 @@ def _markup_charge(cost_fen: int, settings: Settings) -> int:
def charge_fen_official_image(settings: Settings, *, model: str = "") -> int:
- """生图预估:按 TokenFree 按张价;Seedream 按实际工作模型。"""
- from app.services.billing.pricing import charge_fen_for_tokens
+ """生图预估:按 TokenFree 按张价;Seedream 按实际工作模型;无价目时用 gpt-image 保底。"""
from app.services.tokenfree_image import tokenfree_working_image_model
mid = tokenfree_working_image_model(model or "gpt-image-2-5")
rate = lookup_rate(mid)
if rate and rate.billing == "per_call" and rate.cny_per_call > 0:
return _markup_charge(max(1, int(math.ceil(rate.cny_per_call * 100))), settings)
- _, charge = charge_fen_for_tokens(settings.billing_est_seedream_tokens, "seedream", settings=settings)
- return charge
+ yuan = GPT_IMAGE_USD_PER_CALL_FLOOR * usd_cny_rate(settings)
+ return _markup_charge(max(1, int(math.ceil(yuan * 100))), settings)
def charge_fen_official_llm(tokens: int, settings: Settings, *, model: str = "") -> int:
@@ -297,16 +304,32 @@ def charge_fen_official_llm(tokens: int, settings: Settings, *, model: str = "")
return charge
-def charge_fen_official_video(seconds: float, settings: Settings, *, model: str = "") -> int:
- """视频预估:用火山 480P 秒价,不用 TokenFree 占位 37.5。"""
+def normalize_video_resolution(resolution: str | None, settings: Settings | None = None) -> str:
+ """预估用清晰度:只认 480p/720p/1080p。"""
+ raw = (resolution or "").strip().lower()
+ if raw in VIDEO_RESOLUTION_MULT:
+ return raw
+ fallback = str(getattr(settings or get_settings(), "ark_video_resolution", "") or "480p").strip().lower()
+ return fallback if fallback in VIDEO_RESOLUTION_MULT else "480p"
+
+
+def charge_fen_official_video(
+ seconds: float,
+ settings: Settings,
+ *,
+ model: str = "",
+ resolution: str = "",
+) -> int:
+ """视频预估:火山 480P 秒价 × 清晰度倍率,不用 TokenFree 占位 37.5。"""
from app.services.billing.pricing import charge_fen_for_tokens
secs = max(float(seconds or 0), 2.0)
mid = video_catalog_id(model or getattr(settings, "model_video", "") or "seedance-2-5")
vendor = VENDOR_VIDEO_YUAN_PER_SEC_480P.get(mid)
+ mult = VIDEO_RESOLUTION_MULT[normalize_video_resolution(resolution, settings)]
if vendor:
- return _markup_charge(max(1, int(math.ceil(secs * vendor * 100))), settings)
- tok = int(secs * settings.billing_est_seedance_tokens_per_sec)
+ return _markup_charge(max(1, int(math.ceil(secs * vendor * mult * 100))), settings)
+ tok = int(secs * settings.billing_est_seedance_tokens_per_sec * mult)
_, charge = charge_fen_for_tokens(tok, "seedance2:video0", settings=settings)
return charge
@@ -334,7 +357,7 @@ def build_official_rate_rows(
listed = f";TokenFree 表 model_ratio={rate.model_ratio} 疑似占位"
rate_label = (
f"预估按火山 480P 约 {vendor:.3f} 元/秒"
- f"({VIDEO_RATE_SAMPLE_SECONDS:g}秒 ¥{official_yuan:.2f}){listed}"
+ f"({VIDEO_RATE_SAMPLE_SECONDS:g}秒 ¥{official_yuan:.2f};720P×2 / 1080P×4){listed}"
)
elif rate and rate.billing == "per_call":
official_yuan = rate.cny_per_call
diff --git a/backend/tests/test_fragment_video_estimate.py b/backend/tests/test_fragment_video_estimate.py
index bf6341a..6d8cabf 100644
--- a/backend/tests/test_fragment_video_estimate.py
+++ b/backend/tests/test_fragment_video_estimate.py
@@ -19,15 +19,14 @@ async def test_fragment_video_estimate_uses_payload_duration_sec(monkeypatch):
settings = get_settings()
monkeypatch.setattr(settings, "billing_est_seedance_tokens_per_sec", 32_000)
monkeypatch.setattr(settings, "billing_estimate_buffer", 1.2)
- monkeypatch.setattr(settings, "billing_markup", 1.5)
- monkeypatch.setattr(settings, "billing_seedance_video0", 46.0)
+ monkeypatch.setattr(settings, "billing_markup", 1.0)
task = TaskRun(
id=1,
domain="drama",
task_type="fragment_video",
requested_by=1,
- payload={"duration_sec": 16, "fragment_ids": [9]},
+ payload={"duration_sec": 16, "fragment_ids": [9], "resolution": "720p"},
fragment_id=9,
)
db = MagicMock()
@@ -40,7 +39,7 @@ async def test_fragment_video_estimate_uses_payload_duration_sec(monkeypatch):
domain="drama",
task_type="fragment_video",
requested_by=1,
- payload={"duration_sec": 8},
+ payload={"duration_sec": 8, "resolution": "720p"},
fragment_id=9,
),
settings=settings,
@@ -49,6 +48,42 @@ async def test_fragment_video_estimate_uses_payload_duration_sec(monkeypatch):
assert fen16 > fen8
+async def test_fragment_video_estimate_720p_doubles_480p(monkeypatch):
+ """漫剧缺省 720p;视频部分相对 480p 翻倍,静帧加价不变。"""
+ from app.config import get_settings
+ from app.services.tokenfree_pricing import set_cached_rates
+
+ settings = get_settings()
+ monkeypatch.setattr(settings, "billing_estimate_buffer", 1.0)
+ monkeypatch.setattr(settings, "billing_markup", 1.0)
+ monkeypatch.setattr(settings, "billing_usd_cny", 7.0)
+ monkeypatch.setattr(settings, "model_video", "seedance-2-5")
+ set_cached_rates(None)
+ db = MagicMock()
+ db.get = AsyncMock(return_value=None)
+
+ def _task(resolution: str | None) -> TaskRun:
+ payload: dict = {"duration_sec": 5}
+ if resolution:
+ payload["resolution"] = resolution
+ return TaskRun(
+ id=4,
+ domain="drama",
+ task_type="fragment_video",
+ requested_by=1,
+ payload=payload,
+ fragment_id=9,
+ )
+
+ fen_480 = await estimate_task_fen(db, _task("480p"), settings=settings)
+ fen_720 = await estimate_task_fen(db, _task("720p"), settings=settings)
+ fen_default = await estimate_task_fen(db, _task(None), settings=settings)
+ # 5s Seedance 2.5:480p 336 分,720p 672 分;静帧加价相同
+ assert fen_720 - fen_480 == 336
+ assert fen_default == fen_720
+
+
@pytest.mark.asyncio
async def test_fragment_video_estimate_reads_fragment_content(monkeypatch):
"""无 payload duration 时从分镜正文 @duration 解析。"""
diff --git a/backend/tests/test_kepu_continuity.py b/backend/tests/test_kepu_continuity.py
index 02b66d9..57595ce 100644
--- a/backend/tests/test_kepu_continuity.py
+++ b/backend/tests/test_kepu_continuity.py
@@ -4,6 +4,7 @@ from types import SimpleNamespace
from app.services.kepu_continuity import (
image_refs_for_shot,
+ persist_last_frame_from_video,
previous_shot,
previous_usable_shot,
shot_image_ref,
@@ -61,6 +62,38 @@ def test_video_extra_refs_fall_back_to_prev_still():
assert video_extra_refs_for_shot(None) == []
+def test_shot_last_frame_ref_skips_tokenfree_url():
+ """TokenFree 尾帧地址不能传给下一镜,退回已发布静帧。"""
+ prev = _shot(
+ last_frame_url="https://www.tokenfree.com/v1/videos/abc/content",
+ image_ark_url="https://cdn.example.com/shot1.png",
+ )
+ assert shot_last_frame_ref(prev) == "https://cdn.example.com/shot1.png"
+ assert video_extra_refs_for_shot(prev) == ["https://cdn.example.com/shot1.png"]
+
+
+def test_shot_last_frame_ref_prefers_local_still_over_tokenfree_ark():
+ """TokenFree ark 静帧跳过,改用本地 /static。"""
+ prev = _shot(
+ last_frame_url="https://www.tokenfree.com/v1/videos/abc/content",
+ image_ark_url="https://www.tokenfree.com/v1/tasks/t1/artifacts/image-0/content",
+ image_url="/static/generated/p1/shot_001.png",
+ )
+ assert shot_last_frame_ref(prev) == "/static/generated/p1/shot_001.png"
+
+
+def test_persist_last_frame_skips_tokenfree_content_url(monkeypatch):
+ """TokenFree /videos/:id/content 不能当 preferred 写回。"""
+ monkeypatch.setattr("app.services.storage.local_path_from_url", lambda _url: None)
+ out = persist_last_frame_from_video(
+ 1,
+ 1,
+ "/static/x.mp4",
+ preferred_url="https://www.tokenfree.com/v1/videos/abc/content",
+ )
+ assert out is None
+
+
def test_shot_image_ref_skips_tokenfree_and_uses_oss():
"""TokenFree 产物地址不能给上游当参考,改用已发布的公网图。"""
prev = _shot(
diff --git a/backend/tests/test_kepu_phase_billing.py b/backend/tests/test_kepu_phase_billing.py
index 181cfbb..dd7715c 100644
--- a/backend/tests/test_kepu_phase_billing.py
+++ b/backend/tests/test_kepu_phase_billing.py
@@ -3,9 +3,13 @@
from __future__ import annotations
from types import SimpleNamespace
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
from app.config import get_settings
-from app.services.billing.estimates import estimate_phase_fen
+from app.models_tasks import TaskRun
+from app.services.billing.estimates import estimate_phase_fen, estimate_task_fen
from app.services.kepu_stages import (
normalize_kepu_pipeline_phase,
resolve_kepu_billing_phase,
@@ -24,8 +28,13 @@ def _shot(**kwargs):
return SimpleNamespace(**defaults)
-def _project(shots, pipeline_mode="full", project_id=1):
- return SimpleNamespace(id=project_id, shots=shots, pipeline_mode=pipeline_mode)
+def _project(shots, pipeline_mode="full", project_id=1, resolution_mode="preview"):
+ return SimpleNamespace(
+ id=project_id,
+ shots=shots,
+ pipeline_mode=pipeline_mode,
+ resolution_mode=resolution_mode,
+ )
def test_resolve_phase_script_when_no_shots() -> None:
@@ -112,6 +121,45 @@ def test_videos_estimate_only_remaining_shots() -> None:
assert abs(two - one * 2) <= 1
+def test_videos_estimate_hd_doubles_480p_preview() -> None:
+ """HD 且配置 480p 时预扣按 720p(×2)。"""
+ settings = get_settings()
+ settings.ark_video_resolution = "480p"
+ settings.billing_estimate_buffer = 1.0
+ settings.model_video = "seedance-2-5"
+ shots = [_shot(image_url="/i.png", audio_url="/a.wav", duration=5)]
+ preview = estimate_phase_fen(_project(shots), "videos", settings=settings)
+ hd = estimate_phase_fen(
+ _project(shots, resolution_mode="hd"),
+ "videos",
+ settings=settings,
+ )
+ assert hd == preview * 2
+
+
+async def test_shot_regen_video_estimate_uses_project_hd() -> None:
+ """单镜重生成视频预扣跟随项目 HD(480p→720p)。"""
+ settings = get_settings()
+ settings.ark_video_resolution = "480p"
+ settings.billing_estimate_buffer = 1.0
+ settings.model_video = "seedance-2-5"
+ db = MagicMock()
+ db.get = AsyncMock(return_value=SimpleNamespace(resolution_mode="hd"))
+ task = TaskRun(
+ id=9,
+ domain="kepu",
+ task_type="shot_regen_video",
+ requested_by=1,
+ project_id=3,
+ payload={"duration": 5},
+ )
+ hd = await estimate_task_fen(db, task, settings=settings)
+ db.get = AsyncMock(return_value=SimpleNamespace(resolution_mode="preview"))
+ preview = await estimate_task_fen(db, task, settings=settings)
+ assert hd == preview * 2
+
+
def test_normalize_produce_maps_to_current_phase(monkeypatch) -> None:
monkeypatch.setattr(
"app.services.kepu_stages.project_audio_ready",
diff --git a/backend/tests/test_tokenfree_image.py b/backend/tests/test_tokenfree_image.py
index 9af4874..01e167b 100644
--- a/backend/tests/test_tokenfree_image.py
+++ b/backend/tests/test_tokenfree_image.py
@@ -7,6 +7,7 @@ import pytest
from app.services.tokenfree_image import (
build_tokenfree_image_body,
extract_tokenfree_image_url,
+ is_tokenfree_input_text_sensitive,
is_tokenfree_no_distributor,
is_tokenfree_protocol_error,
is_tokenfree_rate_limit,
@@ -115,6 +116,24 @@ def test_raise_seedream_http_error_tokenfree_vs_ark():
_raise_seedream_http_error(502, protocol, model="gpt-image-2-5", tokenfree=False)
+def test_is_tokenfree_input_text_sensitive_skips_protocol_and_429():
+ """协议失败和限流不算审核,避免 compact/style_only 被通道故障误触发。"""
+ protocol = '{"error":{"code":"task_protocol_error","message":"Task protocol request failed"}}'
+ assert is_tokenfree_input_text_sensitive(status_code=502, body=protocol) is False
+ assert is_tokenfree_input_text_sensitive(status_code=429, body="Too many active task observations") is False
+ body = '{"error":{"code":"InputTextSensitive","message":"text sensitive"}}'
+ assert is_tokenfree_input_text_sensitive(status_code=400, body=body) is True
+
+
+def test_raise_seedream_http_error_tokenfree_moderation_uses_audit_text():
+ """TokenFree 审核失败抛「内容审核」,才能走 compact/style_only。"""
+ from app.services.ark import _raise_seedream_http_error
+
+ body = '{"error":{"code":"InputTextSensitive","message":"text sensitive"}}'
+ with pytest.raises(RuntimeError, match="内容审核"):
+ _raise_seedream_http_error(400, body, model="gpt-image-2-5", tokenfree=True)
+
+
@pytest.mark.asyncio
async def test_post_until_not_rate_limited_retries_then_ok():
calls = {"n": 0}
@@ -220,7 +239,6 @@ async def test_seedream_once_falls_back_to_kie_on_protocol_error(monkeypatch):
project_id=1,
shot_no=1,
size="2k",
- prompt_hash_src="湖",
model="gpt-image-2-5",
)
assert result.local_url == "/static/x.png"
@@ -272,6 +290,5 @@ async def test_seedream_once_keeps_tokenfree_error_when_kie_fallback_raises(monk
project_id=1,
shot_no=1,
size="2k",
- prompt_hash_src="湖",
model="gpt-image-2-5",
)
diff --git a/backend/tests/test_tokenfree_pricing.py b/backend/tests/test_tokenfree_pricing.py
index 668e85f..e326cdd 100644
--- a/backend/tests/test_tokenfree_pricing.py
+++ b/backend/tests/test_tokenfree_pricing.py
@@ -62,11 +62,12 @@ def test_parse_pricing_payload_per_call_and_token() -> None:
def test_recommended_models_cover_text_image_video() -> None:
- """短名单覆盖文字/图/视频,且含默认推荐。"""
+ """短名单覆盖文字/图/视频,且含默认推荐;不含 TokenFree 不可用的 Seedream。"""
caps = {row["capability"] for row in RECOMMENDED_MODELS}
assert caps == {"text", "image", "video"}
ids = {row["id"] for row in RECOMMENDED_MODELS}
- assert {"kimi-k2.6", "gpt-image-2-5", "seedance-2-5"} <= ids
+ assert {"kimi-k2.6", "gpt-image-2-5", "seedance-2-5", "seedance-2-0"} <= ids
+ assert "seedream-5-0-pro" not in ids
assert any(row["recommended"] and row["id"] == "kimi-k2.6" for row in RECOMMENDED_MODELS)
@@ -88,16 +89,25 @@ def test_charge_official_image_uses_per_call() -> None:
def test_charge_official_image_falls_back_without_cache() -> None:
- """无价目缓存时回退旧 token 估价。"""
+ """无价目缓存时按 gpt-image 保底,不再退回 8 元/百万 token。"""
settings = get_settings()
settings.billing_markup = 1.5
+ settings.billing_usd_cny = 7.0
settings.billing_seedream_per_m = 8.0
settings.billing_est_seedream_tokens = 45_000
set_cached_rates(None)
- from app.services.billing.pricing import charge_fen_for_tokens
+ # $0.625 × 7 = ¥4.375 → 438 分
+ assert charge_fen_official_image(settings) == 438
+
- _, expected = charge_fen_for_tokens(45_000, "seedream", settings=settings)
- assert charge_fen_official_image(settings) == expected
+def test_charge_official_video_720p_is_double_480p() -> None:
+ """720p 预扣为 480p 的两倍。"""
+ settings = get_settings()
+ settings.billing_markup = 1.0
+ fen_480 = charge_fen_official_video(5.0, settings, model="seedance-2-5", resolution="480p")
+ fen_720 = charge_fen_official_video(5.0, settings, model="seedance-2-5", resolution="720p")
+ assert fen_480 == 336
+ assert fen_720 == 672
def test_charge_official_video_uses_vendor_sec_not_placeholder() -> None:
@@ -108,7 +118,7 @@ def test_charge_official_video_uses_vendor_sec_not_placeholder() -> None:
rates = parse_pricing_payload(_sample_payload(), settings)
set_cached_rates(rates)
try:
- charge = charge_fen_official_video(5.0, settings, model="seedance-2-5")
+ charge = charge_fen_official_video(5.0, settings, model="seedance-2-5", resolution="480p")
# 3.36 元 → 336 分
assert charge == 336
finally:
diff --git a/backend/tests/test_tokenfree_usage.py b/backend/tests/test_tokenfree_usage.py
index 3b4e59d..69cf3f1 100644
--- a/backend/tests/test_tokenfree_usage.py
+++ b/backend/tests/test_tokenfree_usage.py
@@ -75,6 +75,53 @@ def test_parse_upstream_cost_fen_from_newapi_quota():
assert parse_upstream_cost_fen({"quota": 500_000}, settings) is None
+def test_pick_migratable_api_key_skips_moonshot_and_ark():
+ """启动迁 Key 时不要把 Moonshot/方舟 Key 写进 TokenFree。"""
+ from app.schemas_routing import SystemModelChannel
+ from app.services.tokenfree_gateway import pick_migratable_api_key
+
+ moonshot = SystemModelChannel(
+ id="openai-default",
+ name="Moonshot",
+ base_url="https://api.moonshot.cn/v1",
+ api_key="sk-moonshot",
+ )
+ ark = SystemModelChannel(
+ id="ark-default",
+ name="Ark",
+ base_url="https://ark.cn-beijing.volces.com/api/v3",
+ api_key="ark-key",
+ )
+ assert pick_migratable_api_key([moonshot, ark]) == ""
+ tokenfree = SystemModelChannel(
+ id="tokenfree",
+ name="TokenFree",
+ base_url="https://www.tokenfree.com/v1",
+ api_key="sk-tokenfree",
+ )
+ assert pick_migratable_api_key([moonshot, tokenfree]) == "sk-tokenfree"
+ aliased = SystemModelChannel(
+ id="legacy-openai",
+ name="TF",
+ base_url="https://www.tokenfree.com/v1",
+ api_key="sk-from-url",
+ )
+ assert pick_migratable_api_key([moonshot, aliased]) == "sk-from-url"
+
+
+def test_parse_upstream_cost_fen_prefers_quota_over_usd_cost():
+ """New API 的 cost 是美元;与 quota 同时出现时按 quota,避免 0.625 被当成 63 分。"""
+ settings = get_settings()
+ settings.billing_usd_cny = 7.0
+ # 0.625 USD × 500000 quota/USD = 312500 quota → ¥4.375 → 438 分
+ assert parse_upstream_cost_fen(
+ {"usage": {"prompt_tokens": 1, "quota": 312_500, "cost": 0.625}},
+ settings,
+ ) == 438
+ # 无 quota 字段时仍把火山 cost 当人民币元
+ assert parse_upstream_cost_fen({"usage": {"cost": 1.23}}, settings) == 123
+
+
def test_resolve_billing_basis_newapi_quota():
raw = '{"usage": {"prompt_tokens": 10, "quota": 500000}}'
assert resolve_billing_basis(estimated=False, raw_usage_json=raw) == "upstream_cost"
diff --git a/deploy/.env.prod.example b/deploy/.env.prod.example
index de80b72..7d26a8f 100644
--- a/deploy/.env.prod.example
+++ b/deploy/.env.prod.example
@@ -21,11 +21,11 @@ CORS_ORIGINS=https://your-site.example.com,https://admin.your-site.example.com
ARK_MOCK=false
-ARK_API_KEY=your-ark-api-key
+# 开源版统一走 TokenFree New API(管理后台填写 Key;勿填 Moonshot/方舟 Key)
+ARK_API_KEY=your-tokenfree-api-key
-# 文字模型 Kimi(OpenAI 兼容)
-OPENAI_API_KEY=your-openai-or-kimi-api-key
-OPENAI_BASE_URL=https://api.moonshot.cn/v1
+OPENAI_API_KEY=your-tokenfree-api-key
+OPENAI_BASE_URL=https://www.tokenfree.com/v1
MODEL_LLM=kimi-k2.6
USE_CELERY=true
diff --git a/docs/BILLING.md b/docs/BILLING.md
index f4b5be4..d0e004c 100644
--- a/docs/BILLING.md
+++ b/docs/BILLING.md
@@ -43,7 +43,7 @@ charge_fen = cost_fen
未返回 quota 时回退 token 单价。管理端「支付与计费」可「查询 TokenFree 余额」(`GET /v1/dashboard/billing/subscription` + `usage`),并拉取公开价目 `GET https://www.tokenfree.com/api/pricing` 展示推荐模型官方价。
-预扣:生图按 TokenFree 按张价(Seedream 实际走 `gpt-image-2-5`);LLM 按官方 in/out(默认 kimi-k2.6,70/30 拆);视频不用价目表占位 `model_ratio=37.5`,按火山 480P 秒价估。结算仍优先单次 `quota`。
+预扣:生图按 TokenFree 按张价(Seedream 实际走 `gpt-image-2-5`);价目失败时用 gpt-image 保底(约 $0.625/张),不再退回 8 元/百万 token。LLM 按官方 in/out(默认 kimi-k2.6,70/30 拆)。视频不用价目表占位 `model_ratio=37.5`,按火山 480P 秒价 × 清晰度倍率(720P×2 / 1080P×4);漫剧缺省按 720P。结算仍优先单次 `quota`(勿把 New API 的美元 `cost` 当人民币)。
管理端「官方用量对照」复用模型页 TokenFree API Key,拉取 New API 日消耗(`/api/data/self` 或 billing usage,日期无效时按累计额度差分记到当天)并与本地成本对照。