PRINTFILM: AI short-video marketing and AI short-drama creation platform
feat(billing): 媒体模型目录与固定计价体系
yidda79ac164d8
diff --git a/admin/src/components/settings/MediaPriceSettings.tsx b/admin/src/components/settings/MediaPriceSettings.tsxnew file mode 100644index 0000000..fd1f1de--- /dev/null+++ b/admin/src/components/settings/MediaPriceSettings.tsx@@ -0,0 +1,56 @@+import { useEffect, useState } from 'react'+import { api } from '@/api/client'+import { Button } from '@/components/ui/button'++type PriceData = { active_version: number | null; enabled: boolean; prices: Record<string, Record<string, string>>;+ strategies: Array<{ id: string; capability: string; allowed_resolutions: string[]; duration_min?: number; duration_max?: number }> }++export function MediaPriceSettings() {+ const [data, setData] = useState<PriceData | null>(null)+ const [error, setError] = useState('')+ const [notice, setNotice] = useState('')+ const [busy, setBusy] = useState(false)+ async function load() {+ try { setData(await api<PriceData>('/api/admin/settings/billing/media-prices')); setError('') }+ catch (cause) { setError(cause instanceof Error ? cause.message : '价格加载失败') }+ }+ useEffect(() => { void load() }, [])+ async function toggle() {+ if (!data?.active_version) return+ setBusy(true)+ try {+ await api('/api/admin/settings/billing/media-prices/activation', { method: 'PATCH', body: JSON.stringify({ enabled: !data.enabled, expected_version: data.active_version }) })+ await load(); setNotice('计费模式已切换,仅影响新任务,在途任务保持原规则。')+ } catch (cause) { setError(cause instanceof Error ? cause.message : '切换失败') }+ finally { setBusy(false) }+ }+ async function publish() {+ if (!data) return+ setBusy(true); setError(''); setNotice('')+ try {+ const prices = Object.fromEntries(Object.entries(data.prices).map(([model, rows]) =>+ [model, Object.fromEntries(Object.entries(rows).filter(([, value]) => value.trim() !== ''))]))+ await api('/api/admin/settings/billing/media-prices', { method: 'POST', body: JSON.stringify({ prices, expected_version: data.active_version }) })+ await load(); setNotice('价格已发布,新任务立即生效,在途任务保持原价格。')+ } catch (cause) { setError(cause instanceof Error ? cause.message : '发布失败') }+ finally { setBusy(false) }+ }+ return <section className="settings-panel">+ <h3>图片与视频价格</h3>+ <p className="text-sm text-[var(--admin-muted)]">{data?.active_version ? `价格版本 #${data.active_version} · ${data.enabled ? '已启用' : '已停用,新任务沿用原计费'}` : '尚未发布:下方为现有规则换算的价格草稿。'} 图片按张、视频按提交秒数收费;空白档位不可生成。失败不自动切换路由。</p>+ {error && <p role="alert" className="text-red-600">{error}</p>}+ {notice && <p role="status">{notice}</p>}+ {data && ['image', 'video'].map(kind => <div key={kind} className="admin-table-wrap mt-4">+ <h4>{kind === 'image' ? '图片 · 元/张' : '视频 · 元/秒'}</h4>+ <table><thead><tr><th>模型</th><th>支持参数</th><th>分辨率与单价</th></tr></thead>+ <tbody>{data.strategies.filter(strategy => strategy.capability === kind).map(strategy => <tr key={strategy.id}>+ <td>{strategy.id}</td><td>{strategy.duration_max ? `${strategy.duration_min}–${strategy.duration_max} 秒` : '按成功交付张数'}</td>+ <td><div className="flex flex-wrap gap-3">{strategy.allowed_resolutions.map(resolution => <label key={resolution} className="flex items-center gap-2 text-sm">+ {resolution}<input type="number" min="0.0001" max="10000" step="0.0001" aria-label={`${strategy.id} ${resolution} 单价`} placeholder="未配置" className="w-28 rounded border p-2"+ value={data.prices[strategy.id]?.[resolution] ?? ''} onChange={event => setData({ ...data, prices: { ...data.prices, [strategy.id]: { ...data.prices[strategy.id], [resolution]: event.target.value } } })} />+ </label>)}</div></td>+ </tr>)}</tbody></table>+ </div>)}+ <div className="mt-4 flex gap-3"><Button type="button" disabled={!data || busy} onClick={() => void publish()}>{busy ? '发布中…' : '发布价格版本'}</Button><Button type="button" variant="outline" disabled={busy} onClick={() => void load()}>重新加载</Button>{data?.active_version && <Button type="button" variant="outline" disabled={busy} onClick={() => void toggle()}>{data.enabled ? '停用新任务固定计费' : '启用固定计费'}</Button>}</div>+ </section>+}diff --git a/backend/app/media_schema.py b/backend/app/media_schema.pynew file mode 100644index 0000000..3dee5f5--- /dev/null+++ b/backend/app/media_schema.py@@ -0,0 +1,55 @@+"""Idempotent additive media billing migration; never rewrites historical bills."""+from sqlalchemy import text+++MEDIA_COLUMNS = {+ "projects": {"image_resolution": "VARCHAR(16) NOT NULL DEFAULT ''", "video_resolution": "VARCHAR(16) NOT NULL DEFAULT ''"},+ "task_runs": {"billing_snapshot": "JSON", "media_provider_tasks": "JSON"},+ "usage_events": {"billing_detail": "JSON", "delivery_key": "VARCHAR(192)", "cost_status": "VARCHAR(16)"},+}+++class MediaSchemaNotReady(RuntimeError):+ """仅携带缺失结构名称,便于发布命令报错且不泄漏数据库连接信息。"""++ def __init__(self, missing: list[str]):+ self.missing = missing+ super().__init__("媒体计费结构未就绪:" + "、".join(missing))+++async def apply_media_schema_patches(conn):+ """仅补齐缺失的媒体列和唯一索引,不改写历史数据。"""+ rows = await conn.execute(text("SELECT table_name, column_name FROM information_schema.columns "+ "WHERE table_schema = current_schema() AND table_name IN ('projects', 'task_runs', 'usage_events')"))+ present = set(rows.fetchall())+ for table, definitions in MEDIA_COLUMNS.items():+ for column, definition in definitions.items():+ if (table, column) not in present:+ # Identifiers and types come only from the static whitelist above.+ await conn.execute(text(f"ALTER TABLE {table} ADD COLUMN IF NOT EXISTS {column} {definition}"))+ if await conn.scalar(text("SELECT to_regclass('uq_usage_delivery_key')")) is None:+ await conn.execute(text("CREATE UNIQUE INDEX IF NOT EXISTS uq_usage_delivery_key ON usage_events (delivery_key) WHERE delivery_key IS NOT NULL"))+++async def assert_media_schema_ready(conn) -> None:+ """只读检查新代码依赖的表、列和有效唯一索引;缺失时阻止发布。"""+ rows = await conn.execute(text("SELECT table_name, column_name FROM information_schema.columns "+ "WHERE table_schema = current_schema() AND table_name IN "+ "('projects', 'task_runs', 'usage_events', 'media_price_versions')"))+ present = set(rows.fetchall())+ required = {**MEDIA_COLUMNS, "media_price_versions": dict.fromkeys(("id", "prices", "created_by", "created_at"))}+ missing = [f"{table}.{column}" for table, columns in required.items() for column in columns if (table, column) not in present]+ index_ready = await conn.scalar(text(+ "SELECT EXISTS (SELECT 1 FROM pg_index i "+ "JOIN pg_class idx ON idx.oid = i.indexrelid "+ "JOIN pg_class tab ON tab.oid = i.indrelid "+ "JOIN pg_namespace ns ON ns.oid = tab.relnamespace "+ "JOIN pg_attribute col ON col.attrelid = tab.oid AND col.attnum = i.indkey[0] "+ "WHERE ns.nspname = current_schema() AND tab.relname = 'usage_events' "+ "AND idx.relname = 'uq_usage_delivery_key' AND col.attname = 'delivery_key' "+ "AND i.indisunique AND i.indisvalid AND i.indnkeyatts = 1 AND i.indexprs IS NULL)"+ ))+ if not index_ready:+ missing.append("usage_events.uq_usage_delivery_key")+ if missing:+ raise MediaSchemaNotReady(missing)diff --git a/backend/app/services/media_model_presets.py b/backend/app/services/media_model_presets.pyindex 883004f..ac14343 100644--- a/backend/app/services/media_model_presets.py+++ b/backend/app/services/media_model_presets.py@@ -35,35 +35,35 @@ PRESET_MODELS: dict[LogicalModelCapability, tuple[dict[str, str], ...]] = {"id": "seedream-5.0-pro","label": "Seedream 5.0 Pro","note": "成片定妆首选,角色一致性好;按清晰度计费",- "pricing_hint": "清晰度越高越贵",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "约 20–60 秒/张",},{"id": "seedream-5.0","label": "Seedream 5.0","note": "标准静帧,质量与成本均衡",- "pricing_hint": "约 ¥0.33/张",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "约 15–40 秒/张",},{"id": "seedream-5.0-flash","label": "Seedream 5.0 Flash","note": "更快更省,适合草稿与批量试错",- "pricing_hint": "更省 · 约 ¥0.18/张",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "约 10–25 秒/张",},{"id": "gpt-image-2","label": "GPT Image 2","note": "OpenAI 生图,光影与文字表现好,适合海报与精细静帧",- "pricing_hint": "约 ¥0.55/次",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "约 30–90 秒/张",},{"id": "gpt-image-2.5","label": "GPT Image 2.5","note": "OpenAI 新一代生图,细节与文字更稳,适合定妆与精细静帧",- "pricing_hint": "按次计费,通常高于 2.0",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "约 30–120 秒/张",},),@@ -72,21 +72,21 @@ PRESET_MODELS: dict[LogicalModelCapability, tuple[dict[str, str], ...]] = {"id": "seedance-2.5","label": "Seedance 2.5","note": "成片首选,画质更好;4–30 秒,支持到 1080p",- "pricing_hint": "相对更贵 · 清晰度越高越贵",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "约 3–8 分钟/镜",},{"id": "seedance-2.0","label": "Seedance 2.0","note": "标准成片,运镜较稳;4–15 秒,最高 720p",- "pricing_hint": "清晰度越高越贵",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "约 2–5 分钟/镜",},{"id": "seedance-2.0-fast","label": "Seedance 2.0 Fast","note": "2.0 加速档,适合赶进度;4–15 秒,最高 720p",- "pricing_hint": "介于标准与 Mini 之间",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "约 1–4 分钟/镜",},# seedance-2.0-mini:TokenFree 会转到 doubao-seedance-2-0-mini-260615,@@ -95,7 +95,7 @@ PRESET_MODELS: dict[LogicalModelCapability, tuple[dict[str, str], ...]] = {"id": "MiniMax-H3","label": "MiniMax H3","note": "节奏感强、人物生动;4–15 秒,480p / 768p",- "pricing_hint": "出片偏慢 · 约 ¥0.44–0.73/秒",+ "pricing_hint": "按模型与分辨率定价","eta_hint": "偏慢,4s 约 15 分钟起",},),@@ -130,7 +130,7 @@ IMAGE_RESOLUTIONS_GPT_IMAGE_25: tuple[str, ...] = ("1K", "2K", "4K")VIDEO_ASPECT_RATIOS: tuple[str, ...] = ("9:16", "16:9", "1:1")VIDEO_RESOLUTIONS_FULL: tuple[str, ...] = ("480p", "720p", "1080p")VIDEO_RESOLUTIONS_SAFE: tuple[str, ...] = ("480p", "720p")-# MiniMax-H3:TokenFree 枚举为小写 480p / 768p+# MiniMax-H3:内部统一小写;不同上游插件的大小写由提交适配层兼容。VIDEO_RESOLUTIONS_MINIMAX_H3: tuple[str, ...] = ("480p", "768p")@@ -243,100 +243,10 @@ def clamp_default_to_preset(capability: LogicalModelCapability, model_id: str |return ids[0] if ids else ""-def _is_minimax_h3(mid: str) -> bool:- return "minimax" in mid and "h3" in mid.replace("-", "").replace("_", "")---def _is_seedance_mini(mid: str) -> bool:- return "seedance" in mid and "mini" in mid---def _is_seedance_fast(mid: str) -> bool:- return "seedance" in mid and "fast" in mid---def _is_seedance_25(mid: str) -> bool:- return "seedance" in mid and ("2.5" in mid or "2-5" in mid)---def _is_seedance_20(mid: str) -> bool:- """Seedance 2.0 完整档(非 mini / fast / 2.5)。"""- if "seedance" not in mid:- return False- if _is_seedance_mini(mid) or _is_seedance_fast(mid) or _is_seedance_25(mid):- return False- return (- "2-0" in mid- or "2.0" in mid- or mid in {"seedance-2", "seedance2"}- or mid.endswith("seedance-2")- )--def model_generation_options(model_id: str | None) -> dict[str, Any]:- """按模型返回前台可选参数;未知模型给保守默认。"""- mid = normalize_model_name(resolve_preset_alias(model_id) or (model_id or ""))- if not mid:+ """Compatibility facade; model capabilities are owned by registered strategies."""+ from app.services.media_models import get_strategy+ try:+ return get_strategy(model_id or "").describe()+ except ValueError:return {}-- image_ids = {normalize_model_name(x) for x in preset_ids("image")}- video_ids = {normalize_model_name(x) for x in preset_ids("video")}-- # 图像:Seedream / GPT Image 2 为 1K·2K;GPT Image 2.5 开放 4K- if mid in image_ids or "seedream" in mid or mid.startswith("gpt-image"):- resolutions = (- list(IMAGE_RESOLUTIONS_GPT_IMAGE_25)- if "gpt-image-2.5" in mid or "gpt-image-2-5" in mid- else list(IMAGE_RESOLUTIONS_STANDARD)- )- return {- "capability": "image",- "allowed_aspect_ratios": list(IMAGE_ASPECT_RATIOS),- "allowed_resolutions": resolutions,- }-- # 视频:预设表与 Seedance / MiniMax 优先- # Seedance 2.0 / fast / mini:官方输出时长 4–15s;2.5:4–30s(见方舟文档)- if mid in video_ids or "seedance" in mid or _is_minimax_h3(mid):- if _is_seedance_mini(mid) or _is_seedance_fast(mid):- return {- "capability": "video",- "allowed_aspect_ratios": list(VIDEO_ASPECT_RATIOS),- "allowed_resolutions": list(VIDEO_RESOLUTIONS_SAFE),- "duration_min": 4,- "duration_max": 15,- }- if _is_minimax_h3(mid):- return {- "capability": "video",- "allowed_aspect_ratios": list(VIDEO_ASPECT_RATIOS),- "allowed_resolutions": list(VIDEO_RESOLUTIONS_MINIMAX_H3),- "duration_min": 4,- "duration_max": 15,- }- # 仅 Seedance 2.5 开放 1080p 与 30s;2.0 及其它 Seedance 最高 720p / 15s- if _is_seedance_25(mid):- return {- "capability": "video",- "allowed_aspect_ratios": list(VIDEO_ASPECT_RATIOS),- "allowed_resolutions": list(VIDEO_RESOLUTIONS_FULL),- "duration_min": 4,- "duration_max": 30,- }- if _is_seedance_20(mid) or "seedance" in mid:- return {- "capability": "video",- "allowed_aspect_ratios": list(VIDEO_ASPECT_RATIOS),- "allowed_resolutions": list(VIDEO_RESOLUTIONS_SAFE),- "duration_min": 4,- "duration_max": 15,- }- return {- "capability": "video",- "allowed_aspect_ratios": list(VIDEO_ASPECT_RATIOS),- "allowed_resolutions": list(VIDEO_RESOLUTIONS_SAFE),- "duration_min": 4,- "duration_max": 15,- }-- return {}diff --git a/backend/app/services/media_models/__init__.py b/backend/app/services/media_models/__init__.pynew file mode 100644index 0000000..ebbd7e1--- /dev/null+++ b/backend/app/services/media_models/__init__.py@@ -0,0 +1,8 @@+"""Explicit image/video model strategies shared by catalog, admission and execution."""+from .strategies import (+ ImageModelStrategy, MediaModelStrategy, MediaValidationError, VideoModelStrategy,+ get_strategy, strategies,+)++__all__ = ["ImageModelStrategy", "MediaModelStrategy", "MediaValidationError",+ "VideoModelStrategy", "get_strategy", "strategies"]diff --git a/backend/app/services/media_models/catalog.py b/backend/app/services/media_models/catalog.pynew file mode 100644index 0000000..deea6ff--- /dev/null+++ b/backend/app/services/media_models/catalog.py@@ -0,0 +1,31 @@+from .prices import active_book, resolve_strategy+from .runtime import pin_route+++async def priced_catalog(db, catalog: dict) -> dict:+ from app.config import get_settings+ catalog["generation_defaults"] = {"image_resolution": "2K", "video_resolution": get_settings().ark_video_resolution}+ book = await active_book(db)+ catalog["price_version"] = book["version"] if book else None+ catalog["billing_mode"] = "fixed_media" if book else "legacy"+ for key in ("image_models", "video_models"):+ rows = []+ for row in catalog[key]:+ try:+ strategy = resolve_strategy(row["id"])+ except ValueError:+ continue+ row.update(strategy.describe())+ prices = (book["prices"].get(strategy.model_id) or {}) if book else {}+ row["prices"] = prices+ row["price_version"] = catalog["price_version"]+ row["available_resolutions"] = [x for x in strategy.resolutions if x in prices] if book else list(strategy.resolutions)+ try:+ pin_route(strategy.capability, row["id"])+ row["available"] = bool(row["available_resolutions"])+ except ValueError:+ row["available"] = False+ row["pricing_hint"] = "按张计费" if strategy.capability == "image" else "按提交时长计费"+ rows.append(row)+ catalog[key] = rows+ return catalogdiff --git a/backend/app/services/media_models/failure_costs.py b/backend/app/services/media_models/failure_costs.pynew file mode 100644index 0000000..5202f88--- /dev/null+++ b/backend/app/services/media_models/failure_costs.py@@ -0,0 +1,41 @@+"""Known costs of failed upstream attempts are platform costs, never retail charges."""+from sqlalchemy import select++from app.models_tasks import TaskEvent+++async def record_failed_costs(db, task):+ snapshot = task.billing_snapshot or {}+ if snapshot.get("mode") != "fixed_media":+ return+ from app.services.billing.pricing import parse_upstream_cost_fen+ from app.services.billing.usage import record_line++ events = (await db.execute(select(TaskEvent).where(TaskEvent.task_id == task.id,+ TaskEvent.event_type.in_(("upstream.request.failed", "upstream.request.poll"))))).scalars().all()+ for event in events:+ payload = event.payload or {}+ response = payload.get("response")+ body = response.get("body") if isinstance(response, dict) else None+ if not isinstance(body, dict):+ continue+ data = body.get("data") if isinstance(body.get("data"), dict) else {}+ state = str(body.get("status") or data.get("status") or "").lower()+ if event.event_type.endswith(".poll") and state not in {"failed", "failure", "cancelled", "canceled", "expired"}:+ continue+ cost = parse_upstream_cost_fen(body)+ if cost is None:+ cost = parse_upstream_cost_fen(data)+ if cost is None:+ continue+ operation = next((item for item in snapshot["items"] if item["operation_id"] == payload.get("media_operation_id")), None)+ if operation is None:+ operation = next((item for item in snapshot["items"] if payload.get("model") in (item["model_id"], item["route"]["upstream_model"])), None)+ if operation is None:+ continue+ identity = payload.get("provider_task_id") or payload.get("request_id") or str(event.id)+ await record_line(db, user_id=task.requested_by, task_run_id=task.id, domain=task.domain,+ billing_key="seedream" if operation["capability"] == "image" else "seedance2:video0",+ model=operation["model_id"], raw={"usage": {"cost_fen": cost},+ "media_operation_id": operation["operation_id"], "attempt_id": identity,+ "provider_task_id": payload.get("provider_task_id"), "source": "failed_upstream_attempt"})diff --git a/backend/app/services/media_models/planning.py b/backend/app/services/media_models/planning.pynew file mode 100644index 0000000..0387cbd--- /dev/null+++ b/backend/app/services/media_models/planning.py@@ -0,0 +1,136 @@+"""Build all media operations before admission, including composite-tool helper images."""+from __future__ import annotations++import re++from fastapi import HTTPException+from sqlalchemy import select+from sqlalchemy.orm import selectinload++from app.config import get_settings+from app.models import Project+from .prices import active_book, expected_price_version, resolve_strategy+from .runtime import pin_route+from . import MediaValidationError, get_strategy+++async def plan_items(db, task) -> list[dict]:+ settings = get_settings()+ p = task.payload or {}+ def mapping(value, field):+ if value is not None and not isinstance(value, dict):+ raise MediaValidationError(field, "必须是对象")+ return value or {}+ def first(*values):+ return next((value for value in values if value is not None and value != ""), None)+ prepared = mapping(p.get("prepared"), "prepared")+ canvas = mapping(p.get("canvas"), "canvas")+ generation = mapping(p.get("generation") or canvas.get("generation"), "generation")+ items = []++ def add(capability, params=None, *, model=None, target=None, shot_no=None, optional=False):+ if model is not None and not isinstance(model, str):+ raise MediaValidationError("model", "必须是模型 ID 字符串")+ model = model or (settings.model_image if capability == "image" else settings.model_video)+ strategy = resolve_strategy(model)+ normalized = strategy.normalize_and_validate(params or {})+ items.append({"operation_id": f"{capability}:{target if target is not None else len(items)}",+ "capability": capability, "model_id": strategy.model_id, "strategy_id": strategy.model_id,+ "strategy_version": strategy.version, "params": normalized,+ "target_id": target, "shot_no": shot_no, "optional": optional,+ "route": pin_route(capability, model)})++ kind = task.task_type+ if task.domain == "kepu" and kind in {"project_pipeline", "shot_regen_image", "shot_regen_video"}:+ project = (await db.execute(select(Project).where(Project.id == task.project_id).options(selectinload(Project.shots), selectinload(Project.template)))).scalar_one_or_none() if task.project_id else None+ if not project:+ return []+ from app.services.kepu_stages import normalize_kepu_pipeline_phase, shot_image_ready, shot_video_ready+ from app.services.pipeline import _image_size_for, _project_output_ratio+ phase = normalize_kepu_pipeline_phase(str(p.get("phase") or "script"), project)+ shots = project.shots+ if kind != "project_pipeline":+ shots = [x for x in shots if x.id == task.shot_id]+ phase = "assets" if kind == "shot_regen_image" else "videos"+ for shot in shots:+ if phase == "assets" and (kind != "project_pipeline" or not shot_image_ready(shot)):+ add("image", {"size": _image_size_for(project) or settings.ark_image_size,+ "aspect_ratio": _project_output_ratio(project) or "1:1"},+ model=project.image_model or settings.model_image, target=shot.id, shot_no=shot.shot_no)+ if phase == "videos" and (kind != "project_pipeline" or not shot_video_ready(shot)):+ from app.services.seedance_resolutions import project_video_resolution+ resolution = project_video_resolution(project, settings)+ add("video", {"duration": int(shot.duration or 5), "resolution": resolution,+ "aspect_ratio": _project_output_ratio(project) or "9:16"},+ model=project.video_model or settings.model_video, target=shot.id, shot_no=shot.shot_no)+ return items+ if kind in {"asset_image", "v1_image", "tool_image"}:+ model = p.get("model_id") or p.get("model") or generation.get("model")+ params = {"aspect_ratio": p.get("aspect_ratio") or p.get("ratio") or generation.get("aspect_ratio") or "1:1",+ "resolution": p.get("resolution") or p.get("size") or generation.get("resolution") or "2K",+ "count": p.get("count", 1)}+ if kind == "asset_image" and not p.get("aspect_ratio"):+ params["aspect_ratio"] = "3:4" if p.get("kind", "character") == "character" else "16:9"+ add("image", params, model=model, target=task.asset_id or task.shot_id)+ if kind in {"asset_video", "fragment_video", "v1_video", "v1_seedance", "tool_video"}:+ body = mapping(prepared.get("seedance_body"), "prepared.seedance_body")+ model = p.get("model_id") or p.get("model") or body.get("model") or prepared.get("model_id")+ duration = first(p.get("duration_sec"), p.get("duration"), body.get("duration"), prepared.get("duration"))+ resolution = p.get("resolution") or body.get("resolution") or prepared.get("resolution")+ ratio = p.get("aspect_ratio") or p.get("ratio") or body.get("ratio") or prepared.get("ratio")+ helper_needed = kind == "tool_video" and p.get("tool_id") == "t2v"+ if kind == "fragment_video":+ from app.models_drama import DramaEpisodeFragment, DramaEpisode, DramaProject, DramaAsset, DramaFragmentAssetRef+ from app.services.drama.fragment_content_duration import resolve_seedance_duration_from_content+ from app.services.drama.output_settings import resolve_episode_video_output+ fragment_id = task.fragment_id or next(iter(p.get("fragment_ids") or []), None)+ fragment = await db.get(DramaEpisodeFragment, fragment_id) if fragment_id else None+ if fragment:+ if duration is None:+ duration = resolve_seedance_duration_from_content(fragment.content or "", fallback=int(fragment.duration_sec or 8))+ episode = await db.get(DramaEpisode, fragment.episode_id)+ project = await db.get(DramaProject, task.drama_project_id) if task.drama_project_id else None+ ep_ratio, ep_res = resolve_episode_video_output(episode.params if episode else None, project.params if project else None)+ ratio, resolution = ratio or ep_ratio, resolution or ep_res+ if prepared.get("submit_mode") == "seedance_body" or prepared.get("image_url"):+ helper_needed = False+ elif project:+ from sqlalchemy import or_+ from app.services.drama.generation import build_fragment_ref_payloads+ from app.services.drama.build_seedance_generate_body import build_seedance_reference_catalog+ mentioned = [int(value) for value in re.findall(r"@asset:(\d+)", fragment.content or "")]+ linked = select(DramaFragmentAssetRef.asset_id).where(DramaFragmentAssetRef.fragment_id == fragment.id)+ assets = list((await db.execute(select(DramaAsset).where(DramaAsset.project_id == project.id,+ or_(DramaAsset.id.in_(linked), DramaAsset.id.in_(mentioned))))).scalars().all())+ references = build_seedance_reference_catalog(build_fragment_ref_payloads(project, assets))+ helper_needed = not (references.images or references.audios)+ else:+ helper_needed = True+ add("video", {"duration": duration if duration is not None else (5 if task.domain in {"studio", "api"} else 8),+ "resolution": resolution or ("480p" if task.domain in {"studio", "api"} else "720p"),+ "aspect_ratio": ratio or "9:16",+ **({"generate_audio": p["generate_audio"]} if "generate_audio" in p else {}),+ **({"content": body["content"]} if "content" in body else {})},+ model=model, target=task.fragment_id or task.asset_id or task.shot_id)+ if helper_needed:+ add("image", {"resolution": "2K", "aspect_ratio": ratio or "9:16"}, optional=True)+ return items+++async def prepare_task_media(db, task) -> None:+ if task.billing_snapshot is not None:+ return+ items = await plan_items(db, task)+ if not items:+ return+ book = await active_book(db)+ expected = expected_price_version.get()+ if expected is None:+ expected = (task.payload or {}).get("price_version")+ if expected is not None and expected != (book["version"] if book else 0):+ raise HTTPException(409, detail="价格已更新,请刷新报价后重新提交")+ for item in items:+ if book:+ item.update(get_strategy(item["strategy_id"]).quote(item["params"], book["prices"]))+ task.billing_snapshot = {"mode": "fixed_media" if book else "legacy", "version": 1,+ "price_version": book["version"] if book else None, "items": items}diff --git a/backend/app/services/media_models/prices.py b/backend/app/services/media_models/prices.pynew file mode 100644index 0000000..791ec1d--- /dev/null+++ b/backend/app/services/media_models/prices.py@@ -0,0 +1,115 @@+"""Versioned retail prices, independent of upstream costs and pricing network calls."""+from __future__ import annotations++from contextvars import ContextVar+from decimal import Decimal, InvalidOperation+from typing import Any++from fastapi import HTTPException+from sqlalchemy import select+from sqlalchemy.dialects.postgresql import insert++from app.models_settings import AppSettings, MediaPriceVersion+from . import MediaValidationError, get_strategy, strategies++expected_price_version: ContextVar[int | None] = ContextVar("expected_media_price_version", default=None)+++def validate_prices(prices: dict) -> dict[str, dict[str, str]]:+ if not isinstance(prices, dict):+ raise MediaValidationError("prices", "必须是价格表")+ result: dict[str, dict[str, str]] = {}+ for model, rows in prices.items():+ strategy = get_strategy(model)+ if strategy.model_id != model or not isinstance(rows, dict):+ raise MediaValidationError("prices", "请使用规范模型 ID 和分辨率价格表")+ result[model] = {}+ for resolution, raw in rows.items():+ if resolution not in strategy.resolutions:+ raise MediaValidationError("resolution", f"{model} 不支持 {resolution}")+ try:+ price = Decimal(str(raw))+ if isinstance(raw, bool) or not price.is_finite() or price <= 0 or price > Decimal("10000"):+ raise ValueError+ if price != price.quantize(Decimal("0.0001")):+ raise ValueError+ except (InvalidOperation, ValueError):+ raise MediaValidationError("price", "单价须大于 0、不超过 10000 元,最多四位小数") from None+ result[model][resolution] = format(price, ".4f")+ return result+++async def active_book(db, *, include_disabled: bool = False) -> dict[str, Any] | None:+ # Dedicated settings row prevents unrelated model settings saves from losing the pointer.+ pointer = await db.get(AppSettings, "media_pricing", populate_existing=True)+ version = (pointer.config_json or {}).get("active_version") if pointer else None+ if not version:+ return None+ enabled = (pointer.config_json or {}).get("enabled", True)+ if not enabled and not include_disabled:+ return None+ row = await db.get(MediaPriceVersion, int(version))+ if row is None:+ raise RuntimeError("生效媒体价格版本不存在")+ return {"version": row.id, "prices": row.prices, "enabled": enabled}+++async def publish_book(db, *, prices: dict, expected_version: int | None, user_id: int) -> dict:+ clean = validate_prices(prices)+ await db.execute(insert(AppSettings).values(id="media_pricing", config_json={}).on_conflict_do_nothing(index_elements=[AppSettings.id]))+ pointer = (await db.execute(select(AppSettings).where(AppSettings.id == "media_pricing").with_for_update().execution_options(populate_existing=True))).scalar_one()+ current = (pointer.config_json or {}).get("active_version")+ if current != expected_version:+ raise HTTPException(409, detail="价格版本已变化,请刷新后重试")+ row = MediaPriceVersion(prices=clean, created_by=user_id)+ db.add(row)+ await db.flush()+ pointer.config_json = {**(pointer.config_json or {}), "active_version": row.id, "enabled": True}+ await db.flush()+ return {"version": row.id, "prices": row.prices}+++async def set_pricing_enabled(db, *, enabled: bool, expected_version: int):+ pointer = (await db.execute(select(AppSettings).where(AppSettings.id == "media_pricing").with_for_update().execution_options(populate_existing=True))).scalar_one_or_none()+ if not pointer or (pointer.config_json or {}).get("active_version") != expected_version:+ raise HTTPException(409, detail="价格版本已变化,请刷新后重试")+ pointer.config_json = {**pointer.config_json, "enabled": enabled}+ await db.flush()+++def quote_items(items: list[dict], book: dict) -> dict:+ if not 1 <= len(items) <= 200:+ raise MediaValidationError("items", "须提供 1–200 条生成明细")+ lines = []+ for item in items:+ strategy = resolve_strategy(str(item.get("model_id") or ""))+ lines.append(strategy.quote(item.get("params") or {}, book["prices"]))+ return {"price_version": book["version"], "items": lines,+ "total_fen": sum(x["total_fen"] for x in lines)}+++def resolve_strategy(model_id: str):+ from app.services.model_settings import get_routing_snapshot+ logical = next((x for x in get_routing_snapshot().logical_models if x.id.lower() == model_id.lower()), None)+ return get_strategy(logical.strategy_id if logical and logical.strategy_id else model_id)+++def initial_draft() -> dict:+ """Freeze currently available legacy estimates as an editable draft, never auto-publish."""+ from app.config import get_settings+ from app.services.tokenfree_pricing import charge_fen_official_image, charge_fen_official_video+ settings = get_settings()+ prices = {}+ for strategy in strategies():+ rows = {}+ for resolution in strategy.resolutions:+ try:+ amount = (charge_fen_official_image(settings, model=strategy.model_id, size=resolution)+ if strategy.capability == "image" else+ charge_fen_official_video(10, settings, model=strategy.model_id, resolution=resolution) / 10)+ if amount > 0:+ rows[resolution] = format(Decimal(str(amount)) / 100, ".4f")+ except (ValueError, KeyError, TypeError):+ continue+ prices[strategy.model_id] = rows+ return pricesdiff --git a/backend/app/services/media_models/runtime.py b/backend/app/services/media_models/runtime.pynew file mode 100644index 0000000..32a27d6--- /dev/null+++ b/backend/app/services/media_models/runtime.py@@ -0,0 +1,120 @@+"""Task-local immutable media operations and credential-free route snapshots."""+from __future__ import annotations++from contextvars import ContextVar+from typing import Any+from urllib.parse import urlsplit++from app.config import get_settings+from app.schemas_routing import ResolvedModelRoute+from app.services.logical_model_router import resolve_logical_model+from app.services.model_settings import get_routing_snapshot+from .prices import resolve_strategy+from . import get_strategy++current_snapshot: ContextVar[dict | None] = ContextVar("media_task_snapshot", default=None)+current_operation: ContextVar[dict | None] = ContextVar("media_operation", default=None)+++def _public_route(route: dict) -> dict:+ address = urlsplit(route["base_url"])+ if address.username or address.password or address.query or address.fragment:+ raise ValueError("route: 渠道地址不能包含凭据或查询参数,请使用专用 API Key 字段")+ return route+++def pin_route(capability: str, model_id: str) -> dict:+ settings = get_settings()+ strategy = resolve_strategy(model_id)+ snapshot = get_routing_snapshot()+ logical = next((model for model in getattr(snapshot, "logical_models", []) if model.id.lower() == model_id.lower()), None)+ if logical is not None and not logical.enabled:+ raise ValueError(f"model: {model_id} 已停用")+ route = resolve_logical_model(capability, model_id)+ if route is None and logical is None and model_id != strategy.model_id:+ route = resolve_logical_model(capability, strategy.model_id)+ if route:+ if get_strategy(route.upstream_model).model_id != strategy.model_id:+ raise ValueError("route: 上游绑定与所选模型策略不匹配")+ return _public_route(route.model_dump(exclude={"api_key"}))+ if snapshot.channels and not (settings.ark_mock or settings.local_media_mock):+ raise ValueError(f"route: {model_id} 没有可用渠道,不会自动切换模型")+ return _public_route({"capability": capability, "logical_model_id": model_id,+ "upstream_model": resolve_strategy(model_id).model_id,+ "channel_id": "__runtime__", "channel_name": "Runtime",+ "base_url": settings.ark_base_url, "protocol": "openai", "api_format": "openai"})+++def restore_route(saved: dict) -> ResolvedModelRoute:+ settings = get_settings()+ if saved["channel_id"] == "__runtime__":+ key = settings.ark_api_key+ else:+ channel = next((x for x in get_routing_snapshot().channels if x.id == saved["channel_id"]), None)+ if not channel or not channel.enabled or not channel.api_key:+ raise RuntimeError("固定渠道已停用或凭证不可用,不会自动切换路由")+ key = channel.api_key+ return ResolvedModelRoute(**saved, api_key=key or "")+++def operation_for(capability: str, *, target: int | None = None, shot_no: int | None = None, model: str | None = None) -> dict | None:+ snapshot = current_snapshot.get()+ if not snapshot:+ return None+ items = [x for x in snapshot.get("items", []) if x["capability"] == capability]+ if target is not None or shot_no is not None:+ field, value = ("shot_no", shot_no) if shot_no is not None else ("target_id", target)+ exact = [x for x in items if x.get(field) == value]+ if exact:+ return exact[0]+ if any(x.get("target_id") is not None or x.get("shot_no") is not None for x in items):+ raise RuntimeError(f"{capability}: 此任务没有预留指定资产或镜头")+ current = current_operation.get()+ if target is None and shot_no is None and current and any(x["operation_id"] == current["operation_id"] for x in items):+ return current+ if model:+ exact = [x for x in items if model in (x["model_id"], x["route"]["upstream_model"], x["route"]["logical_model_id"])]+ if exact:+ return exact[0]+ if items:+ return items[0]+ raise RuntimeError(f"{capability}: 此任务没有预留该生成操作")+++def execution_params(capability: str, params: dict, *, target: int | None = None, shot_no: int | None = None, model: str | None = None) -> tuple[Any, dict, ResolvedModelRoute | None]:+ operation = operation_for(capability, target=target, shot_no=shot_no, model=model)+ if operation:+ strategy = get_strategy(operation["strategy_id"])+ # Admission owns billing dimensions. Runtime supplies prompt and actual reference URLs.+ merged = {**params, **{key: operation["params"][key] for key in ("resolution", "duration", "aspect_ratio") if key in operation["params"]}}+ validated = strategy.normalize_and_validate(merged)+ current_operation.set(operation)+ return strategy, validated, restore_route(operation["route"])+ strategy = resolve_strategy(model or (get_settings().model_image if capability == "image" else get_settings().model_video))+ validated = strategy.normalize_and_validate(params)+ return strategy, validated, None+++def stamp_usage(raw: dict | None, *, delivery: str | None = None) -> dict:+ result = dict(raw or {})+ operation = current_operation.get()+ if operation:+ result["media_operation_id"] = operation["operation_id"]+ if delivery:+ result["delivery_id"] = delivery+ return result+++async def existing_provider_task() -> str | None:+ from app.database import AsyncSessionLocal+ from app.models_tasks import TaskRun+ from app.services.billing.context import get_current_task_run_id+ task_id = get_current_task_run_id()+ operation = current_operation.get()+ if not task_id or not operation or operation["capability"] != "video":+ return None+ async with AsyncSessionLocal() as db:+ task = await db.get(TaskRun, task_id)+ if task:+ return (task.media_provider_tasks or {}).get(operation["operation_id"])+ return Nonediff --git a/backend/app/services/media_models/strategies.py b/backend/app/services/media_models/strategies.pynew file mode 100644index 0000000..8ac2df5--- /dev/null+++ b/backend/app/services/media_models/strategies.py@@ -0,0 +1,291 @@+from __future__ import annotations++import re+from decimal import Decimal, InvalidOperation, ROUND_CEILING+from typing import Any+++class MediaValidationError(ValueError):+ def __init__(self, field: str, message: str):+ self.field = field+ super().__init__(f"{field}: {message}")+++IMAGE_RATIOS = ("auto", "1:1", "16:9", "9:16", "4:3", "3:4", "3:2", "2:3", "21:9")+VIDEO_RATIOS = ("9:16", "16:9", "1:1")+++def integer(value: Any, field: str, lo: int, hi: int) -> int:+ try:+ if isinstance(value, str) and len(value) > 64:+ raise ValueError+ number = Decimal(str(value))+ if isinstance(value, bool) or not number.is_finite() or number != number.to_integral_value():+ raise ValueError+ except (ValueError, InvalidOperation, TypeError):+ raise MediaValidationError(field, "必须是整数") from None+ # Compare Decimal bounds before allocating an integer (e.g. 1e999999999).+ if not lo <= number <= hi:+ raise MediaValidationError(field, f"必须在 {lo}–{hi} 之间")+ return int(number)+++class MediaModelStrategy:+ model_id: str+ capability: str+ version = 1+ resolutions: tuple[str, ...]+ ratios: tuple[str, ...]+ max_reference_images = 9+ max_reference_audios = 0+ max_reference_videos = 0+ supports_generate_audio = False+ max_count = 1 # Existing gateway delivers one output per request.+ duration_min = 4+ duration_max = 15++ def describe(self) -> dict[str, Any]:+ result: dict[str, Any] = {+ "strategy_id": self.model_id, "strategy_version": self.version,+ "capability": self.capability,+ "allowed_resolutions": list(self.resolutions),+ "allowed_aspect_ratios": list(self.ratios),+ "billing_unit": "image" if self.capability == "image" else "second",+ "max_count": self.max_count,+ "max_outputs_per_request": 1,+ "reference_limits": {"images": self.max_reference_images,+ "audios": self.max_reference_audios,+ "videos": self.max_reference_videos},+ "defaults": {"resolution": self.resolutions[min(1, len(self.resolutions) - 1)],+ "aspect_ratio": "1:1" if self.capability == "image" else "9:16",+ "count": 1},+ }+ if self.capability == "video":+ result.update(duration_min=self.duration_min, duration_max=self.duration_max,+ duration_step=1, modes=["text_to_video", "image_to_video"])+ result["defaults"]["duration"] = 8+ result["supports_audio"] = self.supports_generate_audio+ else:+ result["modes"] = ["text_to_image", "image_to_image"]+ return result++ def normalize_and_validate(self, params: dict[str, Any]) -> dict[str, Any]:+ if not isinstance(params, dict):+ raise MediaValidationError("params", "必须是对象")+ allowed = {"prompt", "negative", "negative_prompt", "resolution", "size", "aspect_ratio", "ratio",+ "count", "reference_images", "reference_audios", "reference_videos", "style_ref_urls", "ref_urls", "image_url"}+ if self.capability == "video":+ allowed |= {"duration", "seconds", "generate_audio", "watermark", "return_last_frame",+ "first_frame", "last_frame", "reference_audios", "reference_videos", "content"}+ for key in params:+ if key not in allowed:+ raise MediaValidationError(key, "该模型不支持此参数")+ for key in ("resolution", "size", "aspect_ratio", "ratio"):+ if key in params and params[key] is not None and not isinstance(params[key], str):+ raise MediaValidationError(key, "必须是字符串")+ out = {**self.describe()["defaults"], **params}+ res = str(params.get("resolution") or params.get("size") or out["resolution"]).strip()+ if self.capability == "image":+ res = self.image_resolution(res)+ else:+ res = res.lower()+ if res not in self.resolutions:+ raise MediaValidationError("resolution", f"支持 {', '.join(self.resolutions)}")+ out["resolution"] = res+ ratio = str(params.get("aspect_ratio") or params.get("ratio") or out["aspect_ratio"]).strip()+ if ratio not in self.ratios:+ raise MediaValidationError("aspect_ratio", f"支持 {', '.join(self.ratios)}")+ out["aspect_ratio"] = ratio+ out["count"] = integer(out["count"], "count", 1, self.max_count)+ for field, maximum in (("reference_images", self.max_reference_images),+ ("reference_audios", self.max_reference_audios),+ ("reference_videos", self.max_reference_videos)):+ values = params.get(field, params.get("ref_urls", []) if field == "reference_images" else [])+ if not isinstance(values, list) or len(values) > maximum:+ raise MediaValidationError(field, f"最多支持 {maximum} 个参考素材")+ if any(not isinstance(value, str) or not value.strip() for value in values):+ raise MediaValidationError(field, "参考素材必须是非空 URL 字符串")+ out[field] = values+ if params.get("image_url"):+ if not isinstance(params["image_url"], str):+ raise MediaValidationError("image_url", "必须是 URL 字符串")+ out["reference_images"] = [*out["reference_images"], params["image_url"]]+ out.pop("image_url", None)+ styles = params.get("style_ref_urls") or []+ if not isinstance(styles, list) or any(not isinstance(value, str) or not value.strip() for value in styles):+ raise MediaValidationError("style_ref_urls", "必须是参考图 URL 数组")+ if len(out["reference_images"]) + len(styles) > self.max_reference_images:+ raise MediaValidationError("reference_images", "主体和风格参考图合计超限")+ if self.capability == "video":+ out["duration"] = integer(params.get("duration", params.get("seconds", 8)),+ "duration", self.duration_min, self.duration_max)+ for flag in ("generate_audio", "watermark", "return_last_frame"):+ if flag in params and not isinstance(params[flag], bool):+ raise MediaValidationError(flag, "必须是布尔值")+ if params.get("generate_audio") and not self.supports_generate_audio:+ raise MediaValidationError("generate_audio", "该模型暂不支持声音生成")+ for frame in ("first_frame", "last_frame"):+ if params.get(frame) and not isinstance(params[frame], str):+ raise MediaValidationError(frame, "必须是参考图 URL 字符串")+ if params.get("first_frame") and out["reference_images"]:+ raise MediaValidationError("reference_images", "不能与 first_frame 同时使用")+ content = params.get("content") or []+ if not isinstance(content, list):+ raise MediaValidationError("content", "必须是数组")+ images = [x for x in content if isinstance(x, dict) and x.get("type") == "image_url"]+ audios = [x for x in content if isinstance(x, dict) and x.get("type") == "audio_url"]+ videos = [x for x in content if isinstance(x, dict) and x.get("type") == "video_url"]+ for name, values, maximum in (("reference_images", images, self.max_reference_images),+ ("reference_audios", audios, self.max_reference_audios),+ ("reference_videos", videos, self.max_reference_videos)):+ if len(values) + len(out[name]) > maximum:+ raise MediaValidationError(name, f"最多支持 {maximum} 个参考素材")+ if len(images) + len(out["reference_images"]) + bool(params.get("first_frame")) + bool(params.get("last_frame")) > self.max_reference_images:+ raise MediaValidationError("reference_images", "首尾帧与参考图合计超限")+ roles = {x.get("role") for x in images}+ if "first_frame" in roles and "reference_image" in roles:+ raise MediaValidationError("reference_images", "首帧不能与多参考图同时使用")+ return out++ def image_resolution(self, size: str) -> str:+ if len(size) > 64:+ raise MediaValidationError("resolution", "图片分辨率格式过长")+ upper = size.upper()+ if upper in {"1K", "2K", "3K", "4K"}:+ return upper+ from app.services.drama.seedream_options import SEEDREAM_SIZE_MAP+ for tier, mapping in SEEDREAM_SIZE_MAP.items():+ if size.lower() in mapping.values():+ return tier+ match = re.fullmatch(r"(\d+)[xX×](\d+)", size)+ if match:+ area = int(match[1]) * int(match[2])+ if area <= 0 or area > 4096 * 4096:+ raise MediaValidationError("size", "不支持的像素尺寸")+ return "1K" if area <= 1_600_000 else "2K" if area <= 4_624_220 else "4K"+ raise MediaValidationError("resolution", "不支持的图片分辨率")++ def build_provider_request(self, params: dict[str, Any], route: Any) -> dict[str, Any]:+ p = self.normalize_and_validate(params)+ model = route.get("upstream_model") if isinstance(route, dict) else route.upstream_model+ if self.capability == "image":+ from app.services.drama.seedream_options import SEEDREAM_SIZE_MAP+ size = SEEDREAM_SIZE_MAP[p["resolution"]].get(p["aspect_ratio"], p["resolution"])+ return {"model": model, "prompt": p.get("prompt", ""), "size": size,+ "resolution": p["resolution"], "aspect_ratio": p["aspect_ratio"],+ "ref_urls": p["reference_images"], "style_ref_urls": p.get("style_ref_urls", [])}+ body = {key: p[key] for key in ("duration", "resolution", "generate_audio", "watermark", "return_last_frame") if key in p}+ content = list(p.get("content") or [])+ if p.get("prompt"):+ content.append({"type": "text", "text": p["prompt"]})+ for frame in ("first_frame", "last_frame"):+ if p.get(frame):+ content.append({"type": "image_url", "image_url": {"url": p[frame]}, "role": frame})+ for kind, field, role in (("image", "reference_images", "reference_image"),+ ("audio", "reference_audios", "reference_audio"),+ ("video", "reference_videos", "reference_video")):+ content.extend({"type": f"{kind}_url", f"{kind}_url": {"url": url}, "role": role} for url in p[field])+ body.update(model=model, ratio=p["aspect_ratio"], content=content)+ return body++ def quote(self, params: dict[str, Any], price_snapshot: dict[str, Any]) -> dict[str, Any]:+ p = self.normalize_and_validate(params)+ try:+ price = Decimal(str(price_snapshot[self.model_id][p["resolution"]]))+ if not price.is_finite() or price <= 0:+ raise ValueError+ except (KeyError, InvalidOperation, ValueError, TypeError):+ raise MediaValidationError("price", f"{self.model_id}/{p['resolution']} 尚未配置价格") from None+ multiplier = p["duration"] if self.capability == "video" else 1+ amount = int((price * multiplier * 100).to_integral_value(rounding=ROUND_CEILING))+ return {"model_id": self.model_id, "strategy_id": self.model_id, "strategy_version": self.version,+ "capability": self.capability, "resolution": p["resolution"],+ "duration": p.get("duration"), "count": p["count"],+ "unit_price_yuan": format(price, ".4f"), "unit_charge_fen": amount,+ "total_fen": amount * p["count"], "params": p}+++class ImageModelStrategy(MediaModelStrategy):+ max_count = 100 # Batched delivery uses separate one-image gateway requests.+ capability = "image"+ resolutions = ("1K", "2K")+ ratios = IMAGE_RATIOS+++class Seedream50ProStrategy(ImageModelStrategy):+ model_id = "seedream-5.0-pro"+++class Seedream50Strategy(ImageModelStrategy):+ model_id = "seedream-5.0"+++class Seedream50FlashStrategy(ImageModelStrategy):+ model_id = "seedream-5.0-flash"+++class GptImage2Strategy(ImageModelStrategy):+ model_id = "gpt-image-2"+++class GptImage25Strategy(ImageModelStrategy):+ model_id = "gpt-image-2.5"+ resolutions = ("1K", "2K", "4K")+++class VideoModelStrategy(MediaModelStrategy):+ capability = "video"+ resolutions = ("480p", "720p")+ ratios = VIDEO_RATIOS+ max_reference_audios = 3+ max_reference_videos = 3+ supports_generate_audio = True+++class Seedance25Strategy(VideoModelStrategy):+ model_id = "seedance-2.5"+ resolutions = ("480p", "720p", "1080p")+ duration_max = 30+++class Seedance20Strategy(VideoModelStrategy):+ model_id = "seedance-2.0"+++class Seedance20FastStrategy(VideoModelStrategy):+ model_id = "seedance-2.0-fast"+++class MiniMaxH3Strategy(VideoModelStrategy):+ model_id = "MiniMax-H3"+ resolutions = ("480p", "768p")+ max_reference_audios = 0+ max_reference_videos = 0+++_STRATEGIES = tuple(cls() for cls in (Seedream50ProStrategy, Seedream50Strategy, Seedream50FlashStrategy,+ GptImage2Strategy, GptImage25Strategy, Seedance25Strategy,+ Seedance20Strategy, Seedance20FastStrategy, MiniMaxH3Strategy))+++def strategies() -> tuple[MediaModelStrategy, ...]:+ return _STRATEGIES+++def get_strategy(model_id: str) -> MediaModelStrategy:+ from app.services.media_model_presets import resolve_preset_alias+ raw = resolve_preset_alias(model_id).lower()+ raw = {"doubao-seedance-2-0": "seedance-2.0", "doubao-seedance-2-5": "seedance-2.5",+ "ark-seedream": "seedream-5.0-pro", "kie-seedream-5": "seedream-5.0"}.get(raw, raw)+ for strategy in _STRATEGIES:+ if raw == strategy.model_id.lower():+ return strategy+ # Known dated Ark IDs; unknown families do not receive guessed capabilities.+ for prefix, canonical in (("doubao-seedance-2-5-", "seedance-2.5"),+ ("doubao-seedance-2-0-fast-", "seedance-2.0-fast"),+ ("doubao-seedance-2-0-", "seedance-2.0"),+ ("doubao-seedream-5-0-pro-", "seedream-5.0-pro"),+ ("doubao-seedream-5-0-", "seedream-5.0")):+ if raw.startswith(prefix) and raw[len(prefix):].isdigit():+ return get_strategy(canonical)+ raise MediaValidationError("model", f"未注册模型策略:{model_id}")diff --git a/backend/app/services/seedance_resolutions.py b/backend/app/services/seedance_resolutions.pyindex 1d3a98c..2ae65f6 100644--- a/backend/app/services/seedance_resolutions.py+++ b/backend/app/services/seedance_resolutions.py@@ -4,6 +4,16 @@ from __future__ import annotationsfrom app.services.model_routing_config import normalize_model_name++def project_video_resolution(project, settings=None) -> str:+ from app.config import get_settings+ chosen = str(getattr(project, "video_resolution", "") or "").strip().lower()+ if chosen:+ return chosen+ config = settings or get_settings()+ fallback = str(config.ark_video_resolution or "480p").strip().lower()+ return "720p" if getattr(project, "resolution_mode", "") == "hd" and fallback == "480p" else fallback+# 全量 UI / 白名单(含 MiniMax 的 768p;不上 4k)ALL_VIDEO_RESOLUTIONS: tuple[str, ...] = ("480p", "720p", "768p", "1080p")# mini / fast:渠道明确仅两档@@ -70,7 +80,7 @@ def clamp_video_resolution(model_id: str | None, resolution: str | None) -> str:def format_video_resolution_for_upstream(model_id: str | None, resolution: str | None) -> str:"""提交上游的清晰度字符串。- TokenFree MiniMax 插件枚举只认小写 480p / 768p(大写 480P 会报 plugin_usage_invalid)。+ 内部统一小写;TokenFree 不同 MiniMax 插件存在大小写差异,提交适配层处理明确的枚举拒绝。"""return clamp_video_resolution(model_id, resolution)diff --git a/backend/scripts/prepare_media_schema.py b/backend/scripts/prepare_media_schema.pynew file mode 100644index 0000000..d0f028d--- /dev/null+++ b/backend/scripts/prepare_media_schema.py@@ -0,0 +1,57 @@+"""Explicit additive migration for installations with database bootstrap disabled."""+from __future__ import annotations++import asyncio+import argparse+import os+from pathlib import Path+import sys+++async def prepare(*, check_only: bool = False) -> None:+ """迁移并校验,或在只读事务中检查当前目标库;失败自动回滚。"""+ from sqlalchemy import text+ from sqlalchemy.ext.asyncio import create_async_engine+ from app.config import get_settings+ from app.models_settings import MediaPriceVersion+ from app.media_schema import apply_media_schema_patches, assert_media_schema_ready++ engine = create_async_engine(get_settings().database_url, connect_args={"server_settings": {+ "application_name": "printfilm-media-schema", "statement_timeout": "45000",+ "idle_in_transaction_session_timeout": "45000", "lock_timeout": "10000",+ }})+ try:+ async with engine.begin() as conn:+ if check_only:+ await conn.execute(text("SET TRANSACTION READ ONLY"))+ else:+ await conn.run_sync(lambda sync: MediaPriceVersion.__table__.create(sync, checkfirst=True))+ await apply_media_schema_patches(conn)+ await assert_media_schema_ready(conn)+ finally:+ await engine.dispose()+++def main(argv: list[str] | None = None) -> int:+ """缺少结构时返回非零供发布流程中止;不打印 DSN、凭据或业务数据。"""+ parser = argparse.ArgumentParser(description="媒体计费增量迁移与发布前结构检查")+ parser.add_argument("--check", action="store_true", help="只读校验结构,不执行迁移;未就绪返回 1")+ args = parser.parse_args(argv)+ backend = Path(__file__).resolve().parents[1]+ os.chdir(backend)+ sys.path.insert(0, str(backend))+ from app.media_schema import MediaSchemaNotReady+ try:+ asyncio.run(prepare(check_only=args.check))+ except MediaSchemaNotReady as error:+ print(f"{error}。请先执行媒体计费迁移,停止本次发布。", file=sys.stderr)+ return 1+ except Exception as error:+ print(f"媒体计费结构准备失败({type(error).__name__}),请检查数据库连接。", file=sys.stderr)+ return 1+ print("媒体计费结构检查通过。" if args.check else "媒体计费结构已就绪;尚未发布价格时,新任务继续沿用原计费。")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/backend/tests/test_media_fixed_billing.py b/backend/tests/test_media_fixed_billing.pynew file mode 100644index 0000000..6deba7d--- /dev/null+++ b/backend/tests/test_media_fixed_billing.py@@ -0,0 +1,146 @@+from decimal import Decimal+from unittest.mock import patch++import pytest+from fastapi import HTTPException+from sqlalchemy import select++from app.models import UsageEvent+from app.models_settings import MediaPriceVersion+from app.models_tasks import TaskRun+from app.services.billing.context import billing_scope+from app.services.billing.newapi_bill import apply_log_quota+from app.services.billing.settlement import freeze_for_task, settle_task+from app.services.billing.usage import record_line+from app.services.media_models.planning import prepare_task_media+from app.services.media_models.prices import active_book, publish_book, validate_prices+from app.services.media_models.runtime import current_snapshot, operation_for, pin_route, restore_route+from conftest import make_user++[email protected]("value", ["NaN", "Infinity", "0", "-1", "1.00001", True, "10001"])+def test_bad_price_rejected(value):+ with pytest.raises(ValueError):+ validate_prices({"seedream-5.0-pro": {"2K": value}})+++async def test_price_versions_are_immutable_and_conflicting_publish_rejected(db_session):+ db = db_session+ a = await publish_book(db, prices={"seedream-5.0-pro": {"2K": "0.1234"}}, expected_version=None, user_id=1)+ b = await publish_book(db, prices={"seedream-5.0-pro": {"2K": "0.5000"}}, expected_version=a["version"], user_id=1)+ assert (await active_book(db))["version"] == b["version"]+ assert (await db.get(MediaPriceVersion, a["version"])).prices["seedream-5.0-pro"]["2K"] == "0.1234"+ with pytest.raises(HTTPException) as error:+ await publish_book(db, prices={}, expected_version=a["version"], user_id=1)+ assert error.value.status_code == 409+++async def test_partial_delivery_uses_snapshot_and_upstream_cannot_replace_retail(db_session, monkeypatch):+ db = db_session+ user = await make_user(db)+ await publish_book(db, prices={"seedream-5.0-pro": {"2K": "0.1234"}}, expected_version=None, user_id=user.id)+ task = TaskRun(domain="api", task_type="v1_image", requested_by=user.id,+ payload={"model": "seedream-5.0-pro", "resolution": "2K"}, status="running")+ await prepare_task_media(db, task)+ db.add(task)+ await db.flush()+ await freeze_for_task(db, task)+ initial = task.billing_snapshot["items"][0]+ async with billing_scope(task.id, snapshot=task.billing_snapshot):+ event = await record_line(db, user_id=user.id, billing_key="seedream", model="seedream-5.0-pro",+ raw={"delivery_id": "persisted-result-1", "media_operation_id": initial["operation_id"],+ "usage": {"cost_fen": 500}})+ duplicate = await record_line(db, user_id=user.id, billing_key="seedream", model="seedream-5.0-pro",+ raw={"delivery_id": "persisted-result-1", "media_operation_id": initial["operation_id"]})+ assert duplicate.id == event.id+ assert event.charge_fen == 13+ apply_log_quota(event, {"quota": 500000, "id": 98})+ assert event.charge_fen == 13+ assert event.cost_fen > 13+ task.status = "failed" # Another operation may fail after this delivery.+ result = await settle_task(db, task.id)+ assert result["charged"] == 13+ assert (await settle_task(db, task.id))["charged"] == 13+++async def test_failed_without_delivery_refunds_all(db_session):+ db = db_session+ user = await make_user(db)+ await publish_book(db, prices={"seedance-2.5": {"720p": "0.5000"}}, expected_version=None, user_id=user.id)+ task = TaskRun(domain="api", task_type="v1_video", requested_by=user.id,+ payload={"model": "seedance-2.5", "resolution": "720p", "duration": 5}, status="running")+ await prepare_task_media(db, task)+ db.add(task)+ await db.flush()+ await freeze_for_task(db, task)+ from app.models_tasks import TaskEvent+ db.add(TaskEvent(task_id=task.id, event_type="upstream.request.failed", payload={+ "media_operation_id": task.billing_snapshot["items"][0]["operation_id"],+ "request_id": "failed-attempt-1", "model": "seedance-2.5",+ "response": {"body": {"status": "failed", "usage": {"cost_fen": 37}}},+ }))+ await db_session.flush()+ task.status = "failed"+ result = await settle_task(db, task.id)+ assert result == {"charged": 0, "refunded": 250}+ event = (await db.execute(select(UsageEvent).where(UsageEvent.task_run_id == task.id))).scalar_one()+ assert event.cost_fen == 37+ assert event.charge_fen == 0+ assert event.billing_detail["delivered"] is False+++def test_media_route_does_not_fall_back_to_another_model(monkeypatch):+ from app.schemas_routing import DefaultModels, LogicalModel+ from app.services.model_settings import RoutingSnapshot+ from app.services.logical_model_router import resolve_logical_model_candidates+ snapshot = RoutingSnapshot(channels=[], logical_models=[LogicalModel(id="seedance-2.0", capability="video")], default_models=DefaultModels())+ monkeypatch.setattr("app.services.logical_model_router.get_routing_snapshot", lambda: snapshot)+ with patch("app.services.logical_model_router._routes_for_logical_model") as routes:+ assert resolve_logical_model_candidates("video", "seedance-2.5") == []+ routes.assert_not_called()+++async def test_fixed_price_team_task_uses_owner_wallet_and_member_budget(db_session):+ from tests.test_team_billing import seed_team+ from app.services.billing.settlement import ensure_balance_for_task+ from app.models_team_billing import TeamMonthlyUsage+ team, owner, member = await seed_team(db_session)+ await publish_book(db_session, prices={"seedream-5.0-pro": {"2K": "0.1234"}}, expected_version=None, user_id=owner.id)+ task = TaskRun(domain="drama", task_type="asset_image", requested_by=member.id, team_id=team.id,+ payload={"model_id": "seedream-5.0-pro"}, status="pending")+ await prepare_task_media(db_session, task)+ task.billing_estimate_fen = await ensure_balance_for_task(db_session, member, task)+ db_session.add(task)+ await db_session.flush()+ await freeze_for_task(db_session, task)+ async with billing_scope(task.id, snapshot=task.billing_snapshot):+ await record_line(db_session, user_id=member.id, billing_key="seedream", model="seedream-5.0-pro", raw={"delivery_id": "team-image"})+ task.status = "succeeded"+ await settle_task(db_session, task.id)+ assert owner.balance_fen == 1987+ assert member.balance_fen == 90000+ usage = (await db_session.execute(select(TeamMonthlyUsage).where(TeamMonthlyUsage.team_id == team.id, TeamMonthlyUsage.user_id == member.id))).scalar_one()+ assert (usage.spent_fen, usage.reserved_fen) == (13, 0)+++async def test_fixed_price_disabled_billing_never_charges_wallet(db_session, monkeypatch):+ from app.config import get_settings+ user = await make_user(db_session)+ await publish_book(db_session, prices={"seedream-5.0-pro": {"2K": "0.1234"}}, expected_version=None, user_id=user.id)+ task = TaskRun(domain="api", task_type="v1_image", requested_by=user.id, payload={"model": "seedream-5.0-pro"}, status="running")+ await prepare_task_media(db_session, task)+ db_session.add(task)+ await db_session.flush()+ monkeypatch.setattr(get_settings(), "billing_enabled", False)+ await freeze_for_task(db_session, task)+ async with billing_scope(task.id, snapshot=task.billing_snapshot):+ event = await record_line(db_session, user_id=user.id, billing_key="seedream", raw={"delivery_id": "free-image"})+ task.status = "succeeded"+ result = await settle_task(db_session, task.id)+ assert event.charge_fen == result["charged"] == 0+ assert user.balance_fen == 100000diff --git a/backend/tests/test_media_fixed_routes.py b/backend/tests/test_media_fixed_routes.pynew file mode 100644index 0000000..8641b09--- /dev/null+++ b/backend/tests/test_media_fixed_routes.py@@ -0,0 +1,104 @@+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock++import httpx+import pytest++from app.config import Settings+from app.models_tasks import TaskRun+from app.schemas_routing import SystemModelChannel+from app.services.ark import ArkGateway+from app.services.billing.context import billing_scope+from app.services.media_models import get_strategy+from app.services.media_models.runtime import current_operation, operation_for+from conftest import make_user+++def operation():+ strategy = get_strategy("seedance-2.5")+ return {"operation_id": "video:0", **strategy.quote({"duration": 5, "resolution": "720p"},+ {strategy.model_id: {"720p": "0.5"}}), "route": {+ "capability": "video", "logical_model_id": strategy.model_id,+ "upstream_model": "doubao-seedance-2-5-260628", "channel_id": "alpha", "channel_name": "Alpha",+ "base_url": "https://alpha.test/v1", "protocol": "openai", "api_format": "openai",+ }}+++def gateway(monkeypatch):+ alpha = SystemModelChannel(id="alpha", name="Alpha", base_url="https://changed.test/v1", api_key="alpha-key")+ beta = SystemModelChannel(id="beta", name="Beta", base_url="https://beta.test/v1", api_key="beta-key")+ monkeypatch.setattr("app.services.media_models.runtime.get_routing_snapshot", lambda: SimpleNamespace(channels=[alpha, beta]))+ result = ArkGateway(Settings(ark_mock=False, local_media_mock=False))+ monkeypatch.setattr(result, "_ark_api_key", lambda: "global-wrong-key")+ return result, alpha+++async def test_submit_failure_never_tries_second_channel_or_model(gateway, monkeypatch):+ ark, alpha = gateway+ request = AsyncMock(return_value=httpx.Response(503, text="unavailable"))+ monkeypatch.setattr(ark, "_request_media", request)+ async with billing_scope(None, snapshot={"items": [operation()]}):+ with pytest.raises(RuntimeError, match="503"):+ await ark.gen_video_seedance_body({"model": "seedance-2.5", "duration": 5, "content": [{"type": "text", "text": "test"}]})+ request.assert_awaited_once()+ assert request.await_args.args[2] == "https://alpha.test/v1/videos"+ assert request.await_args.kwargs["headers"]["Authorization"] == "Bearer alpha-key"+ assert request.await_args.kwargs["json"]["model"] == "doubao-seedance-2-5-260628"+ assert "api_key" not in operation()["route"]+++async def test_poll_uses_saved_address_and_credentials_even_when_defaults_change(gateway, monkeypatch):+ ark, alpha = gateway+ request = AsyncMock(return_value=httpx.Response(200, json={"id": "original-id", "status": "completed"}))+ monkeypatch.setattr("app.services.ark.observed_request", request)+ async with billing_scope(None, snapshot={"items": [operation()]}):+ result = await ark.fetch_task_once("original-id")+ assert request.await_args.args[2] == "https://alpha.test/v1/videos/original-id"+ assert request.await_args.kwargs["headers"]["Authorization"] == "Bearer alpha-key"+ assert result.url == "https://alpha.test/v1/videos/original-id/content"+++async def test_disabled_pinned_channel_fails_without_network(gateway, monkeypatch):+ ark, alpha = gateway+ alpha.enabled = False+ request = AsyncMock()+ monkeypatch.setattr("app.services.ark.observed_request", request)+ async with billing_scope(None, snapshot={"items": [operation()]}):+ with pytest.raises(RuntimeError, match="不会自动切换"):+ await ark.fetch_task_once("original-id")+ request.assert_not_awaited()+++async def test_recovery_reuses_accepted_provider_id_without_submit(gateway, db_session, monkeypatch):+ ark, alpha = gateway+ user = await make_user(db_session)+ op = operation()+ task = TaskRun(domain="api", task_type="v1_video", requested_by=user.id,+ billing_snapshot={"items": [op]}, media_provider_tasks={op["operation_id"]: "accepted-id"})+ db_session.add(task)+ await db_session.flush()+ @asynccontextmanager+ async def sessions():+ yield db_session+ monkeypatch.setattr("app.database.AsyncSessionLocal", sessions)+ request = AsyncMock()+ monkeypatch.setattr(ark, "_request_media", request)+ async with billing_scope(task.id, snapshot=task.billing_snapshot):+ assert await ark.gen_video_seedance_body({"model": "seedance-2.5", "duration": 5}) == "accepted-id"+ request.assert_not_awaited()+++async def test_database_ids_do_not_collide_with_shot_numbers():+ first, second = operation(), operation()+ first.update(operation_id="video:2", target_id=2, shot_no=1)+ second.update(operation_id="video:3", target_id=3, shot_no=2)+ async with billing_scope(None, snapshot={"items": [first, second]}):+ assert operation_for("video", target=2)["operation_id"] == "video:2"+ assert operation_for("video", shot_no=2)["operation_id"] == "video:3"diff --git a/backend/tests/test_media_planning.py b/backend/tests/test_media_planning.pynew file mode 100644index 0000000..78b664f--- /dev/null+++ b/backend/tests/test_media_planning.py@@ -0,0 +1,51 @@+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from app.models_tasks import TaskRun+from app.services.media_models.catalog import priced_catalog+from app.services.media_models.planning import plan_items+from app.services.media_models.prices import initial_draft, publish_book, validate_prices++[email protected]("phase,expected", [("assets", [("image", 2)]), ("videos", [("video", 1), ("video", 2)]), ("script", [])])+async def test_pipeline_plans_only_missing_outputs_with_per_shot_identity(phase, expected):+ project = SimpleNamespace(id=1, image_model="seedream-5.0-pro", video_model="seedance-2.5",+ output_ratio="9:16", resolution_mode="hd", template=None, shots=[+ SimpleNamespace(id=1, shot_no=1, duration=5, image_url="saved.png", video_url=None),+ SimpleNamespace(id=2, shot_no=2, duration=8, image_url=None, video_url=None),+ ])+ db = SimpleNamespace(execute=AsyncMock(return_value=Mock(scalar_one_or_none=lambda: project)))+ task = TaskRun(domain="kepu", task_type="project_pipeline", project_id=1, payload={"phase": phase})+ items = await plan_items(db, task)+ assert [(item["capability"], item["target_id"]) for item in items] == expected+ if phase == "videos":+ assert [item["params"]["duration"] for item in items] == [5, 8]+ assert len({item["operation_id"] for item in items}) == 2+++async def test_composite_tool_reserves_video_and_helper_image():+ task = TaskRun(domain="studio", task_type="tool_video", payload={"tool_id": "t2v", "model_id": "seedance-2.5", "duration": 5, "resolution": "1080p"})+ items = await plan_items(None, task)+ assert [item["capability"] for item in items] == ["video", "image"]+ assert items[0]["params"]["resolution"] == "1080p"+ assert items[1]["params"]["resolution"] == "2K"+++async def test_catalog_removes_unknown_strategies_and_hides_unpriced_tiers(db_session):+ await publish_book(db_session, prices={"seedream-5.0-pro": {"1K": "0.15"}}, expected_version=None, user_id=1)+ result = await priced_catalog(db_session, {"image_models": [{"id": "seedream-5.0-pro"}, {"id": "unknown"}], "video_models": [{"id": "seedance-2.5"}]})+ assert len(result["image_models"]) == 1+ assert result["image_models"][0]["available_resolutions"] == ["1K"]+ assert result["video_models"][0]["available"] is False+ assert result["billing_mode"] == "fixed_media"+++def test_draft_is_valid_and_does_not_publish():+ draft = initial_draft()+ assert len(draft) == 9+ assert validate_prices(draft) == draftdiff --git a/backend/tests/test_media_pricing_api.py b/backend/tests/test_media_pricing_api.pynew file mode 100644index 0000000..1f6ae3f--- /dev/null+++ b/backend/tests/test_media_pricing_api.py@@ -0,0 +1,110 @@+from unittest.mock import AsyncMock+from types import SimpleNamespace++import httpx+import pytest+from sqlalchemy import func, select++from app.database import get_db+from app.deps import get_current_admin, get_current_user+from app.main import app+from app.models import UsageEvent+from app.models_tasks import TaskRun+from app.services.ark import ImageResult+from app.services.media_models.prices import active_book, publish_book+from conftest import make_user+++async def client(db_session):+ user = await make_user(db_session)+ async def database():+ yield db_session+ saved = dict(app.dependency_overrides)+ from app.api.v1.generation import _resolve_api_user+ app.dependency_overrides.update({get_db: database, get_current_user: lambda: user,+ get_current_admin: lambda: user, _resolve_api_user: lambda: user})+ async with httpx.AsyncClient(transport=httpx.ASGITransport(app=app, raise_app_exceptions=False), base_url="http://test") as http:+ yield http, user+ app.dependency_overrides.clear()+ app.dependency_overrides.update(saved)+++async def test_admin_publish_catalog_and_quote_have_same_price(client, db_session):+ http, user = client+ response = await http.post("/api/admin/settings/billing/media-prices", json={+ "prices": {"seedream-5.0-pro": {"2K": "0.1234"}}, "expected_version": None,+ })+ assert response.status_code == 200, response.text+ version = response.json()["version"]+ catalog = (await http.get("/api/media-models")).json()+ model = next(item for item in catalog["image_models"] if item["id"] == "seedream-5.0-pro")+ assert model["prices"]["2K"] == "0.1234"+ assert model["available_resolutions"] == ["2K"]+ assert catalog["price_version"] == version+ quote = await http.post("/api/billing/media/quote", json={"price_version": version, "items": [+ {"model_id": "seedream-5.0-pro", "params": {"resolution": "2K", "count": 3}},+ ]})+ assert quote.status_code == 200, quote.text+ assert quote.json()["total_fen"] == 39+ assert quote.json()["price_version"] == version+ assert "api_key" not in quote.text+++async def test_stale_catalog_and_unpriced_resolution_never_create_task(client, db_session, monkeypatch):+ http, user = client+ book = await publish_book(db_session, prices={"seedream-5.0-pro": {"2K": "0.10"}}, expected_version=None, user_id=user.id)+ provider = AsyncMock()+ monkeypatch.setattr("app.api.v1.generation.get_ark", lambda: SimpleNamespace(gen_image=provider))+ before = await db_session.scalar(select(func.count(TaskRun.id)))+ response = await http.post("/api/v1/images/generations", headers={"X-Media-Price-Version": str(book["version"] + 1)}, json={"prompt": "test", "model": "seedream-5.0-pro"})+ assert response.status_code == 409, response.text+ response = await http.post("/api/v1/images/generations", json={"prompt": "test", "model": "seedream-5.0-pro", "resolution": "1K"})+ assert response.status_code == 422, response.text+ assert await db_session.scalar(select(func.count(TaskRun.id))) == before+ provider.assert_not_awaited()+++async def test_api_partial_delivery_is_persisted_and_charged_once(client, db_session, monkeypatch):+ http, user = client+ await publish_book(db_session, prices={"seedream-5.0-pro": {"2K": "0.1234"}}, expected_version=None, user_id=user.id)+ provider = AsyncMock(side_effect=[ImageResult(local_url="/static/one.png"),+ ImageResult(local_url="/static/two.png"), RuntimeError("provider unavailable")])+ monkeypatch.setattr("app.api.v1.generation.get_ark", lambda: SimpleNamespace(gen_image=provider))+ monkeypatch.setattr("app.services.storage.republish_url", lambda url, **kwargs: url)+ response = await http.post("/api/v1/images/generations", json={"prompt": "test", "model": "seedream-5.0-pro", "count": 3})+ assert response.status_code >= 400+ task = (await db_session.execute(select(TaskRun).where(TaskRun.requested_by == user.id))).scalar_one()+ assert task.status == "failed"+ assert task.billing_estimate_fen == 39+ assert task.billing_charged_fen == 26+ assert task.billing_refunded_fen == 13+ assert task.result_payload["urls"] == ["/static/one.png", "/static/two.png"]+ assert await db_session.scalar(select(func.count(UsageEvent.id)).where(UsageEvent.task_run_id == task.id)) == 2+++async def test_disable_only_affects_new_tasks_and_rejects_stale_fixed_price(client, db_session):+ http, user = client+ book = await publish_book(db_session, prices={"seedance-2.5": {"720p": "0.50"}}, expected_version=None, user_id=user.id)+ from app.services.media_models.planning import prepare_task_media+ task = TaskRun(domain="api", task_type="v1_video", requested_by=user.id, payload={"model": "seedance-2.5", "resolution": "720p", "duration": 5})+ await prepare_task_media(db_session, task)+ response = await http.patch("/api/admin/settings/billing/media-prices/activation", json={"enabled": False, "expected_version": book["version"]})+ assert response.status_code == 200+ assert await active_book(db_session) is None+ assert task.billing_snapshot["mode"] == "fixed_media"+ response = await http.post("/api/v1/videos/generations", headers={"X-Media-Price-Version": str(book["version"])}, json={"prompt": "test", "image_url": "https://test/a.jpg", "model": "seedance-2.5"})+ assert response.status_code == 409, response.text+++async def test_normal_user_cannot_publish_prices(client, db_session):+ http, user = client+ app.dependency_overrides.pop(get_current_admin)+ response = await http.post("/api/admin/settings/billing/media-prices", json={"prices": {}, "expected_version": None})+ assert response.status_code == 403+ assert await active_book(db_session) is Nonediff --git a/backend/tests/test_media_schema.py b/backend/tests/test_media_schema.pynew file mode 100644index 0000000..85067b3--- /dev/null+++ b/backend/tests/test_media_schema.py@@ -0,0 +1,76 @@+"""Additive migration skips existing columns and never rewrites billing data."""+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from app.media_schema import apply_media_schema_patches+from app import media_schema+++async def test_existing_media_schema_does_not_acquire_ddl_locks():+ columns = [("projects", name) for name in ("image_resolution", "video_resolution")]+ columns += [("task_runs", name) for name in ("billing_snapshot", "media_provider_tasks")]+ columns += [("usage_events", name) for name in ("billing_detail", "delivery_key", "cost_status")]+ result = Mock()+ result.fetchall.return_value = columns+ conn = SimpleNamespace(execute=AsyncMock(return_value=result), scalar=AsyncMock(return_value="uq_usage_delivery_key"))+ await apply_media_schema_patches(conn)+ conn.execute.assert_awaited_once()+ assert "information_schema.columns" in str(conn.execute.await_args.args[0])+++async def test_missing_media_columns_are_added_without_rewriting_history():+ result = Mock()+ result.fetchall.return_value = []+ conn = SimpleNamespace(execute=AsyncMock(return_value=result), scalar=AsyncMock(return_value=None))+ await apply_media_schema_patches(conn)+ commands = [str(call.args[0]) for call in conn.execute.await_args_list][1:]+ assert len(commands) == 8+ assert all(command.startswith("ALTER TABLE ") for command in commands[:-1])+ assert commands[-1].startswith("CREATE UNIQUE INDEX IF NOT EXISTS uq_usage_delivery_key")+ assert not any("UPDATE " in command or "DELETE " in command for command in commands)+++def ready_columns():+ """模拟已经完成图视频计费迁移的数据库元数据。"""+ return [("projects", name) for name in ("image_resolution", "video_resolution")] + [+ ("task_runs", "billing_snapshot"), ("task_runs", "media_provider_tasks"),+ ("usage_events", "billing_detail"), ("usage_events", "delivery_key"),+ ("usage_events", "cost_status"), ("media_price_versions", "id"),+ ("media_price_versions", "prices"), ("media_price_versions", "created_by"),+ ("media_price_versions", "created_at"),+ ]+++async def test_ready_schema_check_only_reads_metadata():+ result = Mock()+ result.fetchall.return_value = ready_columns()+ conn = SimpleNamespace(execute=AsyncMock(return_value=result), scalar=AsyncMock(return_value=True))+ await media_schema.assert_media_schema_ready(conn)+ conn.execute.assert_awaited_once()+ assert str(conn.execute.await_args.args[0]).startswith("SELECT ")+ assert str(conn.scalar.await_args.args[0]).startswith("SELECT ")+++async def test_missing_column_or_index_blocks_release_with_actionable_names():+ result = Mock()+ result.fetchall.return_value = [column for column in ready_columns() if column != ("task_runs", "billing_snapshot")]+ conn = SimpleNamespace(execute=AsyncMock(return_value=result), scalar=AsyncMock(return_value=False))+ with pytest.raises(RuntimeError) as caught:+ await media_schema.assert_media_schema_ready(conn)+ assert caught.value.missing == ["task_runs.billing_snapshot", "usage_events.uq_usage_delivery_key"]+++async def test_missing_price_table_blocks_release_before_prices_are_published():+ result = Mock()+ result.fetchall.return_value = [column for column in ready_columns() if column[0] != "media_price_versions"]+ conn = SimpleNamespace(execute=AsyncMock(return_value=result), scalar=AsyncMock(return_value=True))+ with pytest.raises(RuntimeError) as caught:+ await media_schema.assert_media_schema_ready(conn)+ assert "media_price_versions.prices" in caught.value.missingdiff --git a/backend/tests/test_media_schema_cli.py b/backend/tests/test_media_schema_cli.pynew file mode 100644index 0000000..92c97a0--- /dev/null+++ b/backend/tests/test_media_schema_cli.py@@ -0,0 +1,56 @@+"""发布检查在迁移前后执行,检查模式不建表或补列。"""+from contextlib import asynccontextmanager+from types import SimpleNamespace+from unittest.mock import AsyncMock, Mock++import pytest++from app import config, media_schema+from scripts import prepare_media_schema as cli++[email protected]("check_only", [True, False])+async def test_check_mode_is_read_only_and_prepare_verifies_before_commit(monkeypatch, check_only):+ from sqlalchemy.ext import asyncio as sqlalchemy_asyncio+ from app.models_settings import MediaPriceVersion+ conn = SimpleNamespace(run_sync=AsyncMock(), execute=AsyncMock())+ @asynccontextmanager+ async def begin():+ yield conn+ engine = SimpleNamespace(begin=begin, dispose=AsyncMock())+ monkeypatch.setattr(config, "get_settings", lambda: SimpleNamespace(database_url="postgresql+asyncpg://test.invalid/media_test"))+ monkeypatch.setattr(sqlalchemy_asyncio, "create_async_engine", Mock(return_value=engine))+ patches = AsyncMock()+ verify = AsyncMock()+ monkeypatch.setattr(media_schema, "apply_media_schema_patches", patches)+ monkeypatch.setattr(media_schema, "assert_media_schema_ready", verify, raising=False)+ await cli.prepare(check_only=check_only)+ verify.assert_awaited_once_with(conn)+ assert patches.await_count == int(not check_only)+ assert conn.run_sync.await_count == int(not check_only)+ if check_only:+ assert str(conn.execute.await_args.args[0]) == "SET TRANSACTION READ ONLY"+ else:+ create_table = Mock()+ sync = object()+ monkeypatch.setattr(MediaPriceVersion.__table__, "create", create_table)+ conn.run_sync.await_args.args[0](sync)+ create_table.assert_called_once_with(sync, checkfirst=True)+ engine.dispose.assert_awaited_once()+++def test_cli_check_failure_returns_nonzero_without_printing_credentials(monkeypatch, capsys):+ prepare = AsyncMock(side_effect=RuntimeError("postgresql://[email protected]/db"))+ monkeypatch.setattr(cli, "prepare", prepare)+ assert cli.main(["--check"]) == 1+ output = capsys.readouterr()+ assert "secret-password" not in output.err+ prepare.assert_awaited_once_with(check_only=True)+++def test_cli_check_reports_missing_schema_and_blocks_release(monkeypatch, capsys):+ prepare = AsyncMock(side_effect=media_schema.MediaSchemaNotReady(["task_runs.billing_snapshot"]))+ monkeypatch.setattr(cli, "prepare", prepare)+ assert cli.main(["--check"]) == 1+ assert "task_runs.billing_snapshot" in capsys.readouterr().errdiff --git a/backend/tests/test_media_strategies.py b/backend/tests/test_media_strategies.pynew file mode 100644index 0000000..9889b7e--- /dev/null+++ b/backend/tests/test_media_strategies.py@@ -0,0 +1,83 @@+from decimal import Decimal++import pytest++from app.services.media_models import get_strategy, strategies++[email protected]("model,resolutions,maximum", [+ ("seedream-5.0-pro", ["1K", "2K"], None),+ ("gpt-image-2.5", ["1K", "2K", "4K"], None),+ ("seedance-2.5", ["480p", "720p", "1080p"], 30),+ ("seedance-2.0", ["480p", "720p"], 15),+ ("MiniMax-H3", ["480p", "768p"], 15),+])+def test_model_contract(model, resolutions, maximum):+ description = get_strategy(model).describe()+ assert description["allowed_resolutions"] == resolutions+ assert description.get("duration_max") == maximum+++def test_alias_and_registry():+ assert len(strategies()) == 9+ assert get_strategy("seedance-2-5").model_id == "seedance-2.5"+ assert get_strategy("doubao-seedance-2-0-260128").model_id == "seedance-2.0"+ with pytest.raises(ValueError, match="model"):+ get_strategy("not-registered")++[email protected]("params,field", [+ ({"resolution": "1080p"}, "resolution"),+ ({"duration": 30}, "duration"),+ ({"duration": 4.5}, "duration"),+ ({"duration": True}, "duration"),+ ({"duration": "1e999999999"}, "duration"),+ ({"duration": "9" * 10000}, "duration"),+ ({"aspect_ratio": "21:9"}, "aspect_ratio"),+ ({"surprise": True}, "surprise"),+ ({"reference_images": ["https://a"] * 10}, "reference_images"),+])+def test_invalid_parameters_are_rejected_without_clamping(params, field):+ with pytest.raises(ValueError, match=field):+ get_strategy("seedance-2.0").normalize_and_validate(params)+++def test_fixed_price_per_output_rounding():+ strategy = get_strategy("gpt-image-2.5")+ params = strategy.normalize_and_validate({"resolution": "4k", "count": 3})+ quote = strategy.quote(params, {"gpt-image-2.5": {"4K": "0.0125"}})+ assert quote["unit_charge_fen"] == 2+ assert quote["total_fen"] == 6+ assert quote["unit_price_yuan"] == "0.0125"+++def test_video_quote_uses_submitted_duration():+ strategy = get_strategy("MiniMax-H3")+ params = strategy.normalize_and_validate({"resolution": "768p", "duration": 8})+ quote = strategy.quote(params, {"MiniMax-H3": {"768p": Decimal("0.1234")}})+ assert quote["unit_charge_fen"] == 99+ assert quote["duration"] == 8+++def test_missing_price_is_not_token_fallback():+ strategy = get_strategy("seedream-5.0")+ with pytest.raises(ValueError, match="price"):+ strategy.quote(strategy.normalize_and_validate({}), {})+++def test_image_pixel_mapping_and_upstream_request():+ strategy = get_strategy("seedream-5.0-pro")+ params = strategy.normalize_and_validate({"size": "1584x2816", "aspect_ratio": "9:16"})+ assert params["resolution"] == "2K"+ body = strategy.build_provider_request(params, {"upstream_model": "seedream-5-0-pro"})+ assert body["model"] == "seedream-5-0-pro"+ assert body["size"] == "1584x2816"+ with pytest.raises(ValueError, match="resolution"):+ strategy.normalize_and_validate({"resolution": "4K"})+++def test_first_frame_and_reference_images_are_mutually_exclusive():+ with pytest.raises(ValueError, match="reference_images"):+ get_strategy("seedance-2.5").normalize_and_validate({+ "first_frame": "https://first", "reference_images": ["https://ref"],+ })diff --git a/backend/tests/test_video_plugin_enum.py b/backend/tests/test_video_plugin_enum.pynew file mode 100644index 0000000..dea4042--- /dev/null+++ b/backend/tests/test_video_plugin_enum.py@@ -0,0 +1,54 @@+"""MiniMax 多插件枚举兼容,拒绝响应才允许重试。"""+from unittest.mock import AsyncMock++import httpx+import pytest++from app.services.tokenfree_video import post_video_create++[email protected]("status,code,retries", [(400, "plugin_usage_invalid", 2), (500, "plugin_usage_invalid", 1), (400, "other", 1), (200, "", 1)])+async def test_plugin_enum_retry(monkeypatch, status, code, retries):+ """只对明确拒绝的枚举错误重试,不修改原任务快照。"""+ body = {"model": "MiniMax-H3", "seconds": "13", "metadata": {"resolution": "480p", "ratio": "9:16"}}+ first = httpx.Response(status, json={"code": code})+ accepted = httpx.Response(200, json={"task_id": "ok"})+ request = AsyncMock(side_effect=[first, accepted])+ monkeypatch.setattr("app.services.tasks.upstream.observed_request", request)+ await post_video_create(None, "POST", "https://example.test/videos", json=body)+ assert request.await_count == retries+ assert body["metadata"]["resolution"] == "480p"+ if retries == 2:+ assert request.await_args_list[1].kwargs["json"]["metadata"] == {"resolution": "480P", "ratio": "9:16"}+++async def test_plugin_enum_retry_is_bounded(monkeypatch):+ """另一插件也拒绝时停止,不能无限翻转或改档。"""+ request = AsyncMock(return_value=httpx.Response(400, json={"code": "plugin_usage_invalid"}))+ monkeypatch.setattr("app.services.tasks.upstream.observed_request", request)+ response = await post_video_create(None, "POST", "https://example.test/videos", json={"model": "MiniMax-H3", "metadata": {"resolution": "768P"}})+ assert response.status_code == 400+ assert request.await_count == 2+ assert request.await_args.kwargs["json"]["metadata"]["resolution"] == "768p"++[email protected]("model,resolution,error", [+ ("seedance-2.0", "480p", {"code": "plugin_usage_invalid"}),+ ("MiniMax-H3", "1080p", {"code": "plugin_usage_invalid"}),+ ("MiniMax-H3", "480p", {"code": "plugin_usage_invalid", "task_id": "accepted"}),+])+async def test_other_models_and_accepted_tasks_not_retried(monkeypatch, model, resolution, error):+ """不改变模型、画质档位或重复提交已经有任务号的请求。"""+ request = AsyncMock(return_value=httpx.Response(400, json=error))+ monkeypatch.setattr("app.services.tasks.upstream.observed_request", request)+ await post_video_create(None, "POST", "https://example.test/videos", json={"model": model, "metadata": {"resolution": resolution}})+ assert request.await_count == 1+++async def test_timeout_not_retried(monkeypatch):+ """提交结果不明确时禁止自动重发。"""+ request = AsyncMock(side_effect=httpx.ReadTimeout("timeout"))+ monkeypatch.setattr("app.services.tasks.upstream.observed_request", request)+ with pytest.raises(httpx.ReadTimeout):+ await post_video_create(None, "POST", "https://example.test/videos", json={"model": "MiniMax-H3", "metadata": {"resolution": "480p"}})+ assert request.await_count == 1diff --git a/docs/MEDIA_MODEL_STRATEGIES.md b/docs/MEDIA_MODEL_STRATEGIES.mdnew file mode 100644index 0000000..72c9ee3--- /dev/null+++ b/docs/MEDIA_MODEL_STRATEGIES.md@@ -0,0 +1,62 @@+# 图视频模型策略与站内定价++模型能力由 `backend/app/services/media_models/` 内的九个策略定义。前台目录、参数校验、请求转换、报价和任务受理共用这些策略。图片按模型、分辨率、成功交付张数收费;视频按模型、分辨率、提交的生成秒数收费。每张/条向上取整到分后汇总,单价使用四位小数的 Decimal 元。++科普项目新增 `image_resolution`、`video_resolution`,可在风格配置页按模型选择。历史项目字段为空时仍使用原图像尺寸及站点视频清晰度规则;显式设置的视频分辨率优先于旧 `preview/hd` 推导。++## 发布与兼容++数据库迁移是发布的前置条件。`DATABASE_BOOTSTRAP_ENABLED=false` 时,启动 API 不会自动补齐数据库结构;不能以进程启动成功或 `/api/health` 返回正常代替迁移验收。即使环境开启启动建表,上线仍按以下顺序显式执行并校验。++1. 备份目标数据库,确认本次发布使用的代码版本、数据库目标及恢复方案。+2. 使用**目标环境数据库凭证**,在本次发布代码的 `backend` 目录、该环境的 Python 虚拟环境内执行迁移。Windows 示例:`.venv/Scripts/python.exe scripts/prepare_media_schema.py`。脚本幂等创建媒体价格版本表、补齐下表七列及交付去重唯一索引,不重算历史账单。+3. 在相同环境执行 `.venv/Scripts/python.exe scripts/prepare_media_schema.py --check`,确认退出码为 `0`。该模式只读检查必需表、列及交付唯一索引,缺失时退出码为 `1`;迁移命令本身也会在完成后自动校验。**迁移或校验失败,停止发布,不继续重启 API/Worker。**+4. 校验通过后,再更新并重启 API、Worker,部署前端及管理端。未发布价格时继续使用原计费;新受理的媒体任务仍会保存参数和固定路由。+5. 使用有权限的账号,对目标环境中实际存在且可访问的项目执行认证业务接口冒烟:读取项目、读取分集、读取任务列表,并检查返回数据和服务日志。分集接口示例为 `GET /api/drama/episodes?project_id=<目标项目ID>`;验收需确认 HTTP 200 且返回结构和数据符合预期,不能只检查 `/api/health`。+6. 在发布记录中保存备份标识、迁移与 `--check` 的结果、发布版本及业务冒烟结果。以上任一步骤失败均不得继续发布或开放新版本流量。++| 数据表 | 新增字段或结构 |+|---|---|+| `projects` | `image_resolution`、`video_resolution` |+| `task_runs` | `billing_snapshot`、`media_provider_tasks` |+| `usage_events` | `billing_detail`、`delivery_key`、`cost_status`;`uq_usage_delivery_key` 交付唯一索引 |+| `media_price_versions` | 不可变媒体价格版本表 |++价格发布是独立操作,不以“尚未开启固定价格”为由省略上述结构迁移。在管理端「支付与计费 → 图片与视频价格」检查初始草稿,填写要开放的分辨率单价,再发布版本。草稿是当前旧规则的换算参考,不代表价格已生效;留空的分辨率不开放生成。价格发布立即影响新受理任务。停用固定计费只影响新任务;已受理任务继续使用自己的策略、价格、路由快照。旧历史任务、历史账单不重算。++回滚应用时,必须保留新版本任务的执行与结算代码,先停用新任务固定计费并等在途任务结束;不能用不识别快照的旧 Worker 处理新任务。后续升级模型策略需要保留在途任务使用的策略版本。++### 2026-10-24:漏执行数据库迁移导致分集查询 500++- **现象**:本地 `GET /api/drama/episodes?project_id=422` 返回 500,日志出现 `UndefinedColumnError`,缺少 `task_runs.billing_snapshot` 等字段。此项目 ID 仅用于记录本次复现,上线冒烟应选择目标环境中有权限访问的项目。+- **原因**:本地设置 `DATABASE_BOOTSTRAP_ENABLED=false`,代码已包含媒体计费重构,但目标库未执行配套增量迁移,七个新增字段、媒体价格版本表及交付唯一索引未准备齐全。业务查询会读取新增 ORM 字段,因此即使未发布价格,也会受影响。+- **修复**:在本地目标库执行 `backend/scripts/prepare_media_schema.py` 补齐结构。修复后,同一接口连续两次返回 200,均正常读取 12 集;相关回归测试 16 条通过。本次验证不代表生产环境已经迁移。+- **防复发**:将“备份 → 目标库迁移 → `--check` 成功 → 重启 API/Worker → 认证业务接口冒烟”固定为上线顺序;失败即停止。记录检查结果,禁止仅凭健康检查或服务成功启动判定发布完成。++## 固定路由++任务每项操作锁定渠道 ID、上游模型、协议与地址,不保存 API Key。执行、轮询、下载沿用原渠道,并读取该渠道当前有效凭证;渠道停用或凭证失效时明确失败,不切换其他渠道或模型。++视频请求成功返回任务号后,按操作记录在 `task_runs.media_provider_tasks`;恢复执行复用原任务号。轮询或下载故障不会创建新视频任务,也不剥离参考音频重新生成。用户手动重试创建新任务,使用重新确定的路由和价格。++## 交付与成本++- 结果保存到受管存储并关联业务记录后计费;图片批量中间结果也保存到任务结果,后续失败只扣已交付项。+- 交付键按任务、生成操作和结果身份去重,数据库唯一索引与任务行锁共同防止重复收费。不同镜头或不同图片不会被按任务整体去重。+- 无交付失败/取消全额解冻;部分交付按成功明细扣费。内部工具生成并交付的首帧图片另按图片价计费,报价和冻结包含该项。+- `charge_fen` 是站内售价;`cost_fen` 是上游成本。上游没有返回费用时成本为待核实,不能把待核实的 0 当免费成本。New API 对账只更新新计费行的成本,不能修改用户实扣。+- LLM、TTS 及团队所有者付款、成员月额度继续沿用现有规则。++## 接口++| 接口 | 用途 |+|---|---|+| `GET /api/media-models` | 策略能力、可用档位、站内价格、价格版本 |+| `POST /api/billing/media/quote` | `{items: [{model_id, params}], price_version?}`,返回单项及总报价 |+| `GET /api/admin/settings/billing/media-prices` | 生效/停用状态、价格表或初始草稿、策略能力 |+| `POST /api/admin/settings/billing/media-prices` | `{prices: {model_id: {resolution: "元单价"}}, expected_version}`,发布不可变新版本 |+| `PATCH /api/admin/settings/billing/media-prices/activation` | `{enabled, expected_version}`,切换新任务计费模式 |++前端生成请求携带 `X-Media-Price-Version`(旧模式目录为 0)。价格或模式发生变化返回 409,在建任务、冻结资金、提交上游之前结束。刷新目录后由用户重新提交,不自动重发生成请求。开放 API 也可在请求体提供 `price_version`。++图片开放 API 支持 `model`、`resolution`、`count`;视频支持 `model`、`resolution`、`duration` 和画幅。缺省值兼容原请求形式,但模型不支持的组合会返回字段错误,不自动降档。diff --git a/frontend/src/components/billing/MediaCostNotice.tsx b/frontend/src/components/billing/MediaCostNotice.tsxnew file mode 100644index 0000000..4f43208--- /dev/null+++ b/frontend/src/components/billing/MediaCostNotice.tsx@@ -0,0 +1,16 @@+import { useMediaModelsCatalog } from '../../hooks/useMediaModelsCatalog'+import { mediaQuoteFen } from '../../lib/mediaQuote'++export function MediaCostNotice({ modelId, resolution, seconds, count = 1 }: {+ modelId?: string; resolution?: string; seconds?: number; count?: number+}) {+ const catalog = useMediaModelsCatalog()+ if (!catalog || catalog.billing_mode !== 'fixed_media') return null+ const model = [...catalog.image_models, ...catalog.video_models].find(item => item.id === modelId)+ const price = model?.prices?.[resolution || '']+ const amount = mediaQuoteFen(price, count, seconds ?? 1)+ return <span className="media-cost-notice" role="status">+ {model?.available === false ? '模型暂不可用' : amount === null ? '当前参数无法报价,请选择已定价档位' :+ `¥${price}/${seconds === undefined ? '张' : '秒'} × ${seconds ?? count}${seconds === undefined ? ' 张' : ' 秒'}${seconds !== undefined && count > 1 ? ` × ${count} 条` : ''} = 预计 ¥${(amount / 100).toFixed(2)}`}+ </span>+}diff --git a/frontend/src/components/billing/ProjectMediaCostSummary.tsx b/frontend/src/components/billing/ProjectMediaCostSummary.tsxnew file mode 100644index 0000000..4e36574--- /dev/null+++ b/frontend/src/components/billing/ProjectMediaCostSummary.tsx@@ -0,0 +1,22 @@+import type { Project } from '../../api'+import { useMediaModelsCatalog } from '../../hooks/useMediaModelsCatalog'+import { mediaQuoteFen } from '../../lib/mediaQuote'+import { MediaCostNotice } from './MediaCostNotice'++export function ProjectMediaCostSummary({ project }: { project: Project }) {+ const catalog = useMediaModelsCatalog()+ if (catalog?.billing_mode !== 'fixed_media') return null+ const images = project.shots.filter(shot => !shot.image_url)+ const videos = project.pipeline_mode === 'image_text' ? [] : project.shots.filter(shot => !shot.video_url && shot.video_skip_reason !== 'privacy')+ const modelId = project.video_model || catalog.defaults.video_model+ const video = catalog.video_models.find(item => item.id === modelId)+ const fallback = catalog.generation_defaults?.video_resolution || '480p'+ const resolution = project.video_resolution || (project.resolution_mode === 'hd' && fallback === '480p' ? '720p' : fallback)+ const parts = videos.map(shot => mediaQuoteFen(video?.prices?.[resolution], 1, Math.trunc(shot.duration)))+ const videoFen = parts.every(value => value !== null) ? parts.reduce<number>((sum, value) => sum + (value ?? 0), 0) : null+ return <div className="media-cost-notice" role="status">+ {images.length > 0 && <div>待生成图片:<MediaCostNotice modelId={project.image_model || catalog.defaults.image_model} resolution={project.image_resolution || '2K'} count={images.length} /></div>}+ {videos.length > 0 && <div>待生成视频:{resolution} · {videos.length} 条 · {videos.reduce((sum, shot) => sum + Math.trunc(shot.duration), 0)} 秒 · {videoFen === null ? '当前参数尚未定价' : `预计 ¥${(videoFen / 100).toFixed(2)}`}</div>}+ {(images.length > 0 || videos.length > 0) && <small>各阶段分别冻结;图视频按成功交付结算,配音等费用另计。</small>}+ </div>+}diff --git a/frontend/src/components/drama/DramaMediaModelPicker.tsx b/frontend/src/components/drama/DramaMediaModelPicker.tsxindex 16f5369..deb01b5 100644--- a/frontend/src/components/drama/DramaMediaModelPicker.tsx+++ b/frontend/src/components/drama/DramaMediaModelPicker.tsx@@ -56,7 +56,7 @@ export function DramaMediaModelPicker({const kind = mediaModelIconKind(m.id)const badge = mediaModelCapabilityBadge(m)const desc = (m.description || '').trim()- const price = (m.pricing_hint || '').trim()+ const price = m.prices && Object.keys(m.prices).length ? Object.entries(m.prices).map(([resolution, amount]) => `${resolution} ¥${amount}/${m.billing_unit === 'second' ? '秒' : '张'}`).join(' · ') : (m.pricing_hint || '').trim()const eta = (m.eta_hint || '').trim()const clip = mediaModelClipDurationLabel(m)const metaBits = [clip, eta].filter(Boolean)@@ -64,6 +64,7 @@ export function DramaMediaModelPicker({<buttonkey={m.id}type="button"+ disabled={m.available === false}className={`fc-gen-model-card${selected ? ' selected' : ''}`}title={mediaModelHoverText(m)}aria-label={`${m.label}${desc ? `,${desc}` : ''}${metaBits.length ? `,${metaBits.join(',')}` : ''}${price ? `,${price}` : ''}`}diff --git a/frontend/src/hooks/useMediaModelsCatalog.ts b/frontend/src/hooks/useMediaModelsCatalog.tsindex 519b38d..d8525fc 100644--- a/frontend/src/hooks/useMediaModelsCatalog.ts+++ b/frontend/src/hooks/useMediaModelsCatalog.ts@@ -4,14 +4,18 @@ import { api, type MediaModelOption, type MediaModelsCatalog } from '../api'let cached: MediaModelsCatalog | null = nulllet inflight: Promise<MediaModelsCatalog> | null = null+let fetchedAt = 0+const listeners = new Set<(value: MediaModelsCatalog) => void>()-function loadCatalog(): Promise<MediaModelsCatalog> {- if (cached) return Promise.resolve(cached)+function loadCatalog(force = false): Promise<MediaModelsCatalog> {+ if (!force && cached && Date.now() - fetchedAt < 60_000) return Promise.resolve(cached)if (!inflight) {inflight = api.mediaModels().then((cat) => {cached = cat+ fetchedAt = Date.now()+ listeners.forEach(listener => listener(cat))return cat- })+ }).finally(() => { inflight = null })}return inflight}@@ -21,6 +25,12 @@ export function useMediaModelsCatalog() {useEffect(() => {let cancelled = false+ const receive = (value: MediaModelsCatalog) => { if (!cancelled) setCatalog(value) }+ listeners.add(receive)+ const refresh = () => { void loadCatalog(true).catch(() => {}) }+ const timer = setInterval(() => { void loadCatalog().catch(() => {}) }, 60_000)+ window.addEventListener('focus', refresh)+ window.addEventListener('media-prices-changed', refresh)loadCatalog().then((cat) => {if (!cancelled) setCatalog(cat)@@ -30,6 +40,10 @@ export function useMediaModelsCatalog() {})return () => {cancelled = true+ listeners.delete(receive)+ clearInterval(timer)+ window.removeEventListener('focus', refresh)+ window.removeEventListener('media-prices-changed', refresh)}}, [])diff --git a/frontend/src/lib/generationMedia.ts b/frontend/src/lib/generationMedia.tsnew file mode 100644index 0000000..d41a32c--- /dev/null+++ b/frontend/src/lib/generationMedia.ts@@ -0,0 +1,12 @@+import { useCallback } from 'react'+import { AudioLines, Image, Video } from 'lucide-react'+import { useI18n } from '../i18n'++export type MediaKind = 'video' | 'image' | 'audio'+export const mediaKinds: MediaKind[] = ['video', 'image', 'audio']+export const mediaIcons = { video: Video, image: Image, audio: AudioLines }++export function useGenerationText() {+ const { locale } = useI18n()+ return useCallback((zh: string, en: string) => locale === 'en' ? en : zh, [locale])+}diff --git a/frontend/src/lib/mediaPriceVersion.ts b/frontend/src/lib/mediaPriceVersion.tsnew file mode 100644index 0000000..5278063--- /dev/null+++ b/frontend/src/lib/mediaPriceVersion.ts@@ -0,0 +1,4 @@+let version: number | null = null++export function getMediaPriceVersion(): number | null { return version }+export function setMediaPriceVersion(value: number | null): void { version = value }diff --git a/frontend/src/lib/mediaQuote.ts b/frontend/src/lib/mediaQuote.tsnew file mode 100644index 0000000..f4849ff--- /dev/null+++ b/frontend/src/lib/mediaQuote.ts@@ -0,0 +1,8 @@+/** Decimal prices use 1/10000 yuan units, rounding each delivered output up to fen. */+export function mediaQuoteFen(price: string | undefined, quantity = 1, seconds = 1): number | null {+ if (!price || !/^\d+(\.\d{1,4})?$/.test(price) || !Number.isInteger(quantity) || !Number.isInteger(seconds) || quantity < 1 || seconds < 1) return null+ const [whole, fraction = ''] = price.split('.')+ const units = BigInt(whole) * 10000n + BigInt(fraction.padEnd(4, '0'))+ if (units <= 0n) return null+ return Number(((units * BigInt(seconds) + 99n) / 100n) * BigInt(quantity))+}diff --git a/frontend/tests/media-quote.test.mjs b/frontend/tests/media-quote.test.mjsnew file mode 100644index 0000000..a4e4c23--- /dev/null+++ b/frontend/tests/media-quote.test.mjs@@ -0,0 +1,19 @@+import assert from 'node:assert/strict'+import test from 'node:test'+import { mediaQuoteFen } from '../src/lib/mediaQuote.ts'++test('round each image before multiplying count', () => {+ assert.equal(mediaQuoteFen('0.0125', 3), 6)+ assert.equal(mediaQuoteFen('0.1000', 2), 20)+})++test('video uses submitted seconds with exact decimal arithmetic', () => {+ assert.equal(mediaQuoteFen('0.1234', 1, 8), 99)+ assert.equal(mediaQuoteFen('0.2900', 1, 10), 290)+})++test('invalid or missing price never becomes free', () => {+ for (const price of [undefined, '', 'NaN', '-1', '0', '0.12345']) assert.equal(mediaQuoteFen(price), null)+ assert.equal(mediaQuoteFen('1', 1, 0), null)+ assert.equal(mediaQuoteFen('1', 1, 4.5), null)+})