PRINTFILM: AI short-video marketing and AI short-drama creation platform
fix: Seedance 参考音频绑定与时长校验,接入 GPT Image 2.5
yib1217b9e613b
diff --git a/admin/src/lib/tokenfreeRecommendedModels.ts b/admin/src/lib/tokenfreeRecommendedModels.tsindex df5186b..9914e7d 100644--- a/admin/src/lib/tokenfreeRecommendedModels.ts+++ b/admin/src/lib/tokenfreeRecommendedModels.ts@@ -14,6 +14,7 @@ export const PRESET_MODELS: Record<ModelCapability, PresetModelOption[]> = {{ id: "seedream-5.0", label: "Seedream 5.0" },{ id: "seedream-5.0-flash", label: "Seedream 5.0 Flash" },{ id: "gpt-image-2", label: "GPT Image 2" },+ { id: "gpt-image-2.5", label: "GPT Image 2.5" },],video: [{ id: "seedance-2.5", label: "Seedance 2.5" },@@ -67,8 +68,12 @@ const PRESET_MODEL_ALIASES: Record<string, string> = {"seedream5.0": "seedream-5.0",seedream5: "seedream-5.0","seedream-5-0-flash": "seedream-5.0-flash",- "gpt-image-2-5": "gpt-image-2",- "gpt-image-2.5": "gpt-image-2",+ "gpt-image-2-5": "gpt-image-2.5",+ "gpt-image-2.5": "gpt-image-2.5",+ "gpt-image-2.5-sunburst": "gpt-image-2.5",+ "gpt-image-2-5-sunburst": "gpt-image-2.5",+ "gpt-image-2.5-flare": "gpt-image-2.5",+ "gpt-image-2-5-flare": "gpt-image-2.5","gemini-3.1-flash-tts": "qwen-tts-2025-05-22",};diff --git a/backend/app/api/drama/canvas.py b/backend/app/api/drama/canvas.pyindex ccc8417..88f2067 100644--- a/backend/app/api/drama/canvas.py+++ b/backend/app/api/drama/canvas.py@@ -83,20 +83,25 @@ async def save_canvas(asset.asset_type = asset_typeif url:asset.url = str(url)- asset.cover = str(url)+ # 音频/音色节点勿把媒体 URL 写进 cover(否则 Seedance 会当参考图)+ if asset_type in {"audio", "voice"} or kind in {"audio", "voice"}:+ asset.cover = None+ else:+ asset.cover = str(url)params = dict(asset.params or {})params["canvas"] = nodeparams["canvas_node_id"] = nidasset.params = paramsexisting[nid] = assetelse:+ is_audio_node = asset_type in {"audio", "voice"} or kind in {"audio", "voice"}db.add(DramaAsset(project_id=project.id,type=kind if kind else "none",asset_type=asset_type,name=name,- cover=str(url) if url else None,+ cover=None if is_audio_node else (str(url) if url else None),url=str(url) if url else None,params={"canvas_node_id": nid, "canvas": node},)diff --git a/backend/app/services/ark.py b/backend/app/services/ark.pyindex 7099810..7abd154 100644--- a/backend/app/services/ark.py+++ b/backend/app/services/ark.py@@ -458,6 +458,18 @@ def _format_seedance_create_error(return "分镜文案未通过内容审核,请修改敏感表述后重试"if "resource download failed" in text and "audio" in text.lower():return "参考音频无法下载,请检查角色音色绑定后重试"+ # 参考图槽位收到非图片(常见:音色 cover 写成 mp3)+ if re.search(r"invalid image format", text, re.I) or (+ re.search(r"File type not supported", text, re.I)+ and re.search(r"content\[\d+\]", text, re.I)+ ):+ idx, label = _seedance_content_slot_label(text, content_labels)+ who = label or (f"提交内容第 {idx + 1} 项 / content[{idx}]" if idx >= 0 else "某张参考图")+ return (+ f"参考图格式无效:{who}。"+ "上游按图片校验失败(常见原因:音频文件被误当作参考图,或链接不是 PNG/JPG/WEBP)。"+ "请检查本镜引用的角色/场景封面,确认音色资产未占用参考图槽位后重试。"+ )# Seedance r2v:reference_audio 时长须 ≥ 1.8 秒if re.search(r"audio duration.*(?:1\.8|greater than or equal)", text, re.I) or ("audio duration" in text.lower() and "content[" in text.lower()@@ -976,20 +988,40 @@ class ArkGateway:# TokenFree 按逻辑路由解析出的上游模型原样发送,不硬改模型名chosen = (upstream_model or "").strip()if on_tokenfree and "gpt-image" in chosen.lower():- # Kie / gpt-image 实际按 1K·2K 档;画幅靠 aspect_ratio 自然语言约束。- # 无 aspect_ratio 时保留 WxH,避免把唯一画幅信号压成「清晰度2K」。+ from app.services.tokenfree_image import gpt_image_caps_at_2k++ # GPT Image 2 只吃 1K/2K;2.5 保留 4K。画幅靠 aspect_ratio 自然语言约束。raw_size = str(resolved_size or "").strip()upper = raw_size.upper()- if upper in {"3K", "4K"}:- resolved_size = "2K"- elif "x" in raw_size.lower() and str(aspect_ratio or "").strip():- try:- w_s, _, h_s = raw_size.lower().partition("x")- area = int(w_s) * int(h_s)- resolved_size = "2K" if area >= 1500 * 1500 else "1K"- except ValueError:+ if gpt_image_caps_at_2k(chosen):+ if upper in {"3K", "4K"}:resolved_size = "2K"- if on_tokenfree:+ elif "x" in raw_size.lower() and str(aspect_ratio or "").strip():+ try:+ w_s, _, h_s = raw_size.lower().partition("x")+ area = int(w_s) * int(h_s)+ resolved_size = "2K" if area >= 1500 * 1500 else "1K"+ except ValueError:+ resolved_size = "2K"+ elif upper in {"3K", "4K"} or "x" in raw_size.lower():+ resolved_size = raw_size+ from app.services.tokenfree_image import (+ build_tokenfree_openai_image_body,+ is_gpt_image_25,+ )++ # 2.5 的渠道是 image-generation,走 /responses 会报 default 分组无 distributor+ if on_tokenfree and is_gpt_image_25(chosen):+ path = "/images/generations"+ body = build_tokenfree_openai_image_body(+ model=chosen,+ prompt=full_prompt,+ size=str(resolved_size or ""),+ aspect_ratio=str(aspect_ratio or ""),+ ref_urls=subject_refs,+ style_ref_urls=style_refs,+ )+ elif on_tokenfree:path = "/responses"body = build_tokenfree_image_body(model=chosen,@@ -1450,6 +1482,16 @@ class ArkGateway:content,project_id=project_id,)+ # 提交上游前硬校验 reference_audio 时长,避免 InvalidParameter 才暴露+ from app.services.drama.voice_reference_audio import (+ validate_seedance_body_reference_audios,+ )++ await validate_seedance_body_reference_audios(+ payload,+ content_labels=content_labels,+ project_id=project_id,+ )payload["duration"] = self._seedance_duration(payload.get("duration", 8),model=str(payload.get("model") or ""),diff --git a/backend/app/services/drama/build_seedance_generate_body.py b/backend/app/services/drama/build_seedance_generate_body.pyindex 6db71f0..3b52d94 100644--- a/backend/app/services/drama/build_seedance_generate_body.py+++ b/backend/app/services/drama/build_seedance_generate_body.py@@ -55,6 +55,10 @@ SEEDANCE_SCENE_SECTION_HEADER = ("【强制约束:场景】以下场景的空间结构、环境陈设、光影氛围必须与对应参考图严格一致,""严禁替换为其他场景或大幅偏离参考画面:")+SEEDANCE_MUSIC_SECTION_HEADER = (+ "【强制约束:参考音乐】以下音频是全片背景音乐参考,不是角色对白音色。"+ "配乐的旋律、节奏与情绪必须贴合对应参考音频;无台词镜头保持闭嘴,禁止把这段音乐念成对白:"+)SEEDANCE_PROP_SECTION_HEADER = ("【强制约束:道具】以下道具的外形、材质与关键细节必须与对应参考图严格一致,""严禁替换为其他物品或丢失标志性特征:"@@ -186,17 +190,45 @@ def read_asset_voice_audio_url(params: Any) -> str | None:return None-# 解析资产可用的图片 URL+# 音频后缀:禁止当作 reference_image(音色 cover 常被写成 mp3)+_AUDIO_URL_SUFFIXES = (+ ".mp3",+ ".wav",+ ".m4a",+ ".aac",+ ".ogg",+ ".flac",+ ".opus",+ ".webm",+)+++def _looks_like_audio_url(url: str) -> bool:+ """URL 路径是否像音频文件(忽略 query)。"""+ path = (url or "").split("?", 1)[0].strip().lower()+ return any(path.endswith(suffix) for suffix in _AUDIO_URL_SUFFIXES)+++# 解析资产可用的图片 URL(绝不返回音频;voice/audio 资产不进参考图)def resolve_reference_image_url(asset: dict[str, Any]) -> str | None:cover = (asset.get("cover") or "").strip()url = (asset.get("url") or "").strip()- asset_type = asset.get("assetType")- category_type = asset.get("type")+ asset_type = str(asset.get("assetType") or "").strip().lower()+ category_type = str(asset.get("type") or "").strip().lower()++ # 音色/音频节点:cover 可能被写成试听 URL,绝不能进 image_url+ if asset_type in {"audio", "voice"} or category_type in {"audio", "voice", "narration"}:+ return None- if asset_type == "image" or category_type in ("character", "scene", "prop", "material"):- return cover or url or None+ candidate = ""+ if asset_type == "image" or category_type in ("character", "scene", "prop", "material", "image"):+ candidate = cover or url+ else:+ candidate = cover- return cover or None+ if not candidate or _looks_like_audio_url(candidate):+ return None+ return candidate# 解析写入提示词的资产名称@@ -699,6 +731,19 @@ def _name_is_token_prefix(text: str, name: str) -> bool:return (not rest) or rest[0] in _NAME_TOKEN_BOUNDARIES+def _mention_audio_index(+ asset: dict[str, Any] | None,+ catalog: SeedanceReferenceCatalog,+) -> int | None:+ """角色/旁白音色与画布独立音频都要写成 @音频N,否则上游不使用该参考音频。"""+ if not asset or asset.get("id") is None:+ return None+ kind = str(asset.get("type") or "").lower()+ if kind not in {"character", "narration", "audio", "voice"}:+ return None+ return (getattr(catalog, "audio_index_by_asset_id", {}) or {}).get(int(asset["id"]))++# 将单个 @asset 占位符替换为正文描述def replace_asset_mention_token(asset_id: int,@@ -709,11 +754,7 @@ def replace_asset_mention_token(if not asset:return ""image_index = (getattr(catalog, "image_index_by_asset_id", {}) or {}).get(int(asset["id"]))- audio_index = None- if str(asset.get("type") or "").lower() in {"character", "narration"}:- audio_index = (getattr(catalog, "audio_index_by_asset_id", {}) or {}).get(- int(asset["id"])- )+ audio_index = _mention_audio_index(asset, catalog)return format_body_asset_mention(_asset_prompt_name_for_mention(asset),image_index,@@ -741,9 +782,7 @@ def replace_asset_mentions_without_duplicate_names(parts: list[str] = []if image_index is not None:parts.append(f"@图片{image_index}/参考图{image_index}")- if audio_index is not None and str(- (asset_by_id.get(asset_id) or {}).get("type") or ""- ).lower() in {"character", "narration"}:+ if _mention_audio_index(asset_by_id.get(asset_id), catalog) is not None:parts.append(f"@音频{audio_index}/参考音频{audio_index}")token = f"({','.join(parts)})" if parts else ""end = match.end()@@ -825,6 +864,35 @@ def build_reference_index_section(return "\n".join([header, *lines])+def build_music_reference_section(+ reference: list[dict[str, Any]] | None,+ catalog: SeedanceReferenceCatalog,+) -> str | None:+ """独立音频节点写成背景音乐口令;角色音色仍走对白约束,避免互相覆盖。"""+ if not SEEDANCE_ATTACH_REFERENCE_AUDIO:+ return None+ lines: list[str] = []+ seen: set[int] = set()+ for asset in reference or []:+ if str(asset.get("type") or "").lower() not in {"audio", "voice"}:+ continue+ asset_id = int(asset["id"])+ if asset_id in seen:+ continue+ seen.add(asset_id)+ audio_index = (catalog.audio_index_by_asset_id or {}).get(asset_id)+ if audio_index is None:+ continue+ name = resolve_other_asset_prompt_name(asset)+ lines.append(+ f"背景音乐使用@音频{audio_index}(参考音频{audio_index})「{name}」,"+ "贯穿有配乐的镜头,不要当作任何人声对白"+ )+ if not lines:+ return None+ return "\n".join([SEEDANCE_MUSIC_SECTION_HEADER, *lines])++# 将分镜脚本转为正文提示词def _normalize_body_whitespace(text: str) -> str:lines = [@@ -934,6 +1002,7 @@ def build_seedance_prompt_text(if SEEDANCE_ATTACH_REFERENCE_AUDIOelse []),+ build_music_reference_section(reference, resolved_catalog),build_reference_index_section(reference,"character",diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.pyindex d789e56..fa360cf 100644--- a/backend/app/services/drama/generation.py+++ b/backend/app/services/drama/generation.py@@ -1539,6 +1539,23 @@ async def prepare_fragment_video_for_submit(),})+ content_labels = describe_seedance_content_slots(+ ref_payloads,+ continuity_url,+ has_text=bool((prompt or "").strip()),+ style_board_url=video_board_url or None,+ content=prompt,+ )+ # 准备阶段先校验时长,过短/过长直接失败并提示(提交阶段 ark 仍会再拦一次)+ from app.services.drama.voice_reference_audio import (+ validate_seedance_body_reference_audios,+ )++ await validate_seedance_body_reference_audios(+ body,+ content_labels=content_labels,+ project_id=project.id,+ )return FragmentVideoPrepared(submit_mode="seedance_body",seedance_body=body,@@ -1546,13 +1563,7 @@ async def prepare_fragment_video_for_submit(duration=duration,ratio=ratio,resolution=resolution,- content_labels=describe_seedance_content_slots(- ref_payloads,- continuity_url,- has_text=bool((prompt or "").strip()),- style_board_url=video_board_url or None,- content=prompt,- ),+ content_labels=content_labels,model_id=mid,)diff --git a/backend/app/services/drama/voice_reference_audio.py b/backend/app/services/drama/voice_reference_audio.pyindex 57d5ee1..a3f67a9 100644--- a/backend/app/services/drama/voice_reference_audio.py+++ b/backend/app/services/drama/voice_reference_audio.py@@ -146,6 +146,85 @@ def is_voice_duration_too_short(return float(duration) + 1e-6 < float(min_sec)+def is_voice_duration_too_long(+ duration: float | None,+ *,+ max_sec: float = SEEDANCE_REFERENCE_AUDIO_MAX_SEC,+) -> bool:+ """是否超过 Seedance reference_audio 上限。"""+ if duration is None:+ return False+ return float(duration) > float(max_sec) + 1e-6+++def _reference_audio_slot_label(+ index: int,+ content_labels: list[str] | None,+) -> str:+ if content_labels and 0 <= index < len(content_labels):+ label = str(content_labels[index] or "").strip()+ if label:+ return label+ return f"提交内容第 {index + 1} 项 / content[{index}]"+++async def validate_seedance_body_reference_audios(+ body: dict[str, Any],+ *,+ content_labels: list[str] | None = None,+ project_id: int = 0,+ min_sec: float = SEEDANCE_REFERENCE_AUDIO_MIN_SEC,+ max_sec: float = SEEDANCE_REFERENCE_AUDIO_MAX_SEC,+) -> None:+ """提交上游前校验 content[] 内 reference_audio 时长;不合规则抛中文 RuntimeError。"""+ content = body.get("content") if isinstance(body, dict) else None+ if not isinstance(content, list):+ return++ work_dir = storage_svc.project_dir(project_id or 0) / "voice_probe"+ work_dir.mkdir(parents=True, exist_ok=True)+ duration_by_url: dict[str, float | None] = {}++ for index, item in enumerate(content):+ if not isinstance(item, dict):+ continue+ if item.get("type") != "audio_url":+ continue+ role = str(item.get("role") or "").strip()+ if role and role != "reference_audio":+ continue+ audio = item.get("audio_url") if isinstance(item.get("audio_url"), dict) else {}+ url = str((audio or {}).get("url") or "").strip()+ if not url:+ who = _reference_audio_slot_label(index, content_labels)+ raise RuntimeError(+ f"参考音频地址为空:{who}。请重新绑定角色/旁白试听后再生成该分镜。"+ )++ if url not in duration_by_url:+ duration_by_url[url] = await probe_voice_url_duration(url, work_dir=work_dir)+ duration = duration_by_url[url]+ who = _reference_audio_slot_label(index, content_labels)++ if duration is None:+ raise RuntimeError(+ f"无法读取参考音频时长:{who}。"+ "请检查音色文件是否可访问,或重新上传/生成试听后再生成该分镜。"+ )+ if is_voice_duration_too_short(duration, min_sec=min_sec):+ raise RuntimeError(+ f"参考音频过短:{who},当前约 {duration:.1f} 秒,"+ f"Seedance 要求时长 ≥ {min_sec:g} 秒。"+ "请打开对应角色或旁白,重新生成或上传更长的试听音频(建议 ≥ 2 秒)后再生成该分镜。"+ )+ if is_voice_duration_too_long(duration, max_sec=max_sec):+ raise RuntimeError(+ f"参考音频过长:{who},当前约 {duration:.1f} 秒,"+ f"Seedance 要求时长 ≤ {max_sec:g} 秒。"+ "请截短试听音频后再生成该分镜。"+ )++# 合成完成后:过短补足、过长截断,并重新发布def finalize_voice_reference_url(url: str,@@ -273,7 +352,13 @@ async def backfill_long_voice_references()if changed:asset.url = new_url- asset.cover = new_url+ # 音色 cover 勿写音频 URL,否则会误进 Seedance reference_image+ cover = (asset.cover or "").split("?", 1)[0].strip().lower()+ if any(+ cover.endswith(ext)+ for ext in (".mp3", ".wav", ".m4a", ".aac", ".ogg", ".webm")+ ) or not (asset.cover or "").strip():+ asset.cover = ""params = dict(asset.params or {}) if isinstance(asset.params, dict) else {}params["referenceAudioTrimmed"] = Trueasset.params = paramsdiff --git a/backend/app/services/drama/voice_synthesis.py b/backend/app/services/drama/voice_synthesis.pyindex f44ac98..bc8cc7a 100644--- a/backend/app/services/drama/voice_synthesis.py+++ b/backend/app/services/drama/voice_synthesis.py@@ -201,7 +201,10 @@ async def synthesize_voice_asset(asset_id=asset.id,)asset.url = audio_url- asset.cover = asset.cover or audio_url+ # 不把 mp3 写入 cover:避免 Seedance 把音色资产当成 reference_image+ cover = (asset.cover or "").split("?", 1)[0].strip().lower()+ if any(cover.endswith(ext) for ext in (".mp3", ".wav", ".m4a", ".aac", ".ogg", ".webm")):+ asset.cover = ""params: dict[str, Any] = dict(asset.params or {})params["voicePrompt"] = promptparams["sampleText"] = textdiff --git a/backend/app/services/media_model_presets.py b/backend/app/services/media_model_presets.pyindex e0b947d..2397812 100644--- a/backend/app/services/media_model_presets.py+++ b/backend/app/services/media_model_presets.py@@ -42,23 +42,30 @@ PRESET_MODELS: dict[LogicalModelCapability, tuple[dict[str, str], ...]] = {"id": "seedream-5.0","label": "Seedream 5.0","note": "标准静帧,质量与成本均衡",- "pricing_hint": "约 $0.045/张",+ "pricing_hint": "约 ¥0.33/张","eta_hint": "约 15–40 秒/张",},{"id": "seedream-5.0-flash","label": "Seedream 5.0 Flash","note": "更快更省,适合草稿与批量试错",- "pricing_hint": "更省 · 约 $0.025/张",+ "pricing_hint": "更省 · 约 ¥0.18/张","eta_hint": "约 10–25 秒/张",},{"id": "gpt-image-2","label": "GPT Image 2","note": "OpenAI 生图,光影与文字表现好,适合海报与精细静帧",- "pricing_hint": "约 $0.075/次",+ "pricing_hint": "约 ¥0.55/次","eta_hint": "约 30–90 秒/张",},+ {+ "id": "gpt-image-2.5",+ "label": "GPT Image 2.5",+ "note": "OpenAI 新一代生图,细节与文字更稳,适合定妆与精细静帧",+ "pricing_hint": "按次计费,通常高于 2.0",+ "eta_hint": "约 30–120 秒/张",+ },),"video": ({@@ -88,7 +95,7 @@ PRESET_MODELS: dict[LogicalModelCapability, tuple[dict[str, str], ...]] = {"id": "MiniMax-H3","label": "MiniMax H3","note": "节奏感强、人物生动;4–15 秒,仅 720p",- "pricing_hint": "出片偏慢 · 约 $0.06–0.10/秒",+ "pricing_hint": "出片偏慢 · 约 ¥0.44–0.73/秒","eta_hint": "偏慢,4s 约 15 分钟起",},),@@ -115,8 +122,10 @@ IMAGE_ASPECT_RATIOS: tuple[str, ...] = ("2:3","21:9",)-# Seedream:前端只给 1K/2K,避免选 3K 被静默降档+# Seedream / GPT Image 2:前端只给 1K/2K,避免选更高档被静默降档IMAGE_RESOLUTIONS_STANDARD: tuple[str, ...] = ("1K", "2K")+# GPT Image 2.5 支持到 4K+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")@@ -147,8 +156,12 @@ PRESET_MODEL_ALIASES: dict[str, str] = {"seedream5": "seedream-5.0","seedream-5-0-flash": "seedream-5.0-flash","seedream-5.0-flash": "seedream-5.0-flash",- "gpt-image-2-5": "gpt-image-2",- "gpt-image-2.5": "gpt-image-2",+ "gpt-image-2-5": "gpt-image-2.5",+ "gpt-image-2.5": "gpt-image-2.5",+ "gpt-image-2.5-sunburst": "gpt-image-2.5",+ "gpt-image-2-5-sunburst": "gpt-image-2.5",+ "gpt-image-2.5-flare": "gpt-image-2.5",+ "gpt-image-2-5-flare": "gpt-image-2.5","gemini-3.1-flash-tts": "qwen-tts-2025-05-22","gemini-3.1-flash": "qwen-tts-2025-05-22",}@@ -269,12 +282,17 @@ def model_generation_options(model_id: str | None) -> dict[str, Any]: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 仍按同档参数兼容+ # 图像:Seedream / GPT Image 2 为 1K·2K;GPT Image 2.5 开放 4Kif 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": list(IMAGE_RESOLUTIONS_STANDARD),+ "allowed_resolutions": resolutions,}# 视频:预设表与 Seedance / MiniMax 优先diff --git a/backend/app/services/model_settings.py b/backend/app/services/model_settings.pyindex 16ad0e3..5a2cb62 100644--- a/backend/app/services/model_settings.py+++ b/backend/app/services/model_settings.py@@ -400,7 +400,7 @@ async def _ensure_tokenfree_channel(db: AsyncSession, existing: list[SystemModelcurrent_key = migrated_keyfrom app.services.media_model_presets import all_preset_channel_models- # 渠道 models 固定为站点预设并集(含 gpt-image-2 / 仅 qwen-tts)+ # 渠道 models 固定为站点预设并集(含 gpt-image-2 / gpt-image-2.5 / 仅 qwen-tts)preset = all_preset_channel_models()if list(token_row.models or []) != preset:token_row.models = presetdiff --git a/backend/app/services/tokenfree_image.py b/backend/app/services/tokenfree_image.pyindex 26042c8..f328763 100644--- a/backend/app/services/tokenfree_image.py+++ b/backend/app/services/tokenfree_image.py@@ -34,6 +34,70 @@ def is_seedream_family(model: str) -> bool:return "seedream" in mid+def gpt_image_caps_at_2k(model: str) -> bool:+ """GPT Image 2 仅 1K/2K;2.5 支持到 4K,不降档。"""+ mid = (model or "").strip().lower()+ if "gpt-image" not in mid:+ return False+ return "2.5" not in mid and "2-5" not in mid+++def is_gpt_image_25(model: str) -> bool:+ """GPT Image 2.5:TokenFree 只在 image-generation 渠道放行,不走 /responses。"""+ mid = (model or "").strip().lower()+ return "gpt-image-2.5" in mid or "gpt-image-2-5" in mid+++def gpt_image_resolution_tier(size: str) -> str:+ """把 1K/2K/4K 或像素面积收成计费档(价目表达式读 resolution)。"""+ raw = (size or "").strip().upper().replace(" ", "")+ if raw in {"1K", "2K", "4K"}:+ return raw+ if "X" not in raw:+ return "2K"+ left, _, right = raw.partition("X")+ if not left.isdigit() or not right.isdigit():+ return "2K"+ width, height = int(left), int(right)+ longest = max(width, height)+ if longest >= 3000:+ return "4K"+ if longest >= 1600:+ return "2K"+ return "1K"+++def build_tokenfree_openai_image_body(+ *,+ model: str,+ prompt: str,+ size: str = "",+ aspect_ratio: str = "",+ ref_urls: list[str] | None = None,+ style_ref_urls: list[str] | None = None,+) -> dict[str, Any]:+ """GPT Image 2.5:POST /images/generations(openai 渠道),并带上 resolution 供计费。"""+ narrative = build_tokenfree_image_body(+ model=model,+ prompt=prompt,+ size=size,+ aspect_ratio=aspect_ratio,+ ref_urls=ref_urls,+ style_ref_urls=style_ref_urls,+ )+ pixel = (size or "").strip()+ if not _is_pixel_size(pixel):+ pixel = "1024x1024"+ return {+ "model": narrative["model"],+ "prompt": narrative["input"],+ "size": pixel,+ "n": 1,+ "resolution": gpt_image_resolution_tier(size),+ "response_format": "url",+ }++def tokenfree_working_image_model(model: str) -> str:"""原样返回渠道/路由配置的上游模型名,不做改写。"""return (model or "").strip()@@ -301,7 +365,11 @@ def tokenfree_image_user_error(*, model: str = "", status_code: int = 0, body: s)return "出图通道暂时失败,请稍后再点「生成画面」"if is_tokenfree_no_distributor(status_code=status_code, body=body):- return "出图通道暂时失败,请稍后再点「生成画面」"+ who = (model or "该图像模型").strip() or "该图像模型"+ return (+ f"当前 TokenFree 分组未开通 {who}(无可用渠道)。"+ "请在 TokenFree 控制台为 default 分组配置该模型后再生成。"+ )payload = _parse_json_object(body)if payload and is_tokenfree_image_task_failed(payload):return tokenfree_image_failed_task_message(payload)diff --git a/backend/app/services/tokenfree_pricing.py b/backend/app/services/tokenfree_pricing.pyindex 6f2c301..db1ef8b 100644--- a/backend/app/services/tokenfree_pricing.py+++ b/backend/app/services/tokenfree_pricing.py@@ -4,6 +4,7 @@ from __future__ import annotationsimport loggingimport math+import reimport timefrom dataclasses import dataclassfrom typing import Any@@ -201,7 +202,14 @@ RECOMMENDED_MODELS: tuple[dict[str, Any], ...] = ("id": "gpt-image-2","capability": "image","label": "GPT Image 2",- "note": "OpenAI 生图,约 $0.075/次",+ "note": "OpenAI 生图,约 ¥0.55/次",+ "recommended": False,+ },+ {+ "id": "gpt-image-2.5",+ "capability": "image",+ "label": "GPT Image 2.5",+ "note": "OpenAI 新一代生图,细节与文字更稳","recommended": False,},{@@ -412,18 +420,44 @@ def parse_pricing_payload(payload: dict[str, Any], settings: Settings | None = Nreturn out+def _gpt_image_id_variants(model: str) -> list[str]:+ """gpt-image-2.5 ↔ gpt-image-2-5 等目录写法互查。"""+ mid = (model or "").strip()+ if not mid:+ return []+ out: list[str] = [mid]+ dotted = re.sub(r"(?i)gpt-image-2-5", "gpt-image-2.5", mid)+ hyphen = re.sub(r"(?i)gpt-image-2\.5", "gpt-image-2-5", mid)+ for alt in (dotted, hyphen):+ if alt and alt not in out:+ out.append(alt)+ return out++def lookup_rate(model: str, rates: dict[str, OfficialRate] | None = None) -> OfficialRate | None:- """按模型 id 精确或忽略大小写查找。"""+ """按模型 id 精确或忽略大小写查找(含 gpt-image 点分/连字符)。"""mid = (model or "").strip()table = rates if rates is not None else cached_rates()if not mid or not table:return None- hit = table.get(mid)- if hit:- return hit- key = mid.lower()+ candidates = _gpt_image_id_variants(mid)+ try:+ from app.services.media_model_presets import resolve_preset_alias++ aliased = resolve_preset_alias(mid)+ if aliased:+ for alt in _gpt_image_id_variants(aliased):+ if alt not in candidates:+ candidates.append(alt)+ except Exception: # noqa: BLE001+ pass+ for cand in candidates:+ hit = table.get(cand)+ if hit:+ return hit+ keys = {c.lower() for c in candidates}for name, row in table.items():- if name.lower() == key:+ if name.lower() in keys:return rowreturn None@@ -547,11 +581,9 @@ def resolve_billing_image_size(settings: Settings, *, model: str = "", size: str# z-image / qwen 等生成侧强制 1K,计费同步if _is_compact_tokenfree_image_model(working) or _is_compact_tokenfree_image_model(upstream):return "1K"- if (- is_seedream_pro_model(upstream)- or "sunburst" in working.lower()- or "gpt-image" in working.lower()- ):+ from app.services.tokenfree_image import gpt_image_caps_at_2k++ if is_seedream_pro_model(upstream) or gpt_image_caps_at_2k(working) or gpt_image_caps_at_2k(upstream):if raw.strip().upper() in {"3K", "4K"}:return "2K"return rawdiff --git a/backend/tests/test_media_model_presets.py b/backend/tests/test_media_model_presets.pyindex c222c96..aa0d3c9 100644--- a/backend/tests/test_media_model_presets.py+++ b/backend/tests/test_media_model_presets.py@@ -24,6 +24,7 @@ def test_all_preset_channel_models_covers_four_caps() -> None:assert "seedream-5.0" in modelsassert "seedream-5.0-flash" in modelsassert "gpt-image-2" in models+ assert "gpt-image-2.5" in modelsassert "seedance-2.5" in modelsassert "seedance-2.0-fast" in modelsassert "MiniMax-H3" in models@@ -35,6 +36,7 @@ def test_all_preset_channel_models_covers_four_caps() -> None:"seedream-5.0","seedream-5.0-flash","gpt-image-2",+ "gpt-image-2.5",]assert preset_ids("audio") == ["qwen-tts-2025-05-22"]assert set(preset_ids("video")) == {@@ -66,8 +68,11 @@ def test_clamp_seedream_aliases_to_canonical() -> None:assert clamp_default_to_preset("image", "seedream-5-0") == "seedream-5.0"assert clamp_default_to_preset("image", "seedream-5.0-flash") == "seedream-5.0-flash"assert clamp_default_to_preset("image", "gpt-image-2") == "gpt-image-2"- assert clamp_default_to_preset("image", "gpt-image-2.5") == "gpt-image-2"+ assert clamp_default_to_preset("image", "gpt-image-2.5") == "gpt-image-2.5"+ assert clamp_default_to_preset("image", "gpt-image-2-5") == "gpt-image-2.5"+ assert clamp_default_to_preset("image", "gpt-image-2.5-sunburst") == "gpt-image-2.5"assert is_preset_model("image", "gpt-image-2") is True+ assert is_preset_model("image", "gpt-image-2.5") is Trueassert is_preset_model("image", "seedream-5.0") is Trueassert is_preset_model("image", "nano-banana-2") is False@@ -90,11 +95,13 @@ def test_build_body_clamps_minimax_duration() -> None:def test_image_options_standard_1k_2k() -> None:- for mid in ("seedream-5.0-pro", "seedream-5.0", "seedream-5.0-flash"):+ for mid in ("seedream-5.0-pro", "seedream-5.0", "seedream-5.0-flash", "gpt-image-2"):opts = model_generation_options(mid)assert opts["capability"] == "image"assert opts["allowed_resolutions"] == ["1K", "2K"]assert "3:4" in opts["allowed_aspect_ratios"]+ opts25 = model_generation_options("gpt-image-2.5")+ assert opts25["allowed_resolutions"] == ["1K", "2K", "4K"]def test_minimax_h3_video_options() -> None:diff --git a/backend/tests/test_seedance_content_labels.py b/backend/tests/test_seedance_content_labels.pyindex 981c99f..3120f15 100644--- a/backend/tests/test_seedance_content_labels.py+++ b/backend/tests/test_seedance_content_labels.py@@ -84,6 +84,77 @@ def test_style_board_sits_after_assets_before_continuity():assert all(item.get("role") == "reference_image" for item in items if item.get("type") == "image_url")+def test_voice_asset_cover_mp3_not_in_image_slots():+ """音色 cover 写成 mp3 时不得进 reference_image(否则上游 content[n] invalid image format)。"""+ reference = [+ {+ "id": 1,+ "type": "character",+ "name": "甲",+ "cover": "https://cdn.example.com/a.jpg",+ "url": "",+ "params": {"voiceAudio": {"url": "https://cdn.example.com/voice.mp3"}},+ },+ {+ "id": 2,+ "type": "scene",+ "name": "室",+ "cover": "https://cdn.example.com/s.jpg",+ "url": "",+ "params": {},+ },+ {+ "id": 3,+ "type": "voice",+ "assetType": "audio",+ "name": "试听",+ "cover": "https://cdn.example.com/voice.mp3",+ "url": "https://cdn.example.com/voice.mp3",+ "params": {},+ },+ ]+ script = "甲:你好。"+ items = build_seedance_content_items(script, reference)+ labels = describe_seedance_content_slots(+ reference, None, has_text=True, content=script+ )+ image_urls = [+ item["image_url"]["url"]+ for item in items+ if item.get("type") == "image_url"+ ]+ audio_urls = [+ item["audio_url"]["url"]+ for item in items+ if item.get("type") == "audio_url"+ ]+ assert image_urls == [+ "https://cdn.example.com/a.jpg",+ "https://cdn.example.com/s.jpg",+ ]+ assert "voice.mp3" not in "".join(image_urls)+ assert "https://cdn.example.com/voice.mp3" in audio_urls+ assert len(labels) == len(items)+ assert labels[3].startswith("角色音色") or "音色" in labels[3]+++def test_character_cover_mp3_rejected_as_image():+ """角色 cover 误写成音频时也不进 reference_image。"""+ from app.services.drama.build_seedance_generate_body import resolve_reference_image_url++ assert (+ resolve_reference_image_url(+ {+ "id": 9,+ "type": "character",+ "cover": "https://cdn.example.com/bad.mp3",+ "url": "",+ }+ )+ is None+ )++def test_style_board_ignored_without_catalog_images():continuity = "https://cdn.example.com/prev_last.jpg"board = "https://cdn.example.com/ghibli-board.png"diff --git a/backend/tests/test_seedance_create_error_format.py b/backend/tests/test_seedance_create_error_format.pyindex 3bd7438..b9717d1 100644--- a/backend/tests/test_seedance_create_error_format.py+++ b/backend/tests/test_seedance_create_error_format.py@@ -3,6 +3,20 @@from app.services.ark import _format_seedance_create_error+def test_format_seedance_invalid_image_format():+ body = (+ '{"error":{"code":"InvalidParameter","message":'+ '"The parameter `content[3]` specified in the request is not valid: '+ 'invalid image format (detected format); received: M4A. '+ 'Request id: 021792136049408d"}}'+ )+ labels = ["分镜文案", "角色「甲」", "场景「室」", "参考图「试听」"]+ msg = _format_seedance_create_error(400, body, content_labels=labels)+ assert "参考图格式无效" in msg+ assert "试听" in msg+ assert "1.8" not in msg++def test_format_seedance_audio_duration_too_short_with_label():body = ('{"error":{"code":"InvalidParameter","message":'diff --git a/backend/tests/test_seedance_prompt_sanitize.py b/backend/tests/test_seedance_prompt_sanitize.pyindex d3079c9..4aba035 100644--- a/backend/tests/test_seedance_prompt_sanitize.py+++ b/backend/tests/test_seedance_prompt_sanitize.py@@ -326,6 +326,32 @@ def test_asset_colon_not_treated_as_speaker_dialogue():assert "@asset:9002" in formatted+def test_canvas_music_audio_is_bound_as_reference_audio():+ """画布独立音频要进 content,并在正文写成 @音频,否则 Seedance 不用这段配乐。"""+ music = {+ "id": 7881,+ "type": "audio",+ "assetType": "audio",+ "name": "新音频",+ "cover": "",+ "url": "https://cdn.example.com/music.mp3",+ "params": {},+ }+ scene = _scene(7877, "广场")+ script = "【音效】脚步踏土声,音乐参考音频@asset:7881 【台词】无;口型:闭嘴。"+ items = build_seedance_content_items(script, [scene, music], burn_subtitles=False)+ audios = [+ item["audio_url"]["url"]+ for item in items+ if item.get("type") == "audio_url" and item.get("role") == "reference_audio"+ ]+ assert audios == ["https://cdn.example.com/music.mp3"]+ prompt = str(items[0]["text"])+ assert "【强制约束:参考音乐】" in prompt+ assert "@音频1" in prompt+ assert "说出全部对白" not in prompt++def test_hearsay_not_split_as_freeform_dialogue():"""「据说/听说」不得被拆成【对白】。"""from app.services.drama.build_seedance_generate_body import normalize_canvas_freeform_speechdiff --git a/backend/tests/test_tokenfree_image.py b/backend/tests/test_tokenfree_image.pyindex 4ea34d8..dfad928 100644--- a/backend/tests/test_tokenfree_image.py+++ b/backend/tests/test_tokenfree_image.py@@ -80,6 +80,32 @@ def test_build_tokenfree_image_body_separates_style_and_subject_refs():assert text.index("画风参考图") < text.index("构图与主体参考")+def test_gpt_image_25_uses_openai_generations_body():+ """2.5 必须走 images/generations 字段,并带 resolution 供 1K/2K/4K 计费。"""+ from app.services.tokenfree_image import (+ build_tokenfree_openai_image_body,+ gpt_image_resolution_tier,+ is_gpt_image_25,+ )++ assert is_gpt_image_25("gpt-image-2.5") is True+ assert is_gpt_image_25("gpt-image-2") is False+ assert gpt_image_resolution_tier("3520x4694") == "4K"+ assert gpt_image_resolution_tier("1776x2368") == "2K"+ body = build_tokenfree_openai_image_body(+ model="gpt-image-2.5",+ prompt="角色设定",+ size="1776x2368",+ aspect_ratio="3:4",+ )+ assert body["model"] == "gpt-image-2.5"+ assert body["size"] == "1776x2368"+ assert body["resolution"] == "2K"+ assert body["response_format"] == "url"+ assert "prompt" in body and "input" not in body+ assert "3:4" in body["prompt"]++def test_tokenfree_working_image_model_passthrough():"""按渠道配置原样发送,不硬改 Seedream / 2.5。"""assert tokenfree_working_image_model("seedream-5-0-pro") == "seedream-5-0-pro"@@ -174,9 +200,11 @@ def test_sunburst_model_not_found_is_channel_dead():'"message":"分组 default 下模型 gpt-image-2-5-sunburst 无可用的渠道distributor"}}')assert is_tokenfree_no_distributor(status_code=503, body=body) is True- assert "暂时失败" in tokenfree_image_user_error(- model="gpt-image-2-5-sunburst", status_code=503, body=body+ msg = tokenfree_image_user_error(+ model="gpt-image-2.5", status_code=503, body=body)+ assert "未开通" in msg+ assert "gpt-image-2.5" in msgdef test_is_tokenfree_no_distributor():diff --git a/backend/tests/test_tokenfree_pricing.py b/backend/tests/test_tokenfree_pricing.pyindex a54dd73..c4d18ee 100644--- a/backend/tests/test_tokenfree_pricing.py+++ b/backend/tests/test_tokenfree_pricing.py@@ -54,6 +54,9 @@ def test_parse_pricing_payload_per_call_and_token() -> None:image = rates["gpt-image-2-5"]assert image.billing == "per_call"assert image.cny_per_call == 4.375+ # 点分 id 应能命中价目里的连字符键+ assert lookup_rate("gpt-image-2.5", rates) is image+ assert lookup_rate("gpt-image-2-5", rates) is imagellm = rates["kimi-k2.6"]assert llm.billing == "token"assert abs(llm.cny_in_per_1m - 10.1866) < 0.01@@ -187,6 +190,7 @@ def test_recommended_models_cover_text_image_video_audio() -> None:"kimi-k2.6","seedream-5.0-pro","gpt-image-2",+ "gpt-image-2.5","seedance-2.5","seedance-2.0","MiniMax-H3",@@ -278,11 +282,12 @@ def test_charge_official_image_uses_sunburst_size_tiers() -> None:assert kie_sunburst_credits_for_size("4K") == 16assert charge_fen_official_image(settings, model="gpt-image-2", size="1K") == 21assert charge_fen_official_image(settings, model="gpt-image-2", size="2K") == 35- # 生成侧把 gpt-image 的 3K/4K 钳到 2K,计费同步为 2K 档+ # GPT Image 2 的 4K 钳到 2K;2.5 保留 4Kassert charge_fen_official_image(settings, model="gpt-image-2", size="4K") == 35assert kie_sunburst_credits_for_size("4K") == 16assert resolve_billing_image_size(settings, model="seedream-5-0-pro", size="3K") == "2K"- assert resolve_billing_image_size(settings, model="gpt-image-2-5-sunburst", size="4K") == "2K"+ assert resolve_billing_image_size(settings, model="gpt-image-2", size="4K") == "2K"+ assert resolve_billing_image_size(settings, model="gpt-image-2.5", size="4K") == "4K"def test_charge_official_video_720p() -> None:@@ -411,6 +416,7 @@ def test_build_official_rate_rows_marks_video_vendor() -> None:rows = build_official_rate_rows(rates, settings)by_id = {row["id"]: row for row in rows}assert "gpt-image-2" in by_id+ assert "gpt-image-2.5" in by_idassert by_id["seedream-5.0-pro"]["capability"] == "image"assert by_id["seedance-2.5"]["basis"] == "vendor_sec"assert "结算参考" in by_id["seedance-2.5"]["rate_label"]diff --git a/backend/tests/test_voice_reference_audio.py b/backend/tests/test_voice_reference_audio.pyindex 158378c..50efa3a 100644--- a/backend/tests/test_voice_reference_audio.py+++ b/backend/tests/test_voice_reference_audio.py@@ -1,12 +1,18 @@-"""参考音色时长:下限与补足。"""+"""参考音色时长:下限与补足、提交前校验。"""++from unittest.mock import AsyncMock, patch++import pytestfrom app.services.drama.voice_reference_audio import (SEEDANCE_REFERENCE_AUDIO_MAX_SEC,SEEDANCE_REFERENCE_AUDIO_MIN_SEC,VOICE_REFERENCE_MIN_SEC,VOICE_REFERENCE_TARGET_SEC,+ is_voice_duration_too_long,is_voice_duration_too_short,patch_params_voice_url,+ validate_seedance_body_reference_audios,)from app.services.drama.voice_synthesis import build_voice_sample_line_short@@ -24,6 +30,12 @@ def test_is_voice_duration_too_short():assert is_voice_duration_too_short(None) is False+def test_is_voice_duration_too_long():+ assert is_voice_duration_too_long(30.0) is False+ assert is_voice_duration_too_long(30.5) is True+ assert is_voice_duration_too_long(None) is False++def test_sample_line_long_enough_for_tts():line = build_voice_sample_line_short("双龙")# 中文 TTS 约 3–4 字/秒;两句应明显长于 1.8s@@ -39,3 +51,64 @@ def test_patch_params_voice_url():next_params = patch_params_voice_url(params, "/static/new.mp3")assert next_params["voiceAudio"]["url"] == "/static/new.mp3"assert next_params["canvas"]["voiceAudio"]["url"] == "/static/new.mp3"+++def _seedance_body_with_audio(url: str = "https://cdn.example.com/v.mp3") -> dict:+ return {+ "content": [+ {"type": "text", "text": "分镜"},+ {+ "type": "audio_url",+ "audio_url": {"url": url},+ "role": "reference_audio",+ },+ ]+ }+++async def test_validate_reference_audio_rejects_too_short():+ body = _seedance_body_with_audio()+ labels = ["分镜文案", "角色音色「禹」"]+ with patch(+ "app.services.drama.voice_reference_audio.probe_voice_url_duration",+ new=AsyncMock(return_value=1.2),+ ):+ with pytest.raises(RuntimeError, match="参考音频过短") as exc:+ await validate_seedance_body_reference_audios(+ body, content_labels=labels, project_id=1+ )+ assert "禹" in str(exc.value)+ assert "1.2" in str(exc.value)+++async def test_validate_reference_audio_rejects_too_long():+ body = _seedance_body_with_audio()+ with patch(+ "app.services.drama.voice_reference_audio.probe_voice_url_duration",+ new=AsyncMock(return_value=31.0),+ ):+ with pytest.raises(RuntimeError, match="参考音频过长"):+ await validate_seedance_body_reference_audios(body, project_id=1)+++async def test_validate_reference_audio_rejects_unreadable():+ body = _seedance_body_with_audio()+ with patch(+ "app.services.drama.voice_reference_audio.probe_voice_url_duration",+ new=AsyncMock(return_value=None),+ ):+ with pytest.raises(RuntimeError, match="无法读取参考音频时长"):+ await validate_seedance_body_reference_audios(body, project_id=1)+++async def test_validate_reference_audio_accepts_valid():+ body = _seedance_body_with_audio()+ with patch(+ "app.services.drama.voice_reference_audio.probe_voice_url_duration",+ new=AsyncMock(return_value=22.0),+ ):+ await validate_seedance_body_reference_audios(body, project_id=1)diff --git a/docs/BILLING.md b/docs/BILLING.mdindex 18964f2..4c4a29c 100644--- a/docs/BILLING.md+++ b/docs/BILLING.md@@ -74,7 +74,7 @@ billing_expr USD sell = official_CNY / 7.3 * 1.5管理端「支付与计费」可「查询 TokenFree 余额」(`GET /v1/dashboard/billing/subscription` + `usage`),并拉取公开价目展示推荐模型官方价。-预扣:生图 API 按逻辑模型路由解析出的上游模型名原样调用 TokenFree(如渠道启用的 `gpt-image-2` / `seedream-5-0-pro`,不做硬改写)。价目里有按次价或表达式时,预扣与结算都用该规则(例如 `gpt-image-2` 的 `model_price`),不再改用 Kie 积分。价目缺失时 **gpt-image / sunburst** 才按 Kie 积分档保底(1K 6 / 2K 10 / 4K 16 积分;默认 3.5 分/积分)。**按张官价不再乘 `billing_estimate_buffer`(默认 1.2)**。LLM / 视频 / TTS 估价仍乘缓冲。视频有 `billing_expr` 时按表达式(分辨率 × 秒,默认无参考视频);没有表达式才用本站秒价表。漫剧缺省按 720P。勿把 New API 的美元 `cost` 当人民币。+预扣:生图 API 按逻辑模型路由解析出的上游模型名原样调用 TokenFree(如渠道启用的 `gpt-image-2` / `gpt-image-2.5` / `seedream-5-0-pro`,不做硬改写;`gpt-image-2-5` 等历史写法规范到 `gpt-image-2.5`)。价目里有按次价或表达式时,预扣与结算都用该规则(例如 `gpt-image-2` 的 `model_price`),价目键会互查点分/连字符。价目缺失时 **gpt-image / sunburst** 才按 Kie 积分档保底(1K 6 / 2K 10 / 4K 16 积分;默认 3.5 分/积分)。**按张官价不再乘 `billing_estimate_buffer`(默认 1.2)**。LLM / 视频 / TTS 估价仍乘缓冲。视频有 `billing_expr` 时按表达式(分辨率 × 秒,默认无参考视频);没有表达式才用本站秒价表。漫剧缺省按 720P。勿把 New API 的美元 `cost` 当人民币。管理端「官方用量对照」复用模型页 TokenFree API Key,拉取 New API 日消耗(`/api/data/self` 或 billing usage,日期无效时按累计额度差分记到当天)并与本地成本对照。diff --git a/frontend/src/lib/dramaGenError.ts b/frontend/src/lib/dramaGenError.tsindex 9ee30a4..7fe3ed6 100644--- a/frontend/src/lib/dramaGenError.ts+++ b/frontend/src/lib/dramaGenError.ts@@ -31,7 +31,7 @@ function extractContentIndex(raw: string): number | null {/** 判断文案是否像「具体根因」(优先于「重试上限」等包装句) */function looksLikeRootCause(text: string): boolean {- return /PrivacyInformation|InputImageSensitive|SensitiveContentDetected|参考图疑似|参考音频过短|may contain real person|Seedance create error|上一镜失败|无法衔接|分镜已变更|分镜上下文|InputTextSensitive|resource download failed|audio_url|audio duration|Credits insufficient|File type not supported|参考图格式不支持/i.test(+ return /PrivacyInformation|InputImageSensitive|SensitiveContentDetected|参考图疑似|参考音频过短|参考音频过长|无法读取参考音频时长|may contain real person|Seedance create error|上一镜失败|无法衔接|分镜已变更|分镜上下文|InputTextSensitive|resource download failed|audio_url|audio duration|Credits insufficient|File type not supported|参考图格式不支持|invalid image format|参考图格式无效|未开通/i.test(text,)}@@ -183,16 +183,49 @@ export function formatDramaGenError(raw: string | null | undefined): DramaGenErr}}+ if (/无法读取参考音频时长|参考音频地址为空/i.test(text)) {+ const named = extractNamedSlot(text)+ return {+ title: '参考音频无法校验',+ message: named+ ? `无法读取 ${named} 的参考音频时长或地址无效。`+ : text.length > 160+ ? `${text.slice(0, 160)}…`+ : text,+ suggestion: '请检查角色/旁白试听文件是否可访问,重新上传或生成后再生成该分镜。',+ }+ }++ if (/参考音频过长/i.test(text)) {+ const named = extractNamedSlot(text)+ const dur = text.match(/当前约\s*([\d.]+)\s*秒/)+ return {+ title: '参考音频过长',+ message: named+ ? `${named} 参考音频过长${dur ? `(约 ${dur[1]} 秒)` : ''},须 ≤ 30 秒。`+ : text.length > 160+ ? `${text.slice(0, 160)}…`+ : text,+ suggestion: '请截短对应角色/旁白试听音频后再生成该分镜。这不是参考图问题。',+ }+ }+// Seedance r2v:reference_audio 须 ≥ 1.8 秒(不是参考图)- if (/audio duration|参考音频过短|1\.8/i.test(text) && /audio|音色|reference_audio|content\[/i.test(text)) {+ if (+ /参考音频过短/i.test(text) ||+ (/audio duration|1\.8/i.test(text) && /audio|音色|reference_audio|content\[/i.test(text))+ ) {const idx = extractContentIndex(text)const named = extractNamedSlot(text)+ const dur = text.match(/当前约\s*([\d.]+)\s*秒/)const where =named ||(idx != null ? `提交内容第 ${idx + 1} 项 / content[${idx}](参考音频,不是图片)` : '某条角色/旁白音色')return {title: '参考音频过短',- message: `视频服务要求参考音频时长 ≥ 1.8 秒,当前过短:${where}。`,+ message: dur+ ? `${where} 参考音频约 ${dur[1]} 秒,须 ≥ 1.8 秒。`+ : `视频服务要求参考音频时长 ≥ 1.8 秒,当前过短:${where}。`,suggestion:'打开左侧对应角色或旁白资产,重新生成/上传更长的试听音频(建议 ≥ 2 秒)后再生成该分镜。这不是参考图问题。',}@@ -215,6 +248,14 @@ export function formatDramaGenError(raw: string | null | undefined): DramaGenErr}}+ if (/未开通|无可用渠道|distributor/i.test(text)) {+ return {+ title: '图像模型未开通',+ message: text.length > 180 ? `${text.slice(0, 180)}…` : text,+ suggestion: '请管理员在 TokenFree 控制台为 default 分组开通该模型(如 GPT Image 2.5)后再生成。',+ }+ }+if (/File type not supported|参考图格式不支持|不支持 SVG/i.test(text)) {return {title: '参考图格式不支持',@@ -227,6 +268,21 @@ export function formatDramaGenError(raw: string | null | undefined): DramaGenErr}}+ // 参考图槽位收到非图片(常见:音色 mp3 误进 image_url)+ if (/invalid image format|参考图格式无效/i.test(text)) {+ const idx = extractContentIndex(text)+ const named = extractNamedSlot(text)+ const where =+ named ||+ (idx != null ? `提交内容第 ${idx + 1} 项 / content[${idx}]` : '某张参考图')+ return {+ title: '参考图格式无效',+ message: `视频服务按图片校验失败:${where}。这不是参考音频时长问题。`,+ suggestion:+ '请检查本镜角色/场景封面是否为 PNG/JPG/WEBP;若画布上挂了独立音色节点,确认它只作参考音频、不要占用参考图。修好素材后重新生成该分镜。',+ }+ }+if (/Seedance create error\s*400|Kie createTask error/i.test(text)) {const idx = extractContentIndex(text)const named = extractNamedSlot(text)@@ -236,7 +292,8 @@ export function formatDramaGenError(raw: string | null | undefined): DramaGenErrreturn {title: '视频服务拒绝请求',message: `上游返回参数或内容错误,未能创建生成任务${where}。`,- suggestion: '检查本镜参考图、参考音频时长(须 ≥ 1.8 秒)与脚本后重试;若持续失败请联系客服并提供任务号。',+ suggestion:+ '优先检查本镜参考图是否为可访问的 PNG/JPG/WEBP;若错误原文含 audio duration 再查参考音频是否 ≥ 1.8 秒。持续失败请联系客服并提供任务号。',}}diff --git a/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx b/frontend/src/pages/drama/canvas/CanvasAssetNode.tsxindex f0d282a..2abd995 100644--- a/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx+++ b/frontend/src/pages/drama/canvas/CanvasAssetNode.tsx@@ -13,6 +13,7 @@ import {Handle,NodeToolbar,Position,+ useStore,useUpdateNodeInternals,type Node,type NodeProps,@@ -82,8 +83,18 @@ function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasAconst Icon = option.iconconst isText = data.kind === 'text'const mediaSrc = resolveDramaMediaUrl(data.mediaUrl)- const showUpload = selected && CANVAS_UPLOADABLE_KINDS.has(data.kind)- const showGenerate = selected && CANVAS_GENERATABLE_KINDS.has(data.kind)+ /* 框选多张时只给唯一选中节点展开编辑条,其余只显示选中描边 */+ const soloSelected = useStore((state) => {+ let selectedId: string | null = null+ for (const node of state.nodes) {+ if (!node.selected) continue+ if (selectedId) return false+ selectedId = node.id+ }+ return selectedId === id+ })+ const showUpload = soloSelected && CANVAS_UPLOADABLE_KINDS.has(data.kind)+ const showGenerate = soloSelected && CANVAS_GENERATABLE_KINDS.has(data.kind)const voiceLabel = typeof data.voiceLabel === 'string' ? data.voiceLabel : ''const voiceUrl = typeof data.voiceUrl === 'string' ? data.voiceUrl : ''const displayName =@@ -252,7 +263,7 @@ function CanvasAssetNodeComponent({ id, data, selected }: NodeProps<Node<CanvasA}>{isText ? (- selected ? (+ soloSelected ? (<textareaclassName="fc-text-editor nodrag nowheel"value={data.textContent || ''}diff --git a/frontend/src/pages/drama/canvas/FreeCanvasFlow.tsx b/frontend/src/pages/drama/canvas/FreeCanvasFlow.tsxindex a3929b5..7586b8a 100644--- a/frontend/src/pages/drama/canvas/FreeCanvasFlow.tsx+++ b/frontend/src/pages/drama/canvas/FreeCanvasFlow.tsx@@ -4,6 +4,7 @@ import {Background,MiniMap,ReactFlow,+ SelectionMode,useReactFlow,type Connection,type Edge,@@ -164,6 +165,8 @@ export function FreeCanvasFlow({ projectId }: FreeCanvasFlowProps) {onConnect={onConnect}onNodeDragStart={handleNodeDragStart}onNodeDragStop={handleNodeDragStop}+ onSelectionDragStart={handleNodeDragStart}+ onSelectionDragStop={handleNodeDragStop}isValidConnection={isValidConnection}onPaneClick={handlePaneClick}deleteKeyCode={['Backspace', 'Delete']}@@ -172,6 +175,12 @@ export function FreeCanvasFlow({ projectId }: FreeCanvasFlowProps) {minZoom={0.2}maxZoom={2}zoomOnDoubleClick={false}+ selectionOnDrag+ selectionMode={SelectionMode.Partial}+ selectionKeyCode="Shift"+ multiSelectionKeyCode={['Meta', 'Control']}+ panOnDrag={[1, 2]}+ panActivationKeyCode="Space"proOptions={{ hideAttribution: true }}defaultEdgeOptions={{ type: 'default' }}>diff --git a/frontend/src/pages/drama/canvas/canvas.css b/frontend/src/pages/drama/canvas/canvas.cssindex 4dbae0f..179e3a7 100644--- a/frontend/src/pages/drama/canvas/canvas.css+++ b/frontend/src/pages/drama/canvas/canvas.css@@ -69,6 +69,17 @@display: none;}+/* 空白处拖出的框选框 */+.free-canvas-page .react-flow__selection {+ background: rgba(37, 99, 235, 0.08);+ border: 1px solid rgba(37, 99, 235, 0.85);+}++.free-canvas-page .react-flow__nodesselection-rect {+ background: rgba(37, 99, 235, 0.04);+ border: 1px solid rgba(37, 99, 235, 0.55);+}+/* —— Overlays —— */.fc-overlay {pointer-events: none;