Skip to content

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

fix: 生图按张价结算,并修分镜换行片头与配音兜底

yiaab9e9162726
diff --git a/README.md b/README.md
index e77ec2b..ada2a10 100644
--- a/README.md
+++ b/README.md
@@ -139,7 +139,7 @@ ARK_API_KEY=你的 TokenFree 密钥
ARK_BASE_URL=https://www.tokenfree.com/v1
MODEL_IMAGE=doubao-seedream-5-0-260128
MODEL_VIDEO=doubao-seedance-2-5-260628
-MODEL_AUDIO=seed-tts-2.0
+MODEL_AUDIO=qwen-tts-2025-05-22
```
| 变量 | 说明 |
diff --git a/admin/src/lib/tokenfreeRecommendedModels.ts b/admin/src/lib/tokenfreeRecommendedModels.ts
index bbe114c..3c84ddc 100644
--- a/admin/src/lib/tokenfreeRecommendedModels.ts
+++ b/admin/src/lib/tokenfreeRecommendedModels.ts
@@ -7,7 +7,7 @@ export const RECOMMENDED_MODEL_IDS: Record<ModelCapability, string[]> = {
text: ["kimi-k2.6"],
image: ["gpt-image-2-5"],
video: ["seedance-2-5", "seedance-2-0", "seedance-2-0-mini"],
- audio: ["seed-tts-2.0"],
+ audio: ["qwen-tts-2025-05-22"],
};
const CAPABILITY_ORDER: ModelCapability[] = ["text", "image", "video", "audio"];
diff --git a/backend/.env.example b/backend/.env.example
index 48a54ee..c7ea528 100644
--- a/backend/.env.example
+++ b/backend/.env.example
@@ -55,8 +55,8 @@ SEEDANCE_DURATION_MIN=4
SEEDANCE_DURATION_MAX=30
# 科普 Seedance 仍出音轨:只要键盘/点击等操作环境音,不要口播与 BGM
KEPU_SEEDANCE_SFX_AUDIO=true
-# 音频/TTS 上游模型 ID(TokenFree 拉取目录后填入;常见 seed-tts-2.0 / 含 tts 的接入点)
-MODEL_AUDIO=seed-tts-2.0
+# 音频/TTS 上游模型 ID(TokenFree 目录现用 qwen-tts;seed-tts-2.0 已下线)
+MODEL_AUDIO=qwen-tts-2025-05-22
# 豆包语音合成(openspeech,与 TokenFree Key 不同)。S_ 克隆音色仍走此项;未配则 TokenFree 走 /audio/speech
# 新版控制台 API Key(ai-manju 项目里同名 SPEECH_API_KEY)
diff --git a/backend/app/api/drama/episodes.py b/backend/app/api/drama/episodes.py
index d999026..54945c7 100644
--- a/backend/app/api/drama/episodes.py
+++ b/backend/app/api/drama/episodes.py
@@ -55,7 +55,7 @@ from app.services.drama.generation import (
read_fragment_last_frame_url,
reconcile_orphaned_fragment_generations,
)
-from app.services.drama.build_fragments import repair_fragment_timed_layout
+from app.services.drama.build_fragments import prepare_fragment_content
from app.services.drama.fragment_content_duration import resolve_seedance_duration_from_content
from app.services.drama.billing_util import record_seed_assets_llm_usage
from app.services.drama.jobs import (
@@ -85,9 +85,10 @@ logger = logging.getLogger("app.drama.episodes")
def _fragment_out(frag: DramaEpisodeFragment) -> DramaFragmentOut:
asset_ids = [r.asset_id for r in (frag.asset_references or [])]
- content = repair_fragment_timed_layout(
+ content = prepare_fragment_content(
frag.content or "",
duration_sec=int(frag.duration_sec or 0) or None,
+ is_opening=int(frag.sort_order or 0) == 0,
)
return DramaFragmentOut(
id=frag.id,
@@ -522,7 +523,11 @@ async def save_fragments(
ep.fragments.append(frag)
await db.flush()
frag.sort_order = item.sort_order
- frag.content = item.content or ""
+ frag.content = prepare_fragment_content(
+ item.content or "",
+ duration_sec=int(item.duration_sec or 0) or None,
+ is_opening=int(item.sort_order or 0) == 0,
+ )
frag.cover = (item.cover or "")[:1024]
frag.video = (item.video or "")[:1024]
frag.duration_sec = item.duration_sec
diff --git a/backend/app/config.py b/backend/app/config.py
index dbcb136..01128bf 100644
--- a/backend/app/config.py
+++ b/backend/app/config.py
@@ -46,7 +46,7 @@ class Settings(BaseSettings):
# Seedance 2.5 官方范围约 4–30 秒
seedance_duration_min: int = 4
seedance_duration_max: int = 30
- model_audio: str = "seed-tts-2.0"
+ model_audio: str = "qwen-tts-2025-05-22"
# 豆包语音(openspeech)— 与方舟 ARK_API_KEY 不同产品线
volc_tts_app_id: str = ""
volc_tts_access_key: str = ""
@@ -118,7 +118,7 @@ class Settings(BaseSettings):
billing_usd_cny: float = 7.0
# Fallback tokens when API omits usage
billing_est_llm_tokens: int = 80_000
- # Seedream 单张实测约 3–3.5 万 tokens;预估略留余量,避免预扣远高于实扣
+ # Seedream / gpt-image 无 quota 时按张价结算,不再用 4.5 万 token × 8 元/百万
billing_est_seedream_tokens: int = 45_000
billing_est_tts_tokens: int = 5_000
billing_est_seedance_tokens_per_sec: int = 32_000
diff --git a/backend/app/services/ark.py b/backend/app/services/ark.py
index 387644b..7f892a4 100644
--- a/backend/app/services/ark.py
+++ b/backend/app/services/ark.py
@@ -25,7 +25,12 @@ from app.services.logical_model_router import (
resolve_logical_model_id,
resolve_upstream_model,
)
-from app.services.tokenfree_audio import uses_tokenfree_audio
+from app.services.tokenfree_audio import (
+ TOKENFREE_DEFAULT_TTS_MODEL,
+ resolve_tokenfree_tts_model,
+ tokenfree_speech_voice,
+ uses_tokenfree_audio,
+)
from app.services.tokenfree_image import (
build_tokenfree_image_body,
extract_tokenfree_image_url,
@@ -1608,7 +1613,10 @@ class ArkGateway:
def _resolved_audio_model(self) -> str:
routed = (resolve_upstream_model("audio", None) or "").strip()
- return routed or (self.settings.model_audio or "").strip() or "seed-tts-2.0"
+ mid = routed or (self.settings.model_audio or "").strip() or TOKENFREE_DEFAULT_TTS_MODEL
+ if uses_tokenfree_audio(base_url=self.settings.ark_base_url or ""):
+ return resolve_tokenfree_tts_model(mid)
+ return mid
async def _tts_openai_speech(
self,
@@ -1624,6 +1632,9 @@ class ArkGateway:
if not base or not key:
return False
model_id = (model or self._resolved_audio_model()).strip()
+ if uses_tokenfree_audio(base_url=base):
+ model_id = resolve_tokenfree_tts_model(model_id)
+ voice = tokenfree_speech_voice(voice)
async with httpx.AsyncClient(timeout=120.0) as client:
resp = await client.post(
f"{base}/audio/speech",
@@ -1671,6 +1682,7 @@ class ArkGateway:
duration_hint: float = 4.0,
emotion_hint: str | None = None,
) -> str:
+ """整片/单镜配音:豆包 openspeech → TokenFree speech → edge-tts;失败则抛错,不写静音。"""
voice_map = {
"narrator_calm": "zh_female_cancan_uranus_bigtts",
"warm_storyteller": "zh_female_tianmeixiaoyuan_uranus_bigtts",
@@ -1737,18 +1749,17 @@ class ArkGateway:
except Exception as exc: # noqa: BLE001
logger.warning("tokenfree speech failed: %s", exc)
- # edge-tts 兜底(本地无 Key 或上游失败时)
- if not on_tokenfree:
- try:
- await self._tts_edge(clean, dest, voice_hint=speaker)
- url = await _accept_if_audible("edge-tts")
- if url:
- logger.info("TTS edge-tts ok shot=%s bytes=%s", shot_no, dest.stat().st_size)
- return url
- except Exception as exc: # noqa: BLE001
- logger.warning("edge-tts failed: %s", exc)
-
- # 非 TokenFree 或未配置时,再试 /audio/speech
+ # edge-tts 兜底:TokenFree 常无 seed-tts 渠道,豆包未授权时必须仍能出声
+ try:
+ await self._tts_edge(clean, dest, voice_hint=speaker)
+ url = await _accept_if_audible("edge-tts")
+ if url:
+ logger.info("TTS edge-tts ok shot=%s bytes=%s", shot_no, dest.stat().st_size)
+ return url
+ except Exception as exc: # noqa: BLE001
+ logger.warning("edge-tts failed: %s", exc)
+
+ # 非 TokenFree 时再试 /audio/speech(方舟等)
if not on_tokenfree:
try:
ok = await self._tts_openai_speech(clean, speaker, dest, model=audio_model)
@@ -1759,10 +1770,8 @@ class ArkGateway:
except Exception as exc: # noqa: BLE001
logger.warning("Ark TTS failed: %s", exc)
- # 最后才静音(保证合成不中断)
- logger.error("TTS all providers failed; writing silence shot=%s", shot_no)
- await asyncio.to_thread(self._write_silence_mp3, dest, duration_hint)
- return storage.publish_local(dest)
+ logger.error("TTS all providers failed shot=%s", shot_no)
+ raise RuntimeError("配音失败:语音服务暂不可用,请稍后重试")
def _tts_resource_id(self, speaker: str) -> str:
if speaker.startswith("S_"):
diff --git a/backend/app/services/billing/estimates.py b/backend/app/services/billing/estimates.py
index 48ad071..5e7c9c8 100644
--- a/backend/app/services/billing/estimates.py
+++ b/backend/app/services/billing/estimates.py
@@ -60,7 +60,7 @@ def _estimate_assets_fen(project: Project, settings: Settings) -> int:
return 1
total = 0
for _ in range(max(need_img, 0)):
- total += charge_fen_official_image(settings)
+ total += charge_fen_official_image(settings, model=settings.model_image)
if need_tts > 0:
n = max(len(shots), 1)
_, c_tts = charge_fen_for_tokens(
@@ -135,7 +135,7 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
if domain == "kepu":
if task_type in {"shot_regen_image"}:
- c = charge_fen_official_image(s)
+ c = charge_fen_official_image(s, model=s.model_image)
return max(1, math.ceil(c * buf))
if task_type in {"shot_regen_video"}:
dur = float(payload.get("duration") or 5)
@@ -163,7 +163,7 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
if task_type == "seed_assets":
c = charge_fen_official_llm(s.billing_est_llm_tokens * 3, s)
return max(1, math.ceil(c * buf))
- c = charge_fen_official_image(s)
+ c = charge_fen_official_image(s, model=s.model_image)
return max(1, math.ceil(c * buf))
if task_type in {"asset_video", "fragment_video"}:
dur = float(payload.get("duration_sec") or payload.get("duration") or 0)
@@ -195,7 +195,7 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
max(dur, 2.0), s, resolution=_drama_video_resolution(payload)
)
if task_type == "fragment_video":
- c += max(1, charge_fen_official_image(s) // 2)
+ c += max(1, charge_fen_official_image(s, model=s.model_image) // 2)
return max(1, math.ceil(c * buf))
if task_type == "voice_synthesis":
_, c = charge_fen_for_tokens(s.billing_est_tts_tokens, "tts", settings=s)
@@ -210,7 +210,7 @@ async def estimate_task_fen(db: AsyncSession, task: TaskRun, settings: Settings
if domain in {"api", "studio"}:
if task_type in {"v1_image", "tool_image"}:
- c = charge_fen_official_image(s)
+ c = charge_fen_official_image(s, model=s.model_image)
return max(1, math.ceil(c * buf))
if task_type in {"v1_video", "v1_seedance", "tool_video"}:
dur = float(payload.get("duration") or 5)
diff --git a/backend/app/services/billing/pricing.py b/backend/app/services/billing/pricing.py
index dfa0c08..67ac03b 100644
--- a/backend/app/services/billing/pricing.py
+++ b/backend/app/services/billing/pricing.py
@@ -156,10 +156,12 @@ def charge_fen_for_usage(
*,
raw_usage: dict[str, Any] | None = None,
settings: Settings | None = None,
+ model: str = "",
) -> tuple[int, int, bool]:
"""按上游实际成本或 token 用量计算 (cost_fen, charge_fen, used_upstream_cost)。
用户扣费与 TokenFree / 上游成本相同,不再加价。
+ 生图无 quota 时:按张官方价,避免 8 元/百万 token 低估约十倍。
"""
s = settings or get_settings()
upstream_cost = parse_upstream_cost_fen(raw_usage, settings=s)
@@ -167,10 +169,32 @@ def charge_fen_for_usage(
cost = upstream_cost
charge = user_charge_fen(cost, s)
return cost, charge, True
+ if (billing_key or "").strip() == "seedream":
+ catalog = _catalog_image_fen_if_per_call(s, model)
+ if catalog is not None:
+ charge = user_charge_fen(catalog, s)
+ return catalog, charge, False
cost, charge = charge_fen_for_tokens(tokens, billing_key, settings=s)
return cost, charge, False
+def _catalog_image_fen_if_per_call(settings: Settings, model: str) -> int | None:
+ """gpt-image / Seedream(TokenFree 上改走 gpt-image)按张价;token 计价模型返回 None。"""
+ from app.services.tokenfree_image import is_seedream_family, tokenfree_working_image_model
+ from app.services.tokenfree_pricing import charge_fen_official_image, lookup_rate
+
+ raw = (model or getattr(settings, "model_image", "") or "").strip()
+ mid = tokenfree_working_image_model(raw or "gpt-image-2-5")
+ rate = lookup_rate(mid)
+ if rate and rate.billing == "token":
+ return None
+ if rate and rate.billing == "per_call" and rate.cny_per_call > 0:
+ return charge_fen_official_image(settings, model=mid)
+ if is_seedream_family(raw) or "gpt-image" in mid.lower():
+ return charge_fen_official_image(settings, model=mid)
+ return None
+
+
def parse_usage_dict(data: dict[str, Any] | None) -> dict[str, int]:
if not data:
return {"prompt_tokens": 0, "completion_tokens": 0, "total_tokens": 0}
diff --git a/backend/app/services/billing/usage.py b/backend/app/services/billing/usage.py
index c08fe1d..630d8aa 100644
--- a/backend/app/services/billing/usage.py
+++ b/backend/app/services/billing/usage.py
@@ -39,7 +39,7 @@ async def record_line(
total = s.billing_est_llm_tokens
estimated = True
elif billing_key == "seedream":
- total = s.billing_est_seedream_tokens
+ # TokenFree /responses 常回 0 token;按张价在 charge_fen_for_usage 计算
estimated = True
elif billing_key == "tts":
total = s.billing_est_tts_tokens
@@ -48,7 +48,7 @@ async def record_line(
total = s.billing_est_seedance_tokens_per_sec * 5
estimated = True
cost, charge, from_upstream = charge_fen_for_usage(
- total, billing_key, raw_usage=raw, settings=s
+ total, billing_key, raw_usage=raw, settings=s, model=model
)
if from_upstream:
estimated = False
diff --git a/backend/app/services/drama/build_fragments.py b/backend/app/services/drama/build_fragments.py
index fcbe61c..7e7e7d2 100644
--- a/backend/app/services/drama/build_fragments.py
+++ b/backend/app/services/drama/build_fragments.py
@@ -239,6 +239,8 @@ def _strip_screenplay_meta(body: str) -> tuple[str | None, list[str]]:
if location_line is None and SCENE_LOCATION_RE.match(trimmed):
location_line = trimmed
continue
+ if is_production_meta_line(trimmed):
+ continue
narrative.append(trimmed)
return location_line, narrative
@@ -248,6 +250,128 @@ def _strip_production_prefix(line: str) -> str:
return re.sub(r"^【[^】]*】\s*", "", (line or "").strip()).strip()
+_OPENING_CUE_PREFIXES = ("【片头", "【背景介绍")
+_CONTINUATION_START = tuple("((,,、;;…—-")
+
+
+def is_opening_cue_line(line: str) -> bool:
+ """整集片头/背景叠字:只应出现在开幕镜。"""
+ stripped = (line or "").strip()
+ return any(stripped.startswith(prefix) for prefix in _OPENING_CUE_PREFIXES)
+
+
+def is_wrapped_continuation_line(line: str) -> bool:
+ """括号/标点续写行:属于上一句换行,不应单独占一段 @duration。"""
+ body = _strip_production_prefix(line)
+ if not body or body.startswith("@") or is_production_meta_line(body):
+ return False
+ if VISUAL_SHOT_LABEL_RE.match(body):
+ return False
+ if re.match(r"^[^::\n]{1,16}[::]", body):
+ return False
+ return body[0] in _CONTINUATION_START
+
+
+def merge_wrapped_narrative_lines(lines: list[str]) -> list[str]:
+ """把「换行续写」合并回上一行,避免一行一个 3s。"""
+ out: list[str] = []
+ for raw in lines:
+ stripped = (raw or "").strip()
+ if not stripped:
+ continue
+ if out and is_wrapped_continuation_line(stripped):
+ out[-1] = f"{out[-1]} {stripped}"
+ else:
+ out.append(stripped)
+ return out
+
+
+def strip_repeat_opening_cues(content: str) -> str:
+ """非开幕镜去掉片头/背景叠字,保留字幕、BGM、人物介绍。"""
+ kept = [
+ raw
+ for raw in (content or "").replace("\r\n", "\n").split("\n")
+ if not is_opening_cue_line(raw)
+ ]
+ return "\n".join(kept).strip()
+
+
+def prepare_fragment_content(
+ content: str,
+ *,
+ duration_sec: int | None = None,
+ is_opening: bool = False,
+) -> str:
+ """读取/保存/生成前统一:去掉重复片头,并修正过碎的 @duration。"""
+ text = content or ""
+ if not is_opening:
+ text = strip_repeat_opening_cues(text)
+ return repair_fragment_timed_layout(text, duration_sec=duration_sec)
+
+
+def _duration_body_lines(rows: list[str]) -> list[str]:
+ return [
+ ln
+ for ln in rows
+ if ln.strip() and not ln.strip().startswith("@duration:")
+ ]
+
+
+def _join_header_and_blocks(
+ header: list[str],
+ blocks: list[tuple[int, list[str]]],
+) -> str:
+ lines = list(header)
+ for dur, rows in blocks:
+ lines.append(f"@duration:{dur}")
+ lines.extend(_duration_body_lines(rows))
+ return "\n".join(lines).strip()
+
+
+def _coalesce_continuation_blocks(
+ blocks: list[tuple[int, list[str]]],
+) -> list[tuple[int, list[str]]]:
+ """续写行并入上一拍,不新增时长标签。"""
+ packed: list[tuple[int, list[str]]] = []
+ for dur, rows in blocks:
+ body = _duration_body_lines(rows)
+ if packed and body and all(is_wrapped_continuation_line(ln) for ln in body):
+ prev_dur, prev_rows = packed[-1]
+ packed[-1] = (prev_dur, [*prev_rows, *body])
+ continue
+ packed.append((dur, [f"@duration:{dur}", *body]))
+ return packed
+
+
+def _coalesce_timed_blocks_to_budget(
+ blocks: list[tuple[int, list[str]]],
+ target: int,
+) -> list[tuple[int, list[str]]]:
+ """拍数过多导致合计超上限时,合并相邻拍并缩放到 target。"""
+ if not blocks:
+ return blocks
+ target = min(FRAGMENT_TOTAL_MAX, max(FRAGMENT_DURATION_MIN, int(target)))
+ max_beats = max(1, target // FRAGMENT_DURATION_MIN)
+ packed = list(blocks)
+ if len(packed) > max_beats:
+ group = (len(packed) + max_beats - 1) // max_beats
+ merged: list[tuple[int, list[str]]] = []
+ for i in range(0, len(packed), group):
+ chunk = packed[i : i + group]
+ body: list[str] = []
+ dur = 0
+ for block_dur, rows in chunk:
+ dur += block_dur
+ body.extend(_duration_body_lines(rows))
+ dur = min(FRAGMENT_DURATION_MAX, max(FRAGMENT_DURATION_MIN, dur))
+ merged.append((dur, [f"@duration:{dur}", *body]))
+ packed = merged
+ total = sum(d for d, _ in packed)
+ if total != target:
+ packed = _rescale_timed_blocks(packed, target)
+ return packed
+
+
def _is_visual_description_line(line: str) -> bool:
# 空镜/景别/纯画面描写:不得配音、不得烧字幕
trimmed = (line or "").strip()
@@ -857,6 +981,9 @@ def plan_fragments_from_scene(
)
)
+ narrative_lines = merge_wrapped_narrative_lines(
+ [ln for ln in narrative_lines if not is_production_meta_line(ln)]
+ )
for line in narrative_lines:
raw = _inject_character_mentions(line, character_bindings)
for formatted in _expand_narrative_lines(raw):
@@ -1003,8 +1130,8 @@ def _sum_duration_tags(content: str) -> int:
def repair_fragment_timed_layout(content: str, *, duration_sec: int | None = None) -> str:
"""
- 修正旧稿/合并稿中 @duration 仅在末尾或整镜共用一条的问题,
- 改为「@duration + 叙事行」逐段交替(与编辑器场记板位置一致)。
+ 修正旧稿中 @duration 仅在末尾的问题。
+ 现代场记(时长标签已在各段之前)保留段内换行,不把每一行拆成 3s。
"""
text = (content or "").replace("\r\n", "\n").strip()
if not text:
@@ -1012,43 +1139,35 @@ def repair_fragment_timed_layout(content: str, *, duration_sec: int | None = Non
header, blocks = parse_fragment_timed_blocks(text)
meta, header_narrative = _split_header_meta_and_narrative(header)
- narrative: list[str] = list(header_narrative)
+ target = int(duration_sec or 0) or _sum_duration_tags(text) or FRAGMENT_DURATION_MIN
+ target = min(FRAGMENT_TOTAL_MAX, max(FRAGMENT_DURATION_MIN, target))
- if len(blocks) == 1:
- _, rows = blocks[0]
- narrative.extend(
- ln for ln in rows if ln.strip() and not ln.strip().startswith("@duration:")
- )
- elif blocks:
- per_block_ok = True
+ # 现代布局:@duration 已在段前。换行续写并入上一拍;拍数过多再合并到预算内。
+ if blocks and not header_narrative:
+ packed = _coalesce_continuation_blocks(blocks)
+ tagged = sum(d for d, _ in packed)
+ if tagged > target:
+ packed = _coalesce_timed_blocks_to_budget(packed, target)
+ return _join_header_and_blocks(meta, packed)
+
+ narrative = merge_wrapped_narrative_lines(
+ [ln.strip() for ln in header_narrative if ln.strip() and not is_opening_cue_line(ln)]
+ )
+ if blocks:
+ extra: list[str] = []
for _, rows in blocks:
- body = [ln for ln in rows if ln.strip() and not ln.strip().startswith("@duration:")]
- if len(body) != 1:
- per_block_ok = False
- narrative.extend(body)
- if per_block_ok and not header_narrative:
- return text
-
- tag_count = len(re.findall(r"@duration:\d+", text))
- if tag_count > 1 and len(blocks) > 1 and not header_narrative:
- per_block_ok = all(
- len([ln for ln in rows if ln.strip() and not ln.strip().startswith("@duration:")]) == 1
- for _, rows in blocks
- )
- if per_block_ok:
- return text
+ extra.extend(_duration_body_lines(rows))
+ narrative.extend(merge_wrapped_narrative_lines(extra))
if len(narrative) <= 1:
return text
- tagged = _sum_duration_tags(text)
- target = int(duration_sec or tagged or FRAGMENT_DURATION_MIN)
- target = min(FRAGMENT_TOTAL_MAX, max(FRAGMENT_DURATION_MIN, target))
-
timed: list[tuple[int, list[str]]] = []
for ln in narrative:
stripped = ln.strip()
- formatted = ln if stripped.startswith("【") else _format_narrative_line(stripped)
+ if is_production_meta_line(stripped) or is_opening_cue_line(stripped):
+ continue
+ formatted = stripped if stripped.startswith("【") else _format_narrative_line(stripped)
line_dur = _clamp_duration(_estimate_line_duration(formatted))
if line_dur <= 0:
continue
@@ -1059,10 +1178,11 @@ def repair_fragment_timed_layout(content: str, *, duration_sec: int | None = Non
total = sum(d for d, _ in timed)
if total != target:
- timed = _rescale_timed_blocks(timed, target)
-
- body_out = [ln for _, rows in timed for ln in rows]
- return "\n".join([*meta, *body_out]).strip()
+ if len(timed) * FRAGMENT_DURATION_MIN > target:
+ timed = _coalesce_timed_blocks_to_budget(timed, target)
+ else:
+ timed = _rescale_timed_blocks(timed, target)
+ return _join_header_and_blocks(meta, timed)
def _rescale_timed_blocks(
@@ -1088,7 +1208,19 @@ def _rescale_timed_blocks(
return out
-# 将已有超长分镜正文按软/硬上限拆成多条 content(保留片头 cue)
+def _partition_header_cues(header: list[str]) -> tuple[list[str], list[str]]:
+ """片头/背景叠字只跟第一块;字幕、BGM 可随拆镜重复。"""
+ opening: list[str] = []
+ rest: list[str] = []
+ for raw in header:
+ if is_opening_cue_line(raw):
+ opening.append(raw)
+ else:
+ rest.append(raw)
+ return opening, rest
+
+
+# 将已有超长分镜正文按软/硬上限拆成多条 content(片头只留在第一块)
def split_overlong_fragment_content(
content: str,
*,
@@ -1098,22 +1230,28 @@ def split_overlong_fragment_content(
header, blocks = parse_fragment_timed_blocks(content)
if not blocks:
return []
+ opening_header, repeat_header = _partition_header_cues(header)
total = sum(d for d, _ in blocks)
if total <= hard_max:
used = total
- text = "\n".join([*header, *[ln for _, rows in blocks for ln in rows]]).strip()
+ text = "\n".join(
+ [*opening_header, *repeat_header, *[ln for _, rows in blocks for ln in rows]]
+ ).strip()
return [(text, used)] if text else []
chunks: list[tuple[str, int]] = []
body: list[str] = []
used = 0
+ first_chunk = True
def flush() -> None:
- nonlocal body, used
+ nonlocal body, used, first_chunk
if not body:
return
- text = "\n".join([*header, *body]).strip()
+ cues = [*opening_header, *repeat_header] if first_chunk else list(repeat_header)
+ text = "\n".join([*cues, *body]).strip()
chunks.append((text, used))
+ first_chunk = False
body = []
used = 0
diff --git a/backend/app/services/drama/fragment_plan.py b/backend/app/services/drama/fragment_plan.py
index 319db96..f5c6e6a 100644
--- a/backend/app/services/drama/fragment_plan.py
+++ b/backend/app/services/drama/fragment_plan.py
@@ -19,11 +19,14 @@ from app.services.drama.build_fragments import (
_expand_narrative_lines,
_inject_character_mentions,
_rescale_timed_blocks,
+ is_opening_cue_line,
+ merge_wrapped_narrative_lines,
repair_fragment_timed_layout,
build_character_binding,
build_summary_character_lookup,
_bindings_mentioned_in_text,
)
+from app.services.seedance_segments import is_production_meta_line
from app.services.drama.fragment_asset_limit import (
FRAGMENT_MAX_CHARACTERS,
FRAGMENT_MAX_PROPS,
@@ -314,9 +317,12 @@ def normalize_llm_fragment_items(
for index, item in enumerate(items):
if not isinstance(item, dict):
continue
- lines = _coerce_lines(item.get("lines") or item.get("content"))
+ lines = merge_wrapped_narrative_lines(
+ _coerce_lines(item.get("lines") or item.get("content"))
+ )
if not lines:
continue
+ llm_opening_extra: list[str] = []
scene_name = str(item.get("scene_name") or item.get("sceneName") or "").strip() or None
character_names = _coerce_name_list(
item.get("character_names") or item.get("characterNames") or []
@@ -381,6 +387,11 @@ def normalize_llm_fragment_items(
timed_blocks: list[tuple[int, list[str]]] = []
inject_bindings = [*bindings, *prop_bindings]
for line in lines:
+ stripped = line.strip()
+ if is_production_meta_line(stripped) or is_opening_cue_line(stripped):
+ if is_opening_cue_line(stripped):
+ llm_opening_extra.append(stripped)
+ continue
raw = _inject_character_mentions(line, inject_bindings)
for formatted in _expand_narrative_lines(raw):
if not include_subtitles:
@@ -478,7 +489,14 @@ def normalize_llm_fragment_items(
introduced.add(name)
intro_lines = _build_character_intro_lines(to_intro)
- opening_lines = opening_cues if is_opening else []
+ opening_lines: list[str] = []
+ if is_opening:
+ seen_cues = set(opening_cues)
+ opening_lines = list(opening_cues)
+ for extra in llm_opening_extra:
+ if extra not in seen_cues:
+ opening_lines.append(extra)
+ seen_cues.add(extra)
cues = _build_production_cues(
None,
body_lines[:3],
diff --git a/backend/app/services/drama/generation.py b/backend/app/services/drama/generation.py
index e22698c..c0562a2 100644
--- a/backend/app/services/drama/generation.py
+++ b/backend/app/services/drama/generation.py
@@ -35,6 +35,7 @@ from app.services.drama.build_seedance_generate_body import (
resolve_episode_character_intro,
)
from app.services.drama.fragment_asset_limit import cap_fragment_asset_ids
+from app.services.drama.build_fragments import prepare_fragment_content
from app.services.drama.generation_prompt import append_style_prompt, build_generation_prompt
from app.services.drama.image_styles import resolve_image_style_board_url
from app.services.drama.seedream_options import resolve_seedream_model_endpoint, resolve_seedream_size
@@ -1482,7 +1483,11 @@ async def prepare_fragment_video_for_submit(
model_id: str | None = None,
) -> FragmentVideoPrepared:
settings = get_settings()
- prompt = (fragment.content or "").strip() or "短剧分镜"
+ prompt = prepare_fragment_content(
+ fragment.content or "",
+ duration_sec=int(fragment.duration_sec or 0) or None,
+ is_opening=int(fragment.sort_order or 0) == 0,
+ ).strip() or "短剧分镜"
duration = int(fragment.duration_sec or 8)
duration = max(settings.seedance_duration_min, min(duration, settings.seedance_duration_max))
episode = await db.get(DramaEpisode, fragment.episode_id)
diff --git a/backend/app/services/tokenfree_audio.py b/backend/app/services/tokenfree_audio.py
index 5257217..8f94dca 100644
--- a/backend/app/services/tokenfree_audio.py
+++ b/backend/app/services/tokenfree_audio.py
@@ -4,6 +4,11 @@ from __future__ import annotations
from app.services.tokenfree_gateway import TOKENFREE_CHANNEL_ID
+# 账号目录里实际有的 TTS;seed-tts-2.0 不在 TokenFree 价目/渠道中
+TOKENFREE_DEFAULT_TTS_MODEL = "qwen-tts-2025-05-22"
+
+_SEED_TTS_MARKERS = ("seed-tts",)
+
def uses_tokenfree_audio(*, base_url: str = "", channel_id: str = "") -> bool:
"""判断 TTS 是否应走 TokenFree(与视频、LLM 同一 Base URL / Key)。"""
@@ -15,3 +20,23 @@ def uses_tokenfree_audio(*, base_url: str = "", channel_id: str = "") -> bool:
if "volces.com" in raw or "volcengineapi.com" in raw:
return False
return False
+
+
+def resolve_tokenfree_tts_model(model: str | None) -> str:
+ """把已下线的 seed-tts 换成目录内 Qwen TTS。"""
+ mid = (model or "").strip()
+ low = mid.lower()
+ if not mid or any(mark in low for mark in _SEED_TTS_MARKERS):
+ return TOKENFREE_DEFAULT_TTS_MODEL
+ return mid
+
+
+def tokenfree_speech_voice(speaker: str) -> str:
+ """豆包 speaker id → Qwen/OpenAI 兼容音色。"""
+ raw = (speaker or "").strip()
+ low = raw.lower()
+ if low.startswith("zh_male") or "_male_" in low:
+ return "Ethan"
+ if raw in {"Cherry", "Serena", "Ethan", "Chelsie", "alloy"}:
+ return raw
+ return "Cherry"
diff --git a/backend/tests/test_build_fragments.py b/backend/tests/test_build_fragments.py
index 810dd34..1668a90 100644
--- a/backend/tests/test_build_fragments.py
+++ b/backend/tests/test_build_fragments.py
@@ -211,6 +211,77 @@ def test_repair_fragment_timed_layout_splits_trailing_duration_tag():
assert fixed.rfind("@duration:") < fixed.index("小宇和米米击掌")
+def test_repair_keeps_wrapped_line_in_same_duration_beat():
+ from app.services.drama.build_fragments import repair_fragment_timed_layout
+
+ modern = "\n".join(
+ [
+ "【字幕:底部居中·简体中文·逐句轮换·与口播同步】",
+ "【BGM:轻】",
+ "@duration:8",
+ "【画面·无配音仅环境音】站在账房里贴着账,眼睛亮晶晶。",
+ "(探花分科),",
+ ]
+ )
+ fixed = repair_fragment_timed_layout(modern, duration_sec=8)
+ assert fixed.count("@duration:") == 1
+ assert "探花分科" in fixed
+ assert "@duration:3" not in fixed
+
+
+def test_repair_packs_exploded_three_second_beats_to_budget():
+ from app.services.drama.build_fragments import repair_fragment_timed_layout
+ import re
+
+ rows = [
+ "【字幕:底部居中·简体中文】",
+ "【BGM:轻】",
+ ]
+ for i in range(19):
+ rows.extend([f"@duration:3", f"【画面·无配音仅环境音】第{i}句画面。"])
+ fixed = repair_fragment_timed_layout("\n".join(rows), duration_sec=15)
+ total = sum(int(m) for m in re.findall(r"@duration:(\d+)", fixed))
+ assert total <= 15
+ assert fixed.count("@duration:") <= 5
+
+
+def test_strip_repeat_opening_cues_keeps_bgm():
+ from app.services.drama.build_fragments import strip_repeat_opening_cues
+
+ content = "\n".join(
+ [
+ "【BGM:轻柔开阔】",
+ "【片头·集号叠字】第1集|乌龙伯乐压奇才",
+ "【片头·词条特写】史上最难高考",
+ "@duration:4",
+ "【对白·慢速清晰·同步字幕】说书人:大宋嘉祐二年。",
+ ]
+ )
+ out = strip_repeat_opening_cues(content)
+ assert "【片头" not in out
+ assert "【BGM:轻柔开阔】" in out
+ assert "说书人" in out
+
+
+def test_prepare_fragment_content_strips_opening_on_later_shots():
+ from app.services.drama.build_fragments import prepare_fragment_content
+
+ content = "\n".join(
+ [
+ "【BGM:轻】",
+ "【片头·集号叠字】第1集|试集",
+ "@duration:8",
+ "【画面·无配音仅环境音】学堂门口。",
+ "(匾额特写),",
+ ]
+ )
+ later = prepare_fragment_content(content, duration_sec=8, is_opening=False)
+ assert "【片头" not in later
+ assert later.count("@duration:") == 1
+ first = prepare_fragment_content(content, duration_sec=8, is_opening=True)
+ assert "【片头·集号叠字】" in first
+
+
def test_vo_os_dialogue_not_split_by_action_expander():
from app.services.drama.build_fragments import _expand_narrative_lines
diff --git a/backend/tests/test_fragment_plan.py b/backend/tests/test_fragment_plan.py
index 6a2ec3d..53ff01f 100644
--- a/backend/tests/test_fragment_plan.py
+++ b/backend/tests/test_fragment_plan.py
@@ -82,6 +82,51 @@ def test_normalize_llm_injects_intro_once_for_important_cast():
assert "【人物介绍·画面叠字·角色身旁】行刑兵" not in joined
+def test_normalize_llm_opening_cues_only_on_first_fragment():
+ assets = [
+ SimpleNamespace(id=1, type="character", name="苏轼", params={"title": "才子", "roleType": "主角"}),
+ SimpleNamespace(id=10, type="scene", name="汴京街市", params={}),
+ ]
+ opening_block = [
+ "【BGM:轻柔开阔,希望感】",
+ "【片头·集号叠字】第1集|乌龙伯乐压奇才",
+ "【片头·词条特写】史上最难高考",
+ "【片头·标语特写】两风历史",
+ "空镜:汴京晨雾中的学堂门匾。",
+ ]
+ items = [
+ {
+ "duration_sec": 10,
+ "scene_name": "汴京街市",
+ "character_names": [],
+ "is_opening": True,
+ "lines": opening_block,
+ },
+ {
+ "duration_sec": 12,
+ "scene_name": "汴京街市",
+ "character_names": ["苏轼"],
+ "lines": [
+ *opening_block,
+ "苏轼:大宋嘉祐二年。",
+ ],
+ },
+ ]
+ drafts = normalize_llm_fragment_items(
+ items,
+ assets,
+ episode_number=1,
+ episode_name="乌龙伯乐压奇才",
+ project_title="乌龙伯乐压奇才",
+ )
+ assert len(drafts) >= 2
+ assert "【片头·集号叠字】" in drafts[0]["content"]
+ assert "【片头·词条特写】" in drafts[0]["content"]
+ for draft in drafts[1:]:
+ assert "【片头" not in draft["content"]
+ assert "苏轼" in draft["content"]
+
+
def test_normalize_llm_links_prop_and_material():
assets = [
SimpleNamespace(id=1, type="character", name="禹", params={"title": "治水", "roleType": "主角"}),
diff --git a/backend/tests/test_record_seedream_image_usage.py b/backend/tests/test_record_seedream_image_usage.py
index 25b7315..daf0196 100644
--- a/backend/tests/test_record_seedream_image_usage.py
+++ b/backend/tests/test_record_seedream_image_usage.py
@@ -29,7 +29,33 @@ async def test_record_seedream_with_upstream_tokens(db_session: AsyncSession) ->
await db_session.commit()
assert ev.estimated is False
assert ev.total_tokens == 120000
- assert ev.charge_fen >= 1
+ # Seedream 在 TokenFree 上按 gpt-image 张价,不用 12 万 token × 8 元/百万
+ assert ev.charge_fen == 438
+
+
+async def test_record_seedream_empty_usage_uses_per_call_catalog(db_session: AsyncSession) -> None:
+ user = await make_user(db_session)
+ image = ImageResult(
+ local_url="/static/x.png",
+ total_tokens=0,
+ raw_usage={
+ "input_tokens": 0,
+ "output_tokens": 0,
+ "total_tokens": 0,
+ },
+ )
+ ev = await record_seedream_image_usage(
+ db_session,
+ user_id=user.id,
+ model="gpt-image-2-5",
+ domain="drama",
+ image_result=image,
+ )
+ await db_session.commit()
+ assert ev.estimated is True
+ assert ev.charge_fen == 438
+ assert ev.cost_fen == 438
@pytest.mark.asyncio
diff --git a/backend/tests/test_seedream_billing_usage.py b/backend/tests/test_seedream_billing_usage.py
index 88cdbb5..eb2b1cf 100644
--- a/backend/tests/test_seedream_billing_usage.py
+++ b/backend/tests/test_seedream_billing_usage.py
@@ -51,19 +51,22 @@ def test_charge_fen_for_usage_prefers_upstream_cost():
assert charge == 1000
-def test_charge_fen_for_usage_falls_back_to_tokens():
+def test_charge_fen_for_usage_falls_back_to_official_per_call():
settings = get_settings()
settings.billing_markup = 1.5
+ settings.billing_usd_cny = 7.0
settings.billing_seedream_per_m = 8.0
cost, charge, used = charge_fen_for_usage(
1_000_000,
"seedream",
raw_usage={"usage": {"total_tokens": 1_000_000}},
settings=settings,
+ model="gpt-image-2-5",
)
assert used is False
- assert cost == 800
- assert charge == 800
+ # $0.625 × 7 = ¥4.375 → 438 分,而不是 8 元/百万 token
+ assert cost == 438
+ assert charge == 438
def test_build_task_result_includes_usage():
diff --git a/backend/tests/test_split_overlong_fragment.py b/backend/tests/test_split_overlong_fragment.py
index 9ed5010..6c39f40 100644
--- a/backend/tests/test_split_overlong_fragment.py
+++ b/backend/tests/test_split_overlong_fragment.py
@@ -24,3 +24,28 @@ def test_split_overlong_keeps_header_and_caps_chunks():
assert "【字幕:" in text
assert dur <= 15
assert text.count("@duration:") >= 1
+
+
+def test_split_overlong_keeps_opening_cues_only_on_first_chunk():
+ content = "\n".join(
+ [
+ "【字幕:底部居中·简体中文】",
+ "【BGM:庄重史诗】",
+ "【片头·集号叠字】第1集|乌龙伯乐压奇才",
+ "【片头·词条特写】史上最难高考",
+ "@duration:8",
+ "【对白·慢速清晰·同步字幕】禹:第一段足够长的对白内容用来占满时长。",
+ "@duration:8",
+ "【对白·慢速清晰·同步字幕】禹:第二段继续讲治水方案与人心。",
+ "@duration:8",
+ "【对白·慢速清晰·同步字幕】禹:第三段再补一句把合计推过三十秒。",
+ "@duration:8",
+ "【对白·慢速清晰·同步字幕】禹:第四段必须落到下一镜。",
+ ]
+ )
+ chunks = split_overlong_fragment_content(content)
+ assert len(chunks) >= 2
+ assert "【片头·集号叠字】" in chunks[0][0]
+ for text, _dur in chunks[1:]:
+ assert "【片头" not in text
+ assert "【BGM:" in text
diff --git a/backend/tests/test_tokenfree_audio.py b/backend/tests/test_tokenfree_audio.py
index a832607..21e907e 100644
--- a/backend/tests/test_tokenfree_audio.py
+++ b/backend/tests/test_tokenfree_audio.py
@@ -1,6 +1,10 @@
"""TokenFree 音频路由检测。"""
-from app.services.tokenfree_audio import uses_tokenfree_audio
+from app.services.tokenfree_audio import (
+ resolve_tokenfree_tts_model,
+ tokenfree_speech_voice,
+ uses_tokenfree_audio,
+)
from app.services.tokenfree_gateway import TOKENFREE_BASE_URL, TOKENFREE_CHANNEL_ID
@@ -8,3 +12,15 @@ def test_uses_tokenfree_audio():
assert uses_tokenfree_audio(base_url=TOKENFREE_BASE_URL, channel_id=TOKENFREE_CHANNEL_ID)
assert uses_tokenfree_audio(base_url="https://www.tokenfree.com/v1") is True
assert uses_tokenfree_audio(base_url="https://ark.cn-beijing.volces.com/api/v3") is False
+
+
+def test_resolve_tokenfree_tts_model_replaces_seed_tts():
+ assert resolve_tokenfree_tts_model("seed-tts-2.0") == "qwen-tts-2025-05-22"
+ assert resolve_tokenfree_tts_model("") == "qwen-tts-2025-05-22"
+ assert resolve_tokenfree_tts_model("qwen-tts-2025-05-22") == "qwen-tts-2025-05-22"
+
+
+def test_tokenfree_speech_voice_gender():
+ assert tokenfree_speech_voice("zh_female_cancan_uranus_bigtts") == "Cherry"
+ assert tokenfree_speech_voice("zh_male_shaonianzixin_uranus_bigtts") == "Ethan"
+ assert tokenfree_speech_voice("Cherry") == "Cherry"
diff --git a/backend/tests/test_tts_tokenfree_fallback.py b/backend/tests/test_tts_tokenfree_fallback.py
new file mode 100644
index 0000000..39bee43
--- /dev/null
+++ b/backend/tests/test_tts_tokenfree_fallback.py
@@ -0,0 +1,65 @@
+"""TokenFree 无语音渠道时,TTS 必须回退 edge-tts,禁止写静音成片。"""
+
+from __future__ import annotations
+
+from pathlib import Path
+from unittest.mock import AsyncMock
+
+import pytest
+
+from app.config import Settings
+from app.services.ark import ArkGateway
+
+
+def _tts_settings() -> Settings:
+ return Settings(
+ ark_mock=False,
+ ark_api_key="sk-test",
+ ark_base_url="https://www.tokenfree.com/v1",
+ volc_tts_app_id="app",
+ volc_tts_access_key="key",
+ )
+
+
+async def test_tts_tokenfree_falls_back_to_edge(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """豆包 403、TokenFree seed-tts 无渠道时,用 edge-tts 产出可听文件。"""
+ gw = ArkGateway(settings=_tts_settings())
+ monkeypatch.setattr("app.services.storage.project_dir", lambda _pid: tmp_path)
+ monkeypatch.setattr("app.services.storage.publish_local", lambda p: f"/static/{Path(p).name}")
+ monkeypatch.setattr(gw, "_ark_api_key", lambda: "sk-test")
+ monkeypatch.setattr(gw, "_tts_openspeech", AsyncMock(return_value=False))
+ monkeypatch.setattr(gw, "_tts_openai_speech", AsyncMock(return_value=False))
+ monkeypatch.setattr("app.services.ark.is_near_silent_audio", lambda _p: False)
+
+ async def fake_edge(text: str, dest: Path, voice_hint: str = "") -> None:
+ dest.parent.mkdir(parents=True, exist_ok=True)
+ dest.write_bytes(b"a" * 4000)
+
+ monkeypatch.setattr(gw, "_tts_edge", fake_edge)
+ silence = AsyncMock()
+ monkeypatch.setattr(gw, "_write_silence_mp3", silence)
+
+ url = await gw.tts("你好。", "narrator_calm", project_id=1, shot_no=0)
+ assert url.endswith("shot_000_tts.mp3")
+ assert (tmp_path / "shot_000_tts.mp3").stat().st_size == 4000
+ silence.assert_not_called()
+
+
+async def test_tts_raises_when_all_providers_fail(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None:
+ """全部语音上游失败时直接报错,不再写静音文件冒充成功。"""
+ gw = ArkGateway(settings=_tts_settings())
+ monkeypatch.setattr("app.services.storage.project_dir", lambda _pid: tmp_path)
+ monkeypatch.setattr(gw, "_ark_api_key", lambda: "sk-test")
+ monkeypatch.setattr(gw, "_tts_openspeech", AsyncMock(return_value=False))
+ monkeypatch.setattr(gw, "_tts_openai_speech", AsyncMock(return_value=False))
+
+ async def fake_edge(text: str, dest: Path, voice_hint: str = "") -> None:
+ raise RuntimeError("edge down")
+
+ monkeypatch.setattr(gw, "_tts_edge", fake_edge)
+ silence = AsyncMock()
+ monkeypatch.setattr(gw, "_write_silence_mp3", silence)
+
+ with pytest.raises(RuntimeError, match="配音失败"):
+ await gw.tts("你好。", "narrator_calm", project_id=1, shot_no=0)
+ silence.assert_not_called()
diff --git a/docs/BILLING.md b/docs/BILLING.md
index d0e004c..dcc74e3 100644
--- a/docs/BILLING.md
+++ b/docs/BILLING.md
@@ -43,7 +43,7 @@ charge_fen = cost_fen
未返回 quota 时回退 token 单价。管理端「支付与计费」可「查询 TokenFree 余额」(`GET /v1/dashboard/billing/subscription` + `usage`),并拉取公开价目 `GET https://www.tokenfree.com/api/pricing` 展示推荐模型官方价。
-预扣:生图按 TokenFree 按张价(Seedream 实际走 `gpt-image-2-5`);价目失败时用 gpt-image 保底(约 $0.625/张),不再退回 8 元/百万 token。LLM 按官方 in/out(默认 kimi-k2.6,70/30 拆)。视频不用价目表占位 `model_ratio=37.5`,按火山 480P 秒价 × 清晰度倍率(720P×2 / 1080P×4);漫剧缺省按 720P。结算仍优先单次 `quota`(勿把 New API 的美元 `cost` 当人民币)。
+预扣:生图按 TokenFree 按张价(Seedream 实际走 `gpt-image-2-5`);价目失败时用 gpt-image 保底(约 $0.625/张)。结算优先单次 `quota`;无 quota 时同样按张官方价,**不再**用 8 元/百万 token(否则会比预扣低约十倍)。LLM 按官方 in/out(默认 kimi-k2.6,70/30 拆)。视频不用价目表占位 `model_ratio=37.5`,按火山 480P 秒价 × 清晰度倍率(720P×2 / 1080P×4);漫剧缺省按 720P。勿把 New API 的美元 `cost` 当人民币。
管理端「官方用量对照」复用模型页 TokenFree API Key,拉取 New API 日消耗(`/api/data/self` 或 billing usage,日期无效时按累计额度差分记到当天)并与本地成本对照。
diff --git a/docs/releases/2026-09-15.md b/docs/releases/2026-09-15.md
new file mode 100644
index 0000000..0e2ba18
--- /dev/null
+++ b/docs/releases/2026-09-15.md
@@ -0,0 +1,120 @@
+## 2026-09-15 10:45 · 图片结算按张价(热修)
+
+- **操作者**:Agent
+- **方式**:SSH 热修 `billing/pricing.py` / `usage.py` / `estimates.py`;`systemctl restart ai-movie-api`
+- **范围**:api
+- **变更摘要**:
+ - TokenFree 生图 `/v1/responses` 常回 0 token、无 quota,结算原先用 `45000 × 8 元/百万 ≈ 36 分`
+ - 预扣已按 gpt-image 张价(约 438 分 × 1.2 缓冲 = 526 分),两边差约 14 倍
+ - 无上游 quota 时,gpt-image / Seedream 家族改为按张官方价结算;有 `quota`/`cost_fen` 仍优先上游
+- **验证**:
+ - [x] 远端 `http://127.0.0.1:8000/api/health` → `ok:true`,task_runtime healthy,`models.image=seedream-5.0`
+ - [x] `ai-movie-api` active
+ - [x] 远端 `charge_fen_for_usage`:空 usage / 45000 token → 438 分;`cost_fen=500` → 500 分
+- **备注 / 回滚**:
+ - 备份:`/opt/ai_movie_hotfix_image_billing_20260915-1044`
+ - 新单预扣仍约 526 分,实扣约 438 分(+少量 LLM);历史单不重算
+ - 回滚命令(在服务器执行):
+
+```bash
+systemctl stop ai-movie-api
+cp -a /opt/ai_movie_hotfix_image_billing_20260915-1044/*.py /opt/ai_movie/backend/app/services/billing/
+systemctl start ai-movie-api
+```
+
+## 2026-09-15 10:32 · 漫剧分镜换行/片头 + 配音兜底(全量)
+
+- **操作者**:Agent
+- **方式**:`deploy_kepu_8136.py` 全量(`SKIP_BOOTSTRAP=1`);发布前打回滚包
+- **范围**:frontend / admin / api
+- **变更摘要**:
+ - 漫剧分镜:换行续写不再单独占 3s;过碎 `@duration` 会合并进 15s 预算;时长标签可点击切换
+ - 整集片头/背景叠字只留在开幕镜,后续片段读取/保存/生成时去掉重复片头
+ - 默认音频 `qwen-tts-2025-05-22`;TokenFree speech 失败仍回退 edge-tts,不再写静音
+- **验证**:
+ - [x] 远端 `http://127.0.0.1:8000/api/health` → `ok:true`,task_runtime healthy,`models.audio=qwen-tts-2025-05-22`
+ - [x] `https://www.printfilm.com/api/health`(本机 443)→ `ok:true`
+ - [x] `https://www.printfilm.com/` → 200(`index-C9-2A0gl.js`,`Last-Modified: Tue, 15 Sep 2026 02:31:07 GMT`)
+ - [x] `https://admin.printfilm.com/` → 200(`index-CQFdqNyv.js`)
+ - [x] `ai-movie-api` active;worker 保持停用
+- **备注 / 回滚**:
+ - 回滚包:`/opt/ai_movie_rollback_20260915-103130.tgz`(88M,不含 venv / 生成媒体)
+ - 环境备份:`/opt/ai_movie_rollback_20260915-103130.env`
+ - 未改 nginx / 证书 / Postgres·Redis 容器
+ - 已打开的分集页请强刷后再看片头与时长;保存一次会把修正写回库
+ - 回滚命令(在服务器执行):
+
+```bash
+systemctl stop ai-movie-api
+mv /opt/ai_movie/backend/.venv /tmp/ai_movie_venv_keep
+rm -rf /opt/ai_movie
+tar -xzf /opt/ai_movie_rollback_20260915-103130.tgz -C /opt
+mv /tmp/ai_movie_venv_keep /opt/ai_movie/backend/.venv
+cp -a /opt/ai_movie_rollback_20260915-103130.env /opt/ai_movie/backend/.env
+systemctl start ai-movie-api
+```
+
+## 2026-09-15 10:22 · 默认音频改 qwen-tts(热修)
+
+- **操作者**:Agent
+- **方式**:SSH 热修 `tokenfree_audio.py` / `ark.py`;生产 DB 渠道与默认音频改为 `qwen-tts-2025-05-22`;`systemctl restart ai-movie-api`
+- **范围**:api
+- **变更摘要**:
+ - TokenFree 目录无 `seed-tts-2.0`,默认音频逻辑模型改为账号目录内的 `qwen-tts-2025-05-22`
+ - `seed-tts*` 运行时会 remap 到 Qwen TTS;豆包 openspeech 的 `volc_tts_resource_id` 仍为 `seed-tts-2.0`
+ - 实测 TokenFree `POST /v1/audio/speech` 对 qwen-tts 仍返回 500 `not implemented`;豆包 openspeech 仍 403;最终由 edge-tts 出声
+- **验证**:
+ - [x] `https://www.printfilm.com/api/health` → `ok:true`,`models.audio=qwen-tts-2025-05-22`
+ - [x] 生产 `ArkGateway.tts()` 写出 `/static/generated/p0/shot_098_tts.mp3`(17KB,非近静音)
+ - [x] 本地 `tests/test_tokenfree_audio.py` 通过
+- **备注 / 回滚**:
+ - 失败项目请再点「重新配音」;当前可听兜底仍是 edge-tts
+ - 下次全量时 `deploy_kepu_8136.py` 的 `MODEL_AUDIO` 已改为 qwen,避免盖回 seed-tts
+
+## 2026-09-15 10:15 · 科普配音 edge-tts 兜底(热修)
+
+- **操作者**:Agent
+- **方式**:SSH 热修 `ark.py` 后 `systemctl restart ai-movie-api`
+- **范围**:api
+- **变更摘要**:
+ - 线上「整片配音近静音」:豆包 openspeech 403(资源未授权)且 TokenFree 无 `seed-tts-2.0` 渠道时,原先跳过 edge-tts 并写入静音
+ - 现改为始终回退 edge-tts;全部失败则直接报错,不再写静音成片
+- **验证**:
+ - [x] `https://www.printfilm.com/api/health` → `ok:true`,task_runtime healthy
+ - [x] `ai-movie-api` active
+ - [x] 本地 `tests/test_tts_tokenfree_fallback.py` 通过
+- **备注 / 回滚**:
+ - 用户需对失败项目再点一次「重新配音」
+ - 豆包 TTS 资源未授权、TokenFree 无语音模型属上游账号问题,edge-tts 仅为可听兜底
+
+## 2026-09-15 10:07 · TokenFree 专一路由 + 分镜参考图上限(全量)
+
+- **操作者**:Agent
+- **方式**:`deploy_kepu_8136.py` 全量(`SKIP_BOOTSTRAP=1`);发布前打回滚包
+- **范围**:frontend / admin / api
+- **变更摘要**:
+ - 开源版去掉 Kie 客户端与火山方舟管控面配置,图/视频/文本统一走 TokenFree
+ - AI 分镜每镜最多 3 角色、2 道具、1 场景(合计 ≤6)
+ - 视频参考图去重并截到 9 张(`media_ref_limits`)
+ - 用户端失败文案改为 TokenFree 充值/网络提示
+- **验证**:
+ - [x] 远端 `http://127.0.0.1:8000/api/health` → `ok:true`,task_runtime healthy
+ - [x] `https://www.printfilm.com/api/health` → `ok:true`,scheduler/poller/watchdog running
+ - [x] `https://www.printfilm.com/` → 200(`index-D-q2ZcYB.js`,`Last-Modified: Tue, 15 Sep 2026 02:06:02 GMT`)
+ - [x] `https://admin.printfilm.com/` → 200(`index-D_LP16nu.js`)
+ - [x] `ai-movie-api` active;worker 保持停用
+- **备注 / 回滚**:
+ - 回滚包:`/opt/ai_movie_rollback_20260915-100631.tgz`(87M,不含 venv / 生成媒体)
+ - 环境备份:`/opt/ai_movie_rollback_20260915-100631.env`
+ - 未改 nginx / 证书 / Postgres·Redis 容器
+ - 回滚命令(在服务器执行):
+
+```bash
+systemctl stop ai-movie-api
+mv /opt/ai_movie/backend/.venv /tmp/ai_movie_venv_keep
+rm -rf /opt/ai_movie
+tar -xzf /opt/ai_movie_rollback_20260915-100631.tgz -C /opt
+mv /tmp/ai_movie_venv_keep /opt/ai_movie/backend/.venv
+cp -a /opt/ai_movie_rollback_20260915-100631.env /opt/ai_movie/backend/.env
+systemctl start ai-movie-api
+```
diff --git a/docs/releases/README.md b/docs/releases/README.md
index 91554c1..7acc5a9 100644
--- a/docs/releases/README.md
+++ b/docs/releases/README.md
@@ -33,6 +33,11 @@
| 日期 | 摘要 | 文件 |
|------|------|------|
+| 2026-09-15 | 图片结算按张价;杭州热修(无 quota 不再用 36 分 token 保底) | [2026-09-15.md](./2026-09-15.md) |
+| 2026-09-15 | 漫剧分镜换行/片头 + 配音兜底;杭州全量(可回滚) | [2026-09-15.md](./2026-09-15.md) |
+| 2026-09-15 | 默认音频改 qwen-tts;杭州热修(speech 仍 500,edge-tts 兜底) | [2026-09-15.md](./2026-09-15.md) |
+| 2026-09-15 | 科普配音 edge-tts 兜底;杭州热修 | [2026-09-15.md](./2026-09-15.md) |
+| 2026-09-15 | TokenFree 专一路由 + 分镜参考图上限;杭州全量(可回滚) | [2026-09-15.md](./2026-09-15.md) |
| 2026-09-14 | 漫剧每镜资产上限 + Kie 9 张;杭州全量(可回滚) | [2026-09-14.md](./2026-09-14.md) |
| 2026-09-14 | 科普逐镜衔接 + 扫描修复;杭州全量(可回滚) | [2026-09-14.md](./2026-09-14.md) |
| 2026-09-12 | 保存分镜新建镜 MissingGreenlet;分镜保护顺序 + 挂回 #609 成片;杭州热修 | [2026-09-12.md](./2026-09-12.md) |
diff --git a/frontend/src/lib/dramaEpisodePromptEditor.ts b/frontend/src/lib/dramaEpisodePromptEditor.ts
index 25f1e61..404539c 100644
--- a/frontend/src/lib/dramaEpisodePromptEditor.ts
+++ b/frontend/src/lib/dramaEpisodePromptEditor.ts
@@ -8,7 +8,7 @@ export type DramaMentionChipData = {
export const DURATION_CHIP_SELECTOR = '[data-duration-sec]'
export const MENTION_CHIP_SELECTOR = "[data-mention='true']"
export const CONTENT_TOKEN_PATTERN = /@(asset:\d+|duration:\d+)/g
-export const DURATION_PRESET_OPTIONS = [4, 5, 8, 10, 12, 15] as const
+export const DURATION_PRESET_OPTIONS = [3, 4, 5, 8, 10, 12, 15] as const
/** 新分镜建议:镜内 @duration 合计上限(秒) */
export const FRAGMENT_CONTENT_DURATION_MAX = 15
/** Seedance 单镜/API 硬上限(秒);旧稿可高于建议值 */
@@ -233,6 +233,7 @@ export function createDurationChipElement(seconds: number) {
chipEl.contentEditable = 'false'
chipEl.dataset.mention = 'true'
chipEl.dataset.durationSec = String(seconds)
+ chipEl.title = `时长 ${seconds}s,编辑时点击切换`
const labelEl = document.createElement('span')
labelEl.dataset.durationLabel = 'true'
@@ -246,10 +247,22 @@ export function createDurationChipElement(seconds: number) {
// 更新已有时长标签秒数
export function updateDurationChipElement(chipEl: HTMLElement, seconds: number) {
chipEl.dataset.durationSec = String(seconds)
+ chipEl.title = `时长 ${seconds}s,编辑时点击切换`
const labelEl = chipEl.querySelector<HTMLElement>('[data-duration-label]')
if (labelEl) labelEl.textContent = `${seconds}s`
}
+// 点击场记板时长标签时,在预设秒数间循环
+export function nextDurationPresetSeconds(current: number) {
+ const presets = DURATION_PRESET_OPTIONS
+ const idx = presets.findIndex((sec) => sec === current)
+ if (idx < 0) {
+ const next = presets.find((sec) => sec > current)
+ return next ?? presets[presets.length - 1]
+ }
+ return presets[(idx + 1) % presets.length]
+}
+
// 在 Range 处插入时长标签
export function insertDurationChipAtRange(range: Range, seconds: number) {
const selection = window.getSelection()
diff --git a/frontend/src/pages/drama/EpisodeEditPromptEditor.tsx b/frontend/src/pages/drama/EpisodeEditPromptEditor.tsx
index 627c1c1..7916108 100644
--- a/frontend/src/pages/drama/EpisodeEditPromptEditor.tsx
+++ b/frontend/src/pages/drama/EpisodeEditPromptEditor.tsx
@@ -8,10 +8,12 @@ import {
insertDurationChipAtRange,
insertMentionChipAtRange,
insertPlainTextAtRange,
+ nextDurationPresetSeconds,
renderPromptEditorContent,
resolveChipFromAsset,
serializePromptEditorContent,
sumContentDurationSeconds,
+ updateDurationChipElement,
type MentionCaretRect,
} from '../../lib/dramaEpisodePromptEditor'
import type { AssetScope } from './dramaEpisodeEditUtils'
@@ -203,6 +205,15 @@ export function EpisodeEditPromptEditor({
if (chip?.dataset.assetId) onOpenAsset?.(Number(chip.dataset.assetId))
return
}
+ const durationChip = (e.target as HTMLElement).closest<HTMLElement>('[data-duration-sec]')
+ if (durationChip && editorRef.current?.contains(durationChip)) {
+ e.preventDefault()
+ const current = Number(durationChip.dataset.durationSec)
+ updateDurationChipElement(durationChip, nextDurationPresetSeconds(current))
+ emitContent()
+ closeMentionPopover()
+ return
+ }
syncMentionTrigger()
}}
onKeyDown={(e) => {
diff --git a/frontend/src/pages/drama/drama.css b/frontend/src/pages/drama/drama.css
index a9f6c05..c2f79a5 100644
--- a/frontend/src/pages/drama/drama.css
+++ b/frontend/src/pages/drama/drama.css
@@ -4997,6 +4997,15 @@
vertical-align: middle;
}
+.drama-ep-prompt-editor.is-editing .drama-ep-duration-chip {
+ cursor: pointer;
+}
+
+.drama-ep-prompt-editor.is-editing .drama-ep-duration-chip:hover {
+ border-color: #94a3b8;
+ background: #e2e8f0;
+}
+
.drama-ep-chip-icon {
display: inline-flex;
width: 14px;