feat: add rhythm captions, same-frame dialogue review and API guide

This commit is contained in:
zhanghao 2026-12-01 10:48:19 +08:00
parent c06bc03ae5
commit 7fe5a853af
112 changed files with 26091 additions and 331 deletions

View File

@ -2,10 +2,12 @@
面向本地模型的创作工作台:Vue 3、Element Plus、Pinia 前端,FastAPI、SQLAlchemy async、MySQL 后端,通过 HTTP 和 SSE 提供登录、素材管理、异步任务与实时状态。
[故事工作室操作手册](frontend/public/help/story.html) · [API 接口使用说明](frontend/public/help/api.html)。网站入口分别为 `/help/story.html` 和 `/help/api.html`。
## 当前交付状态
- 工程目录:`E:\workspace\hybrid\cmvr-visual`;服务器源码目录:`/workspace/projects/cmvr-visual`。
- 生产 MySQL为用户指定的`192.168.28.10:3306/cmvr-visual`,使用`visual_*`表和Alembic版本表,当前schema为008(2026-11-26完成迁移)。本地开发使用独立业务库与STATE_ROOT;不能让两环境协调器领取同一批任务。启动只校验结构,不自动改表;数据库账号由私有配置提供。
- 当前业务 API 要求生产 MySQL 的 Alembic 版本为 `009`。从 `008` 升级时先备份,再执行迁移。本地开发使用独立业务库和 STATE_ROOT。服务启动时校验结构,数据库连接由各环境的私有配置提供。
- 可编辑自动成片支持一次自动生成、局部重生成、旁白/字幕编辑和从运行恢复版本。2026-11-26发布`c67183a`前已联合备份并在副本验证008迁移;生产21张原有业务表10773条记录核对未变,登录、历史资源分段读取、SSE和就绪检查通过。默认视频模型为H3 v1,TP2有独立能力门禁;真实画面质量仍需按故事审片,不能把代码开放等同于所有连续性能力已认证。
- 默认管理员为 `admin`,初始密码保持用户指定的私有配置;重启不重置已有密码。头像菜单支持本人修改登录用户名和密码;账户页仅供管理员新增、启停或删除用户。新增用户初始密码允许6–256字符,主动修改密码要求12位以上。
- 本机私有`.env.local`保存本地真实服务配置,生产私有`.env`保存在llmuser工作空间的当前发布目录,`.env.preview`只用于历史预览。秘密不提交Git、不打印到日志、不复制进文档;示例配置不含可用密码。
@ -102,7 +104,7 @@ API 和 TTS 容器不挂GPU、宿主`/proc`或Docker socket,根文件系统只
## Windows 本地开发:连接真实 MySQL 与远端模型
当前使用`E:\workspace\hybrid\cmvr-visual`。前端和业务API在Windows本机运行,模型使用既有服务器推理队列;MySQL主机可相同,但`MYSQL_DATABASE`和`STATE_ROOT`必须与生产隔离。当前私有开发库为`cmvr_visual_local_v4`,新安装示例为独立的`cmvr_visual_local`。完成独立库迁移和所需素材核对后,再把本地私有配置的`RUN_COORDINATOR`设为true;不能让两个协调器连接生产`cmvr-visual`领取同一批任务,也无需为已隔离的本地开发停止生产网站。真实服务模式只校验结构,不自动建库、改表或回退SQLite。
当前使用`E:\workspace\hybrid\cmvr-visual`。前端和业务API在Windows本机运行,模型使用既有服务器推理队列;MySQL主机可相同,但`MYSQL_DATABASE`和`STATE_ROOT`必须与生产隔离。当前私有开发库为`cmvr_visucal_dev`,新安装示例为独立的`cmvr_visual_local`。完成独立库迁移和所需素材核对后,再把本地私有配置的`RUN_COORDINATOR`设为true;不能让两个协调器连接生产`cmvr-visual`领取同一批任务,也无需为已隔离的本地开发停止生产网站。真实服务模式只校验结构,不自动建库、改表或回退SQLite。
准备本机 Python 3.11+、Node/pnpm,以及 `ffmpeg`/`ffprobe`。已有虚拟环境、依赖和 `.env.local` 时跳过相应步骤,避免覆盖私有配置:
@ -192,7 +194,7 @@ pnpm format:check
私有 `.env` 至少配置 `CMVR_MODE=production`、`MYSQL_HOST`、`MYSQL_PORT`、`MYSQL_DATABASE`、`MYSQL_USER`、`MYSQL_PASSWORD` 及管理员初始化信息。推荐这些分离字段,后端用 `URL.create` 处理数据库名与密码特殊字符;不要手工拼接连接串。正式库不可达时启动失败,不会切换 SQLite。
现有六表先经过精确基线检查再登记001,002增补工作流等表,003增加批次持久hold,004增加私有内容及共享素材支持。当前生产启动要求004,并检查列、类型、索引和约束;只有显式test/preview模式使用`create_all`。从源码backend目录、已安全加载数据库环境后执行:
现有六表先经过精确基线检查再登记001,002增补工作流等表,003增加批次持久hold,004增加私有内容及共享素材支持。当前生产启动要求009,并检查列、类型、索引和约束;只有显式test/preview模式使用`create_all`。从源码backend目录、已安全加载数据库环境后执行:
```bash
# 仅匹配的、尚未版本化的旧六表数据库执行一次:

View File

@ -0,0 +1,19 @@
"""Persist an optional caption preference at story creation."""
import sqlalchemy as sa
from alembic import op
revision = "009"
down_revision = "008"
branch_labels = None
depends_on = None
def upgrade():
columns = sa.inspect(op.get_bind()).get_columns("visual_drafts")
if not any(c["name"] == "caption_birth_intent" for c in columns):
op.add_column("visual_drafts", sa.Column("caption_birth_intent", sa.JSON(), nullable=True))
def downgrade():
op.drop_column("visual_drafts", "caption_birth_intent")

View File

@ -6,6 +6,8 @@ import asyncio
import json
import math
import os
import re
import unicodedata
from pathlib import Path
import uuid
import wave
@ -423,6 +425,77 @@ async def cacheable_segment(path, settings, canvas, frames):
)
async def subtitle_filter_args(cues, work, canvas, ffmpeg_bin):
if not cues:
return []
font = "Microsoft YaHei" if os.name == "nt" else "Noto Sans CJK SC"
# 只在排版层换行;SRT、台词、手工锁以及识别的原文保持同一份数据。
width_units = max(5, int(canvas[0] * 0.88 / 26))
def wrap(text):
lines, line, used = [], [], 0
for char in text:
width = (
0
if unicodedata.combining(char)
else (2 if unicodedata.east_asian_width(char) in "WF" else 1)
)
if used + width > width_units and line:
lines.append("".join(line))
line, used = [], 0
line.append(char)
used += width
return "\n".join([*lines, "".join(line)])
displayed = [wrap(c["text"]) for c in cues]
if len(cues) > 32 or any("\n" in s for s in displayed):
filters = await run_process([ffmpeg_bin, "-hide_banner", "-filters"], timeout=10)
if re.search(rb"^\s*\S+\s+ass\s+V->V", filters, re.MULTILINE):
# 24fps 每个边界向下取整至 ASS 厘秒,该时刻位于上一帧之后、本帧之内。
def stamp(frame):
seconds, centis = divmod(frame * 100 // 24, 100)
hours, seconds = divmod(seconds, 3600)
minutes, seconds = divmod(seconds, 60)
return f"{hours}:{minutes:02}:{seconds:02}.{centis:02}"
header = (
f"[Script Info]\nScriptType: v4.00+\nPlayResX: {canvas[0]}\nPlayResY: {canvas[1]}\n"
"WrapStyle: 2\nScaledBorderAndShadow: yes\n[V4+ Styles]\n"
"Format: Name, Fontname, Fontsize, PrimaryColour, SecondaryColour, OutlineColour, BackColour,"
" Bold, Italic, Underline, StrikeOut, ScaleX, ScaleY, Spacing, Angle, BorderStyle, Outline,"
" Shadow, Alignment, MarginL, MarginR, MarginV, Encoding\n"
f"Style: Default,{font},48,&H00FFFFFF,&H00FFFFFF,&H00000000,&H00000000,"
"0,0,0,0,100,100,0,0,1,3,0,2,0,0,60,1\n[Events]\n"
"Format: Layer, Start, End, Style, Name, MarginL, MarginR, MarginV, Effect, Text\n"
)
# 入口 Subtitle 已拒绝反斜线、花括号和控制字符;逗号可用于最后一列。
rows = (
f"Dialogue: 0,{stamp(c['start_frame'])},{stamp(c['end_frame'])},Default,,0,0,0,,"
+ text.replace("\n", r"\N")
+ "\n"
for c, text in zip(cues, displayed, strict=True)
)
(work / "subtitles.ass").write_text(header + "".join(rows), encoding="utf-8")
return ["-vf", "ass=filename=subtitles.ass"]
filters = []
for index, cue in enumerate(cues):
name = f"cue-{index:04d}.txt"
(work / name).write_text(displayed[index], encoding="utf-8")
filters.append(
f"drawtext=font='{font}':textfile={name}:expansion=none:fontcolor=white:fontsize=48:borderw=3:"
f"x=(w-tw)/2:y=h-th-60:enable='gte(n,{cue['start_frame']})*lt(n,{cue['end_frame']})'"
)
graph = ",".join(filters)
if len(graph) < 7000:
return ["-vf", graph]
script = work / "subtitle-filter.txt"
script.write_text(graph, encoding="utf-8")
version = (await run_process([ffmpeg_bin, "-version"], timeout=10)).decode(errors="replace")
major = re.search(r"ffmpeg version (?:n)?(\d+)", version)
option = "-/filter:v" if major and int(major[1]) >= 7 else "-filter_script:v"
return [option, script.name]
async def compose_workflow(plan, work_dir, control=None, *, settings, sources, audio=None):
"""Render a frozen multi-shot timeline from internal resolved asset paths."""
if len(sources) != len(plan.spec["shots"]):
@ -611,15 +684,6 @@ async def compose_workflow(plan, work_dir, control=None, *, settings, sources, a
command += [*input_options(), "-i", str(audio)]
else:
command += ["-f", "lavfi", "-i", "anullsrc=channel_layout=stereo:sample_rate=48000"]
filters = []
# Windows 未安装 Noto 时 FFmpeg 会静默回退至西文字体,必须选用已有中文字库。
subtitle_font = "Microsoft YaHei" if os.name == "nt" else "Noto Sans CJK SC"
for index, cue in enumerate(plan.spec["render"]["subtitles"]):
name = f"cue-{index:04d}.txt"
(work / name).write_text(cue["text"], encoding="utf-8")
filters.append(
f"drawtext=font='{subtitle_font}':textfile={name}:expansion=none:fontcolor=white:fontsize=48:borderw=3:x=(w-tw)/2:y=h-th-60:enable='gte(n,{cue['start_frame']})*lt(n,{cue['end_frame']})'"
)
if audio:
if "source_end_sample" in audio_spec:
start, end = audio_spec["source_start_sample"], audio_spec["source_end_sample"]
@ -632,8 +696,7 @@ async def compose_workflow(plan, work_dir, control=None, *, settings, sources, a
else:
af = f"atrim=duration={duration_text}"
command += ["-map", "0:v:0", "-map", "1:a:0"]
if filters:
command += ["-vf", ",".join(filters)]
command += await subtitle_filter_args(plan.spec["render"]["subtitles"], work, plan.canvas, settings.ffmpeg_bin)
command += [
"-af",
af,
@ -684,7 +747,7 @@ async def compose_workflow(plan, work_dir, control=None, *, settings, sources, a
"width": width,
"height": height,
"clip_count": len(sources),
"subtitle_count": len(filters),
"subtitle_count": len(plan.spec["render"]["subtitles"]),
}
return CpuResult(
[target],

View File

@ -103,6 +103,55 @@ def validate(task, inputs, p):
p.get("profile") != profile(task) and not (task == SYNC and preview)
):
raise _invalid("对白模型版本不匹配。")
if task == SPEECH_INSPECT and "turn_policy" in p:
from .native_av import TURN_POLICY, TURN_SOURCES
_keys(inputs, {"asset_ids"})
ids = inputs.get("asset_ids")
if not isinstance(ids, list) or len(ids) != len(TURN_SOURCES):
raise _invalid("双人验收需要完整的十项候选素材")
for value in ids:
_id(value)
if len(set(ids)) != len(ids):
raise _invalid("双人参考及原声素材必须独立")
_keys(
p,
{
"profile",
"turn_policy",
"certificate_sha256",
"first_frame_sha256",
"speaker_ids",
"turns",
},
)
if p["turn_policy"] != TURN_POLICY or any(
not re.fullmatch("[0-9a-f]{64}", str(p.get(k, "")))
for k in ("certificate_sha256", "first_frame_sha256")
):
raise _invalid("双人专用认证或首帧摘要无效")
speakers, turns = p.get("speaker_ids"), p.get("turns")
if (
not isinstance(speakers, list)
or len(speakers) != 2
or not isinstance(turns, list)
or len(turns) != 2
):
raise _invalid("同框轮读需要两位角色各一句")
for who in speakers:
_id(who)
for row in turns:
_keys(row, {"utterance_id", "speaker_id", "text"})
_id(row.get("utterance_id"))
_id(row.get("speaker_id"))
_string(row.get("text"), 2000)
if (
len(set(speakers)) != 2
or {r["speaker_id"] for r in turns} != set(speakers)
or len({r["utterance_id"] for r in turns}) != 2
):
raise _invalid("双人发言归属或台词编号无效")
return
if task == SPEECH_INSPECT:
_keys(inputs, {"audio_asset_id", "reference_asset_id", "speaker_id", "expected_text"})
_keys(p, {"profile", "sample_rate", "source_start_sample", "source_end_sample", "native_av_policy"})
@ -301,6 +350,20 @@ def visible_faces(path):
async def prepare(provider, task, inputs, parameters, assets, context=None):
if task == SPEECH_INSPECT and "turn_policy" in parameters:
from .native_av import turn_certificate, turn_evidence, TURN_CERTIFICATION_REASON
validate(task, inputs, parameters)
snapshot = await provider.upstream_capabilities()
if turn_certificate(snapshot, turn_evidence(snapshot)) != parameters["certificate_sha256"]:
raise MediaError("capability_unavailable", TURN_CERTIFICATION_REASON)
paths = [Path(provider._asset(aid, assets)) for aid in inputs["asset_ids"]]
uploaded = (
[await provider._upload_input(path) for path in paths]
if provider.settings.inference_remote_files
else list(map(str, paths))
)
return dict(task_type=task,input=dict(asset_paths=uploaded),parameters=dict(parameters),timeout_seconds=1800)
if task == SPEECH_INSPECT and parameters.get("native_av_policy") == "native_av_v1":
from .native_av import alignment_available, ALIGNMENT_REASON

View File

@ -138,6 +138,10 @@ async def run_cpu(provider, task_type, inputs, parameters, assets, work):
proxy, inputs, assets, work, sampling_policy=DIALOGUE_REVIEW_SAMPLING_POLICY
)
result.result["decision"] = result.result["verdict"]
if inputs["expected"].get("turns"):
from app.services.artifacts import digest_file
result.result["video_sha256"] = digest_file(provider._asset(inputs["video_asset_id"], assets))
if inputs["expected"].get("source_visual_policy") == SOURCE_VISUAL_POLICY:
result.result["source_visual_policy"] = SOURCE_VISUAL_POLICY
if assessment:

View File

@ -3,6 +3,7 @@
import re
from app.domain import native_silence
from app.domain.native_av import TURN_POLICY
from app.domain.video_generation import (
H3_NATIVE_AV_PROFILE,
@ -10,6 +11,7 @@ from app.domain.video_generation import (
H3_NATIVE_AV_PROFILES,
)
TURN_CERTIFICATION_REASON = "同框轮读缺少独立的逐轮验收和冻结留出集认证,可编辑草稿及离线试验。"
CERTIFICATION_REASON = "H3原生音视频尚未启用或尚未完成独立实测认证。"
REVISION = "12253298adb81e36757eabebb81d2ba1c0cc70cc"
RUNTIME_REVISION = "f53d552036a0d1bd5570782a39cd40cfabf112bc"
@ -151,3 +153,55 @@ async def alignment_available(provider):
return alignment_enabled(provider.settings, await provider.upstream_capabilities())
except Exception:
return False
TURN_SOURCES = (
"video",
"native_audio",
"speech_audio",
"speech_report",
"first_frame",
"visual_review",
"face_0",
"face_1",
"voice_0",
"voice_1",
)
def turn_evidence(snapshot):
dialogue = snapshot.get("dialogue", {}) if isinstance(snapshot, dict) else {}
evidence = dialogue.get("two_person_turns") if isinstance(dialogue, dict) else None
return evidence if isinstance(evidence, dict) else {}
def turn_certificate(snapshot, parameters):
ev = turn_evidence(snapshot)
profile = parameters.get("profile")
tp2 = profile == H3_NATIVE_AV_TP2_PROFILE
if (
profile in H3_NATIVE_AV_PROFILES
and ev.get("available") is True
and ev.get("audited") is True
and ev.get("decision") == "pass"
and ev.get("policy") == TURN_POLICY
and ev.get("release_policy") == "h3-two-person-turns-release-v1"
and ev.get("revision") == REVISION
and ev.get("runtime_revision") == (TP2_RUNTIME_REVISION if tp2 else RUNTIME_REVISION)
and ev.get("profile") == profile
and ev.get("fps") == 24
and ev.get("language") == "Chinese"
and [ev.get("width"), ev.get("height")]
== [parameters.get("width"), parameters.get("height")]
== [1344, 768]
and ev.get("num_frames") == parameters.get("num_frames")
and ev.get("num_frames") in range(124, 159 if tp2 else 346, 17)
and ev.get("tasks") == 24
and type(ev.get("first_pass")) is int
and type(ev.get("overall_pass")) is int
and 18 <= ev["first_pass"] <= ev["overall_pass"] <= 24
and ev["overall_pass"] >= 22
and re.fullmatch("[0-9a-f]{64}", str(ev.get("report_sha256", "")))
):
return ev["report_sha256"]
return None

View File

@ -4,10 +4,63 @@ from app.core.security import Actor
from app.schemas.editors import SaveEditor, RestoreEditor, PlanEditor, StartEditor, EditorMode
from app.schemas.dialogue_commands import EnableDialogue, ForkPrepared
from app.services import editors as service
from app.schemas.editors import ForkSpeakerCuts, PreviewCaptions, ReviewTurns
from app.services import caption_revision
from fastapi.responses import PlainTextResponse
router = APIRouter(prefix="/editors", tags=["editors"])
@router.post("/{draft_id}/dialogue/fork-cuts")
async def fork_speaker_cuts(
draft_id: str,
body: ForkSpeakerCuts,
request: Request,
idempotency_key: str | None = Header(None),
actor: Actor = Depends(csrf_actor),
):
from app.services.dialogue_cuts import fork_cuts
return await fork_cuts(request.app.state, actor, draft_id, body, idempotency_key)
@router.post("/{draft_id}/runs/{run_id}/turns/{shot_id}/review")
async def review_turns(
draft_id: str,
run_id: str,
shot_id: str,
body: ReviewTurns,
request: Request,
idempotency_key: str | None = Header(None),
actor: Actor = Depends(csrf_actor),
):
from app.services.turn_review import review
return await review(request.app.state, actor, draft_id, run_id, shot_id, body, idempotency_key)
@router.post("/{draft_id}/captions/preview")
async def preview_captions(
draft_id: str, body: PreviewCaptions, request: Request, actor: Actor = Depends(current_actor)
):
return await caption_revision.preview(request.app.state, actor, draft_id, body)
@router.get("/{draft_id}/runs/{run_id}/captions.srt", response_class=PlainTextResponse)
async def export_captions(
draft_id: str, run_id: str, request: Request, actor: Actor = Depends(current_actor)
):
content = await caption_revision.export_frozen(request.app.state, actor, draft_id, run_id)
return PlainTextResponse(
content,
media_type="application/x-subrip; charset=utf-8",
headers={
"Content-Disposition": f'attachment; filename="captions-{run_id}.srt"',
"Cache-Control": "private, no-store",
},
)
@router.post("/{draft_id}/dialogue/fork-prepared", status_code=201)
async def fork_dialogue_prepared(
draft_id: str,

View File

@ -2,7 +2,7 @@ from dataclasses import dataclass, field
from sqlalchemy import inspect, text, Boolean, String, Text
from sqlalchemy.dialects.mysql import TINYINT
CURRENT_SCHEMA_REVISION = "008"
CURRENT_SCHEMA_REVISION = "009"
SUPPORTED_SCHEMA_REVISIONS = frozenset({CURRENT_SCHEMA_REVISION})

View File

@ -107,8 +107,8 @@ def supports_sample_timing(raw):
if hasattr(raw, "model_dump"):
raw = raw.model_dump(mode="json")
if "spec" in raw:
return raw.get("schema_version") in (2, 3)
return raw.get("schema_version") in (4, 5)
return raw.get("schema_version") in (2, 3, 4)
return raw.get("schema_version") in (4, 5, 6)
def compile_story_timing(spec):

View File

@ -189,6 +189,56 @@ class StorySpecV5(StorySpecV4):
return self
class DialogueSpeakerV6(DialogueSpeaker):
model_speaker_number: int | None = Field(
default=None, strict=True, ge=1, le=1000, exclude_if=lambda x: x is None
)
face_reference_asset_id: StableId | None = Field(default=None, exclude_if=lambda x: x is None)
voice_reference_asset_id: StableId | None = Field(default=None, exclude_if=lambda x: x is None)
class DialogueSpecV6(DialogueSpec):
generation: Literal["native_av"] = "native_av"
speakers: list[DialogueSpeakerV6] = Field(default_factory=list, max_length=1000)
class ShotPerformanceV6(ShotPerformance):
dialogue_staging: Literal["two_person_turns"] | None = Field(
default=None, exclude_if=lambda x: x is None
)
first_frame_sha256: str | None = Field(
default=None, pattern=r"^[0-9a-f]{64}$", exclude_if=lambda x: x is None
)
listener_reactions: dict[StableId, Annotated[str, Field(max_length=500)]] = Field(
default_factory=dict, max_length=1000, exclude_if=lambda x: not x
)
class StoryShotV6(StoryShotV5):
performance: ShotPerformanceV6 = Field(default_factory=ShotPerformanceV6)
class StorySpecV6(StorySpecV5):
schema_version: Literal[6] = 6
shots: list[StoryShotV6] = Field(min_length=1, max_length=1000)
dialogue: DialogueSpecV6 = Field(default_factory=DialogueSpecV6)
@model_validator(mode="after")
def check_turn_authoring(self):
numbers = [
sp.model_speaker_number
for sp in self.dialogue.speakers
if sp.model_speaker_number is not None
]
if len(numbers) != len(set(numbers)):
raise ValueError("角色模型编号必须唯一")
for shot in self.shots:
p = shot.performance
if set(p.listener_reactions).difference(p.native_utterance_ids or []):
raise ValueError("听者动作必须引用本镜台词")
return self
def _spec(raw):
if hasattr(raw, "model_dump"):
raw = raw.model_dump(mode="json")
@ -197,7 +247,7 @@ def _spec(raw):
def has_dialogue(raw):
spec = _spec(raw)
return spec.get("schema_version") == 5 and spec.get("dialogue", {}).get("enabled", True)
return spec.get("schema_version") in (5, 6) and spec.get("dialogue", {}).get("enabled", True)
def has_continuity(raw):
@ -223,7 +273,7 @@ def upgrade_dialogue_manifest(manifest):
m = validate_manifest(manifest)
if m["source_kind"] != "story":
raise ValueError("仅故事支持对白")
if m["schema_version"] == 3:
if m["schema_version"] in (3, 4) and m["spec"].get("schema_version") in (5, 6):
return m
speakers = [
dict(id=_child_id(e["id"], "speaker", 0), entity_id=e["id"], name=e["name"] or "角色")
@ -251,7 +301,7 @@ def upgrade_dialogue_manifest(manifest):
shot["performance"] = dict(
sequence_id=seq, visible_speaker_ids=visible if len(visible) <= 2 else []
)
m.update(schema_version=3)
m.update(schema_version=max(3,m["schema_version"]))
m["spec"].update(schema_version=5, dialogue=dict(generation="native_av", language="Chinese", sequences=sequences, speakers=speakers))
if m["audio"]["mode"] == "manual_track":
m["audio"]["mix_mode"] = "manual_mix"
@ -454,7 +504,7 @@ def prepare_dialogue(manifest, speech_bindings, capabilities):
from app.domain.editors import editor_issues, validate_manifest
m = validate_manifest(manifest)
if m["schema_version"] != 3:
if m["schema_version"] not in (3, 4):
raise ValueError("对白准备要求 V3 编辑清单")
spec = m["spec"]
d = spec["dialogue"]

View File

@ -20,8 +20,10 @@ def validate_manifest(manifest):
m["spec"] = parse(raw).model_dump(mode="json")
if raw.get("schema_version") == 4 and m["schema_version"] != 2:
raise ValueError("V4 story requires V2 editor")
if (raw.get("schema_version") == 5) != (m["schema_version"] == 3):
raise ValueError("V5 story requires V3 editor")
if (raw.get("schema_version") in (5, 6)) != (m["schema_version"] in (3, 4)):
raise ValueError("dialogue story requires dialogue editor")
if raw.get("schema_version") == 6 and m["schema_version"] != 4:
raise ValueError("V6 story requires V4 editor")
ids = m["shot_ids"]
if (
len(ids) != len(m["spec"]["shots"])
@ -35,9 +37,9 @@ def validate_manifest(manifest):
if len({x["id"] for x in group}) != len(group):
raise ValueError("duplicate stable id")
roles = {"frame": "image", "video": "video"}
if m["schema_version"] in (2, 3):
if m["schema_version"] in (2, 3, 4):
roles.update(end_frame="image", join_anchor="image")
if m["schema_version"] == 3:
if m["schema_version"] in (3, 4):
roles.update(
original_audio="audio",
base_video="video",
@ -51,12 +53,14 @@ def validate_manifest(manifest):
)
valid_keys = {f"{role}:{sid}" for role in roles for sid in ids}
valid_keys.update("audio:" + x["id"] for x in m["audio"]["segments"])
if m["schema_version"] == 3:
if m["schema_version"] in (3, 4):
from app.domain.dialogue import speech_stem_id
dialogue = m["spec"]["dialogue"]
speakers = {u["id"]: u["speaker_id"] for u in dialogue["utterances"]}
lines = speakers.keys()
if any(e["utterance_id"] not in lines for e in m["captions"].get("edits", [])):
raise ValueError("字幕编辑对应的父台词不存在")
roles["speech_stem"] = "audio"
if any(key.startswith("speech_stem:") for key in m["bindings"]):
for seq in dialogue["sequences"]:
@ -111,7 +115,7 @@ def manifest_from_draft(draft):
for id in ids
],
}
dialogue_story = story and spec.get("schema_version") == 5
dialogue_story = story and spec.get("schema_version") in (5, 6)
if dialogue_story:
audio["segments"] = []
audio["mix_mode"] = "manual_mix" if old.get("audio") else "composed"
@ -127,7 +131,7 @@ def manifest_from_draft(draft):
]
return validate_manifest(
dict(
schema_version={4: 2, 5: 3}.get(spec.get("schema_version"), 1) if story else 1,
schema_version={4: 2, 5: 3, 6: 4}.get(spec.get("schema_version"), 1) if story else 1,
source_kind="story" if story else "workflow",
editing_mode="manual" if dialogue_story else "auto",
spec=spec,
@ -139,13 +143,34 @@ def manifest_from_draft(draft):
)
def apply_birth_captions(draft, manifest):
"""仅消费创建事务保存的作者选择;历史草稿一直为空。"""
intent = draft.caption_birth_intent
dialogue = manifest["spec"].get("dialogue") or {}
if not intent or not dialogue.get("enabled") or dialogue.get("generation") != "native_av":
return False
draft.caption_birth_intent = None
caps = manifest["captions"]
if caps.get("mode") == "manual" or caps.get("presentation"):
return False
if intent["mode"] in {"none", "manual"}:
caps["mode"] = intent["mode"]
return True
if (dialogue.get("language") or "Chinese") != "Chinese":
caps["mode"] = intent["mode"]
return True
manifest["schema_version"] = 4
caps.update(mode=intent["mode"], presentation=intent["presentation"], edits=[])
return True
def editor_issues(manifest):
m = manifest
shots = {
id: s.get("edit", {}).get("duration_frames", s.get("duration_frames", 120))
for id, s in zip(m["shot_ids"], m["spec"]["shots"])
}
if m["spec"].get("schema_version") in (4, 5):
if m["spec"].get("schema_version") in (4, 5, 6):
from app.domain.continuity import compile_story_timing
shots = {
@ -238,7 +263,7 @@ MODE_CAPABILITIES = {"mode_switch": True, "manual": True, "auto": True, "name_ed
def invalidate_join_anchors(manifest, previous):
"""Discard derived frames whose source binding or selected trim changed."""
if manifest.get("schema_version") not in (2, 3):
if manifest.get("schema_version") not in (2, 3, 4):
return
def sources(m):

View File

@ -3,6 +3,8 @@
import re
import unicodedata
TURN_POLICY = "h3-two-person-turns-screen-v1"
def _normalize(value, *, fold_single_digits):
if not isinstance(value, str):
@ -88,3 +90,187 @@ def align_native_utterances(report, utterances, *, audio_offset_samples=0):
if cursor != len(checked):
raise ValueError("原声包含未分配的额外对白")
return aligned
def validate_turn_report(report, contract, aligned, sources, frames):
"""将服务端逐轮证据重新绑定到本轮选片、原声与参考,拒绝旧请求或不完整报告。"""
from app.domain.stories import digest
speaker_ids = contract["speaker_ids"]
intent = dict(
speaker_ids=speaker_ids,
turns=contract["turns"],
first_frame_sha256=contract["first_frame_sha256"],
references=[sources[k] for k in ("face_0", "face_1", "voice_0", "voice_1")],
)
if (
report.get("policy") != TURN_POLICY
or report.get("controls") is not False
or report.get("certificate_sha256") != contract["certificate_sha256"]
or not contract["certificate_sha256"]
or report.get("source_sha256") != sources
or sources["first_frame"] != contract["first_frame_sha256"]
or report.get("author_sha256") != digest(intent)
):
raise ValueError("候选报告与本次原片、原声、角色参考或认证版本不匹配")
checks = report.get("checks", {})
if (
not isinstance(checks, dict)
or not isinstance(report.get("turns"), list)
or len(report["turns"]) != 2
or len(aligned) != 2
):
raise ValueError("双人逐轮证据不完整")
mandatory = (
"geometry",
"audio_binding",
"tracking",
"visual",
*["tail_" + s for s in speaker_ids],
)
if any(
not isinstance(checks.get(k), dict)
or checks[k].get("decision") not in ("pass", "indeterminate", "reject")
for k in mandatory
):
raise ValueError("双人原片、跟踪或收尾测量缺失")
if checks["audio_binding"]["decision"] != "pass" or checks["geometry"]["decision"] != "pass":
raise ValueError("候选音轨或画面规格无法验证")
if (
checks["visual"].get("source_matched") is not True
or checks["visual"].get("review_sha256") != sources["visual_review"]
):
raise ValueError("整镜视觉检查与候选来源不符")
geometry = checks["geometry"]
if [
geometry.get("width"),
geometry.get("height"),
geometry.get("fps"),
geometry.get("frames"),
] != [1344, 768, 24, frames]:
raise ValueError("双人画布或帧数与本次配置不符")
states = [v.get("decision") for v in checks.values() if isinstance(v, dict)]
for row, time, turn in zip(report["turns"], aligned, contract["turns"], strict=True):
who = turn["speaker_id"]
listener = next(s for s in speaker_ids if s != who)
if (
not isinstance(row, dict)
or row.get("utterance_id") != turn["utterance_id"]
or time["utterance_id"] != turn["utterance_id"]
or row.get("expected_speaker_id") != who
or row.get("listener_id") != listener
or row.get("start_sample") != time["start_sample"]
or row.get("end_sample") != time["end_sample"]
or row.get("decision") not in ("pass", "reject", "indeterminate")
or not isinstance(row.get("voice"), dict)
):
raise ValueError("轮次证据与指定台词、角色或实测时间不匹配")
observed = row["voice"].get("observed_speaker_id")
if (
observed is not None
and observed != who
or row.get("listener_sync", {}).get("decision") == "pass"
or row.get("speaker_sync", {}).get("decision") == "reject"
):
return "reject"
if row["decision"] == "pass" and (
observed != who
or row.get("speaker_sync", {}).get("decision") != "pass"
or row.get("listener_rest", {}).get("decision") != "pass"
or not isinstance(row.get("listener_sync"), dict)
):
raise ValueError("自动通过的轮次缺少声线与双脸同步对照")
states.append(row["decision"])
if checks["tracking"]["decision"] == "pass":
tracks = report.get("tracks")
if (
not isinstance(tracks, dict)
or set(tracks) != set(speaker_ids)
or any(not isinstance(t, list) or len(t) != frames for t in tracks.values())
):
raise ValueError("双脸连续轨迹缺失")
for side, role in enumerate(speaker_ids):
for i, obs in enumerate(tracks[role]):
scores = obs.get("identity_similarities") if isinstance(obs, dict) else None
if (
not isinstance(scores, list)
or len(scores) != 2
or any(type(s) not in (int, float) or not -1.001 <= s <= 1.001 for s in scores)
or scores[side] < 0.4
or scores[side] - scores[1 - side] < 0.14
or obs.get("frame") != i
or not isinstance(obs.get("box"), list)
or len(obs["box"]) != 4
or type(obs.get("track_iou")) not in (int, float)
or not 0.35 <= obs["track_iou"] <= 1
):
raise ValueError("人脸轨迹缺少逐帧独立身份、连续性或位置证据")
verdict = (
"reject"
if "reject" in states
else "pass"
if all(s == "pass" for s in states)
else "indeterminate"
)
if report.get("decision") != verdict:
raise ValueError("候选总评与逐轮证据不一致")
return verdict
CONTENT_POLICY = "whisper-sensevoice-consensus-v1"
def content_consensus(report, expected):
from app.domain.native_silence import verified_silence
if not isinstance(expected, str):
return False
if not expected.strip():
return verified_silence(report, expected)
normalized = normalize_native_text(expected)
if not normalized:
return False
fields = dict(
content_verification_policy=CONTENT_POLICY,
content_decision_source="whisper_sensevoice_consensus",
secondary_status="completed",
secondary_asr_revision="90c1c61912018b70ada0fcc024ea24aca62f2e63",
secondary_runtime_revision="6991744856587fa44379e8b5dcc432debffeb1be",
normalized_expected_text=normalized,
normalized_transcript=normalized,
normalized_secondary_transcript=normalized,
)
if any(report.get(k) != v for k, v in fields.items()):
return False
for name in ("content_error_rate", "secondary_content_error_rate"):
if type(report.get(name)) not in (int, float) or report[name] != 0:
return False
for name in ("transcript", "secondary_transcript"):
if (
not isinstance(report.get(name), str)
or normalize_native_text(report[name]) != normalized
):
return False
return True
def source_audio_matches_video(audio, video):
"""核对由原生提取任务签入的同源关系,单独读报告无需重新进行画面验收。"""
from app.domain.stories import digest
provenance = audio.get("provenance") or {}
sidecar = (video.get("provenance") or {}).get("native_source_audio_asset_id")
return bool(
video.get("sha256")
and audio.get("sha256")
and sidecar
and sidecar == provenance.get("source_audio_asset_id")
and audio.get("sample_rate") == 48000
and type(audio.get("sample_count")) is int
and audio["sample_count"] > 0
and provenance.get("native_av_policy") == "native_av_v1"
and type(provenance.get("audio_offset_samples")) is int
and provenance["audio_offset_samples"] >= 0
and audio.get("context_hash")
== digest(dict(video_sha=video["sha256"], policy="native_av_v1"))
)

View File

@ -44,6 +44,65 @@ def _spoken_seconds(lines):
return result + 1.0
TURN_STAGING = "two_person_turns"
def _compile_turns(spec, shot, utterances, speakers, issue):
sid, perf = shot["id"], shot["performance"]
visible = perf.get("visible_speaker_ids", [])
speaking = [u["speaker_id"] for u in utterances]
if (
spec.get("schema_version") != 6
or len(speaking) != 2
or len(set(speaking)) != 2
or len(visible) != 2
or set(visible) != set(speaking)
or not perf.get("native_utterance_ids")
or perf.get("lip_sync") == "off"
):
issue("native_turn_assignment_invalid", sid, "同框首发需要两位在场角色依次各说一句")
return []
if (
spec.get("profile") == "portrait_1080_v1"
or spec["dialogue"].get("language", "Chinese") != "Chinese"
):
issue("native_turn_scope_invalid", sid, "同框首发仅支持中文横屏固定双人中近景")
for field in ("model_speaker_number", "face_reference_asset_id", "voice_reference_asset_id"):
values = [speakers[key].get(field) for key in speaking]
if not all(values) or len(set(values)) != 2:
issue(
"native_turn_reference_required",
sid,
"请分别绑定两位角色的稳定编号、独立参考脸及验声样本",
)
break
if not perf.get("first_frame_sha256"):
issue("native_turn_frame_required", sid, "请确认双人首帧中从左到右的角色对应")
controls = ("<d>", "</d>", "<scenetrans>", "<cutoff>")
author_fields = [
shot.get("visual_prompt", ""),
shot.get("motion_prompt", ""),
*perf.get("listener_reactions", {}).values(),
*(u.get("delivery", "") for u in utterances),
*(speakers[k].get("native_voice") or "" for k in speaking),
]
if any(token in field for field in author_fields for token in controls):
issue(
"native_dialogue_control_token",
sid,
"画面、声线和听者动作不能包含模型保留的对白控制标记",
)
return [
dict(
utterance_id=u["id"],
speaker_id=u["speaker_id"],
listener_id=speaking[1 - i],
listener_reaction=perf.get("listener_reactions", {}).get(u["id"], "安静倾听"),
)
for i, u in enumerate(utterances)
]
def compile_native_shots(manifest):
m = deepcopy(manifest)
spec, issues, result = m["spec"], [], []
@ -107,13 +166,15 @@ def compile_native_shots(manifest):
sid, perf, edit = shot["id"], shot["performance"], shot["edit"]
utterances = [lines[uid] for uid in allocations[sid]]
who = {u["speaker_id"] for u in utterances}
if len(perf.get("visible_speaker_ids", [])) > 1:
duo = perf.get("dialogue_staging") == TURN_STAGING
turns = _compile_turns(spec, shot, utterances, speakers, issue) if duo else []
if not duo and len(perf.get("visible_speaker_ids", [])) > 1:
issue(
"native_two_faces_unavailable",
sid,
"双人同框尚未通过原生对白认证,请先按说话人切镜",
)
if len(who) > 1:
if not duo and len(who) > 1:
issue(
"native_multiple_speakers_in_shot", sid, "当前请按说话人切镜,每镜最多一个发言角色"
)
@ -191,11 +252,13 @@ def compile_native_shots(manifest):
)
visual = "\n".join(s for s in (shot.get("visual_prompt"), shot.get("motion_prompt")) if s)
spoken = []
for u in utterances:
for index, u in enumerate(utterances):
speaker = speakers[u["speaker_id"]]
number = 1 + next(
i for i, sp in enumerate(dialogue["speakers"]) if sp["id"] == speaker["id"]
)
# V6 单人镜头可仅用一个局部编号。已指定编号的角色始终沿用作者编号。
number = speaker.get("model_speaker_number") or (1 if spec["schema_version"] == 6 else number)
voice = speaker.get("native_voice") or "自然、清晰且有辨识度的声音"
text = u.get("spoken_text") or u["text"]
if any(token in text for token in ("<d>", "</d>", "<scenetrans>", "<cutoff>")):
@ -208,6 +271,15 @@ def compile_native_shots(manifest):
)
delivery = ",".join(x for x in (voice, u.get("delivery", "")) if x)
action = "says" if visible else "says in an off-screen voiceover"
if turns:
turn = turns[index]
side = "左侧" if perf["visible_speaker_ids"][0] == speaker["id"] else "右侧"
listener = speakers[turn["listener_id"]]["name"]
spoken.append(
f"{side}{speaker['name']} (S{number}),声线与语气:{delivery},说:<d>[Chinese] {text}</d>。"
f"{listener}闭唇,{turn['listener_reaction']}。发言结束后{speaker['name']}自然闭唇。"
)
continue
spoken.append(
f"{speaker['name']} (S{number})"
+ f" with the following voice and delivery: {delivery}; {action}: <d>[{language}] {text}</d>"
@ -215,6 +287,7 @@ def compile_native_shots(manifest):
)
prompt = (
"integrated_multimodal_description: [Shot 1] "
+ ("固定双人中近景,两张脸持续同框,不切镜。\n" if duo else "")
+ visual
+ "\n"
+ "\n".join(spoken)
@ -231,8 +304,20 @@ def compile_native_shots(manifest):
"contract": "native-dialogue-v1",
"shot": {k: v for k, v in shot.items() if k != "edit"},
"context": spec.get("context"),
"scenes": spec.get("scenes"),
"entities": spec.get("entities"),
"scenes": (
[s for s in spec.get("scenes", []) if s["id"] == shot.get("scene_id")]
if spec["schema_version"] == 6
else spec.get("scenes")
),
"entities": (
sorted((
e
for e in spec.get("entities", [])
if e["id"] in {c["entity_id"] for c in shot.get("cast", [])}
), key=lambda entity: entity["id"])
if spec["schema_version"] == 6
else spec.get("entities")
),
"utterances": utterances,
"voices": [
{"id": key, "native_voice": speakers[key].get("native_voice")}
@ -247,7 +332,12 @@ def compile_native_shots(manifest):
dict(
shot_id=sid,
utterance_ids=allocations[sid],
speaker_id=next(iter(who), None),
speaker_id=None if duo else next(iter(who), None),
**(
dict(turns=turns, first_frame_sha256=perf.get("first_frame_sha256"))
if duo
else {}
),
parameters=params,
prompt=prompt,
context_hash=context,

View File

@ -0,0 +1,250 @@
"""从同源识别和双声道活动提取可复核的字幕边界。所有声音证据仍在 48k 素材坐标。"""
from collections import defaultdict
from itertools import groupby
from math import isfinite
import re
import unicodedata
from uuid import NAMESPACE_URL, uuid5
from app.domain.native_av import (
align_native_utterances,
normalize_native_text,
content_consensus,
source_audio_matches_video,
)
from app.domain.native_silence import MODEL_SHA256, POLICY, REVISION
VERSION = "native-rhythm-v1"
WINDOW = 1536 # Silero 每窗 512 个 16k 样本
PAUSE = 14400
SEMANTIC = re.compile(
r"[+-]?\d+(?:[.::/]\d+)*(?:%|%)?|"
r"[A-Za-z0-9]+(?:[-_./'’][A-Za-z0-9]+)*"
)
def display_text(source, punctuation):
if punctuation == "preserve":
return source
# 小数、时刻、型号、缩写中的符号保留;源文本中的正常空格也保留。
protected = {i for token in SEMANTIC.finditer(source) for i in range(*token.span())}
parts = []
skipped = False
for i, ch in enumerate(source):
if i not in protected and unicodedata.category(ch).startswith("P"):
skipped = True
continue
if skipped and parts and parts[-1].isalnum() and ch.isalnum():
if parts[-1].isascii() or ch.isascii():
parts.append(" ")
parts.append(ch)
skipped = False
return re.sub(" +", " ", "".join(parts)).strip(" ")
def stable_id(uid, start, end):
return uuid5(NAMESPACE_URL, f"cmvr:rhythm:{uid}:{start}:{end}").hex
def _activity(report):
vad = report.get("silence_verification")
count = report["source_end_sample"]
if type(count) is not int or count <= 0:
raise ValueError("原声音轨长度无效")
windows = (count + WINDOW - 1) // WINDOW
required = dict(
policy=POLICY,
revision=REVISION,
model_sha256=MODEL_SHA256,
status="completed",
source="silero-vad-onnx-cpu",
decision="speech",
source_audio_sha256=report["audio_sha256"],
source_start_sample=0,
source_end_sample=count,
sample_rate=16000,
sample_count=(count + 2) // 3,
window_size_samples=512,
window_count=windows,
channels=2,
threshold=0.5,
negative_threshold=0.35,
)
if (
not isinstance(vad, dict)
or not 1 <= windows <= 10000
or any(type(vad.get(k)) is not type(v) or vad[k] != v for k, v in required.items())
):
raise ValueError("缺少匹配原声的双声道语音窗")
channels = vad.get("channel_probabilities")
if (
not isinstance(channels, list)
or len(channels) != 2
or any(
not isinstance(c, list)
or len(c) != windows
or any(type(p) not in (int, float) or not isfinite(p) or not 0 <= p <= 1 for p in c)
for c in channels
)
):
raise ValueError("双声道逐窗概率无效")
pairs = list(zip(*channels, strict=True))
if vad.get("probabilities") != [max(pair) for pair in pairs]:
raise ValueError("逐窗概率与声道证据不符")
# 连续两窗强信号、双声道与周围弱信号共同支持边界;孤立峰保留为噪声候选。
spans = []
for active, group in groupby(enumerate(pairs), key=lambda v: min(v[1]) >= 0.35):
if not active:
continue
block = list(group)
if not any(
min(left[1]) >= 0.5 and min(right[1]) >= 0.5 for left, right in zip(block, block[1:])
):
continue
a, b = block[0][0] * WINDOW, min(count, (block[-1][0] + 1) * WINDOW)
if spans and a - spans[-1][1] < PAUSE:
spans[-1] = spans[-1][0], b
else:
spans.append((a, b))
if not spans:
raise ValueError("没有连续且两声道一致的语音活动")
return spans
def _source_ends(source, words):
# 标点归到前一个分句;跨词的发音稿改写或多对一字形只能确认为整句。
spoken = "".join(w["text"] for w in words)
normalized = normalize_native_text(source)
if normalize_native_text(spoken) != normalized:
return None
glyphs = [i for i, ch in enumerate(source) if normalize_native_text(ch)]
if len(glyphs) != len(normalized):
return None
glyphs.append(len(source))
cursor, ends = 0, []
for w in words:
cursor += len(normalize_native_text(w["text"]))
if cursor >= len(glyphs):
return None
ends.append(glyphs[cursor])
if not ends or ends[-1] != len(source):
return None
return ends
def _phrases(line, words, spans, pacing):
source = line["text"]
whole = [
(
0,
len(source),
spans[0][0],
spans[-1][1],
"automatic" if pacing == "sentence" else "sentence_fallback",
)
]
if pacing == "sentence" or len(spans) == 1:
return whole
ends = _source_ends(source, words)
if not ends:
return whole
word_groups = []
for word in words:
matches = [
i
for i, (a, b) in enumerate(spans)
if word["start_sample"] < b and a < word["end_sample"]
]
if len(matches) != 1:
return whole
word_groups.append(matches[0])
groups = [
(key, list(items)) for key, items in groupby(enumerate(word_groups), key=lambda t: t[1])
]
if [k for k, _ in groups] != list(range(len(spans))) or any(b - a < 12000 for a, b in spans):
return whole
output, start = [], 0
for key, items in groups:
end = ends[items[-1][0]]
if any(m.start() < end < m.end() for m in SEMANTIC.finditer(source)):
return whole
output.append((start, end, *spans[key], "automatic"))
start = end
return output
def measure_shot(sid, assigned, bindings, report, pacing, *, two_person=False):
audio = bindings.get("native_audio:" + sid) or {}
video = bindings.get("video:" + sid) or {}
evidence = (bindings.get("native_alignment:" + sid) or {}).get("provenance") or {}
sha = audio.get("sha256")
expected = "".join(u.get("spoken_text") or u["text"] for u in assigned)
required = dict(
native_av_policy="native_av_v1",
audio_sha256=sha,
sample_rate=48000,
source_start_sample=0,
source_end_sample=audio.get("sample_count"),
speaker_id=sid if two_person else assigned[0]["speaker_id"],
expected_text=expected,
decision="pass",
asr_revision="41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
word_alignment_status="completed",
)
matched_gate = (
evidence.get("video_sha256") == video.get("sha256")
and evidence.get("audio_sha256") == sha
and evidence.get("native_av_policy") == "native_av_v1"
and evidence.get("shot_id") == sid
)
if two_person:
# 整轨识别以镜头 ID 标识;说话人的归属来自已通过或已人工签认的逐轮验收。
gate_sha = (bindings.get("native_alignment:" + sid) or {}).get("sha256")
if (
not matched_gate
or not gate_sha
or gate_sha != (bindings.get("native_report:" + sid) or {}).get("sha256")
or evidence.get("turn_decision") not in {"pass", "manual"}
or not evidence.get("turn_report_asset_id")
or not evidence.get("turn_report_sha256")
or not evidence.get("turn_certificate_sha256")
):
raise ValueError("同框对白的逐轮身份、原声或候选版本尚未核对")
if (
not isinstance(report, dict)
or not sha
or not video.get("sha256")
or not (matched_gate or source_audio_matches_video(audio, video))
or any(report.get(k) != v for k, v in required.items())
or report.get("reasons")
or not content_consensus(report, expected)
):
raise ValueError("原声、完整台词或识别版本尚未核对")
aligned = align_native_utterances(report, assigned)
activity = _activity(report)
by_turn = defaultdict(list)
for a, b in activity:
hits = [u["utterance_id"] for u in aligned if u["start_sample"] < b and a < u["end_sample"]]
if len(hits) != 1:
raise ValueError("语音活动无法唯一分配给发言轮次")
by_turn[hits[0]].append((a, b))
result = {}
for line, aligned_line in zip(assigned, aligned, strict=True):
spans = by_turn[line["id"]]
words = aligned_line["words"]
if not spans or any(
w["end_sample"] > report["source_end_sample"]
or not any(w["start_sample"] < b and a < w["end_sample"] for a, b in spans)
for w in words
):
raise ValueError("部分台词缺少对应的发声证据")
result[line["id"]] = _phrases(line, words, spans, pacing)
offset = (audio.get("provenance") or {}).get("audio_offset_samples", 0)
if (
type(offset) is not int
or offset < 0
or (matched_gate and evidence.get("audio_offset_samples") != offset)
):
raise ValueError("原声偏移与选用镜头不符")
return result, offset

View File

@ -197,6 +197,10 @@ def parse_story_spec(raw):
if not isinstance(raw, dict):
raise ValueError("expected story object")
version = raw.get("schema_version", 3)
if version == 6:
from app.domain.dialogue import StorySpecV6
return StorySpecV6.model_validate(raw)
if version == 5:
from app.domain.dialogue import StorySpecV5
@ -324,7 +328,7 @@ def compile_story(spec, assets):
0,
"Use the following subject aliases to bind descriptions and spatial relations; do not draw these alias labels or numbers as text.",
)
if spec.schema_version in (4, 5):
if spec.schema_version in (4, 5, 6):
context = {k: v for k, v in shot.continuity.state_in.model_dump().items() if v}
if context:
state_prompt = "Initial state: " + json.dumps(
@ -345,7 +349,7 @@ def compile_story(spec, assets):
"references": refs,
"profile": spec.profile,
}
if spec.schema_version in (4, 5):
if spec.schema_version in (4, 5, 6):
continuity = shot.continuity.model_dump()
visual.update(schema_version=4, state_in=continuity["state_in"], prompt=prompt)
results.append(
@ -360,7 +364,7 @@ def compile_story(spec, assets):
"state_out": shot.continuity.state_out.model_dump(),
"continuity": continuity,
}
if spec.schema_version in (4, 5)
if spec.schema_version in (4, 5, 6)
else {}
),
"references": refs,

View File

@ -141,7 +141,7 @@ class TimelinePlan:
def ordered_step_keys(snapshot):
"""The frozen shot array is authoritative, including shot_10 and later."""
if snapshot.get("schema_version") in (3, 4, 5):
if snapshot.get("schema_version") in (3, 4, 5, 6):
return ["compose"]
return [shot["key"] for shot in snapshot["shots"]] + ["compose"]

View File

@ -19,6 +19,7 @@ class WorkflowDraft(Base):
name: Mapped[str] = mapped_column(String(255))
kind: Mapped[str] = mapped_column(String(48), default="three_shot")
spec: Mapped[dict] = mapped_column(JSON, default=dict)
caption_birth_intent: Mapped[dict | None] = mapped_column(JSON(none_as_null=True), nullable=True)
editor_manifest: Mapped[dict | None] = mapped_column(JSON, nullable=True)
revision: Mapped[int] = mapped_column(Integer, default=1)
version: Mapped[int] = mapped_column(Integer, default=1)

View File

@ -1,7 +1,7 @@
"""编辑结构验证独立于时间线可执行性,越界草稿必须可以保存。"""
from typing import Literal
from pydantic import Field, model_validator, field_validator
from pydantic import Field, model_validator, field_validator, model_serializer
from app.domain.timeline import Strict, Audio
from app.domain.stories import ID
from app.schemas.editor_audio import EditorAudioV2, EditorAudioV3
@ -117,6 +117,68 @@ class EditorManifestV3(EditorManifestV2):
captions: EditorCaptionsV3 = Field(default_factory=EditorCaptionsV3)
class CaptionPresentation(Strict):
punctuation: Literal["hide", "preserve"]
pacing: Literal["rhythm", "sentence"]
class CaptionEdit(Strict):
audio_sha256: str | None = Field(
default=None, pattern=r"^[0-9a-f]{64}$", exclude_if=lambda x: x is None
)
id: str = Field(pattern=ID)
utterance_id: str = Field(pattern=ID)
source_text: str = Field(min_length=1, max_length=2000)
source_start: int = Field(ge=0)
source_end: int = Field(gt=0)
deleted: bool = False
text_override: bool = False
timing_override: bool = False
text: str | None = Field(default=None, max_length=2000)
start_frame: int | None = None
end_frame: int | None = None
@model_validator(mode="after")
def valid_edit(self):
if not self.source_start < self.source_end <= len(self.source_text):
raise ValueError("字幕编辑的来源范围无效")
if not self.deleted and self.text_override and not (self.text or "").strip():
raise ValueError("请填写保护的字幕文字")
if (
not self.deleted
and self.timing_override
and (self.start_frame is None or self.end_frame is None)
):
raise ValueError("请填写保护的镜内起止帧")
return self
class EditorCaptionsV4(EditorCaptionsV3):
presentation: CaptionPresentation | None = None
edits: list[CaptionEdit] | None = Field(default=None, max_length=3000)
@model_validator(mode="after")
def check_extension(self):
if (self.presentation is None) != (self.edits is None):
raise ValueError("字幕策略与编辑记录必须一起提交")
if self.edits and len({e.id for e in self.edits}) != len(self.edits):
raise ValueError("字幕编辑 ID 重复")
return self
@model_serializer(mode="wrap")
def omit_absent(self, handler):
data = handler(self)
if self.presentation is None:
data.pop("presentation", None)
data.pop("edits", None)
return data
class EditorManifestV4(EditorManifestV3):
schema_version: Literal[4] = 4
captions: EditorCaptionsV4 = Field(default_factory=EditorCaptionsV4)
def parse_editor_manifest(raw):
if isinstance(raw, EditorManifest):
return raw
@ -129,12 +191,14 @@ def parse_editor_manifest(raw):
return EditorManifestV2.model_validate(raw)
if version == 3:
return EditorManifestV3.model_validate(raw)
if version == 4:
return EditorManifestV4.model_validate(raw)
raise ValueError("unsupported editor version")
class SaveEditor(Strict):
expected_version: int = Field(ge=1)
manifest: EditorManifest | EditorManifestV2 | EditorManifestV3
manifest: EditorManifest | EditorManifestV2 | EditorManifestV3 | EditorManifestV4
name: str | None = Field(default=None, min_length=1, max_length=255)
@field_validator("manifest", mode="before")
@ -160,7 +224,7 @@ class RestoreEditor(Strict):
class PlanEditor(Strict):
expected_version: int = Field(ge=1)
output_goal: Literal["media", "film"] = "film"
output_goal: Literal["media", "film", "caption_film", "caption_inspect", "mix_film"] = "film"
targets: list[str] = Field(default_factory=list, max_length=3002)
force: list[str] = Field(default_factory=list, max_length=3002)
execution_mode: Literal["interactive", "batch"] = "interactive"
@ -174,3 +238,28 @@ class StartEditor(PlanEditor):
class EditorMode(Strict):
expected_version: int = Field(ge=1)
mode: Literal["auto", "manual"]
class ForkSpeakerCuts(Strict):
expected_version: int = Field(ge=1)
shot_id: str = Field(pattern=ID)
confirm: bool = False
name: str | None = Field(default=None, min_length=1, max_length=120)
class ReviewTurns(Strict):
expected_version: int = Field(ge=1)
report_sha256: str = Field(pattern=r"^[0-9a-f]{64}$")
decision: Literal["accept"]
note: str = Field(min_length=1, max_length=1000)
class PreviewCaptions(Strict):
expected_version: int = Field(ge=1)
utterance_id: str | None = Field(default=None, pattern=ID)
manifest: EditorManifest | EditorManifestV2 | EditorManifestV3 | EditorManifestV4 | None = None
@field_validator("manifest", mode="before")
@classmethod
def parse_preview_version(cls, value):
return parse_editor_manifest(value) if value is not None else None

View File

@ -1,11 +1,12 @@
from typing import Literal
from pydantic import Field, field_validator
from app.schemas.editors import CaptionPresentation
from app.domain.timeline import Strict
from app.domain.stories import StorySpecV3, parse_story_spec
from app.domain.continuity import StorySpecV4
from app.domain.dialogue import StorySpecV5
from app.domain.dialogue import StorySpecV5, StorySpecV6
class StoryRequest(Strict):
@ -16,16 +17,18 @@ class StoryRequest(Strict):
class StoryCreate(StoryRequest):
captions_mode: Literal["none","manual","script","ai_script"] | None = None
caption_presentation: CaptionPresentation | None = None
create_folder: bool = True
folder_id: str | None = None
name: str = Field(min_length=1, max_length=255)
spec: StorySpecV3 | StorySpecV4 | StorySpecV5
spec: StorySpecV3 | StorySpecV4 | StorySpecV5 | StorySpecV6
class StoryPatch(StoryRequest):
folder_id: str | None = None
name: str | None = Field(default=None, min_length=1, max_length=255)
spec: StorySpecV3 | StorySpecV4 | StorySpecV5 | None = None
spec: StorySpecV3 | StorySpecV4 | StorySpecV5 | StorySpecV6 | None = None
class Version(Strict):

View File

@ -0,0 +1,114 @@
"""对选中镜头的已有净音轨重新做语音检查。这个计划仅能创建音频检查任务。"""
from copy import deepcopy
from app.adapters.provider.native_av import alignment_enabled
from app.core.errors import fail
from app.domain.continuity import compile_story_timing
from app.domain.native_av import source_audio_matches_video
from app.domain.stories import digest
from app.services.editor_media import assigned_utterance_ids
async def plan_source_inspection(session, draft, manifest, body, settings):
from app.services.orchestration.dialogue_engine import _recipe
from app.services.orchestration.editor_engine import _asset
from app.services.orchestration.native_dialogue_engine import _audio_review_context
body = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body
targets = body.get("targets", [])
if (
len(targets) != 1
or body.get("force")
or targets[0] not in {"native_report:" + sid for sid in manifest["shot_ids"]}
):
fail(422, "invalid_target", "仅分析已有原声时请选择一个镜头的语音报告")
target = targets[0]
sid = target.split(":", 1)[1]
issues, recipes, hashes = [], [], {}
spec = manifest["spec"]
dialogue = spec.get("dialogue", {})
bindings = manifest["bindings"]
video, audio = (bindings.get(prefix + sid) or {} for prefix in ("video:", "native_audio:"))
aligned_capability = alignment_enabled(settings, getattr(settings, "_native_av_upstream", {}))
def issue(code, message):
issues.append(dict(code=code, unit_id=sid, message=message))
if not dialogue.get("enabled") or dialogue.get("generation") != "native_av":
issue("native_source_required", "请选择已启用原生对白的镜头")
elif not source_audio_matches_video(audio, video):
issue("caption_audio_missing", "缺少与所选视频同源的 48 kHz 未混音对白,无法仅分析原声")
else:
for binding, kind in ((video, "video"), (audio, "audio")):
if not await _asset(session, draft.owner_id, binding, settings, kind):
issue("caption_source_changed", "已选原视频或净音轨不可访问或校验失败")
break
hashes[binding["asset_id"]] = binding["sha256"]
if (bindings.get(target) or {}).get("locked"):
issue("caption_report_locked", "语音报告已锁定,请先解除保护")
if not aligned_capability:
issue("caption_analysis_unavailable", "已有原声音频识别能力尚未就绪")
if not issues:
shot = next(s for s in spec["shots"] if s["id"] == sid)
sequences = {q["id"]: q for q in dialogue["sequences"]}
by_uid = {u["id"]: u for u in dialogue["utterances"]}
lines = [by_uid[uid] for uid in assigned_utterance_ids(shot, sequences)]
if (
not lines
or len({u["speaker_id"] for u in lines}) != 1
or shot["performance"].get("dialogue_staging") == "two_person_turns"
):
issue("caption_single_speaker_required", "请选择已分配单人台词的原声镜头")
else:
speaker = lines[0]["speaker_id"]
expected = "".join(u.get("spoken_text") or u["text"] for u in lines)
recipes.append(
_recipe(
"inspect_source",
"audio.dialogue.inspect",
sid,
target,
forced=True,
inputs=dict(expected_text=expected, speaker_id=speaker),
parameters=dict(
profile="dialogue-audio-v1",
sample_rate=48000,
native_av_policy="native_av_v1",
),
context=_audio_review_context(audio["sha256"], expected, speaker),
)
)
signature = digest(
dict(
operation="caption-source-inspect-v1",
manifest=manifest,
targets=targets,
recipe=recipes,
hashes=hashes,
issues=issues,
execution_mode=body.get("execution_mode", "interactive"),
output_folder_id=body.get("output_folder_id", draft.folder_id),
capable=aligned_capability,
)
)
return dict(
output_goal="caption_inspect",
source_version=draft.version,
plan_hash=signature,
steps=[dict(key=r["key"], kind=r["kind"], unit_id=sid, status="generate") for r in recipes],
issues=issues,
_recipes=recipes,
_capabilities=dict(reference_shas=hashes),
_prepared=dict(
production_materialized=True,
effective_manifest=deepcopy(manifest),
timing=compile_story_timing(spec),
utterances=[],
issues=[],
steps=[],
native_av_policy="native_av_v1",
)
if recipes
else None,
)

View File

@ -0,0 +1,333 @@
"""编辑预览读取作者草稿,下载和字幕返修只采用同一用户的冻结成片。"""
from copy import deepcopy
from sqlalchemy import select
from app.core.errors import fail
from app.domain.editors import validate_manifest
from app.domain.native_dialogue import enabled as native_enabled
from app.domain.rhythm_captions import VERSION as RHYTHM_VERSION
from app.domain.timeline import Subtitle
from app.models import Asset, WorkflowDraft, WorkflowRun, WorkflowStep
from app.services.auth import require_session_user
from app.services.snapshots import owned
from app.services.workflows import digest, verified_output
def encode_srt(rows):
def stamp(frame):
# 向下量化:例如第 1 帧的 PTS 为 41.667 ms,写 42 ms 会使逐帧播放晚亮一帧。
milliseconds = frame * 1000 // 24
seconds, ms = divmod(milliseconds, 1000)
minutes, second = divmod(seconds, 60)
hours, minute = divmod(minutes, 60)
return f"{hours:02}:{minute:02}:{second:02},{ms:03}"
entries = []
for index, value in enumerate(rows, 1):
row = Subtitle.model_validate(value)
entries.append(
f"{index}\n{stamp(row.start_frame)} --> {stamp(row.end_frame)}\n{row.text}\n"
)
return "\n".join(entries)
def frozen_rows(run, step):
if step is not None:
cues = (step.result_json or {}).get("cues")
if isinstance(cues, list):
return cues
# 逐步人工成片把最终送入合成器的字幕直接冻结在 render 中。
if run.run_kind == "legacy" and "render_inputs" in run.spec_snapshot:
cues = (run.spec_snapshot.get("render") or {}).get("subtitles")
if isinstance(cues, list):
return cues
return None
async def export_frozen(runtime, actor, draft_id, run_id):
async with runtime.db.session() as session:
await require_session_user(session, actor)
await owned(session, WorkflowDraft, draft_id, actor.id)
run = await owned(session, WorkflowRun, run_id, actor.id)
if run.draft_id != draft_id:
fail(404, "resource_not_found", "此运行不属于该故事")
if run.state != "succeeded" or run.output_goal != "film" or not run.current_output_asset_id:
fail(409, "caption_version_unavailable", "请选择已经完成的成片版本")
film = await owned(session, Asset, run.current_output_asset_id, actor.id)
if not film.ready or film.kind != "video" or film.library_scope != "private":
fail(409, "caption_version_unavailable", "该成片已不可用")
step = await session.scalar(
select(WorkflowStep).where(
WorkflowStep.run_id == run.id,
WorkflowStep.kind == "captions.compile",
WorkflowStep.state == "succeeded",
)
)
rows = frozen_rows(run, step)
if rows is None:
fail(409, "caption_version_unavailable", "这个历史版本没有可导出的冻结字幕")
return encode_srt(rows)
async def load_caption_reports(session, owner_id, manifest, settings, shot_ids=None):
"""旧版只把逐词净时间写入 binding,完整的 VAD 窗还在对应 JSON 资产中。"""
from app.services.orchestration.native_dialogue_engine import _read_report
reports = {}
bindings = manifest["bindings"]
for sid in manifest["shot_ids"] if shot_ids is None else shot_ids:
binding = bindings.get("native_report:" + sid)
if not binding:
continue
asset = await session.get(Asset, binding["asset_id"])
if (
not asset
or asset.owner_id != owner_id
or asset.deleted_at is not None
or not asset.ready
or asset.library_scope != "private"
or asset.kind != "json"
or asset.sha256 != binding.get("sha256")
or not await verified_output(asset, settings)
):
continue
report = _read_report(asset, settings)
audio_sha = bindings.get("native_audio:" + sid, {}).get("sha256")
if audio_sha and report.get("audio_sha256") == audio_sha:
reports[sid] = report
return reports
async def caption_projection(session, owner, m, settings, *, prepared=None, utterance_id=None):
from app.services.editor_media import preview_captions
options, shot_ids = {}, None
if utterance_id:
from app.services.editor_media import caption_shot_ids
shot_ids = caption_shot_ids(m, utterance_id)
options["utterance_id"] = utterance_id
reports = (
await load_caption_reports(session, owner, m, settings, shot_ids)
if (m["captions"].get("presentation") and m["captions"]["mode"] != "none")
else {}
)
return preview_captions(m, m["bindings"], reports=reports, prepared=prepared, **options)
async def preview(runtime, actor, draft_id, body):
from app.services.editors import check_version, load_manifest
async with runtime.db.session() as session:
await require_session_user(session, actor)
draft = await owned(session, WorkflowDraft, draft_id, actor.id)
check_version(draft, body.expected_version)
saved = await load_manifest(session, draft)
m = deepcopy(saved)
if body.manifest is not None:
candidate = body.manifest.model_dump(mode="json")
# 预览只能试改作者字幕。词时证据、选择的原声和人脸验收始终取服务端版本。
m["schema_version"] = candidate["schema_version"]
m["captions"] = candidate["captions"]
m = validate_manifest(m)
if candidate["shot_ids"] != saved["shot_ids"] or media_signature(
validate_manifest(candidate)
) != media_signature(validate_manifest(saved)):
fail(
409, "caption_sources_changed", "音画来源已改变,请先保存镜头和对白,再预览字幕"
)
result = await caption_projection(
session, actor.id, m, runtime.settings, utterance_id=body.utterance_id
)
return {**result, "version": draft.version, "fps": 24}
def media_signature(m):
"""签入作者音画意图、选用媒体和音频时基,排除字幕显示及编辑器版本。"""
spec = deepcopy(m["spec"])
render = spec.get("render", {})
for key in ("audio", "subtitles", "total_frames"):
render.pop(key, None)
dialogue = spec.get("dialogue", {})
for key in ("speakers", "utterances", "sequences"):
if key in dialogue:
dialogue[key] = sorted(dialogue[key], key=lambda row: row["id"])
inputs = {}
for name, binding in m["bindings"].items():
# 同一原声可以重新对齐;更新识别报告只影响字幕,原来的混音仍可复用。
if name.partition(":")[0] in {"frame", "video", "native_audio"}:
inputs[name] = {k: binding.get(k) for k in ("asset_id", "sha256", "context_hash")}
if name.startswith("native_audio:"):
inputs[name]["offset"] = (binding.get("provenance") or {}).get(
"audio_offset_samples", 0
)
inputs[name]["sample_count"] = binding.get("sample_count")
return digest(
{"shot_ids": m["shot_ids"], "spec": spec, "audio": m["audio"], "bindings": inputs}
)
async def plan_caption_film(session, draft, m, body, settings):
from app.domain.editors import collect_manifest_asset_ids
from app.services.orchestration.dialogue_engine import _recipe
from app.services.orchestration.editor_engine import _asset
data = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body
if data.get("targets") or data.get("force"):
fail(422, "invalid_target", "仅字幕返修不接受生成或强制重算目标")
issues, recipes, hashes = [], [], {}
prepared = {}
def issue(code, message):
issues.append(dict(code=code, unit_id="captions", message=message))
films = select(WorkflowRun.id).where(
WorkflowRun.draft_id == draft.id,
WorkflowRun.owner_id == draft.owner_id,
WorkflowRun.deleted_at.is_(None),
WorkflowRun.state == "succeeded",
WorkflowRun.output_goal == "film",
WorkflowRun.current_output_asset_id.is_not(None),
)
# 从历史成片恢复再编辑时,优先沿用显式恢复的那一版。纯素材运行没有成片混音。
base_id = None
for candidate in dict.fromkeys([m.get("base_run_id"), draft.current_run_id]):
if candidate and await session.scalar(films.where(WorkflowRun.id == candidate)):
base_id = candidate
break
if base_id is None:
base_id = await session.scalar(
films.order_by(WorkflowRun.created_at.desc(), WorkflowRun.id.desc()).limit(1)
)
base = await session.get(WorkflowRun, base_id) if base_id else None
if (
not native_enabled(m)
or not base
or not base.result_manifest
or not (base.prepared_plan or {}).get("timing")
):
issue(
"caption_source_unavailable", "此故事尚无可复用的历史成片混音。已有原片和净音轨可选“重新混音并成片”,也可先预览字幕"
)
elif media_signature(validate_manifest(base.result_manifest)) != media_signature(
validate_manifest(m)
):
if media_signature(
{**validate_manifest(m), "audio": base.result_manifest["audio"]}
) == media_signature(validate_manifest(base.result_manifest)):
issue("caption_mix_unavailable", "配乐或增益已改变,请使用“重新混音并成片”一并更新字幕")
else:
issue("caption_sources_changed", "选用的镜头或对白已改变,请先核对当前原片与原声")
else:
mix_step = await session.scalar(
select(WorkflowStep).where(
WorkflowStep.run_id == base.id,
WorkflowStep.step_key == "dialogue_mix",
WorkflowStep.state == "succeeded",
)
)
mix = (mix_step.result_json if mix_step else None) or {}
timing = base.prepared_plan["timing"]
if (
not mix.get("track")
or mix.get("sample_count") != timing["total_frames"] * 2000
or mix.get("mix_version", "audio-mix-v2") != "audio-mix-v2"
or not await _asset(session, draft.owner_id, mix, settings, "audio")
):
issue("caption_mix_unavailable", "原成片的混音缺失或已变化,请先重新混音")
else:
for aid in collect_manifest_asset_ids(m) | {mix["asset_id"]}:
asset = await session.get(Asset, aid)
if (
not asset
or asset.owner_id != draft.owner_id
or not asset.ready
or asset.deleted_at
or asset.library_scope != "private"
):
issue("caption_source_unavailable", "选用的成片来源素材已不存在或不可访问")
break
hashes[aid] = asset.sha256
for sid in m["shot_ids"]:
video = m["bindings"].get("video:" + sid, {})
if not video or not await _asset(session, draft.owner_id, video, settings, "video"):
issue("caption_source_unavailable", "缺少可重烧字幕的原始镜头视频")
break
if not issues:
prepared = dict(
production_materialized=True,
effective_manifest=deepcopy(m),
timing=deepcopy(timing),
utterances=deepcopy(base.prepared_plan.get("utterances", [])),
issues=[],
steps=[],
native_av_policy="native_av_v1",
)
projection = await caption_projection(
session, draft.owner_id, m, settings, prepared=prepared
)
issues.extend(projection["issues"])
if not issues:
recipes = [
_recipe("dialogue_mix", "audio.mix", "audio", reuse=mix),
frozen_caption_recipe(projection),
_recipe(
"compose",
"video.compose",
"film",
dependencies=["dialogue_mix", "dialogue_captions"],
),
]
signature = digest(
dict(
operation="caption_film_v1",
algorithm=RHYTHM_VERSION,
source=base.id if base else None,
manifest=m,
body={k: v for k, v in data.items() if k != "expected_plan_hash"},
recipes=recipes,
assets=hashes,
issues=issues,
)
)
return revision_plan(draft, recipes, hashes, issues, prepared, signature)
def frozen_caption_recipe(projection):
from app.services.editor_media import rendered_cues
from app.services.orchestration.dialogue_engine import _recipe
return _recipe(
"dialogue_captions",
"captions.compile",
"captions",
reuse={
"cues": rendered_cues(projection),
"display_rows": projection["rows"],
"caption_projection": digest({"algorithm": RHYTHM_VERSION, "rows": projection["rows"]}),
},
)
def revision_plan(draft, recipes, hashes, issues, prepared, signature):
steps = [
dict(
key=r["key"],
unit_id=r["unit_id"],
kind=r["kind"],
status="reuse" if r["reuse"] else "generate",
)
for r in recipes
]
return dict(
output_goal="film",
source_version=draft.version,
steps=steps,
issues=issues,
plan_hash=signature,
_recipes=recipes,
_capabilities={"reference_shas": hashes},
_prepared=prepared,
)

View File

@ -10,6 +10,7 @@ from app.services.snapshots import owned
async def enable_dialogue(runtime, actor, draft_id, body, key):
from app.core.errors import fail
from app.domain.dialogue import upgrade_dialogue_manifest
from app.domain.editors import apply_birth_captions
from app.services.editors import check_version, dto, load_manifest, write_manifest
from app.services.editor_modes import assert_idle
@ -32,13 +33,16 @@ async def enable_dialogue(runtime, actor, draft_id, body, key):
fail(422, "dialogue_story_required", "对白模式仅适用于故事")
await assert_idle(session, draft)
manifest = await load_manifest(session, draft)
if manifest.get("schema_version") != 3 or not draft.editor_manifest:
changed = False
if manifest.get("schema_version") not in (3, 4) or not draft.editor_manifest:
manifest = upgrade_dialogue_manifest(manifest)
manifest["editing_mode"] = "auto"
await write_manifest(session, draft, manifest, runtime.settings)
changed = True
elif manifest.get("spec", {}).get("dialogue", {}).get("generation") != "native_av":
# 历史已冻结运行保持原图;只有显式启用命令升级作者草稿。
manifest["spec"]["dialogue"].update(generation="native_av", language="Chinese")
changed = True
if apply_birth_captions(draft, manifest) or changed:
await write_manifest(session, draft, manifest, runtime.settings)
receipt.resource_json = {"draft_id": draft.id}
result = await dto(session, draft)
@ -84,7 +88,7 @@ async def apply_pending_result(db, run_id, settings):
or run.apply_state != "pending"
or run.state != "succeeded"
or run.desired_state == "cancel"
or run.spec_snapshot.get("schema_version") != 5
or run.spec_snapshot.get("schema_version") not in (5, 6)
):
return False
result = await apply_run_result(session, run, settings)
@ -117,7 +121,7 @@ async def fork_prepared(runtime, actor, draft_id, body, key):
source = await owned(session, WorkflowDraft, draft_id, actor.id)
check_version(source, body.expected_version)
run = await owned(session, WorkflowRun, body.run_id, actor.id)
if run.draft_id != draft_id or run.spec_snapshot.get("schema_version") != 5:
if run.draft_id != draft_id or run.spec_snapshot.get("schema_version") not in (5, 6):
fail(404, "resource_not_found", "准备结果不属于此故事")
if (
not run.prepared_plan

View File

@ -0,0 +1,193 @@
"""预览同框转切镜,确认后以独立故事保存,原候选仍归原故事。"""
from copy import deepcopy
from uuid import NAMESPACE_URL, uuid5
from app.core.errors import fail
from app.core.maintenance import require_writable
from app.domain.dialogue import speech_stem_id
from app.domain.native_dialogue import compile_native_shots
from app.models import WorkflowDraft
from app.services.auth import require_session_user
from app.services.editors import check_version, dto, load_manifest, write_manifest
from app.services.snapshots import owned
from app.services.submissions import accept_submission, request_payload
def project_cuts(manifest, shot_id, name):
m = deepcopy(manifest)
spec = m["spec"]
if spec.get("schema_version") != 6 or shot_id not in m["shot_ids"]:
fail(422, "invalid_turn_shot", "请选择同框双人镜头")
index = m["shot_ids"].index(shot_id)
original = spec["shots"][index]
perf = original["performance"]
ids = perf.get("native_utterance_ids") or []
all_lines = {u["id"]: u for u in spec["dialogue"]["utterances"]}
roles = {s["id"]: s for s in spec["dialogue"]["speakers"]}
lines = [all_lines[uid] for uid in ids if uid in all_lines]
if (
perf.get("dialogue_staging") != "two_person_turns"
or len(lines) != 2
or len({u["speaker_id"] for u in lines}) != 2
or len(ids) != 2
):
fail(422, "invalid_turn_shot", "需要两位角色按顺序各说一句,才能预览切镜")
sequence = next(
(
s
for s in spec["dialogue"]["sequences"]
if s["id"] == perf.get("sequence_id") and shot_id in s["shot_ids"]
),
None,
)
if not sequence or any(uid not in sequence["utterance_ids"] for uid in ids):
fail(422, "invalid_turn_shot", "台词不属于镜头段落")
warnings = [
"副本需要为两位角色各生成一张单人首帧和一段原声视频,重做本镜对白检查及后续混音、成片。"
]
locks = ["structure_locked"] if perf.get("structure_locked") else []
old_entities = {e["id"]: e for e in spec["entities"]}
# 保留第一镜的稳定编号,使旧的镜头局部锚仍可回看、核对;台词锚继续引用原始台词 ID。
new_id = uuid5(NAMESPACE_URL, f"cmvr:cut:{shot_id}:{ids[1]}").hex
if new_id in m["shot_ids"]:
fail(409, "cut_id_conflict", "副本中已存在同一次切镜的镜头编号")
new_shots = []
for i, line in enumerate(lines):
role = roles[line["speaker_id"]]
s = deepcopy(original)
s["id"] = shot_id if i == 0 else new_id
s["name"] = f"{original.get('name') or '对白'} · {role['name']}"
s["cast"] = [
c
for c in s["cast"]
if c["entity_id"] == role["entity_id"]
or old_entities[c["entity_id"]]["kind"] != "person"
]
if not any(c["entity_id"] == role["entity_id"] for c in s["cast"]):
fail(422, "invalid_turn_cast", "说话人须出现在原镜演员表中")
for c in s["cast"]:
if i:
c["id"] = uuid5(NAMESPACE_URL, f"cmvr:cut-cast:{new_id}:{c['id']}").hex
if c["entity_id"] == role["entity_id"]:
c["position"] = "画面中央"
s["visual_prompt"] = (
f"沿用本场景的地点、布光和服饰;{role['name']}的单人中近景,清晰呈现正面或四分之三侧脸。"
)
s["motion_prompt"] = (
f"{role['name']}面向画外对手自然说出本句,收声后闭唇,保持眼神和轻微反应。"
)
s["performance"] = {
k: v
for k, v in perf.items()
if k not in ("dialogue_staging", "first_frame_sha256", "listener_reactions")
}
s["performance"].update(
visible_speaker_ids=[role["id"]],
native_utterance_ids=[line["id"]],
lip_sync="auto",
duration_mode="auto",
)
s["continuity"].update(transition="cut", endpoint_mode="first_frame")
s["edit"].update(start_frame=0, dedup_frames=0)
new_shots.append(s)
second_index = sequence["shot_ids"].index(shot_id) + 1
sequence["shot_ids"].insert(second_index, new_id)
m["shot_ids"].insert(index + 1, new_id)
spec["shots"][index : index + 1] = new_shots
affected = {shot_id, *(speech_stem_id(shot_id, line["speaker_id"]) for line in lines)}
next_join = (
"join_anchor:" + m["shot_ids"][index + 2] if index + 2 < len(m["shot_ids"]) else None
)
for key, binding in list(m["bindings"].items()):
if key.partition(":")[2] in affected or key == next_join:
if binding.get("locked"):
locks.append(key)
del m["bindings"][key]
if locks:
warnings.append("受保护的镜头结构或选片会被替换,请先核对并解除对应锁:" + "、".join(locks))
for cue in m["captions"]["cues"]:
if cue.get("shot_id") == shot_id:
warnings.append(f"字幕 {cue['id']} 保留在第一镜原局部帧,请复核是否应移到第二镜。")
if any(c.get("anchor") == "absolute" for c in m["captions"]["cues"]):
warnings.append("全片绝对锚字幕保留原帧位,请随新时长复核。")
if any(
r.get("utterance_id") in ids and r.get("timing_override")
for r in m["captions"].get("edits", [])
):
warnings.append("两句台词的锁时记录均已保留,请在获得新原声后复核。")
if any(a.get("shot_id") == shot_id for a in [*m["audio"]["segments"], *m["audio"]["layers"]]):
warnings.append("原镜头锚定的音频段或配乐仍锚定第一镜,请复核覆盖区间。")
m["base_run_id"] = None
projection = compile_native_shots(m)
derived = {r["shot_id"]: r for r in projection["shots"]}
shots = []
for shot, line in zip(new_shots, lines, strict=True):
frames = derived[shot["id"]]["parameters"]["num_frames"]
shot["edit"]["duration_frames"] = frames
shots.append(
dict(
speaker_id=line["speaker_id"],
speaker_name=roles[line["speaker_id"]]["name"],
text=line["text"],
duration_frames=frames,
)
)
spec["render"]["total_frames"] = sum(
s["edit"]["duration_frames"] - s["edit"].get("dedup_frames", 0) for s in spec["shots"]
)
warnings.extend(
i["message"] for i in projection["issues"] if i["unit_id"] in {shot_id, new_id, *ids}
)
if len(m["shot_ids"]) > min(60, m.get("production", {}).get("max_shots", 60)):
warnings.append("新增镜头后已超过整片制作镜数上限,需调整制作计划。")
return m, dict(shots=shots, warnings=list(dict.fromkeys(warnings)), name=name), locks
async def fork_cuts(runtime, actor, draft_id, body, key):
if body.confirm:
require_writable(runtime.settings)
async with runtime.db.session() as session:
await require_session_user(session, actor)
source = await owned(session, WorkflowDraft, draft_id, actor.id)
if body.confirm:
receipt = await accept_submission(
session,
actor.id,
"editor.dialogue.fork_cuts",
key,
1,
dict(draft_id=draft_id, **request_payload(body)),
)
if receipt.resource_json:
target = await owned(
session, WorkflowDraft, receipt.resource_json["draft_id"], actor.id
)
return await dto(session, target)
check_version(source, body.expected_version)
if source.kind != "story_v3":
fail(422, "invalid_turn_shot", "切镜副本仅适用于故事")
name = (body.name or (source.name[:110] + " · 切镜版")).strip()
if not name:
fail(422, "name_required", "请输入副本名称")
projected, preview, locks = project_cuts(
await load_manifest(session, source), body.shot_id, name
)
if not body.confirm:
return preview
if locks:
fail(409, "cut_dependency_locked", preview["warnings"][1])
target = WorkflowDraft(
owner_id=actor.id,
name=name,
kind=source.kind,
folder_id=source.folder_id,
spec=deepcopy(projected["spec"]),
)
session.add(target)
await session.flush()
await write_manifest(session, target, projected, runtime.settings)
receipt.resource_json = dict(draft_id=target.id)
result = await dto(session, target)
await session.commit()
return result

View File

@ -120,21 +120,35 @@ def _dialogue_projection(manifest, bindings, prepared, *, allow_pending):
return manifest, {}
if prepared is None:
from app.domain.native_dialogue import enabled as native_enabled, compile_native_shots
if native_enabled(manifest):
native = compile_native_shots(manifest)
actual = []
for shot, timing in zip(native["shots"], native["timing"]["shots"], strict=True):
evidence = bindings.get("native_alignment:" + shot["shot_id"], {}).get("provenance", {})
evidence = bindings.get("native_alignment:" + shot["shot_id"], {}).get(
"provenance", {}
)
video = bindings.get("video:" + shot["shot_id"], {})
audio = bindings.get("native_audio:" + shot["shot_id"], {})
if evidence.get("native_av_policy") != "native_av_v1" or evidence.get("video_sha256") != video.get("sha256") or evidence.get("audio_sha256") != audio.get("sha256"):
if (
evidence.get("native_av_policy") != "native_av_v1"
or evidence.get("video_sha256") != video.get("sha256")
or evidence.get("audio_sha256") != audio.get("sha256")
):
if allow_pending:
return manifest, {}
raise ValueError("原生对白逐词验收尚未就绪,无法确定字幕时间")
actual.extend({**u, "start_sample": u["start_sample"] + timing["start_frame"] * 2000,
"end_sample": u["end_sample"] + timing["start_frame"] * 2000}
for u in evidence.get("utterances", []))
prepared = dict(effective_manifest=native["manifest"], utterances=actual, issues=native["issues"])
actual.extend(
{
**u,
"start_sample": u["start_sample"] + timing["start_frame"] * 2000,
"end_sample": u["end_sample"] + timing["start_frame"] * 2000,
}
for u in evidence.get("utterances", [])
)
prepared = dict(
effective_manifest=native["manifest"], utterances=actual, issues=native["issues"]
)
manifest = native["manifest"]
if prepared is None:
# 某一段未测时,后续段落绝对起点也未确定;草稿保留作者覆盖,成片明确阻塞。
@ -241,7 +255,13 @@ def _materialize_cues(manifest, bindings, utterance_ranges):
return cues
def compile_captions(manifest, bindings, *, prepared=None):
def captions_manual(cue):
return cue.get("anchor") not in {"utterance", "audio_segment"} or (
cue.get("text_override") or cue.get("timing_override")
)
def _legacy_rows(manifest, bindings, *, prepared=None, limit_count=True):
if manifest.get("captions", {}).get("mode", "none") == "none":
return []
manifest, utterance_ranges = _dialogue_projection(
@ -279,7 +299,84 @@ def compile_captions(manifest, bindings, *, prepared=None):
row = Subtitle(start_frame=offset + a, end_frame=offset + b, text=cue["text"])
except ValueError as exc:
raise ValueError("字幕文字为空或含不支持的控制字符") from exc
output.append(row.model_dump())
if len(output) > 1000:
sid = cue.get("shot_id") or next(
(sid for sid, (left, right) in shots.items() if left <= offset + a < right), None
)
shot_start = shots[sid][0] if sid else 0
output.append(
dict(
**row.model_dump(),
id=cue["id"],
utterance_id=cue.get("utterance_id"),
turn_id=cue.get("utterance_id"),
shot_id=sid,
source_text=cue["text"],
source_start=0,
source_end=len(cue["text"]),
local_start_frame=offset + a - shot_start,
local_end_frame=offset + b - shot_start,
text_override=cue.get("text_override", False),
timing_override=cue.get("timing_override", False),
status="manual" if captions_manual(cue) else "automatic",
algorithm_version="legacy",
)
)
if limit_count and len(output) > 1000:
raise ValueError("字幕数量超过1000条")
return sorted(output, key=lambda row: (row["start_frame"], row["end_frame"]))
def assigned_utterance_ids(shot, sequences):
perf = shot.get("performance") or {}
ids = perf.get("native_utterance_ids")
if ids is not None:
return ids
seq = sequences.get(perf.get("sequence_id"), {})
return seq.get("utterance_ids", []) if len(seq.get("shot_ids", [])) == 1 else []
def caption_shot_ids(manifest, utterance_id):
spec = manifest["spec"]
sequences = {s["id"]: s for s in spec.get("dialogue", {}).get("sequences", [])}
return {
shot["id"]
for shot in spec["shots"]
if utterance_id in assigned_utterance_ids(shot, sequences)
}
def preview_captions(manifest, bindings, *, reports=None, prepared=None, utterance_id=None):
"""所有使用者读取同一份按全片帧排序的显示表;草稿保留待校时行。"""
captions = manifest.get("captions", {})
if captions.get("mode", "none") == "none":
return dict(rows=[], issues=[])
if captions.get("presentation"):
from app.services.rhythm_projection import project_captions
return project_captions(
manifest, bindings, reports or {}, prepared, utterance_id=utterance_id
)
try:
rows = _legacy_rows(manifest, bindings, prepared=prepared)
if utterance_id is not None:
rows = [r for r in rows if r["utterance_id"] == utterance_id]
return dict(rows=rows, issues=[])
except ValueError as exc:
return dict(
rows=[],
issues=[dict(code="caption_timing_pending", unit_id="captions", message=str(exc))],
)
def compile_captions(manifest, bindings, *, prepared=None, reports=None):
result = preview_captions(manifest, bindings, reports=reports, prepared=prepared)
return rendered_cues(result)
def rendered_cues(result):
if result["issues"]:
issue = result["issues"][0]
raise ValueError(f"{issue['message']}({issue['unit_id']})")
return [
{key: row[key] for key in ("start_frame", "end_frame", "text")} for row in result["rows"]
]

View File

@ -10,14 +10,14 @@ from app.core.errors import fail
def require_auto(d):
if d.editor_manifest and not is_editor_auto(d) and d.spec.get("schema_version") != 5:
if d.editor_manifest and not is_editor_auto(d) and d.spec.get("schema_version") not in (5, 6):
fail(409, "editor_mode_conflict", "当前为逐步骤确认,请先切换为自动成片")
def manual_spec(d, strict=False):
if d.spec.get("schema_version") == 5 and strict:
if d.spec.get("schema_version") in (5, 6) and strict:
fail(409, "dialogue_editor_required", "请使用对白编辑器的成片步骤")
if not d.editor_manifest or is_editor_auto(d) or d.spec.get("schema_version") == 5:
if not d.editor_manifest or is_editor_auto(d) or d.spec.get("schema_version") in (5, 6):
return deepcopy(d.spec)
m = d.editor_manifest
raw = deepcopy(m["spec"])
@ -219,7 +219,7 @@ async def sync_manual_patch(s, d, new_spec):
from app.services.editors import sync_editor_refs
m = deepcopy(d.editor_manifest)
if m["schema_version"] == 3 and new_spec.get("schema_version") != 5:
if m["schema_version"] in (3, 4) and new_spec.get("schema_version") not in (5, 6):
fail(409, "dialogue_editor_required", "请使用支持对白版本的编辑器")
baseline = manual_spec(d)
render = new_spec.get("render", {})
@ -227,6 +227,8 @@ async def sync_manual_patch(s, d, new_spec):
m["audio"]["track"] = deepcopy(render.get("audio"))
m["audio"]["mode"] = "manual_track" if render.get("audio") else "silent"
if render.get("subtitles", []) != baseline.get("render", {}).get("subtitles", []):
if m["captions"].get("presentation"):
fail(409, "caption_editor_required", "请在成片页修改节奏字幕,以保留分段和人工锁定")
m["captions"]["mode"] = "manual" if render.get("subtitles") else "none"
# 对投影里没有改变的字幕保留稳定ID、锚点及人工override;只转换确实改动的条目。
from app.services.editor_media import compile_captions
@ -290,10 +292,10 @@ async def sync_manual_patch(s, d, new_spec):
if not k.startswith(("frame:", "video:", "end_frame:", "join_anchor:"))
or k.split(":", 1)[1] in ids
}
for sid in ids if m["schema_version"] != 3 else []:
for sid in ids if m["schema_version"] not in (3, 4) else []:
if not any(x.get("shot_id") == sid for x in m["audio"]["segments"]):
m["audio"]["segments"].append(dict(id=uuid.uuid4().hex, shot_id=sid, text=""))
if m["schema_version"] == 3:
if m["schema_version"] in (3, 4):
from app.services.editors import sanitize_dialogue_bindings
lines = {u["id"] for u in m["spec"]["dialogue"]["utterances"]}
@ -332,7 +334,7 @@ async def sync_manual_selection(s, d, row, asset, candidate=None):
m["bindings"][key] = b
else:
m["bindings"].pop(key, None)
if m["schema_version"] == 3:
if m["schema_version"] in (3, 4):
from app.services.editors import sanitize_dialogue_bindings
sanitize_dialogue_bindings(m, d.editor_manifest)

View File

@ -54,7 +54,7 @@ async def sync_editor_refs(session, draft, manifest):
def image_refs(value):
if isinstance(value, dict):
for key, item in value.items():
if key == "image_asset_id" and item:
if key in {"image_asset_id", "face_reference_asset_id"} and item:
yield item
elif key == "reference_asset_ids":
yield from item
@ -74,6 +74,7 @@ async def sync_editor_refs(session, draft, manifest):
fail(422, "wrong_asset_kind", "背景音乐和音效需要音频素材")
dialogue = manifest["spec"].get("dialogue", {})
speech_ids = {sp["voice"].get("reference_asset_id") for sp in dialogue.get("speakers", [])}
speech_ids.update(sp.get("voice_reference_asset_id") for sp in dialogue.get("speakers", []))
speech_ids.update(u.get("asset_id") for u in dialogue.get("utterances", []))
if any(assets[aid].kind != "audio" for aid in speech_ids - {None}):
fail(422, "wrong_asset_kind", "对白录音和参考音色必须是音频素材")
@ -168,7 +169,7 @@ def check_version(draft, version):
async def write_manifest(session, draft, manifest, settings=None):
if draft.spec.get("schema_version") == 5 and manifest.get("schema_version") != 3:
if draft.spec.get("schema_version") in (5, 6) and manifest.get("schema_version") not in (3, 4):
fail(409, "dialogue_editor_required", "请使用支持对白的编辑器保存")
m = validate_manifest(manifest)
if settings:
@ -268,14 +269,33 @@ def sanitize_dialogue_bindings(manifest, old):
old_shots = {s["id"]: s for s in old["spec"]["shots"]}
d = spec.get("dialogue", {})
old_d = old["spec"].get("dialogue", {})
def native_context(dialogue, shot):
seq = next((q for q in dialogue.get("sequences", []) if q["id"] == shot.get("performance", {}).get("sequence_id")), {})
performance = shot.get("performance") or {}
seq = next(
(q for q in dialogue.get("sequences", []) if q["id"] == performance.get("sequence_id")),
{},
)
utterances = {u["id"]: u for u in dialogue.get("utterances", [])}
ordered = [utterances[uid] for uid in seq.get("utterance_ids", []) if uid in utterances]
talkers = {u["speaker_id"] for u in ordered}
return dict(generation=dialogue.get("generation"), language=dialogue.get("language"),
sequence=seq, utterances=ordered,
speakers=[sp for sp in dialogue.get("speakers", []) if sp["id"] in talkers],shot=shot)
ids = performance.get("native_utterance_ids")
inferred_sequence = None
if ids is None:
# 旧多镜段落可能早于逐镜台词分配。依赖不明确时沿用整段失效规则。
ids = seq.get("utterance_ids", [])
inferred_sequence = seq
ordered = [utterances[uid] for uid in ids if uid in utterances]
talkers = {u["speaker_id"] for u in ordered} | set(
performance.get("visible_speaker_ids", [])
)
speakers = {sp["id"]: sp for sp in dialogue.get("speakers", []) if sp["id"] in talkers}
return dict(
generation=dialogue.get("generation"),
language=dialogue.get("language"),
utterances=ordered,
speakers=speakers,
inferred_sequence=inferred_sequence,
shot=shot,
)
line_maps = [{u["id"]: u for u in x.get("utterances", [])} for x in (d, old_d)]
old_seqs = {q["id"]: q for q in old_d.get("sequences", [])}
dirty_sequences = set()
@ -353,7 +373,7 @@ def sanitize_dialogue_bindings(manifest, old):
def sanitize_bindings(manifest, old):
if manifest.get("schema_version") == 3:
if manifest.get("schema_version") in (3, 4):
sanitize_dialogue_bindings(manifest, old)
if manifest.get("schema_version") == 2:
for key, binding in list(manifest["bindings"].items()):
@ -366,7 +386,7 @@ def sanitize_bindings(manifest, old):
fail(422, "derived_binding_readonly", "实际接续锚点只能由服务端从选用视频生成")
invalidate_join_anchors(manifest, old)
for key, b in manifest["bindings"].items():
if manifest.get("schema_version") == 3 and key.partition(":")[0] in DIALOGUE_DERIVED:
if manifest.get("schema_version") in (3, 4) and key.partition(":")[0] in DIALOGUE_DERIVED:
continue
previous = old.get("bindings", {}).get(key, {})
if previous.get("asset_id") == b["asset_id"] and previous.get("sha256") == b["sha256"]:
@ -396,7 +416,7 @@ async def run_manifest(session, run):
return {**deepcopy(run.plan_snapshot["manifest"]), "base_run_id": run.id}
source = SimpleNamespace(
id=run.draft_id,
kind="story_v3" if run.spec_snapshot.get("schema_version") in (3, 4, 5) else "three_shot",
kind="story_v3" if run.spec_snapshot.get("schema_version") in (3, 4, 5, 6) else "three_shot",
spec=run.spec_snapshot,
editor_manifest=None,
)
@ -452,7 +472,7 @@ async def apply_run_result(session, run, settings):
.with_for_update()
)
dialogue_run = run.spec_snapshot.get("schema_version") == 5
dialogue_run = run.spec_snapshot.get("schema_version") in (5, 6)
expected_mode = (run.plan_snapshot or {}).get("manifest", {}).get("editing_mode")
if (
not owner
@ -501,7 +521,14 @@ async def command(runtime, actor, draft_id, body, key, operation):
await assert_idle(s, d)
if operation == "editor.save":
m = body.manifest.model_dump(mode="json")
expected_mode = editing_mode(d) if d.spec.get("schema_version") == 5 else "auto"
previous = d.editor_manifest or {}
if previous.get("schema_version") == 4 and (
m["schema_version"] != 4
or m["spec"]["schema_version"] < d.spec["schema_version"]
or previous["captions"].get("presentation") and not m["captions"].get("presentation")
):
fail(409, "editor_upgrade_required", "此草稿已使用新版字幕或同框对白,请刷新编辑器后保存")
expected_mode = editing_mode(d) if d.spec.get("schema_version") in (5, 6) else "auto"
if m["editing_mode"] != expected_mode:
fail(409, "editor_mode_conflict", "编辑模式只能通过切换命令修改")
m["editing_mode"] = expected_mode
@ -523,12 +550,12 @@ async def command(runtime, actor, draft_id, body, key, operation):
if r.output_goal == "film" and r.state == "succeeded" and r.current_output_asset_id:
d.current_run_id = r.id
restored = await run_manifest(s, r)
if d.spec.get("schema_version") == 5 and restored.get("schema_version") != 3:
if d.spec.get("schema_version") in (5, 6) and restored.get("schema_version") not in (3, 4):
from app.domain.dialogue import upgrade_dialogue_manifest
restored = upgrade_dialogue_manifest(restored)
restored["editing_mode"] = (
editing_mode(d) if d.spec.get("schema_version") == 5 else "auto"
editing_mode(d) if d.spec.get("schema_version") in (5, 6) else "auto"
)
await write_manifest(s, d, restored, runtime.settings)
else:
@ -589,7 +616,7 @@ async def start_editor_request(runtime, actor, draft_id, body, key):
require_auto(d)
m = await load_manifest(s, d)
replay = previous is not None and bool(previous.resource_json)
if m.get("schema_version") == 3 and not replay:
if m.get("schema_version") in (3, 4) and not replay and body.output_goal not in {"caption_film", "mix_film"}:
from app.services.system import refresh_dialogue_capabilities
await refresh_dialogue_capabilities(runtime)
@ -623,7 +650,7 @@ async def plan_editor_request(runtime, actor, draft_id, body):
WorkflowDraft.deleted_at.is_(None),
)
)
if version == 5:
if version in (5, 6) and body.output_goal not in {"caption_film", "mix_film"}:
from app.services.system import refresh_dialogue_capabilities
await refresh_dialogue_capabilities(runtime)

View File

@ -0,0 +1,194 @@
"""已有原生镜头重混音,冻结已选画面、原声和帧表,只构造声音与合成步骤。"""
from copy import deepcopy
from app.core.errors import fail
from app.core.runtime_policy import read_runtime_policy
from app.domain.continuity import compile_story_timing
from app.domain.native_av import source_audio_matches_video
from app.domain.native_dialogue import enabled as native_enabled
from app.domain.stories import digest
from app.models import Asset
from app.services.caption_revision import caption_projection, frozen_caption_recipe, revision_plan
from app.services.editor_media import assigned_utterance_ids
from app.services.orchestration.dialogue_engine import _recipe
from app.services.orchestration.editor_engine import _asset
def _local_timing(sid, shot, timing, audio, video, gate, expected_ids):
evidence = gate.get("provenance") or {}
offset = (audio.get("provenance") or {}).get("audio_offset_samples")
frames = timing["contribution_frames"]
if (
not source_audio_matches_video(audio, video)
or evidence.get("shot_id") != sid
or evidence.get("native_av_policy") != "native_av_v1"
or evidence.get("video_sha256") != video.get("sha256")
or evidence.get("audio_sha256") != audio.get("sha256")
or evidence.get("native_context") != video.get("context_hash")
or evidence.get("audio_offset_samples") != offset
):
raise ValueError("缺少已核验的同源净音轨及该候选的原声时基")
if (
timing.get("source_start_frame")
or timing.get("dedup_frames")
or video.get("duration_frames") != frames
or abs(audio["sample_count"] + offset - frames * 2000) > 600
):
raise ValueError("当前选段与已验收的完整原片、原声帧数不一致")
if shot["performance"].get("dialogue_staging") == "two_person_turns" and (
evidence.get("turn_decision") not in {"pass", "manual"}
or not evidence.get("turn_certificate_sha256")
or not evidence.get("turn_report_sha256")
):
raise ValueError("同框原片缺少匹配的逐轮验收")
measured = evidence.get("utterances")
if (
not isinstance(measured, list)
or any(not isinstance(u, dict) for u in measured)
or [u.get("utterance_id") for u in measured] != expected_ids
):
raise ValueError("冻结的对白台词与镜头分配不符")
cursor = offset
for u in measured:
start, end = u.get("start_sample"), u.get("end_sample")
if (
type(start) is not int
or type(end) is not int
or not cursor <= start < end
or end > min(frames * 2000, audio["sample_count"] + offset)
):
raise ValueError("原声中存在无效的逐句时间")
cursor = end
return [
dict(
u,
start_sample=u["start_sample"] + timing["start_frame"] * 2000,
end_sample=u["end_sample"] + timing["start_frame"] * 2000,
)
for u in measured
]
async def plan_remix(session, draft, m, body, settings):
data = body.model_dump(exclude_unset=True) if hasattr(body, "model_dump") else body
if data.get("targets") or data.get("force"):
fail(422, "invalid_target", "重混音专用计划只接受已选原片、净音轨与当前配乐")
issues, recipes, hashes, measured = [], [], {}, []
def issue(code, unit, message):
issues.append(dict(code=code, unit_id=unit, message=message))
timing, prepared = {}, {}
if not native_enabled(m):
issue("mix_native_required", "audio", "重混音专用计划需要已选用的原生对白镜头")
else:
timing = compile_story_timing(m["spec"])
sequences = {s["id"]: s for s in m["spec"]["dialogue"]["sequences"]}
limit = min(
60, m["production"]["max_shots"], read_runtime_policy(settings)["workflow_max_shots"]
)
if len(m["shot_ids"]) > limit or timing["total_frames"] > min(
7200, m["production"]["max_total_frames"]
):
issue("mix_budget_exceeded", "production", "已选时间线超过成片预算")
for shot, t in zip(m["spec"]["shots"], timing["shots"], strict=True):
sid = shot["id"]
bindings = m["bindings"]
video, audio, gate = (
bindings.get(role + ":" + sid) or {}
for role in ("video", "native_audio", "native_alignment")
)
if not video or not await _asset(
session, draft.owner_id, video, settings, "video", t["contribution_frames"]
):
issue("mix_source_missing", sid, "缺少已选用的无字幕原片或原片校验失败")
continue
if not audio or not await _asset(session, draft.owner_id, audio, settings, "audio"):
issue("mix_source_missing", sid, "缺少已选镜头的干净原声音轨或音轨校验失败")
continue
if not gate or not await _asset(session, draft.owner_id, gate, settings, "json"):
issue("mix_timing_missing", sid, "缺少该镜头已验收的原声和字幕时基")
continue
try:
measured.extend(
_local_timing(
sid,
shot,
t,
audio,
video,
gate,
assigned_utterance_ids(shot, sequences)
if m["spec"]["dialogue"].get("enabled")
else [],
)
)
except ValueError as exc:
issue("mix_timing_invalid", sid, str(exc))
continue
hashes.update((b["asset_id"], b["sha256"]) for b in (video, audio, gate))
if m["audio"].get("mode") != "silent" or m["audio"].get("mix_mode") == "manual_mix":
issue("mix_mode_conflict", "audio", "请使用对白自动混音,并将背景音乐放在独立音层")
if len(m["shot_ids"]) + len(m["audio"].get("layers", [])) > 128:
issue("mix_limit", "audio", "镜头原声与音层合计超过128段")
if not issues:
for aid in dict.fromkeys(layer["asset_id"] for layer in m["audio"].get("layers", [])):
asset = await session.get(Asset, aid)
if not asset or not await _asset(
session, draft.owner_id, dict(asset_id=aid, sha256=asset.sha256), settings, "audio"
):
issue("mix_layer_missing", aid, "配乐或音效素材不存在、不可访问或校验失败")
continue
hashes[aid] = asset.sha256
if not issues:
prepared = dict(
production_materialized=True,
effective_manifest=deepcopy(m),
timing=timing,
utterances=measured,
issues=[],
steps=[],
native_av_policy="native_av_v1",
)
projection = await caption_projection(
session, draft.owner_id, m, settings, prepared=prepared
)
issues.extend(projection["issues"])
if not issues:
for i, aid in enumerate(
dict.fromkeys(x["asset_id"] for x in m["audio"].get("layers", []))
):
recipes.append(
_recipe(
f"native_bgm_{i:04d}", "audio.normalize", aid, inputs=dict(asset_id=aid)
)
)
recipes += [
_recipe(
"dialogue_mix",
"audio.mix",
"audio",
dependencies=[r["key"] for r in recipes],
parameters=dict(ducking=m["audio"].get("ducking", True)),
),
frozen_caption_recipe(projection),
_recipe(
"compose",
"video.compose",
"film",
dependencies=["dialogue_mix", "dialogue_captions"],
),
]
signature = digest(
dict(
operation="mix_film_v1",
manifest=m,
timing=timing,
recipes=recipes,
assets=hashes,
issues=issues,
body={k: v for k, v in data.items() if k != "expected_plan_hash"},
)
)
return revision_plan(draft, recipes, hashes, issues, prepared, signature)

View File

@ -673,6 +673,31 @@ class Coordinator:
if hasattr(self.provider, "upstream_capabilities")
else {}
)
if job.run_id and job.task_type in {"video.generate", "audio.dialogue.inspect"}:
from app.models import WorkflowStep
from app.adapters.provider.native_av import (
turn_certificate,
TURN_CERTIFICATION_REASON,
)
async with self.db.session() as session:
recipe = await session.scalar(
select(WorkflowStep.recipe_json).where(
WorkflowStep.run_id == job.run_id,
WorkflowStep.step_key == job.step_key,
)
)
turn = (recipe or {}).get("turn_contract")
if turn:
current = turn_certificate(capabilities, turn["parameters"])
if not current or current != turn.get("certificate_sha256"):
await self._update(
job.id,
state="needs_attention",
phase="native_turns_uncertified",
sync_warning=TURN_CERTIFICATION_REASON,
)
return
features = capabilities.get("features") or {}
project_window = (
isinstance(features, dict) and features.get("project_gpu_window") is True

View File

@ -34,7 +34,7 @@ from app.services.workflows import digest, verified_output, emit_run
def enabled(value):
return value.get("schema_version") == 3 and value.get("spec", {}).get("schema_version") == 5
return value.get("schema_version") in (3, 4) and value.get("spec", {}).get("schema_version") in (5, 6)
def execution_recipes(run):
@ -919,6 +919,19 @@ async def _plan_editor(session, draft, manifest, body, settings, *, tp2_capabili
async def plan_editor(session, draft, manifest, body, settings, *, tp2_capability=None):
from app.domain.native_dialogue import enabled as native_enabled
if (body.get("output_goal") if isinstance(body, dict) else body.output_goal) == "mix_film":
from app.services.mix_revision import plan_remix
plan = await plan_remix(session, draft, manifest, body, settings)
return {key: value for key,value in plan.items() if not key.startswith("_")}
if (body.get("output_goal") if isinstance(body,dict) else body.output_goal) == "caption_inspect":
from app.services.caption_inspect import plan_source_inspection
plan = await plan_source_inspection(session, draft, manifest, body, settings)
return {key:value for key,value in plan.items() if not key.startswith("_")}
if (body.get("output_goal") if isinstance(body, dict) else body.output_goal) == "caption_film":
from app.services.caption_revision import plan_caption_film
plan = await plan_caption_film(session, draft, manifest, body, settings)
return {key: value for key, value in plan.items() if not key.startswith("_")}
if native_enabled(manifest):
from .native_dialogue_engine import plan_editor as native_plan
@ -940,6 +953,17 @@ async def start_editor_run(session, draft, manifest, body, settings, *, tp2_capa
)
from .native_dialogue_engine import plan_editor as native_plan
if (body.get("output_goal") if isinstance(body, dict) else body.output_goal) == "caption_film":
from app.services.caption_revision import plan_caption_film
plan = await plan_caption_film(session, draft, manifest, body, settings)
elif (body.get("output_goal") if isinstance(body, dict) else body.output_goal) == "mix_film":
from app.services.mix_revision import plan_remix
plan = await plan_remix(session, draft, manifest, body, settings)
elif (body.get("output_goal") if isinstance(body,dict) else body.output_goal) == "caption_inspect":
from app.services.caption_inspect import plan_source_inspection
plan = await plan_source_inspection(session,draft,manifest,body,settings)
else:
plan = await native_plan(session, draft, manifest, body, settings)
return await _start_legacy_editor_run(
session, draft, manifest, body, settings, _frozen_plan=plan
@ -1017,6 +1041,12 @@ async def _start_legacy_editor_run(
session.add(
AssetReference(owner_id=run.owner_id, asset_id=aid, ref_kind="run", ref_id=run.id)
)
if body.get("output_goal") == "caption_film":
# 字幕再版沿用上一版混音。源运行以后可删除,新成片需持有独立引用。
from .editor_engine import _add_ref
mix = next(r["reuse"] for r in plan["_recipes"] if r["key"] == "dialogue_mix")
await _add_ref(session, run, await session.get(Asset, mix["asset_id"]))
await session.flush()
await emit_run(session, run, False)
return run
@ -1906,6 +1936,8 @@ def _semantic_hash(kind, resolved):
return [content(v) for v in value]
return hashes.get(value, value) if isinstance(value, str) else value
if kind == "captions.compile" and "caption_projection" in resolved:
return digest({"kind": kind, "projection": resolved["caption_projection"], "cues": resolved["captions"]})
return digest(
{
"kind": kind,
@ -1992,6 +2024,9 @@ async def create_editor_child(session, run, step, settings):
resolved = step.resolved_input_json
if step.kind == "captions.compile":
step.result_json, step.state = {"cues": resolved["captions"]}, "succeeded"
if "display_rows" in resolved:
step.result_json = {**step.result_json, "display_rows": resolved["display_rows"],
"caption_projection": resolved["caption_projection"]}
m = deepcopy(run.result_manifest)
m["captions"]["cues"] = resolved["editable_cues"]
run.result_manifest = m
@ -2979,6 +3014,12 @@ async def advance_editor_run(session, run, settings):
else {}
)
code = detail.get("code", "invalid_dialogue_input")
if code == "native_turn_review_required" and step.kind == "dialogue.accepted":
report = bykey[step.recipe_json["turn_report_key"]].result_json
step.result_json = {"review_request": {"asset_id": report["asset_id"], "sha256": report["sha256"]}}
step.state = "awaiting_review"
step.version += 1
continue
if code in {"quota_exceeded", "storage_insufficient"}:
run.hold_reasons = ["quota" if code == "quota_exceeded" else "storage"]
break
@ -2988,6 +3029,14 @@ async def advance_editor_run(session, run, settings):
)
break
admitted += 1
waiting_review = next((s for s in steps if s.state == "awaiting_review"), None)
if waiting_review and run.state == "running" and not any(
s.state in {"ready", "running"} or s.state == "waiting"
and all(bykey[key].state == "succeeded" for key in s.dependencies) for s in steps
):
run.state = "blocked"
run.error_json = dict(code="native_turn_review_required", step_key=waiting_review.step_key,
message="请逐轮回看双人镜头,确认选用后继续合成")
after = digest(
{
"state": run.state,

View File

@ -507,8 +507,17 @@ async def _asset(session, owner, binding, settings, kind=None, minimum_frames=No
return a
def uses_dialogue_workflow(manifest, body):
goal = body.get("output_goal") if isinstance(body, dict) else body.output_goal
return (
goal in {"caption_film", "caption_inspect", "mix_film"}
or manifest.get("schema_version") in (3, 4)
or manifest["spec"].get("schema_version") in (5, 6)
)
async def plan_editor(session, draft, manifest, body, settings, *, tp2_capability=None):
if manifest.get("schema_version") == 3 or manifest["spec"].get("schema_version") == 5:
if uses_dialogue_workflow(manifest, body):
from app.services.orchestration import dialogue_engine
return await dialogue_engine.plan_editor(
@ -698,7 +707,7 @@ async def plan_editor(session, draft, manifest, body, settings, *, tp2_capabilit
async def start_editor_run(session, draft, manifest, body, settings, *, tp2_capability=None):
if manifest.get("schema_version") == 3 or manifest["spec"].get("schema_version") == 5:
if uses_dialogue_workflow(manifest, body):
from app.services.orchestration import dialogue_engine
return await dialogue_engine.start_editor_run(
@ -1220,7 +1229,7 @@ async def _collect(session, r, step, job, settings):
async def advance_editor_run(session, r, settings):
if r.spec_snapshot.get("schema_version") == 5:
if r.spec_snapshot.get("schema_version") in (5, 6):
from app.services.orchestration import dialogue_engine
return await dialogue_engine.advance_editor_run(session, r, settings)

View File

@ -14,8 +14,8 @@ from app.adapters.provider.continuity_media import (
from app.adapters.storage import safe_file, confined
from app.core.errors import fail
from app.domain.native_dialogue import compile_native_shots
from app.domain.native_av import align_native_utterances, normalize_native_text
from app.domain.native_silence import POLICY as SILENCE_POLICY, verified_silence
from app.domain.native_av import align_native_utterances, content_consensus as _content_consensus
from app.domain.native_silence import POLICY as SILENCE_POLICY
from app.domain.stories import compile_story, ordered_reference_ids
from app.models import Asset, WorkflowStep
from app.services.workflows import digest, verified_output
@ -49,6 +49,22 @@ def _capability(kind, parameters, settings):
return True
def _turn_generation_issue(native, frame, certificate=None):
if (
not frame
or not native.get("first_frame_sha256")
or native["first_frame_sha256"] != frame.get("sha256")
):
return _issue(
"native_turn_frame_changed", native["shot_id"], "请先选定双人首帧并确认左右角色对应"
)
if certificate:
return None
return _issue(
"native_turns_uncertified", native["shot_id"], native_av.TURN_CERTIFICATION_REASON
)
def _video_context(context, frame_sha):
return digest(dict(native_context=context, frame_sha256=frame_sha, policy=POLICY))
@ -96,38 +112,6 @@ def _audio_review_context(audio_sha, expected_text, speaker_id):
)
def _content_consensus(report, expected):
if not isinstance(expected, str):
return False
if not expected.strip():
return verified_silence(report, expected)
normalized = normalize_native_text(expected)
if not normalized:
return False
fields = dict(
content_verification_policy=CONTENT_POLICY,
content_decision_source="whisper_sensevoice_consensus",
secondary_status="completed",
secondary_asr_revision="90c1c61912018b70ada0fcc024ea24aca62f2e63",
secondary_runtime_revision="6991744856587fa44379e8b5dcc432debffeb1be",
normalized_expected_text=normalized,
normalized_transcript=normalized,
normalized_secondary_transcript=normalized,
)
if any(report.get(k) != v for k, v in fields.items()):
return False
for name in ("content_error_rate", "secondary_content_error_rate"):
if type(report.get(name)) not in (int, float) or report[name] != 0:
return False
for name in ("transcript", "secondary_transcript"):
if (
not isinstance(report.get(name), str)
or normalize_native_text(report[name]) != normalized
):
return False
return True
def _read_report(asset, settings):
with safe_file(settings.asset_root, asset.storage_key) as source:
report = json.load(source)
@ -312,6 +296,16 @@ async def plan_editor(session, draft, manifest, body, settings):
)
vr["native_context"] = native["context_hash"]
vr["native_utterance_ids"] = native["utterance_ids"]
if "turns" in native:
certificate = native_av.turn_certificate(
getattr(settings, "_native_av_upstream", {}), native["parameters"]
)
vr["turn_contract"] = dict(
parameters=native["parameters"], certificate_sha256=certificate
)
issue = _turn_generation_issue(native, fr["reuse"], certificate)
if issue:
vr["issue"] = issue
original_video = manifest.get("bindings", {}).get("video:" + sid, {})
if original_video.get("source") == "manual" and not {
"frame:" + sid,
@ -365,6 +359,8 @@ async def plan_editor(session, draft, manifest, body, settings):
reuse=report,
changed=ar["reuse"] is None,
)
if "turns" in native:
qr["turn_contract"] = vr["turn_contract"]
visible_speech = (
native["speaker_id"] is not None
and native["speaker_id"] in shot["performance"]["visible_speaker_ids"]
@ -391,6 +387,8 @@ async def plan_editor(session, draft, manifest, body, settings):
else "画面中所有人物自然放松闭唇,使用眼神和肢体动作表演,不做发音口型"
),
)
if "turns" in native:
expected.update(turns=native["turns"], mouth_expectation="固定机位双人始终同框,依次发言,听者自然反应")
rc = _review_context(source_sha, {aid: assets[aid].sha256 for aid in refs[:3]}, expected)
review = reusable.get("dialogue_report:" + sid)
if review and review.get("context_hash") != rc:
@ -409,12 +407,56 @@ async def plan_editor(session, draft, manifest, body, settings):
reuse=review,
changed=vr["reuse"] is None,
)
dependencies = [vr["key"], ar["key"], qr["key"], rr["key"]]
if "turns" in native:
roles = {sp["id"]: sp for sp in m["spec"]["dialogue"]["speakers"]}
visible = shot["performance"]["visible_speaker_ids"]
reference_ids = [
roles[sp].get(field)
for field in ("face_reference_asset_id", "voice_reference_asset_id")
for sp in visible
]
for field, aid in zip(("image", "image", "audio", "audio"), reference_ids):
if aid and (aid not in assets or assets[aid].kind != field):
vr["issue"] = _issue(
"native_turn_reference_invalid", sid, "双人参考素材与角色用途不匹配"
)
if len({assets[aid].sha256 for aid in reference_ids if aid in assets}) != 4:
vr["issue"] = _issue(
"native_turn_reference_required", sid, "两份参考脸与两份验声样本必须有独立来源"
)
audit_turns = [
dict(
utterance_id=t["utterance_id"],
speaker_id=t["speaker_id"],
text=utterances[t["utterance_id"]].get("spoken_text")
or utterances[t["utterance_id"]]["text"],
)
for t in native["turns"]
]
tr = add(
f"nt_{i:04d}",
"audio.dialogue.inspect",
sid,
deps=list(dependencies),
parameters=dict(
profile="dialogue-audio-v1",
turn_policy=native_av.TURN_POLICY,
certificate_sha256=certificate,
first_frame_sha256=native["first_frame_sha256"],
speaker_ids=visible,
turns=audit_turns,
),
)
tr["reference_ids"] = reference_ids
tr["turn_contract"] = vr["turn_contract"]
dependencies.append(tr["key"])
gr = add(
f"ng_{i:04d}",
"dialogue.accepted",
sid,
"native_alignment:" + sid,
deps=[vr["key"], ar["key"], qr["key"], rr["key"]],
deps=dependencies,
context=vc,
)
gr.update(
@ -424,6 +466,9 @@ async def plan_editor(session, draft, manifest, body, settings):
review_key=rr["key"],
video_key=vr["key"],
)
if "turns" in native:
gr["turn_contract"] = vr["turn_contract"]
gr["turn_report_key"] = tr["key"]
previous_alignment = manifest.get("bindings", {}).get("native_alignment:" + sid, {})
if previous_alignment.get("context_hash") == vc and all(
row["reuse"] for row in (vr, ar, qr, rr)
@ -503,7 +548,16 @@ async def plan_editor(session, draft, manifest, body, settings):
)
)
if body.get("output_goal", "film") == "film":
if len(m["shot_ids"]) > 60 or projection["timing"]["total_frames"] > min(
if len(m["shot_ids"]) + len(m["audio"].get("layers", [])) > 128:
issues.append(
_issue(
"dialogue_mix_limit", "audio", "镜头原声与配乐合计超过128段,请减少配乐层或镜头"
)
)
from app.core.runtime_policy import read_runtime_policy
limits = read_runtime_policy(settings)
if len(m["shot_ids"]) > min(60, limits["workflow_max_shots"], m["production"]["max_shots"]) or projection["timing"]["total_frames"] > min(
7200, m["production"]["max_total_frames"]
):
issues.append(
@ -593,6 +647,19 @@ async def resolve(session, run, step, settings):
video_asset_id=source["asset_id"],
audio_asset_id=source["provenance"]["native_source_audio_asset_id"],
)
elif step.kind == "audio.dialogue.inspect" and parameters.get("turn_policy"):
video = b["video:" + sid]
inputs = dict(
asset_ids=[
video["asset_id"],
video["provenance"]["native_source_audio_asset_id"],
b["native_audio:" + sid]["asset_id"],
b["native_report:" + sid]["asset_id"],
b["frame:" + sid]["asset_id"],
b["dialogue_report:" + sid]["asset_id"],
*recipe["reference_ids"],
]
)
elif step.kind == "audio.dialogue.inspect":
inputs["audio_asset_id"] = b["native_audio:" + sid]["asset_id"]
elif step.kind == "video.dialogue.review":
@ -600,14 +667,37 @@ async def resolve(session, run, step, settings):
elif step.kind == "audio.mix":
inputs = await mix_inputs(session, run)
elif step.kind == "captions.compile":
from app.services.editor_media import compile_captions, materialize_cues
from app.services.editor_media import materialize_cues, preview_captions, rendered_cues
from app.services.caption_revision import load_caption_reports
extra = {}
reports = {}
if m["captions"].get("presentation"):
from app.domain.rhythm_captions import VERSION as rhythm_version
reports = await load_caption_reports(session, run.owner_id, m, settings)
extra["caption_projection"] = digest(
{
"algorithm": rhythm_version,
"policy": m["captions"],
"timing": run.prepared_plan["timing"],
"reports": {sid: b["native_report:" + sid]["sha256"] for sid in reports},
}
)
projection = preview_captions(m, b, prepared=run.prepared_plan, reports=reports)
if m["captions"].get("presentation"):
extra["display_rows"] = projection["rows"]
return dict(
input={},
parameters={},
input_sha256={},
captions=compile_captions(m, b, prepared=run.prepared_plan),
editable_cues=materialize_cues(m, b, prepared=run.prepared_plan),
captions=rendered_cues(projection),
editable_cues=(
m["captions"]["cues"]
if "display_rows" in extra
else materialize_cues(m, b, prepared=run.prepared_plan)
),
**extra,
)
elif step.kind == "video.compose":
inputs, parameters = await _compose_inputs(session, run, settings)
@ -619,6 +709,13 @@ async def resolve(session, run, step, settings):
async def before_child(session, run, step, settings):
contract = step.recipe_json.get("turn_contract")
if contract and step.kind != "dialogue.accepted":
cert = native_av.turn_certificate(
getattr(settings, "_native_av_upstream", {}), contract["parameters"]
)
if not cert or cert != contract.get("certificate_sha256"):
fail(422, "native_turns_uncertified", native_av.TURN_CERTIFICATION_REASON)
if not _capability(step.kind, step.recipe_json["parameters"], settings):
fail(422, "capability_unavailable", "原生能力认证已失效,停止派发")
if step.kind != "dialogue.accepted":
@ -633,6 +730,12 @@ async def accept_shot(session, run, step, settings):
r, m = step.recipe_json, deepcopy(run.result_manifest)
sid = r["unit_id"]
duo = m["spec"].get("schema_version") == 6 and any(
s["id"] == sid and s.get("performance", {}).get("dialogue_staging") == "two_person_turns"
for s in m["spec"]["shots"]
)
if duo and not r.get("turn_report_key"):
fail(409,"invalid_turn_report","同框候选缺少专用验收步骤")
results = {
key: (await _step(session, run, r[key])).result_json
for key in ("video_key", "audio_key", "report_key", "review_key")
@ -649,7 +752,7 @@ async def accept_shot(session, run, step, settings):
for uid in r["native_utterance_ids"]
]
expected = "".join(u.get("spoken_text") or u["text"] for u in utterances)
speaker = utterances[0]["speaker_id"] if utterances else sid
speaker = utterances[0]["speaker_id"] if utterances and not duo else sid
matches = dict(
native_av_policy=POLICY,
audio_sha256=audio["sha256"],
@ -670,7 +773,7 @@ async def accept_shot(session, run, step, settings):
):
fail(409, "invalid_native_alignment", "原声词时间报告与本次音轨、整句台词或识别合同不匹配")
if (
review.get("decision", review.get("verdict")) != "pass"
review.get("decision", review.get("verdict")) not in ({"pass","indeterminate"} if duo else {"pass"})
or results["review_key"].get("provenance", {}).get("video_sha256") != video["sha256"]
or review.get("source_start_frame") != 0
or review.get("source_end_frame") != video["duration_frames"]
@ -704,6 +807,43 @@ async def accept_shot(session, run, step, settings):
utterances=aligned,
audio_offset_samples=audio.get("provenance", {}).get("audio_offset_samples", 0),
)
if duo:
from app.domain.native_av import validate_turn_report
from app.services.turn_review import manually_accepted
audit_step = await _step(session, run, r["turn_report_key"])
audit = audit_step.result_json or {}
if not await _asset(session, run.owner_id, audit, settings, "json"):
fail(409, "invalid_turn_report", "缺少可验证的双人候选报告")
measured = _read_report(await session.get(Asset, audit["asset_id"]), settings)
audit_args = audit_step.resolved_input_json
frozen = audit_args["parameters"]
current = await resolve(session, run, audit_step, settings)
if current != audit_args:
fail(409, "invalid_turn_report", "双人候选来源已改变")
sources = dict(
zip(
native_av.TURN_SOURCES,
(audit_args["input_sha256"][aid] for aid in audit_args["input"]["asset_ids"]),
strict=True,
)
)
try:
status = validate_turn_report(
measured, frozen, aligned, sources, video["duration_frames"]
)
except ValueError as exc:
fail(409, "invalid_turn_report", str(exc))
if status == "reject":
fail(409, "native_turn_rejected", "原声归属、同步或双人画面检查明确失败,请另选候选")
if status == "indeterminate" and not await manually_accepted(session, run, step, audit):
fail(409, "native_turn_review_required", "请逐轮回听并核对原片中的发言人与听者")
binding["provenance"].update(
turn_report_asset_id=audit["asset_id"],
turn_report_sha256=audit["sha256"],
turn_certificate_sha256=frozen["certificate_sha256"],
turn_decision="manual" if status == "indeterminate" else "pass",
)
binding["context_hash"] = video["context_hash"]
old = m["bindings"].get("native_alignment:" + sid, {})
if (
@ -749,7 +889,7 @@ async def mix_inputs(session, run):
if count > maximum:
# 完整 WAV 永久保留;只有经逐词验收证明为非语音的尾部半格可不参与整片混音。
if count - maximum > 600 or any(
u["end_sample"] > maximum for u in evidence["utterances"]
u["end_sample"] > t["contribution_frames"] * 2000 for u in evidence["utterances"]
):
fail(409, "native_audio_overflow", "原声尾部超出视频且没有安全的非语音边界")
count = maximum
@ -933,6 +1073,7 @@ async def collect(session, run, step, job, settings):
if step.kind == "audio.mix":
if count != resolved["input"]["total_frames"] * 2000:
fail(409, "invalid_output", "整片混音没有保持精确样本数")
result["mix_version"] = "audio-mix-v2"
result["track"] = dict(
asset_id=asset.id,
source_start_sample=0,
@ -943,7 +1084,9 @@ async def collect(session, run, step, job, settings):
)
elif kind == "json":
result["report"] = _read_report(asset, settings)
if step.kind == "audio.dialogue.inspect":
if step.kind == "audio.dialogue.inspect" and resolved["parameters"].get("turn_policy"):
result["context_hash"] = digest(resolved)
elif step.kind == "audio.dialogue.inspect":
result["context_hash"] = _audio_review_context(
resolved["input_sha256"][resolved["input"]["audio_asset_id"]],
resolved["input"]["expected_text"],

View File

@ -53,7 +53,7 @@ async def advance_run(session, run_id, settings, *, dialogue_identity=_IDENTITY_
select(WorkflowRun.owner_id, WorkflowRun.draft_id).where(
WorkflowRun.id == run_id,
WorkflowRun.deleted_at.is_(None),
WorkflowRun.spec_snapshot["schema_version"].as_integer() == 5,
WorkflowRun.spec_snapshot["schema_version"].as_integer().in_((5, 6)),
WorkflowRun.run_kind.in_(("story_auto", "workflow_auto")),
)
)
@ -228,7 +228,7 @@ async def advance_workflows(db, settings, provider):
for run_id, owner_id, draft_id, kind, version in runs:
identity = (
(owner_id, draft_id)
if version == 5 and kind in {"story_auto", "workflow_auto"}
if version in (5, 6) and kind in {"story_auto", "workflow_auto"}
else None
)
try:
@ -273,7 +273,7 @@ async def advance_workflows(db, settings, provider):
WorkflowRun.deleted_at.is_(None),
WorkflowRun.state == "succeeded",
WorkflowRun.apply_state == "pending",
WorkflowRun.spec_snapshot["schema_version"].as_integer() == 5,
WorkflowRun.spec_snapshot["schema_version"].as_integer().in_((5, 6)),
)
)
).all()

View File

@ -0,0 +1,301 @@
"""将父台词、素材坐标和编辑例外汇合到可冻结的全片字幕表。"""
from collections import defaultdict
from app.domain.continuity import compile_story_timing
from app.domain.rhythm_captions import VERSION, display_text, measure_shot, stable_id
from app.domain.timeline import Subtitle
def _remap(edit, text):
old = edit["source_text"]
a, b = edit["source_start"], edit["source_end"]
if old == text:
return a, b
piece = old[a:b]
start = text.find(piece)
if (
not piece
or old.find(piece) != a
or old.find(piece, a + 1) != -1
or start < 0
or text.find(piece, start + 1) != -1
):
raise ValueError("人工编辑的原文范围已变化,请核对并重新绑定")
return start, start + len(piece)
def _apply_edits(line, base, edits, punctuation):
"""按原文覆盖;删除范围不复活,拆分没有自动边界时保留为待校时。"""
source, uid = line["text"], line["id"]
overlays = sorted(((*_remap(e, source), e) for e in edits), key=lambda entry: entry[:2])
if any(a < last[1] for last, (a, b, e) in zip(overlays, overlays[1:])):
raise ValueError("此台词的人工编辑范围发生重叠")
starts = {a: left for a, b, left, right, status in base}
ends = {b: right for a, b, left, right, status in base}
def row(a, b, left, right, status, edit=None):
e = edit or {}
if e.get("timing_override"):
left, right = e["start_frame"], e["end_frame"]
text = e["text"] if e.get("text_override") else display_text(source[a:b], punctuation)
return dict(
id=e.get("id") or stable_id(uid, a, b),
source_text=source,
source_start=a,
source_end=b,
text=text,
local_start_frame=left,
local_end_frame=right,
status=status if left is not None and right is not None else "pending",
text_override=e.get("text_override", False),
timing_override=e.get("timing_override", False),
)
output = []
for a, b, e in overlays:
if not e.get("deleted"):
output.append(row(a, b, starts.get(a), ends.get(b), "manual", e))
for a, b, left, right, status in base:
cursor = a
for x, y, e in overlays:
if y <= a:
continue
if x >= b:
break
if cursor < x:
output.append(row(cursor, x, starts.get(cursor), ends.get(x), status))
cursor = max(cursor, y)
if cursor < b:
output.append(row(cursor, b, starts.get(cursor), ends.get(b), status))
return output
def _non_dialogue(manifest, bindings):
from app.services.editor_media import _legacy_rows
captions = manifest["captions"]
m = {
**manifest,
"spec": {
**manifest["spec"],
"dialogue": {**manifest["spec"]["dialogue"], "enabled": False},
},
"captions": {
**captions,
"cues": [c for c in captions["cues"] if c["anchor"] != "utterance"],
},
}
if not m["captions"]["cues"] and not m.get("audio", {}).get("segments"):
return []
# 保留有效的版本化 StorySpec,借用传统四类锚点的换算器。
return _legacy_rows(m, bindings, prepared={"utterances": []}, limit_count=False)
def _limit_rows(rows, issues, punctuation):
"""总计包含手工及旁白;只合并同句、相邻来源、无锁的自动段。"""
excess = len(rows) - 1000
if excess <= 0:
return rows
result = []
for row in rows:
prior = result[-1] if result else None
if (
excess
and prior
and row.get("utterance_id")
and row["utterance_id"] == prior["utterance_id"]
and row["status"] == prior["status"] == "automatic"
and prior["source_end"] == row["source_start"]
):
prior.update(
source_end=row["source_end"],
end_frame=row["end_frame"],
local_end_frame=row["local_end_frame"],
)
prior["text"] = display_text(
prior["source_text"][prior["source_start"] : prior["source_end"]], punctuation
)
prior["id"] = stable_id(row["utterance_id"], prior["source_start"], prior["source_end"])
excess -= 1
else:
result.append(row)
if excess:
loc = result[1000]
issues.append(
dict(
code="caption_limit",
unit_id=loc.get("utterance_id") or loc["id"],
message="字幕数量超过1000条,请在此处或之前合并同句字幕",
)
)
return result
def project_captions(manifest, bindings, reports, prepared, *, utterance_id=None):
from app.services.editor_media import assigned_utterance_ids
caps = manifest["captions"]
presentation = caps["presentation"]
issues = []
def issue(code, uid, message):
issues.append(dict(code=code, unit_id=uid, message=message))
if prepared and prepared.get("effective_manifest"):
manifest = {**prepared["effective_manifest"], "captions": caps}
try:
rows = [] if utterance_id is not None else _non_dialogue(manifest, bindings)
except ValueError as exc:
rows = []
issue("invalid_caption", "captions", str(exc))
spec = manifest["spec"]
dialogue = spec.get("dialogue", {})
if not dialogue.get("enabled"):
return dict(rows=_limit_rows(rows, issues, presentation["punctuation"]), issues=issues)
lines = {u["id"]: u for u in dialogue["utterances"]}
sequences = {seq["id"]: seq for seq in dialogue["sequences"]}
timing = (prepared or {}).get("timing") or compile_story_timing(spec)
timing_by_id = {t["shot_id"]: t for t in timing["shots"]}
resolved = set()
old_cues = {c["utterance_id"]: c for c in caps["cues"] if c["anchor"] == "utterance"}
edits = defaultdict(list)
for e in caps["edits"]:
edits[e["utterance_id"]].append(e)
for shot in spec["shots"]:
sid = shot["id"]
ids = assigned_utterance_ids(shot, sequences)
if utterance_id is not None and utterance_id not in ids:
continue
assigned = [lines[uid] for uid in ids if uid in lines]
if not assigned:
continue
t = timing_by_id[sid]
shot_start, duration = t["start_frame"], t["contribution_frames"]
trim = t.get("source_start_frame", 0) + t.get("dedup_frames", 0)
intervals = {}
reason = "等待原声识别和双声道语音活动证据"
offset = 0
if reports.get(sid) and dialogue.get("generation") == "native_av":
try:
intervals, offset = measure_shot(
sid,
assigned,
bindings,
reports[sid],
presentation["pacing"],
two_person=shot["performance"].get("dialogue_staging") == "two_person_turns",
)
except ValueError as exc:
reason = str(exc)
for line in assigned:
uid, source = line["id"], line["text"]
if utterance_id is not None and uid != utterance_id:
continue
cue = old_cues.get(uid) or {}
if uid in resolved:
issue("caption_duplicate_turn", uid, "同一台词出现在多个镜头,请核对发言轮次")
continue
resolved.add(uid)
if caps["mode"] == "manual" and not cue and not edits[uid]:
continue
fragments = intervals.get(uid, [])
base = [
(
a,
b,
(left + offset + 1000) // 2000 - trim,
(right + offset + 1000) // 2000 - trim,
status,
)
for a, b, left, right, status in fragments
]
if not base:
base = [(0, len(source), None, None, "pending")]
line_edits = edits[uid]
audio_sha = (bindings.get("native_audio:" + sid) or {}).get("sha256")
if any(
not e.get("deleted")
and e.get("timing_override")
and e.get("audio_sha256")
and e["audio_sha256"] != audio_sha
for e in line_edits
):
issue("caption_audio_changed", uid, "原声已更换,请试听并重新确认受保护的字幕时间")
if not line_edits and (cue.get("text_override") or cue.get("timing_override")):
# 旧时间锁锚在已投影的父句(包含音频偏移),不再加偏移。
evidence = (bindings.get("native_alignment:" + sid) or {}).get("provenance") or {}
parent = next(
(u for u in evidence.get("utterances", []) if u["utterance_id"] == uid), {}
)
start, end = base[0][2], base[-1][3]
if cue.get("timing_override"):
start = end = None
if type(parent.get("start_sample")) is int:
origin = (parent["start_sample"] + 1000) // 2000 - trim
start, end = origin + cue["start_frame"], origin + cue["end_frame"]
base = [(0, len(source), start, end, "manual")]
line_edits = [
dict(
cue,
source_start=0,
source_end=len(source),
source_text=source,
start_frame=start,
end_frame=end,
)
]
try:
display = _apply_edits(line, base, line_edits, presentation["punctuation"])
except ValueError as exc:
issue("caption_edit_conflict", uid, str(exc))
display = _apply_edits(line, base, [], presentation["punctuation"])
for row in display:
left, right = row["local_start_frame"], row["local_end_frame"]
row.update(
utterance_id=uid,
turn_id=uid,
shot_id=sid,
speaker_id=line["speaker_id"],
algorithm_version=VERSION,
audio_sha256=audio_sha,
evidence_version=(reports.get(sid) or {}).get("asr_revision"),
start_frame=None if left is None else shot_start + left,
end_frame=None if right is None else shot_start + right,
)
rows.append(row)
if not row["text"].strip():
issue("empty_caption", uid, "显示文字为空")
if left is None or right is None:
issue("caption_timing_pending", uid, "待校时:" + reason)
elif left < 0 or right <= left or right > duration:
issue("caption_out_of_range", uid, "字幕时间超出镜头选用范围,请校时")
else:
try:
Subtitle(
start_frame=row["start_frame"],
end_frame=row["end_frame"],
text=row["text"],
)
except ValueError:
issue("invalid_caption", uid, "字幕含不支持的字符或长度超限")
for uid in lines.keys() - resolved:
if utterance_id is not None and uid != utterance_id:
continue
if caps["mode"] in ("script", "ai_script") or uid in edits or uid in old_cues:
issue("caption_unassigned", uid, "待校时:台词尚未唯一分配到镜头")
rows.sort(key=lambda r: (r["start_frame"] is None, r["start_frame"] or 0, r["source_start"]))
previous = None
for row in rows:
if row["start_frame"] is None or row["end_frame"] is None:
continue
if previous and row["start_frame"] < previous["end_frame"]:
issue(
"caption_overlap",
row.get("utterance_id") or row["id"],
"字幕时间重叠,请核对受保护的时间",
)
if previous is None or row["end_frame"] > previous["end_frame"]:
previous = row
rows = _limit_rows(rows, issues, presentation["punctuation"])
return dict(rows=rows, issues=issues)

View File

@ -194,7 +194,7 @@ def _dialogue_quality_counts(run, steps):
async def snapshot_run(session, owner_id, run_id):
r = await owned(session, WorkflowRun, run_id, owner_id)
if r.spec_snapshot.get("schema_version") == 5:
if r.spec_snapshot.get("schema_version") in (5, 6):
# V5 应用先锁草稿再锁 Run;读快照不能反向获取草稿写锁。
d = await session.scalar(
select(WorkflowDraft).where(
@ -210,7 +210,7 @@ async def snapshot_run(session, owner_id, run_id):
steps = (await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == r.id))).all()
auto = r.run_kind in {"story_auto", "workflow_auto"}
planned = (r.plan_snapshot or {}).get("steps", [])
if r.spec_snapshot.get("schema_version") == 5:
if r.spec_snapshot.get("schema_version") in (5, 6):
planned = [*planned, *(r.prepared_plan or {}).get("steps", [])]
keys = (
list(dict.fromkeys(x["key"] for x in planned))
@ -273,8 +273,14 @@ async def snapshot_run(session, owner_id, run_id):
"hold_reasons",
)
}
from app.services.caption_revision import frozen_rows
caption_step = next((s for s in steps if s.kind == "captions.compile" and s.state == "succeeded"), None)
run.update(
error=r.error_json,
current_output_asset_id=next((a["id"] for a in outputs if a["id"] == r.current_output_asset_id), None),
captions_srt_available=r.state == "succeeded" and r.output_goal == "film"
and any(a["id"] == r.current_output_asset_id for a in outputs)
and frozen_rows(r, caption_step) is not None,
created_at=iso(r.created_at),
started_at=iso(r.started_at),
finished_at=iso(r.finished_at),
@ -291,11 +297,14 @@ async def snapshot_run(session, owner_id, run_id):
frozen_spec=r.spec_snapshot,
editor_manifest=r.result_manifest or (r.plan_snapshot or {}).get("manifest"),
)
if r.spec_snapshot.get("schema_version") == 5:
if r.spec_snapshot.get("schema_version") == 6:
from app.services.turn_review import candidates
run["turn_reviews"] = await candidates(session, r, steps)
if r.spec_snapshot.get("schema_version") in (5, 6):
run["production_materialized"] = bool(
(r.prepared_plan or {}).get("production_materialized")
)
if (r.plan_snapshot or {}).get("manifest", {}).get("schema_version") in (2, 3):
if (r.plan_snapshot or {}).get("manifest", {}).get("schema_version") in (2, 3, 4):
from app.models.workflows import WorkflowVariant, QualityAssessment
variants = (
@ -313,7 +322,7 @@ async def snapshot_run(session, owner_id, run_id):
)
).all()
by_variant = {assessment.variant_id: assessment for assessment in assessments}
if r.spec_snapshot.get("schema_version") == 5:
if r.spec_snapshot.get("schema_version") in (5, 6):
accepted, total = _dialogue_quality_counts(r, steps)
repairs = sum(v.state == "repair_requested" for v in variants)
else:
@ -368,7 +377,7 @@ async def snapshot_run(session, owner_id, run_id):
"revision": r.draft_revision,
"editor_manifest": (r.plan_snapshot or {}).get("manifest"),
}
elif r.spec_snapshot.get("schema_version") in (3, 4, 5):
elif r.spec_snapshot.get("schema_version") in (3, 4, 5, 6):
frozen = {k: v for k, v in r.spec_snapshot.items() if k != "render_inputs"}
run.update(frozen_spec=frozen, render_inputs=r.spec_snapshot["render_inputs"])
frozen_draft = {**draft_dto(d), "spec": frozen, "revision": r.draft_revision}

View File

@ -62,6 +62,17 @@ async def create(runtime, actor, body):
)
s.add(d)
await s.flush()
if body.captions_mode is not None and not d.spec["render"]["subtitles"]:
from app.domain.editors import apply_birth_captions, manifest_from_draft
d.caption_birth_intent = dict(
mode=body.captions_mode,
presentation=body.caption_presentation.model_dump() if body.caption_presentation
else dict(punctuation="hide", pacing="rhythm"),
)
if d.spec.get("dialogue", {}).get("generation") == "native_av":
manifest = manifest_from_draft(d)
if apply_birth_captions(d, manifest):
d.editor_manifest = manifest
for a in assets.values():
await add_ref(s, d, a.id, "draft", d.id)
dto = await emit_story(s, d)
@ -130,7 +141,7 @@ async def patch(runtime, actor, id, body, if_match):
d.name = body.name
cleared = []
if body.spec is not None:
if d.spec.get("schema_version") == 5 and body.spec.schema_version != 5:
if d.spec.get("schema_version") in (5, 6) and body.spec.schema_version < d.spec["schema_version"]:
fail(409, "dialogue_editor_required", "请使用支持对白版本的编辑器")
model, assets = await spec_assets(s, actor.id, body.spec, runtime.settings)
removed_shots = {shot["id"] for shot in d.spec["shots"]} - {
@ -226,7 +237,7 @@ async def create_candidates(runtime, actor, id, body, key, batch=False, retry_id
d = await story(s, id, actor.id)
if is_editor_auto(d):
fail(409, "editor_required", "请使用可编辑成片接口")
if d.spec.get("schema_version") == 5 and (
if d.spec.get("schema_version") in (5, 6) and (
batch or retry_id or body.source_kind == "generated"
):
fail(409, "dialogue_editor_required", "请在对白编辑器中针对该镜头运行生成步骤")
@ -430,7 +441,7 @@ async def select_candidate(runtime, actor, id, body, key, clear=False):
if replay is not None:
return replay
shot = shot_model(d, body.shot_id)
if body.kind == "end_frame" and d.spec.get("schema_version") not in (4, 5):
if body.kind == "end_frame" and d.spec.get("schema_version") not in (4, 5, 6):
fail(422, "invalid_endpoint", "尾帧需要 V4 故事")
h = await current_hash(s, d, body.shot_id, body.kind)
a, c = None, None
@ -678,7 +689,11 @@ async def latest_film(runtime, actor, id):
fail(404, "story_not_found", "故事不存在")
# 仅按正式输出编号找成片。一个自动工作流还可能含有数十个中间视频。
latest = (
select(WorkflowRun.draft_revision, Asset.id.label("asset_id"))
select(
WorkflowRun.id.label("run_id"),
WorkflowRun.draft_revision,
Asset.id.label("asset_id"),
)
.join(Asset, Asset.id == WorkflowRun.current_output_asset_id)
.where(
WorkflowRun.owner_id == actor.id,
@ -698,10 +713,29 @@ async def latest_film(runtime, actor, id):
)
row = (
await session.execute(
select(Asset, latest.c.draft_revision).join(latest, Asset.id == latest.c.asset_id)
select(Asset, latest.c.draft_revision, latest.c.run_id).join(
latest, Asset.id == latest.c.asset_id
)
)
).one_or_none()
return {"asset": asset_dto(row[0]), "draft_revision": row[1]} if row else None
if row is None:
return None
caption_step = await session.scalar(
select(WorkflowStep).where(
WorkflowStep.run_id == row.run_id,
WorkflowStep.kind == "captions.compile",
WorkflowStep.state == "succeeded",
)
)
from app.services.caption_revision import frozen_rows
run = await session.get(WorkflowRun, row.run_id)
return {
"asset": asset_dto(row[0]),
"draft_revision": row.draft_revision,
"run_id": row.run_id,
"captions_srt_available": frozen_rows(run, caption_step) is not None,
}
async def runs(runtime, actor, id, page, page_size):

View File

@ -29,9 +29,9 @@ def shot_model(d, shot_id):
# 整体引用关系已在草稿写入时验证;读取单镜头不重复解析全部千镜头故事。
from app.domain.continuity import StoryShotV4
from app.domain.dialogue import StoryShotV5
from app.domain.dialogue import StoryShotV5, StoryShotV6
model = {4: StoryShotV4, 5: StoryShotV5}.get(d.spec.get("schema_version"), StoryShot)
model = {4: StoryShotV4, 5: StoryShotV5, 6: StoryShotV6}.get(d.spec.get("schema_version"), StoryShot)
return model.model_validate(shot)
@ -70,8 +70,15 @@ async def spec_assets(s, owner, spec, settings=None):
for variant in getattr(item, "forms", []) + getattr(item, "appearances", []):
ids.extend(variant.reference_asset_ids)
assets = {id: await private_asset(s, id, owner, "image") for id in sorted(set(ids))}
if model.schema_version == 5:
if model.schema_version in (5, 6):
dialogue_ids = {sp.voice.reference_asset_id for sp in model.dialogue.speakers}
if model.schema_version == 6:
for speaker in model.dialogue.speakers:
if speaker.face_reference_asset_id:
aid = speaker.face_reference_asset_id
assets[aid] = await private_asset(s, aid, owner, "image")
if speaker.voice_reference_asset_id:
dialogue_ids.add(speaker.voice_reference_asset_id)
dialogue_ids.update(u.asset_id for u in model.dialogue.utterances)
for aid in sorted(dialogue_ids - {None}):
assets[aid] = await private_asset(s, aid, owner, "audio")
@ -325,7 +332,7 @@ async def readiness(s, d, compiled=None, latest=None):
needs_frame = (
video and video.candidate_id and await selection_source_kind(s, video) == "generated"
)
if needs_frame and d.spec.get("schema_version") in (4, 5):
if needs_frame and d.spec.get("schema_version") in (4, 5, 6):
needs_frame = shot_model(d, sid).continuity.transition != "continue"
for kind in ("frame", "video") if needs_frame else ("video",):
row = latest.get((sid, kind))

View File

@ -245,6 +245,9 @@ async def capabilities(runtime):
visual_review_ready = by_task.get("video.dialogue.review", {}).get("available") is True
native_ready = generation_ready and alignment_ready and visual_review_ready
from app.adapters.provider.native_av import (
TURN_CERTIFICATION_REASON,
turn_evidence,
turn_certificate,
CERTIFICATION_REASON as NATIVE_REASON,
ALIGNMENT_REASON,
)
@ -259,6 +262,9 @@ async def capabilities(runtime):
else None
)
snapshot = getattr(runtime.settings, "_native_av_upstream", {})
proof = turn_evidence(snapshot)
turn_ready = bool(native_ready and turn_certificate(snapshot,proof) and any(p["profile"]==proof.get("profile") and p.get("available") for p in native_profiles))
dialogue["native_av"] = dict(
available=native_ready,
production_available=native_ready,
@ -270,9 +276,16 @@ async def capabilities(runtime):
word_alignment=alignment_ready,
visual_review=visual_review_ready,
),
two_person_turns=dict(
supported=True,
available=turn_ready,
reason=None if turn_ready else TURN_CERTIFICATION_REASON,
profile=proof.get("profile") if turn_ready else None,
num_frames=proof.get("num_frames") if turn_ready else None,
),
supports_single_face=native_ready,
supports_two_faces=False,
max_visible_speakers=1,
supports_two_faces=turn_ready,
max_visible_speakers=2 if turn_ready else 1,
language="Chinese",
reason=native_reason,
)
@ -280,17 +293,17 @@ async def capabilities(runtime):
available=native_ready,
production_available=native_ready,
supports_single_face=native_ready,
supports_two_faces=False,
max_visible_speakers=1,
supports_two_faces=turn_ready,
max_visible_speakers=2 if turn_ready else 1,
reason=native_reason,
)
return {
"dialogue": dialogue,
"editable_production": {
"schema_version": 1,
"supported_schema_versions": [1, 2, 3],
"supported_schema_versions": [1, 2, 3, 4],
"preferred_schema_version": 3,
"story_schema_versions": [3, 4, 5],
"story_schema_versions": [3, 4, 5, 6],
"dialogue": dialogue,
"continuity": {
"available": bool(getattr(runtime.settings, "continuity_quality_certified", False)),

View File

@ -0,0 +1,195 @@
"""把作者决定绑定到同一次双人试拍的镜头、视频及质检报告。"""
from sqlalchemy import select
from app.core.errors import fail
from app.core.maintenance import require_writable
from app.domain.native_av import TURN_POLICY
from app.models import Asset, Submission, WorkflowDraft, WorkflowRun, WorkflowStep, utcnow
from app.services.auth import require_session_user
from app.services.snapshots import owned
from app.services.submissions import accept_submission
from app.services.workflows import emit_run, verified_output, wake
OPERATION = "editor.turn_review"
POLICY = TURN_POLICY
async def _decisions(session, run):
receipts = await session.scalars(
select(Submission.resource_json).where(
Submission.owner_id == run.owner_id,
Submission.operation == OPERATION,
Submission.resource_json["run_id"].as_string() == run.id,
)
)
return {
(r["shot_id"], r["report_asset_id"], r["report_sha256"]): r
for r in receipts
if r.get("shot_id")
}
async def manually_accepted(session, run, gate_step, report_binding):
key = (
gate_step.recipe_json["unit_id"],
report_binding.get("asset_id"),
report_binding.get("sha256"),
)
return key in await _decisions(session, run)
def reviewable_turns(check, gate, binding, video):
"""只有验收门检查过的同份原片、两轮台词和声轨可转人工。"""
request = (gate.result_json or {}).get("review_request")
if request != {"asset_id": binding["asset_id"], "sha256": binding["sha256"]}:
return False
contract = (check.resolved_input_json or {}).get("parameters") or {}
roles = contract.get("speaker_ids") or []
intent = contract.get("turns") or []
rows = binding["report"].get("turns") or []
if len(roles) != 2 or len(set(roles)) != 2 or len(intent) != 2 or len(rows) != 2:
return False
end = 0
for expected, row in zip(intent, rows, strict=True):
speaker = expected.get("speaker_id")
start, stop = row.get("start_sample"), row.get("end_sample")
if (
speaker not in roles
or row.get("expected_speaker_id") != speaker
or row.get("listener_id") != next(s for s in roles if s != speaker)
or row.get("utterance_id") != expected.get("utterance_id")
or row.get("decision") not in {"pass", "indeterminate"}
or type(start) is not int
or type(stop) is not int
or not end <= start < stop <= (video.get("duration_frames") or 0) * 2000
):
return False
end = stop
return True
async def candidates(session, run, steps):
by_key = {s.step_key: s for s in steps}
decisions = await _decisions(session, run)
rows = []
for gate in steps:
recipe = gate.recipe_json or {}
if gate.kind != "dialogue.accepted" or not recipe.get("turn_report_key"):
continue
check = by_key.get(recipe["turn_report_key"])
video = by_key.get(recipe["video_key"])
if not check or check.state != "succeeded" or not video:
continue
binding = check.result_json or {}
report = binding.get("report") or {}
source = video.result_json or {}
if (
report.get("policy") != POLICY
or not binding.get("sha256")
or not source.get("asset_id")
or (report.get("source_sha256") or {}).get("video") != source.get("sha256")
):
continue
sid = recipe["unit_id"]
decision = decisions.get((sid, binding["asset_id"], binding["sha256"]))
rows.append(
dict(
shot_id=sid,
report_sha256=binding["sha256"],
report_asset_id=binding["asset_id"],
report=report,
video_asset_id=source["asset_id"],
manual_review=decision,
can_accept=not decision
and report.get("decision") == "indeterminate"
and reviewable_turns(check, gate, binding, source)
and gate.state == "awaiting_review"
and run.desired_state != "cancel"
and run.state not in {"succeeded", "cancelled", "cancelling", "failed"},
)
)
return rows
async def review(runtime, actor, draft_id, run_id, shot_id, body, key):
from app.services.orchestration.native_dialogue_engine import _read_report
from app.services.snapshots import snapshot_run
require_writable(runtime.settings)
if not body.note.strip():
fail(422, "turn_review_note_required", "请填写逐轮复核意见")
async with runtime.db.session() as session:
await require_session_user(session, actor)
await owned(session, WorkflowDraft, draft_id, actor.id)
run = await owned(session, WorkflowRun, run_id, actor.id)
if run.draft_id != draft_id:
fail(404, "resource_not_found", "候选不属于此故事")
receipt = await accept_submission(
session,
actor.id,
OPERATION,
key,
1,
dict(run_id=run.id, draft_id=draft_id, shot_id=shot_id, **body.model_dump()),
)
if receipt.resource_json:
return await snapshot_run(session, actor.id, run.id)
if run.version != body.expected_version:
fail(409, "run_version_conflict", "运行已更新,请刷新后重新查看候选")
steps = (
await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == run.id))
).all()
row = next(
(r for r in await candidates(session, run, steps) if r["shot_id"] == shot_id), None
)
if not row or not row["can_accept"] or row["report_sha256"] != body.report_sha256:
fail(409, "turn_review_unavailable", "该候选已变化或未进入可人工复核状态")
for asset_id, sha in (
(row["report_asset_id"], row["report_sha256"]),
(row["video_asset_id"], row["report"]["source_sha256"]["video"]),
):
asset = await owned(session, Asset, asset_id, actor.id)
if (
not asset.ready
or asset.library_scope != "private"
or asset.sha256 != sha
or not await verified_output(asset, runtime.settings)
):
fail(409, "turn_sources_changed", "候选视频或报告已变化,请重新检查镜头")
if (
asset.id == row["report_asset_id"]
and _read_report(asset, runtime.settings) != row["report"]
):
fail(409, "turn_sources_changed", "报告与冻结记录不一致")
receipt.resource_json = dict(
run_id=run.id,
shot_id=shot_id,
report_asset_id=row["report_asset_id"],
report_sha256=body.report_sha256,
video_asset_id=row["video_asset_id"],
reviewer_id=actor.id,
reviewer_name=actor.display_name or actor.username,
reviewed_at=utcnow().isoformat(),
decision="accept",
note=body.note,
)
gate = next(
s
for s in steps
if s.kind == "dialogue.accepted" and s.recipe_json["unit_id"] == shot_id
)
gate.state = "waiting"
gate.version += 1
if (
run.state == "blocked"
and (run.error_json or {}).get("code") == "native_turn_review_required"
):
run.state, run.error_json = "queued", None
await session.flush()
await emit_run(session, run)
result = await snapshot_run(session, actor.id, run.id)
await session.commit()
wake(runtime)
return result

View File

@ -289,7 +289,7 @@ async def create_child(session, r, step, settings):
if r.deleted_at is not None:
fail(410, "resource_purged", "工作流运行已删除")
snapshot = r.spec_snapshot
if snapshot.get("schema_version") in (3, 4, 5):
if snapshot.get("schema_version") in (3, 4, 5, 6):
if step.kind != "video.compose":
fail(409, "invalid_story_step", "故事运行只允许冻结素材合成")
frozen = snapshot["render_inputs"]
@ -397,7 +397,7 @@ async def control_run(session, r, desired):
if (
desired == "run"
and r.run_kind in {"story_auto", "workflow_auto"}
and (r.spec_snapshot or {}).get("schema_version") == 5
and (r.spec_snapshot or {}).get("schema_version") in (5, 6)
):
blocked = await session.scalar(
select(WorkflowStep.step_key)
@ -690,7 +690,7 @@ async def retry_step(
if j.state not in {"failed", "timed_out", "needs_attention"}:
fail(409, "step_not_retryable", "仅失败步骤允许重试")
if r.run_kind in {"story_auto", "workflow_auto"}:
if r.spec_snapshot.get("schema_version") == 5:
if r.spec_snapshot.get("schema_version") in (5, 6):
from app.services.orchestration.dialogue_engine import create_editor_child
else:
from app.services.orchestration.editor_engine import create_editor_child

View File

@ -33,7 +33,7 @@ def test_routes_and_mysql_metadata_are_unchanged():
}
# 007/008只允许合同内的追加列;原列定义与历史fixture仍逐项比较。
editor_columns = {
"visual_drafts": {"editor_manifest": ("JSON", True)},
"visual_drafts": {"editor_manifest": ("JSON", True), "caption_birth_intent": ("JSON", True)},
"visual_workflow_runs": {
"run_kind": ("VARCHAR(32)", False),
"output_goal": ("VARCHAR(16)", False),
@ -95,6 +95,10 @@ def test_routes_and_mysql_metadata_are_unchanged():
("/mode", "POST", ["200", "422"]),
("/dialogue/enable", "POST", ["200", "422"]),
("/dialogue/fork-prepared", "POST", ["201", "422"]),
("/dialogue/fork-cuts", "POST", ["200", "422"]),
("/captions/preview", "POST", ["200", "422"]),
("/runs/{run_id}/captions.srt", "GET", ["200", "422"]),
("/runs/{run_id}/turns/{shot_id}/review", "POST", ["200", "422"]),
)
]
assert all(r in actual["routes"] for r in editor_routes)

View File

@ -0,0 +1,67 @@
import pytest
from test_dialogue_engine import story
from test_caption_rhythm import STYLE, case
@pytest.mark.parametrize(
"choice,expected",
[
({}, None),
({"captions_mode": "none"}, None),
({"captions_mode": "manual"}, None),
({"captions_mode": "script"}, STYLE),
(
{
"captions_mode": "script",
"caption_presentation": {"punctuation": "preserve", "pacing": "sentence"},
},
{"punctuation": "preserve", "pacing": "sentence"},
),
],
)
async def test_create_intent_is_consumed_on_later_dialogue_enable(system, choice, expected):
c = system.client
created = await c.post("/api/stories", json={"spec": story(), "name": "新故事", **choice})
assert created.status_code == 201, created.text
did = created.json()["id"]
assert created.json()["editor_manifest"] is None
url = f"/api/editors/{did}/dialogue/enable"
enabled = await c.post(
url, json={"expected_version": 1}, headers={"Idempotency-Key": "enable-new"}
)
assert enabled.status_code == 200, enabled.text
m = enabled.json()["manifest"]
assert m["captions"].get("presentation") == expected
assert m["schema_version"] == (4 if expected else 3)
assert m["captions"]["mode"] == choice.get("captions_mode", "none")
assert (await c.get(f"/api/editors/{did}")).json()["manifest"] == m
async def test_explicitly_auto_captioned_native_story_has_default_at_birth(system):
m, _, _ = case()
resp = await system.client.post(
"/api/stories", json={"name": "新建原生对白", "spec": m["spec"], "captions_mode": "script"}
)
assert resp.status_code == 201, resp.text
assert resp.json()["editor_manifest"]["captions"]["presentation"] == STYLE
async def test_new_non_chinese_native_story_keeps_sentence_rendering(system):
m, _, _ = case()
m["spec"]["dialogue"]["language"] = "English"
resp = await system.client.post(
"/api/stories", json={"name": "English", "spec": m["spec"], "captions_mode": "script"}
)
assert resp.status_code == 201, resp.text
editor = resp.json()["editor_manifest"]
assert editor["schema_version"] == 3
assert editor["captions"] == dict(mode="script", cues=[])
async def test_new_native_story_without_automatic_captions_has_no_style(system):
m, _, _ = case()
resp = await system.client.post("/api/stories", json={"name": "无自动字幕", "spec": m["spec"]})
assert resp.status_code == 201, resp.text
editor = (await system.client.get("/api/editors/" + resp.json()["id"])).json()["manifest"]
assert editor["captions"] == dict(mode="none", cues=[])

View File

@ -0,0 +1,62 @@
from copy import deepcopy
import pytest
from test_native_dialogue_workflow import capabilities, native_story, _drive, _start
async def test_inspection_with_no_clean_audio_cannot_start_picture_generation(system):
did, draft = await native_story(system)
sid = draft["manifest"]["shot_ids"][0]
url = f"/api/editors/{did}"
body = dict(
output_goal="caption_inspect",
targets=["native_report:" + sid],
expected_version=draft["version"],
)
res = await system.client.post(url + "/plan", json=body)
assert res.status_code == 200, res.text
plan = res.json()
assert plan["steps"] == [] and plan["issues"][0]["unit_id"] == sid
rejected = await system.client.post(
url + "/runs",
json={**body, "expected_plan_hash": plan["plan_hash"]},
headers={"Idempotency-Key": "existing-audio-only"},
)
assert rejected.status_code == 422
assert not system.provider.submitted_payloads
async def test_existing_audio_inspection_only_submits_single_selected_inspect_job(system, tmp_path):
from app.services.dialogue import apply_pending_result
capabilities(system)
did, draft = await native_story(system)
rid = await _start(system, did, draft["version"])
_, _, state, error, _ = await _drive(system, rid, tmp_path)
assert state == "succeeded", error
await apply_pending_result(system.app.state.db, rid, system.settings)
url = f"/api/editors/{did}"
draft = (await system.client.get(url)).json()
sid = draft["manifest"]["shot_ids"][0]
body = dict(
output_goal="caption_inspect",
targets=["native_report:" + sid],
expected_version=draft["version"],
)
res = await system.client.post(url + "/plan", json=body)
assert res.status_code == 200, res.text
plan = res.json()
assert plan["issues"] == []
assert [(s["kind"], s["status"]) for s in plan["steps"]] == [
("audio.dialogue.inspect", "generate")
]
run = await system.client.post(
url + "/runs",
json={**body, "expected_plan_hash": plan["plan_hash"]},
headers={"Idempotency-Key": "inspect-one"},
)
assert run.status_code == 202, run.text
rid2 = run.json()["run"]["id"]
_, _, state, error, calls = await _drive(system, rid2, tmp_path)
assert state == "succeeded", error
assert calls == {"audio.dialogue.inspect": 1}

View File

@ -0,0 +1,262 @@
from copy import deepcopy
from test_native_dialogue_workflow import native_story
from test_native_dialogue_workflow import capabilities, _start, _drive
async def test_caption_only_plan_never_schedules_generation_to_find_missing_media(system):
did, draft = await native_story(system)
body = {"expected_version": draft["version"], "output_goal": "caption_film"}
response = await system.client.post(f"/api/editors/{did}/plan", json=body)
assert response.status_code == 200, response.text
plan = response.json()
assert plan["steps"] == []
assert plan["issues"][0]["code"] == "caption_source_unavailable"
rejected = await system.client.post(
f"/api/editors/{did}/runs",
json={**body, "expected_plan_hash": plan["plan_hash"]},
headers={"Idempotency-Key": "captions-only"},
)
assert rejected.status_code == 422
assert not system.provider.submitted_payloads
async def test_caption_preview_checks_version_and_does_not_save_changes(system):
did, draft = await native_story(system)
m = deepcopy(draft["manifest"])
m["captions"] = {
"mode": "manual",
"cues": [
{
"id": "a" * 32,
"anchor": "absolute",
"text": "屏幕字幕",
"start_frame": 13,
"end_frame": 29,
}
],
}
url = f"/api/editors/{did}/captions/preview"
preview = await system.client.post(
url, json={"expected_version": draft["version"], "manifest": m}
)
assert preview.status_code == 200, preview.text
assert [(r["text"], r["start_frame"], r["end_frame"]) for r in preview.json()["rows"]] == [
("屏幕字幕", 13, 29)
]
conflict = await system.client.post(url, json={"expected_version": draft["version"] - 1})
assert conflict.status_code == 409
current = (await system.client.get(f"/api/editors/{did}")).json()
assert (
current["version"] == draft["version"]
and current["manifest"]["captions"]["mode"] == "script"
)
def test_frozen_srt_uses_shared_adjacent_boundaries_and_utf8_text():
from app.services.caption_revision import encode_srt
rows = [
{"start_frame": 1, "end_frame": 3, "text": "第一句"},
{"start_frame": 3, "end_frame": 25, "text": "第二句"},
]
output = encode_srt(rows)
assert "00:00:00,041 --> 00:00:00,125\n第一句" in output
assert "00:00:00,125 --> 00:00:01,041\n第二句" in output
def test_manual_film_exports_its_frozen_render_table():
from types import SimpleNamespace
from app.services.caption_revision import frozen_rows
cues = [{"text": "人工确认的字幕。", "start_frame": 1, "end_frame": 12}]
run = SimpleNamespace(
run_kind="legacy", spec_snapshot={"render_inputs": {}, "render": {"subtitles": cues}}
)
assert frozen_rows(run, None) == cues
run.run_kind = "story_auto"
assert frozen_rows(run, None) is None
async def test_subtitle_reburn_keeps_frozen_versions_and_reuses_mixed_audio(
system, tmp_path, other_client
):
from app.services.dialogue import apply_pending_result
capabilities(system)
did, draft = await native_story(system)
rid = await _start(system, did, draft["version"])
_, _, state, error, _ = await _drive(system, rid, tmp_path)
assert state == "succeeded", error
await apply_pending_result(system.app.state.db, rid, system.settings)
base_url = f"/api/editors/{did}"
frozen = await system.client.get(f"{base_url}/runs/{rid}/captions.srt")
assert frozen.status_code == 200 and "-->" in frozen.text
assert (await other_client.get(f"{base_url}/runs/{rid}/captions.srt")).status_code == 404
first_film = (await system.client.get(f"/api/stories/{did}/film")).json()
system.settings.native_dialogue_enabled = False
async def offline():
raise AssertionError("字幕烧录不应调用推理服务")
system.provider.upstream_capabilities = offline
draft = (await system.client.get(base_url)).json()
m = draft["manifest"]
m["captions"]["cues"][0].update(text="新版对白字幕", text_override=True)
saved = await system.client.post(
base_url + "/save",
json={"expected_version": draft["version"], "manifest": m},
headers={"Idempotency-Key": "reburn-edit"},
)
assert saved.status_code == 200, saved.text
assert (await system.client.get(f"{base_url}/runs/{rid}/captions.srt")).text == frozen.text
assert (await system.client.get(f"/api/stories/{did}/film")).json()["asset"][
"id"
] == first_film["asset"]["id"]
body = dict(
expected_version=saved.json()["version"], output_goal="caption_film", execution_mode="batch"
)
plan = (await system.client.post(base_url + "/plan", json=body)).json()
assert not plan["issues"], plan
assert [(s["kind"], s["status"]) for s in plan["steps"]] == [
("audio.mix", "reuse"),
("captions.compile", "reuse"),
("video.compose", "generate"),
]
rid2 = (
await system.client.post(
base_url + "/runs",
json={**body, "expected_plan_hash": plan["plan_hash"]},
headers={"Idempotency-Key": "reburn-start"},
)
).json()["run"]["id"]
_, _, state, error, calls = await _drive(system, rid2, tmp_path)
assert state == "succeeded", error
assert calls == {"video.compose": 1}
assert (await system.client.get(f"{base_url}/runs/{rid}/captions.srt")).text == frozen.text
assert "新版对白字幕" in (await system.client.get(f"{base_url}/runs/{rid2}/captions.srt")).text
latest = (await system.client.get(f"/api/stories/{did}/film")).json()
assert latest["run_id"] == rid2 and latest["captions_srt_available"]
async def test_thousand_cues_render_on_their_exact_frames(tmp_path):
import shutil
import pytest
from app.adapters.media import run_process, subtitle_filter_args
binary = shutil.which("ffmpeg")
if not binary:
pytest.skip("FFmpeg unavailable")
cues = [
dict(start_frame=2 * i, end_frame=2 * i + 1, text=f"对白{i % 10} 3.5%") for i in range(1000)
]
args = await subtitle_filter_args(cues, tmp_path, (256, 144), binary)
assert max(map(len, args)) < 100
result = await run_process(
[
binary,
"-v",
"error",
"-f",
"lavfi",
"-i",
"color=s=256x144:r=24",
*args,
"-frames:v",
"2000",
"-f",
"framemd5",
"-",
],
cwd=tmp_path,
timeout=180,
)
checksums = [
line.rsplit(b",", 1)[1].strip() for line in result.splitlines() if not line.startswith(b"#")
]
assert len(checksums) == 2000
assert len(set(checksums[1::2])) == 1
assert checksums[1] not in checksums[::2] and len(set(checksums[::2])) == 10
async def test_downgrade_cannot_discard_v4_tombstones_or_v6_story(system):
did, draft = await native_story(system)
c = system.client
url = f"/api/editors/{did}"
legacy = deepcopy(draft["manifest"])
m = deepcopy(legacy)
m["schema_version"] = 4
line = m["spec"]["dialogue"]["utterances"][0]
edit = dict(
id="f" * 32,
utterance_id=line["id"],
source_text=line["text"],
source_start=0,
source_end=len(line["text"]),
deleted=True,
)
m["captions"].update(presentation=dict(punctuation="hide", pacing="rhythm"), edits=[edit])
async def save(version, manifest, key):
return await c.post(
url + "/save",
json=dict(expected_version=version, manifest=manifest),
headers={"Idempotency-Key": key},
)
saved = await save(draft["version"], m, "adopt-rhythm")
assert saved.status_code == 200, saved.text
v = saved.json()["version"]
stripped = deepcopy(saved.json()["manifest"])
stripped["captions"].pop("edits")
stripped["captions"].pop("presentation")
for payload, key in ((legacy, "old-client"), (stripped, "stripped-v4")):
resp = await save(v, payload, key)
assert (
resp.status_code == 409 and resp.json()["detail"]["code"] == "editor_upgrade_required"
)
assert (await c.get(url)).json()["manifest"]["captions"]["edits"][0]["deleted"]
paired = deepcopy(m)
paired["spec"]["schema_version"] = 6
saved = await save(v, paired, "adopt-turn-contract")
assert saved.status_code == 200, saved.text
rejected = await save(saved.json()["version"], m, "drop-story-contract")
assert rejected.status_code == 409
assert (await c.get(url)).json()["manifest"]["spec"]["schema_version"] == 6
async def test_trial_of_rhythm_edits_is_preview_only_on_legacy_native_story(system):
did, draft = await native_story(system)
url = f"/api/editors/{did}"
original = deepcopy(draft["manifest"])
candidate = deepcopy(original)
candidate["schema_version"] = 4
line = candidate["spec"]["dialogue"]["utterances"][0]
candidate["captions"].update(
mode="script",
presentation=dict(punctuation="hide", pacing="rhythm"),
edits=[
dict(
id="e" * 32,
utterance_id=line["id"],
source_text=line["text"],
source_start=0,
source_end=len(line["text"]),
text_override=True,
text="仅草稿",
timing_override=True,
start_frame=4,
end_frame=12,
)
],
)
preview = await system.client.post(
url + "/captions/preview",
json={"manifest": candidate, "expected_version": draft["version"]},
)
assert preview.status_code == 200, preview.text
assert [
(row["text"], row["start_frame"], row["end_frame"]) for row in preview.json()["rows"]
] == [("仅草稿", 4, 12)]
current = (await system.client.get(url)).json()
assert current["version"] == draft["version"] and current["manifest"] == original

View File

@ -0,0 +1,436 @@
from copy import deepcopy
import json
from pathlib import Path
import pytest
from fastapi import HTTPException
from app.domain.editors import validate_manifest
from app.services import editor_media
from test_dialogue_domain import A, B, U, C, manifest
STYLE = dict(punctuation="hide", pacing="rhythm")
SHA = "a" * 64
VIDEO = "b" * 64
def case():
m = manifest()
m["schema_version"] = 4
m["captions"].update(mode="script", presentation=STYLE.copy(), edits=[], cues=[])
d = m["spec"]["dialogue"]
d.update(generation="native_av", language="Chinese")
d["utterances"][0]["text"] = "陈叔,以后还开吗?"
speaker = d["utterances"][0]["speaker_id"]
for shot, assigned in zip(m["spec"]["shots"], [[], [U]]):
shot["performance"]["native_utterance_ids"] = assigned
shot["edit"].update(start_frame=0, duration_frames=124, dedup_frames=0)
m["spec"]["render"]["total_frames"] = 248
words = [
dict(text="陈叔", start_sample=0, end_sample=45000),
dict(text="以后还开吗", start_sample=48000, end_sample=112000),
]
r = dict(
audio_sha256=SHA,
sample_rate=48000,
source_start_sample=0,
source_end_sample=153600,
timestamp_source="whisper-word-timestamps",
timestamp_origin="audio_asset",
native_av_policy="native_av_v1",
decision="pass",
word_alignment_status="completed",
expected_text=d["utterances"][0]["text"],
speaker_id=speaker,
asr_revision="41f01f3fe87f28c78e2fbf8b568835947dd65ed9",
content_verification_policy="whisper-sensevoice-consensus-v1",
content_decision_source="whisper_sensevoice_consensus",
secondary_status="completed",
secondary_asr_revision="90c1c61912018b70ada0fcc024ea24aca62f2e63",
secondary_runtime_revision="6991744856587fa44379e8b5dcc432debffeb1be",
transcript="陈叔以后还开吗",
secondary_transcript="陈叔以后还开吗",
normalized_expected_text="陈叔以后还开吗",
normalized_transcript="陈叔以后还开吗",
normalized_secondary_transcript="陈叔以后还开吗",
reasons=[],
content_error_rate=0,
secondary_content_error_rate=0,
words=words,
)
probs = [0.99 if 8 <= i < 23 or 40 <= i < 75 else 0.01 for i in range(100)]
from app.domain.native_silence import POLICY, REVISION, MODEL_SHA256
r["silence_verification"] = dict(
policy=POLICY,
revision=REVISION,
model_sha256=MODEL_SHA256,
status="completed",
source="silero-vad-onnx-cpu",
decision="speech",
channels=2,
source_audio_sha256=SHA,
source_start_sample=0,
source_end_sample=153600,
sample_rate=16000,
sample_count=51200,
window_size_samples=512,
window_count=100,
threshold=0.5,
negative_threshold=0.35,
channel_probabilities=[probs, probs],
probabilities=probs,
)
bindings = {
"video:" + B: dict(sha256=VIDEO),
"native_audio:" + B: dict(
sha256=SHA, sample_count=153600, provenance=dict(audio_offset_samples=4000)
),
"native_alignment:" + B: dict(
provenance=dict(
native_av_policy="native_av_v1",
audio_sha256=SHA,
video_sha256=VIDEO,
shot_id=B,
audio_offset_samples=4000,
)
),
}
return m, bindings, {B: r}
def project(m, b, r):
return editor_media.preview_captions(m, b, reports=r)
def test_v4_keeps_edits_and_rejects_missing_parent_and_ambiguous_ids():
m, b, r = case()
legacy = manifest()
assert "presentation" not in validate_manifest(legacy)["captions"]
assert validate_manifest(m)["captions"]["presentation"] == STYLE
item = dict(
id=C,
utterance_id=U,
source_text="陈叔,以后还开吗?",
source_start=0,
source_end=3,
deleted=True,
)
m["captions"]["edits"] = [item, item]
with pytest.raises(HTTPException):
validate_manifest(m)
m["captions"]["edits"] = [dict(item, utterance_id=A)]
with pytest.raises(HTTPException):
validate_manifest(m)
def test_vad_pauses_and_author_glyphs_use_single_projection():
m, b, r = case()
before = deepcopy(m)
result = project(m, b, r)
assert not result["issues"]
left, right = result["rows"]
assert (left["text"], right["text"]) == ("陈叔", "以后还开吗")
assert 5 <= left["local_start_frame"] <= 9
assert left["end_frame"] + 6 <= right["start_frame"]
assert (left["source_start"], left["source_end"], right["source_end"]) == (0, 3, 9)
assert left["start_frame"] == 124 + left["local_start_frame"]
assert left["audio_sha256"] == SHA and left["status"] == "automatic"
assert editor_media.compile_captions(m, b, reports=r) == [
{k: row[k] for k in ("start_frame", "end_frame", "text")} for row in result["rows"]
]
assert m == before
def test_unmeasured_preview_identifies_parent_and_manual_calibration_resolves_it():
m, b, r = case()
r[B]["silence_verification"]["source_audio_sha256"] = VIDEO
pending = project(m, b, r)
assert pending["issues"][0]["unit_id"] == U
assert pending["rows"][0]["start_frame"] is None
with pytest.raises(ValueError, match="待校时"):
editor_media.compile_captions(m, b, reports=r)
m["captions"]["edits"] = [
dict(
id=C,
utterance_id=U,
source_start=0,
source_end=9,
source_text="陈叔,以后还开吗?",
timing_override=True,
start_frame=7,
end_frame=52,
)
]
assert editor_media.compile_captions(m, b, reports={}) == [
dict(start_frame=131, end_frame=176, text="陈叔以后还开吗")
]
def test_suppression_and_separate_locks_follow_source_range():
m, b, r = case()
parent = m["spec"]["dialogue"]["utterances"][0]
edit = dict(id=C, utterance_id=U, source_start=0, source_end=3, source_text=parent["text"])
m["captions"]["edits"] = [dict(edit, deleted=True)]
assert [row["text"] for row in project(m, b, r)["rows"]] == ["以后还开吗"]
m["captions"]["edits"] = [dict(edit, text_override=True, text="陈叔!")]
left, right = project(m, b, r)["rows"]
assert left["id"] == C and left["text"] == "陈叔!" and left["local_start_frame"] > 0
parent["text"] = "陈叔,陈叔,以后还开吗?"
assert project(m, b, r)["issues"]
def test_display_punctuation_preserves_semantic_tokens():
from app.domain.rhythm_captions import display_text
assert (
display_text("“8:30”,值 -3.25,型号 X-100;don't!", "hide")
== "8:30 值 -3.25 型号 X-100 don't"
)
assert display_text("等……等。", "hide") == "等等"
assert display_text("下班?", "preserve") == "下班?"
def test_real_lamp_historical_rows_and_late_speech():
root = Path(__file__).resolve().parents[2] / "outputs" / "留一盏灯_H3多人对白_20261127"
if not (root / "editor-v3.json").exists():
pytest.skip("local approved production sample is not installed")
m = json.loads((root / "editor-v3.json").read_text(encoding="utf-8-sig"))
frozen = json.loads((root / "字幕_绝对帧.json").read_text(encoding="utf-8-sig"))
assert editor_media.compile_captions(m, m["bindings"]) == frozen
m["schema_version"] = 4
m["captions"].update(presentation=STYLE.copy(), edits=[])
by_sha = {}
for path in root.glob("media/*/speech-report.json"):
r = json.loads(path.read_text(encoding="utf-8-sig"))
by_sha[r["audio_sha256"]] = r
reports = {sid: by_sha[m["bindings"]["native_audio:" + sid]["sha256"]] for sid in m["shot_ids"]}
result = project(m, m["bindings"], reports)
assert set(row["shot_id"] for row in result["rows"]) == set(m["shot_ids"])
assert not result["issues"]
first = [row for row in result["rows"] if row["shot_id"] == m["shot_ids"][0]]
assert [r["text"] for r in first] == ["陈叔", "以后不营业了吗"]
assert (
first[0]["local_start_frame"] > 48
and first[1]["local_start_frame"] - first[0]["local_end_frame"] >= 12
)
(eighth,) = [row for row in result["rows"] if row["shot_id"] == m["shot_ids"][7]]
assert eighth["text"] == "周末让我来吧" and eighth["status"] == "sentence_fallback"
assert 120 <= eighth["local_start_frame"] < eighth["local_end_frame"] <= 158
def test_single_line_recalculation_uses_only_its_shot_without_moving_it():
m, b, r = case()
result = editor_media.preview_captions(m, b, reports=r, utterance_id=U)
assert result == project(m, b, r)
assert editor_media.caption_shot_ids(m, U) == {B}
assert not editor_media.preview_captions(m, b, reports=r, utterance_id=C)["rows"]
def test_native_offsets_are_applied_once_after_trim_and_reorder():
m, b, r = case()
m["spec"]["shots"][1]["edit"].update(start_frame=4, duration_frames=120)
m["spec"]["render"]["total_frames"] = 244
before = project(m, b, r)
assert not before["issues"]
old = before["rows"][0]
assert old["start_frame"] == 128 and old["local_start_frame"] == 4
m["spec"]["shots"].reverse()
m["shot_ids"].reverse()
m["spec"]["dialogue"]["sequences"][0]["shot_ids"].reverse()
after = project(m, b, r)
assert [(row["id"], row["start_frame"] + 124) for row in after["rows"]] == [
(row["id"], row["start_frame"]) for row in before["rows"]
]
@pytest.mark.parametrize("count", [999, 1000, 1001])
def test_limit_counts_absolute_rows_and_auto_phrases_and_merges_only_same_turn(count):
m, b, r = case()
silent, speaking = m["spec"]["shots"]
intros = [dict(deepcopy(silent), id=f"{n + 7900:032x}") for n in range(9)]
m["spec"]["shots"] = [*intros, speaking]
m["shot_ids"] = [shot["id"] for shot in m["spec"]["shots"]]
m["spec"]["dialogue"]["sequences"][0]["shot_ids"] = m["shot_ids"].copy()
m["spec"]["render"]["total_frames"] = len(m["shot_ids"]) * 124
m["captions"]["cues"] = [
dict(id=f"{n + 891:032x}", anchor="absolute", start_frame=n, end_frame=n + 1, text="片名")
for n in range(count - 2)
]
result = project(m, b, r)
assert len(result["rows"]) == min(1000, count)
assert not result["issues"]
if count == 1001:
row = result["rows"][-1]
assert row["text"] == "陈叔以后还开吗" and row["utterance_id"] == U
m["captions"]["edits"] = [
dict(
id=C,
utterance_id=U,
source_text="陈叔,以后还开吗?",
source_start=0,
source_end=3,
text_override=True,
text="陈叔",
)
]
assert any(
i["code"] == "caption_limit" and i["unit_id"] == U for i in project(m, b, r)["issues"]
)
def test_two_manual_halves_can_merge_or_be_suppressed_without_automatic_revival():
m, b, r = case()
template = dict(id=C, utterance_id=U, source_text="陈叔,以后还开吗?", timing_override=True)
m["captions"]["edits"] = [
dict(template, source_start=0, source_end=3, start_frame=8, end_frame=22),
dict(template, id=A, source_start=3, source_end=9, start_frame=30, end_frame=49),
]
assert [(row["id"], row["text"]) for row in project(m, b, r)["rows"]] == [
(C, "陈叔"),
(A, "以后还开吗"),
]
m["captions"]["edits"] = [
dict(template, source_start=0, source_end=9, start_frame=8, end_frame=49)
]
assert [(row["id"], row["text"]) for row in project(m, b, r)["rows"]] == [(C, "陈叔以后还开吗")]
m["captions"]["edits"][0]["deleted"] = True
assert project(m, b, r) == dict(rows=[], issues=[])
def test_source_rewrite_ambiguous_word_map_falls_back_to_entire_utterance():
m, b, r = case()
line = m["spec"]["dialogue"]["utterances"][0]
line["spoken_text"] = line["text"]
line["text"] = "8:30,再开门。"
(row,) = project(m, b, r)["rows"]
assert (row["text"], row["status"]) == ("8:30 再开门", "sentence_fallback")
def test_protected_legacy_utterance_maps_each_lock_and_new_edit_can_unlock_timing():
m, b, r = case()
source = m["spec"]["dialogue"]["utterances"][0]["text"]
m["captions"]["cues"] = [
dict(
id=C,
anchor="utterance",
utterance_id=U,
text="人工改字!",
start_frame=1,
end_frame=6,
text_override=True,
timing_override=True,
)
]
b["native_alignment:" + B]["provenance"]["utterances"] = [
dict(utterance_id=U, start_sample=4000, end_sample=116000)
]
(row,) = project(m, b, r)["rows"]
assert row["id"] == C and row["text_override"] and row["timing_override"]
assert (row["local_start_frame"], row["local_end_frame"], row["text"]) == (3, 8, "人工改字!")
m["captions"]["edits"] = [
dict(
id=C,
utterance_id=U,
source_text=source,
source_start=0,
source_end=len(source),
text_override=True,
text=row["text"],
timing_override=False,
)
]
(edited,) = project(m, b, r)["rows"]
assert edited["text"] == "人工改字!" and not edited["timing_override"]
assert edited["local_start_frame"] > 3 and edited["local_end_frame"] > 8
def test_uncertain_turns_or_overlapping_manual_frames_cannot_be_burned():
m, b, r = case()
source = m["spec"]["dialogue"]["utterances"][0]["text"]
item = dict(
id=C,
utterance_id=U,
source_text=source,
source_start=0,
source_end=3,
timing_override=True,
start_frame=8,
end_frame=56,
)
m["captions"]["edits"] = [item]
assert any(i["code"] == "caption_overlap" for i in project(m, b, r)["issues"])
with pytest.raises(ValueError, match="重叠"):
editor_media.compile_captions(m, b, reports=r)
def test_ambiguous_old_occurrence_of_tombstone_survives_for_review():
m, b, r = case()
source = m["spec"]["dialogue"]["utterances"][0]["text"]
m["captions"]["edits"] = [
dict(
id=C,
utterance_id=U,
source_text="陈叔," + source,
source_start=0,
source_end=3,
deleted=True,
)
]
assert any(i["code"] == "caption_edit_conflict" for i in project(m, b, r)["issues"])
def test_accepted_two_person_audio_uses_shot_scoped_recognition_and_separate_turns():
m, b, r = case()
m["spec"]["schema_version"] = 6
d = m["spec"]["dialogue"]
first = d["utterances"][0]
second = dict(first, id="e" * 32, speaker_id=C, text="以后还开吗?")
first["text"] = "陈叔,"
d["utterances"].append(second)
d["speakers"].append(dict(d["speakers"][0], id=C, name="乙"))
d["sequences"][0]["utterance_ids"] = [U, "e" * 32]
m["spec"]["shots"][1]["performance"].update(
dialogue_staging="two_person_turns", native_utterance_ids=[U, "e" * 32]
)
r[B]["speaker_id"] = B
gate = b["native_alignment:" + B]
gate["sha256"] = "e" * 64
b["native_report:" + B] = dict(sha256=gate["sha256"])
gate["provenance"].update(
turn_decision="pass",
turn_certificate_sha256="c" * 64,
turn_report_sha256="d" * 64,
turn_report_asset_id=C,
)
projected = project(m, b, r)
assert not projected["issues"]
assert [(row["turn_id"], row["speaker_id"], row["text"]) for row in projected["rows"]] == [
(U, first["speaker_id"], "陈叔"),
("e" * 32, C, "以后还开吗"),
]
assert projected["rows"][0]["end_frame"] < projected["rows"][1]["start_frame"]
del gate["provenance"]["turn_decision"]
assert all(row["status"] == "pending" for row in project(m, b, r)["rows"])
def test_replaced_source_preserves_timing_lock_for_explicit_renewal():
m, b, r = case()
source = m["spec"]["dialogue"]["utterances"][0]["text"]
edit = dict(
id=C,
utterance_id=U,
source_text=source,
source_start=0,
source_end=len(source),
timing_override=True,
start_frame=8,
end_frame=52,
audio_sha256="e" * 64,
)
m["captions"]["edits"] = [edit]
stale = project(m, b, r)
assert stale["rows"][0]["local_start_frame"] == 8 and stale["rows"][0]["timing_override"]
assert any(i["code"] == "caption_audio_changed" for i in stale["issues"])
edit["audio_sha256"] = SHA
assert not project(m, b, r)["issues"]

View File

@ -46,8 +46,8 @@ async def test_capabilities_advertise_both_versions_without_enabling_unverified_
assert response.status_code == 200
caps = response.json()["editable_production"]
assert caps["schema_version"] == 1
assert caps["supported_schema_versions"] == [1, 2, 3]
assert caps["story_schema_versions"] == [3, 4, 5]
assert caps["supported_schema_versions"] == [1, 2, 3, 4]
assert caps["story_schema_versions"] == [3, 4, 5, 6]
assert caps["continuity"]["available"] is False

View File

@ -0,0 +1,102 @@
from copy import deepcopy
from test_native_two_person_turns import pair
def test_split_preserves_other_shots_caption_anchors_and_orders():
from app.services.dialogue_cuts import project_cuts
from app.domain.dialogue import StorySpecV6
m = pair()
m["schema_version"] = 4
old = m["shot_ids"][0]
seq = m["spec"]["dialogue"]["sequences"][0]
quiet = deepcopy(m["spec"]["shots"][0])
quiet.update(id="c" * 32, cast=[])
quiet["performance"] = dict(sequence_id=seq["id"], native_utterance_ids=[])
seq["shot_ids"].append(quiet["id"])
m["spec"]["shots"].append(quiet)
m["shot_ids"].append(quiet["id"])
m["bindings"] = {
"video:" + old: {"asset_id": "1" * 32},
"frame:" + quiet["id"]: {"asset_id": "3" * 32},
}
m["captions"]["cues"] = [
{
"id": "d" * 32,
"anchor": "shot",
"shot_id": old,
"text": "掌声",
"start_frame": 12,
"end_frame": 25,
"timing_override": True,
}
]
source = deepcopy(m)
projected, preview, locks = project_cuts(m, old, "双人切镜")
assert m == source
assert not locks
assert preview["shots"][0]["speaker_id"] == m["spec"]["dialogue"]["utterances"][0]["speaker_id"]
assert len(preview["shots"]) == 2 and preview["warnings"]
assert projected["shot_ids"][0] == old and projected["shot_ids"][2] == quiet["id"]
assert projected["spec"]["dialogue"]["sequences"][0]["shot_ids"] == projected["shot_ids"]
assert projected["captions"]["cues"] == m["captions"]["cues"]
assert projected["bindings"] == {"frame:" + quiet["id"]: {"asset_id": "3" * 32}}
assert [s["performance"].get("dialogue_staging") for s in projected["spec"]["shots"]] == [
None,
None,
None,
]
StorySpecV6.model_validate(projected["spec"])
def test_split_lists_irreplaceable_locked_video_and_keeps_it_in_source():
from app.services.dialogue_cuts import project_cuts
m = pair()
sid = m["shot_ids"][0]
m["bindings"]["video:" + sid] = {"locked": True}
_, preview, locks = project_cuts(m, sid, "切镜副本")
assert "video:" + sid in locks
assert any("锁" in w for w in preview["warnings"])
assert m["bindings"]["video:" + sid]["locked"]
async def test_confirm_forks_once_and_keeps_original(system):
from test_native_dialogue_workflow import native_story
from app.models import WorkflowDraft
from sqlalchemy import select, func
did, state = await native_story(system)
m = state["manifest"]
m.update(spec=pair()["spec"], schema_version=4)
for sp in m["spec"]["dialogue"]["speakers"]:
sp.pop("face_reference_asset_id")
sp.pop("voice_reference_asset_id")
saved = await system.client.post(
f"/api/editors/{did}/save",
json=dict(expected_version=state["version"], manifest=m),
headers={"Idempotency-Key": "save-pair-cuts"},
)
assert saved.status_code == 200, saved.text
body = dict(
expected_version=saved.json()["version"], shot_id=m["shot_ids"][0], name="切镜新故事"
)
url = f"/api/editors/{did}/dialogue/fork-cuts"
preview = await system.client.post(url, json={**body, "confirm": False})
assert preview.status_code == 200 and len(preview.json()["shots"]) == 2, preview.text
async with system.app.state.db.session() as s:
assert await s.scalar(select(func.count()).select_from(WorkflowDraft)) == 1
headers = {"Idempotency-Key": "new-cut-story"}
result = await system.client.post(url, json={**body, "confirm": True}, headers=headers)
assert result.status_code == 200, result.text
assert len(result.json()["manifest"]["shot_ids"]) == 2
replay = await system.client.post(url, json={**body, "confirm": True}, headers=headers)
assert replay.status_code == 200 and replay.json() == result.json()
async with system.app.state.db.session() as s:
assert await s.scalar(select(func.count()).select_from(WorkflowDraft)) == 2
source = await s.get(WorkflowDraft, did)
assert (
source.version == saved.json()["version"]
and source.editor_manifest == saved.json()["manifest"]
)

View File

@ -0,0 +1,128 @@
from copy import deepcopy
from sqlalchemy import select
from app.models import Asset, WorkflowDraft, WorkflowRun, WorkflowStep
from app.services.dialogue import apply_pending_result
from test_dialogue_workflow import asset, wav
from test_native_dialogue_workflow import capabilities, native_story, _drive, _start
async def test_remix_with_missing_source_is_non_executable(system):
did, draft = await native_story(system)
url = f"/api/editors/{did}"
body = dict(expected_version=draft["version"], output_goal="mix_film")
response = await system.client.post(url + "/plan", json=body)
assert response.status_code == 200, response.text
plan = response.json()
assert not plan["steps"] and any(
i["unit_id"] == draft["manifest"]["shot_ids"][0] for i in plan["issues"]
)
rejected = await system.client.post(
url + "/runs",
json={**body, "expected_plan_hash": plan["plan_hash"]},
headers={"Idempotency-Key": "missing-source-remix"},
)
assert rejected.status_code == 422
assert not system.provider.submitted_payloads
async def test_mix_revision_recovers_without_prior_mix_and_uses_new_gain_offline(system, tmp_path):
capabilities(system)
did, draft = await native_story(system)
rid = await _start(system, did, draft["version"])
_, _, state, error, _ = await _drive(system, rid, tmp_path)
assert state == "succeeded", error
await apply_pending_result(system.app.state.db, rid, system.settings)
url = f"/api/editors/{did}"
old_srt = (await system.client.get(f"{url}/runs/{rid}/captions.srt")).text
original_film = (await system.client.get(f"/api/stories/{did}/film")).json()["asset"]["id"]
async with system.app.state.db.session() as s:
owner = (await s.get(WorkflowDraft, did)).owner_id
# 老混音回执缺失,但已选的镜头、净音轨和原成片仍在。
old = await s.scalar(
select(WorkflowStep).where(
WorkflowStep.run_id == rid, WorkflowStep.step_key == "dialogue_mix"
)
)
old.result_json = {}
bgm = await asset(s, system, owner, "audio", wav(24000), duration=0.5)
aid = bgm.id
await s.commit()
async def offline():
raise AssertionError("重混音不应依赖推理服务")
system.settings.native_dialogue_enabled = False
system.provider.upstream_capabilities = offline
editor = (await system.client.get(url)).json()
m = deepcopy(editor["manifest"])
original_cues = deepcopy(m["captions"])
m["audio"]["layers"] = [
dict(id="f" * 32, asset_id=aid, anchor="absolute", role="bgm", gain_db=-15.5)
]
saved = await system.client.post(
url + "/save",
json=dict(expected_version=editor["version"], manifest=m),
headers={"Idempotency-Key": "gain"},
)
assert saved.status_code == 200, saved.text
body = dict(expected_version=saved.json()["version"], output_goal="mix_film")
plan = await system.client.post(url + "/plan", json=body)
assert plan.status_code == 200, plan.text
plan = plan.json()
assert not plan["issues"] and {s["kind"] for s in plan["steps"]} == {
"audio.normalize",
"audio.mix",
"captions.compile",
"video.compose",
}, plan
caption_only = (
await system.client.post(url + "/plan", json={**body, "output_goal": "caption_film"})
).json()
assert not caption_only["steps"] and any(
i["code"] == "caption_mix_unavailable" for i in caption_only["issues"]
)
started = await system.client.post(
url + "/runs",
json={**body, "expected_plan_hash": plan["plan_hash"]},
headers={"Idempotency-Key": "only-remix"},
)
assert started.status_code == 202, started.text
new = started.json()["run"]["id"]
result, _, state, error, calls = await _drive(system, new, tmp_path)
assert state == "succeeded", error
assert calls == {"audio.normalize": 1, "audio.mix": 1, "video.compose": 1}
assert result["captions"] == original_cues
assert (await system.client.get(f"{url}/runs/{new}/captions.srt")).text == old_srt
assert (await system.client.get(f"{url}/runs/{rid}/captions.srt")).text == old_srt
async with system.app.state.db.session() as s:
run = await s.get(WorkflowRun, new)
mix = await s.scalar(
select(WorkflowStep).where(WorkflowStep.run_id == new, WorkflowStep.kind == "audio.mix")
)
(segment,) = [x for x in mix.resolved_input_json["input"]["segments"] if x["role"] == "bgm"]
assert segment["gain_db"] == -15.5
assert mix.result_json["sample_count"] == run.prepared_plan["timing"]["total_frames"] * 2000
assert (
run.current_output_asset_id != original_film
and (await s.get(Asset, original_film)).ready
)
# 同一版可安全重混音的镜头分别移除净音轨、损坏已存时基,任何一种都必须停在计划。
from app.services.mix_revision import plan_remix
async with system.app.state.db.session() as session:
d = await session.get(WorkflowDraft, did)
sid = m["shot_ids"][0]
for problem in ("audio", "timing"):
bad = deepcopy(m)
if problem == "audio":
del bad["bindings"]["native_audio:" + sid]
else:
bad["bindings"]["native_alignment:" + sid]["provenance"][
"audio_offset_samples"
] += 2000
blocked = await plan_remix(session, d, bad, body, system.settings)
assert not blocked["steps"] and not blocked["_recipes"]
expected = "mix_source_missing" if problem == "audio" else "mix_timing_invalid"
assert any(i["code"] == expected and i["unit_id"] == sid for i in blocked["issues"])

View File

@ -230,7 +230,7 @@ def _wav(path, frames, rate=32000):
w.writeframes(b"\x10\x00\xf0\xff" * frames)
async def _drive(system, rid, work, *, bad_report=None):
async def _drive(system, rid, work, *, bad_report=None, turn_inspector=None):
from app.services.orchestration.workflow_engine import advance_run
from app.adapters.provider.client import Provider
from test_dialogue_workflow import configure_media_tools
@ -350,6 +350,12 @@ async def _drive(system, rid, work, *, bad_report=None):
)
await _asset(s, system, job, result.outputs[0], kind, **metadata)
job.result_json = result.result
elif step.kind == "audio.dialogue.inspect" and p.get("turn_policy"):
report = turn_inspector(step)
path = itemwork / "turns.json"
path.write_text(json.dumps(report), encoding="utf-8")
await _asset(s, system, job, path, "json")
job.result_json = {"decision":report["decision"]}
elif step.kind == "audio.dialogue.inspect":
audio = await s.get(Asset, job.input_json["audio_asset_id"])
with wave.open(

View File

@ -0,0 +1,387 @@
from copy import deepcopy
import pytest
from pydantic import ValidationError
from test_native_dialogue_engine import manifest
def pair():
m = manifest()
spec = m["spec"]
spec["schema_version"] = 6
d, shot = spec["dialogue"], spec["shots"][0]
one = d["speakers"][0]
two = dict(deepcopy(one), id="5" * 32, entity_id="6" * 32, name="陈叔")
for i, sp in enumerate([one, two]):
sp.update(
model_speaker_number=i + 3,
face_reference_asset_id=str(i + 1) * 32,
voice_reference_asset_id=str(i + 7) * 32,
)
spec["entities"].append(dict(deepcopy(spec["entities"][0]), id=two["entity_id"]))
shot["cast"].append(dict(deepcopy(shot["cast"][0]), id="9" * 32, entity_id=two["entity_id"]))
d["speakers"].append(two)
line = dict(d["utterances"][0], id="a" * 32, speaker_id=two["id"], text="好啊。")
d["utterances"].append(line)
ids = [u["id"] for u in d["utterances"]]
d["sequences"][0]["utterance_ids"] = ids
shot["performance"].update(
dialogue_staging="two_person_turns",
native_utterance_ids=ids,
visible_speaker_ids=[one["id"], two["id"]],
first_frame_sha256="a" * 64,
listener_reactions={ids[0]: "听着点头", ids[1]: "微微一笑"},
)
return m
def test_explicit_v6_turns_use_stable_numbers_and_prompt():
from app.domain.dialogue import StorySpecV6, StorySpecV5
from app.domain.native_dialogue import compile_native_shots
m = pair()
StorySpecV6.model_validate(m["spec"])
with pytest.raises(ValidationError):
StorySpecV5.model_validate(dict(m["spec"], schema_version=5))
r = compile_native_shots(m)
assert not r["issues"]
shot = r["shots"][0]
assert shot["speaker_id"] is None
assert [t["utterance_id"] for t in shot["turns"]] == m["spec"]["dialogue"]["sequences"][0][
"utterance_ids"
]
assert all(word in shot["prompt"] for word in ["S3", "S4", "微微一笑", "点头", "闭"])
m["spec"]["dialogue"]["speakers"].reverse()
assert compile_native_shots(m)["shots"][0]["context_hash"] == shot["context_hash"]
def test_incomplete_pair_is_editable_but_unplannable():
from app.domain.dialogue import StorySpecV6
from app.domain.native_dialogue import compile_native_shots
m = pair()
del m["spec"]["dialogue"]["speakers"][0]["voice_reference_asset_id"]
StorySpecV6.model_validate(m["spec"])
assert "native_turn_reference_required" in {
i["code"] for i in compile_native_shots(m)["issues"]
}
def test_single_native_cert_does_not_admit_two_person_workflow():
from app.services.orchestration.native_dialogue_engine import _turn_generation_issue
m = pair()
from app.domain.native_dialogue import compile_native_shots
shot = compile_native_shots(m)["shots"][0]
assert _turn_generation_issue(shot, {"sha256": "a" * 64})["code"] == "native_turns_uncertified"
assert _turn_generation_issue(shot, {"sha256": "b" * 64})["code"] == "native_turn_frame_changed"
def test_only_turn_scope_certificate_can_open_printed_frame_count():
from app.adapters.provider.native_av import turn_certificate
from app.domain.video_generation import H3_NATIVE_AV_TP2_PROFILE as profile
p = dict(profile=profile, width=1344, height=768, num_frames=158)
assert turn_certificate({"video_generation": {"native_av_tp2": {"available": True}}}, p) is None
proof = dict(
available=True,
decision="pass",
audited=True,
policy="h3-two-person-turns-screen-v1",
release_policy="h3-two-person-turns-release-v1",
profile=profile,
revision="12253298adb81e36757eabebb81d2ba1c0cc70cc",
runtime_revision="423ab90580b2847998591669b8326f47b6d14d8b",
width=1344,
height=768,
num_frames=158,
language="Chinese",
fps=24,
first_pass=18,
overall_pass=22,
tasks=24,
report_sha256="b" * 64,
)
upstream = {"dialogue": {"two_person_turns": proof}}
assert turn_certificate(upstream, p) == "b" * 64
assert turn_certificate(upstream, dict(p, num_frames=141)) is None
assert turn_certificate(upstream, dict(p, width=768, height=1344)) is None
def test_turn_audit_uses_only_owned_asset_slots_and_distinct_refs():
from app.adapters.provider.dialogue_gpu import validate, SPEECH_INSPECT
from app.domain.errors import MediaError
ids = [f"{i:032x}" for i in range(10)]
args = dict(
profile="dialogue-audio-v1",
turn_policy="h3-two-person-turns-screen-v1",
certificate_sha256="d" * 64,
first_frame_sha256="a" * 64,
speaker_ids=["a" * 32, "b" * 32],
turns=[
dict(utterance_id="f" * 32, speaker_id="a" * 32, text="等等。"),
dict(utterance_id="e" * 32, speaker_id="b" * 32, text="好的。"),
],
)
validate(SPEECH_INSPECT, {"asset_ids": ids}, args)
with pytest.raises(MediaError):
validate(SPEECH_INSPECT, {"asset_ids": ids[:-1] + [ids[-2]]}, args)
@pytest.mark.parametrize("candidate_status", ["pass", "indeterminate", "reject", "incomplete"])
async def test_save_pair_then_plan_dedicated_check_and_gate_without_single_face_bypass(
system, tmp_path, candidate_status
):
from io import BytesIO
import wave
from PIL import Image
from app.models import WorkflowDraft
from test_dialogue_workflow import asset
from test_native_dialogue_workflow import native_story, capabilities
from app.adapters.provider.native_av import REVISION, RUNTIME_REVISION, TURN_POLICY
from app.domain.native_dialogue import compile_native_shots
capabilities(system)
did, state = await native_story(system)
m = state["manifest"]
m["schema_version"] = 4
m["spec"] = pair()["spec"]
shot = m["spec"]["shots"][0]
async with system.app.state.db.session() as session:
owner = (await session.get(WorkflowDraft, did)).owner_id
pictures = []
for color in ("navy", "gold", "pink"):
image = BytesIO()
Image.new("RGB", (128, 128), color).save(image, format="PNG")
pictures.append(await asset(session, system, owner, "image", image.getvalue()))
for i, role in enumerate(m["spec"]["dialogue"]["speakers"]):
sound = BytesIO()
with wave.open(sound, "wb") as w:
w.setparams((1, 2, 48000, 0, "NONE", ""))
w.writeframes(bytes([i, 0]) * 48000)
voice = await asset(session, system, owner, "audio", sound.getvalue(), 1)
role.update(face_reference_asset_id=pictures[i].id, voice_reference_asset_id=voice.id)
frame = pictures[2]
m["bindings"]["frame:" + shot["id"]] = dict(
asset_id=frame.id, sha256=frame.sha256, kind="image", source="manual", locked=False
)
shot["performance"]["first_frame_sha256"] = frame.sha256
await session.commit()
saved = await system.client.post(
f"/api/editors/{did}/save",
json=dict(expected_version=state["version"], manifest=m),
headers={"Idempotency-Key": "pair-save"},
)
assert saved.status_code == 200, saved.text
reopened = await system.client.get(f"/api/editors/{did}")
assert (
reopened.status_code == 200
and reopened.json()["manifest"]["spec"]["shots"][0]["performance"]
== saved.json()["manifest"]["spec"]["shots"][0]["performance"]
)
args = dict(
expected_version=saved.json()["version"],
output_goal="media",
targets=["video:" + shot["id"]],
)
p = await system.client.post(f"/api/editors/{did}/plan", json=args)
assert p.status_code == 200, p.text
assert {i["code"] for i in p.json()["issues"]} == {"native_turns_uncertified"}, p.text
assert [r["key"] for r in p.json()["steps"] if r["kind"] == "audio.dialogue.inspect"] == [
"nq_0001",
"nt_0001",
]
refused = await system.client.post(
f"/api/editors/{did}/runs",
json={**args, "expected_plan_hash": p.json()["plan_hash"]},
headers={"Idempotency-Key": "pair-closed"},
)
assert refused.status_code == 422, refused.text
original = system.provider.upstream_capabilities
native = compile_native_shots(m)["shots"][0]
async def audited():
snapshot = await original()
snapshot["dialogue"]["two_person_turns"] = dict(
available=True,
decision="pass",
audited=True,
policy=TURN_POLICY,
release_policy="h3-two-person-turns-release-v1",
revision=REVISION,
runtime_revision=RUNTIME_REVISION,
profile=native["parameters"]["profile"],
width=1344,
height=768,
num_frames=native["parameters"]["num_frames"],
language="Chinese",
fps=24,
first_pass=18,
overall_pass=22,
tasks=24,
report_sha256="f" * 64,
)
return snapshot
system.provider.upstream_capabilities = audited
permitted = await system.client.post(f"/api/editors/{did}/plan", json=args)
assert permitted.status_code == 200 and not permitted.json()["issues"], permitted.text
assert permitted.json()["plan_hash"] != p.json()["plan_hash"]
system.provider.upstream_capabilities = original
revoked = await system.client.post(
f"/api/editors/{did}/runs",
json={**args, "expected_plan_hash": permitted.json()["plan_hash"]},
headers={"Idempotency-Key": "revoked-pair"},
)
assert revoked.status_code in (409, 422), revoked.text
system.provider.upstream_capabilities = audited
run = await system.client.post(
f"/api/editors/{did}/runs",
json={**args, "expected_plan_hash": permitted.json()["plan_hash"]},
headers={"Idempotency-Key": "pair-media"},
)
assert run.status_code == 202, run.text
from test_native_dialogue_workflow import _drive
from app.adapters.provider.native_av import TURN_SOURCES
from app.domain.stories import digest
turns = m["spec"]["dialogue"]["utterances"]
def split_speech(report):
report["words"] = [
dict(text=u["text"], start_sample=12000 + i * 48000, end_sample=48000 + i * 48000)
for i, u in enumerate(turns)
]
def measured(step):
# 外部模型替身只在隔离测试中使用,产物绑定、驱动 DAG 和放行使用真实服务路径。
result = step.resolved_input_json
contract = result["parameters"]
hashes = dict(
zip(
TURN_SOURCES,
[result["input_sha256"][a] for a in result["input"]["asset_ids"]],
strict=True,
)
)
ids = contract["speaker_ids"]
checks = {
k: dict(decision="pass")
for k in (
"geometry",
"audio_binding",
"visual",
"tracking",
*["tail_" + sp for sp in ids],
)
}
checks["geometry"].update(
width=1344, height=768, fps=24, frames=native["parameters"]["num_frames"]
)
checks["visual"].update(source_matched=True, review_sha256=hashes["visual_review"])
return dict(
policy=TURN_POLICY,
controls=False,
certificate_sha256=contract["certificate_sha256"],
source_sha256=hashes,
decision=candidate_status if candidate_status != "incomplete" else "indeterminate",
checks=checks,
tracks={
sp: [
dict(
frame=i,
identity_similarities=[0.9, 0.1] if side == 0 else [0.1, 0.9],
box=[5, 5, 60, 60],
track_iou=1.0,
)
for i in range(native["parameters"]["num_frames"])
]
for side, sp in enumerate(ids)
},
author_sha256=digest(
dict(
speaker_ids=ids,
turns=contract["turns"],
first_frame_sha256=hashes["first_frame"],
references=[hashes[k] for k in ("face_0", "face_1", "voice_0", "voice_1")],
)
),
turns=[]
if candidate_status == "incomplete"
else [
dict(
utterance_id=u["id"],
expected_speaker_id=u["speaker_id"],
listener_id=ids[1 - i],
start_sample=12000 + i * 48000,
end_sample=48000 + i * 48000,
decision=candidate_status
if candidate_status != "incomplete"
else "indeterminate",
voice=dict(
observed_speaker_id=u["speaker_id"]
if candidate_status == "pass"
else ids[1 - i]
if candidate_status == "reject"
else None
),
speaker_sync=dict(decision="pass"),
listener_sync=dict(decision="indeterminate"),
listener_rest=dict(decision="pass"),
)
for i, u in enumerate(turns)
],
)
final, _, status, error, calls = await _drive(
system, run.json()["run"]["id"], tmp_path, bad_report=split_speech, turn_inspector=measured
)
if candidate_status != "pass":
from sqlalchemy import select
from app.models import WorkflowRun, WorkflowStep
rid = run.json()["run"]["id"]
assert status == "blocked", error
async with system.app.state.db.session() as s:
stored = await s.get(WorkflowRun, rid)
version = stored.version
gate = await s.scalar(
select(WorkflowStep).where(
WorkflowStep.run_id == rid, WorkflowStep.step_key == "ng_0001"
)
)
audit = await s.scalar(
select(WorkflowStep).where(
WorkflowStep.run_id == rid, WorkflowStep.step_key == "nt_0001"
)
)
assert gate.state == (
"awaiting_review" if candidate_status == "indeterminate" else "blocked"
)
sha = audit.result_json["sha256"]
review = await system.client.post(
f"/api/editors/{did}/runs/{rid}/turns/{shot['id']}/review",
json=dict(
expected_version=version,
decision="accept",
note="逐轮核对了两位角色的画面和原声",
report_sha256=sha,
),
headers={"Idempotency-Key": "manual-choice"},
)
if candidate_status in ("reject", "incomplete"):
assert review.status_code == 409, review.text
return
assert review.status_code == 200, review.text
final, _, status, error, further = await _drive(
system, rid, tmp_path, bad_report=split_speech, turn_inspector=measured
)
assert not further
assert status == "succeeded", error
assert calls["video.generate"] == 1 and calls["audio.dialogue.inspect"] == 2
assert final["bindings"]["native_alignment:" + shot["id"]]["provenance"]["turn_decision"] == (
"manual" if candidate_status == "indeterminate" else "pass"
)

View File

@ -22,8 +22,8 @@ async def test_readiness_distinguishes_protocol_and_drain_from_gpu_capacity(syst
async def test_editor_capability_explicitly_advertises_compatible_schema(system):
value = (await system.client.get("/api/capabilities")).json()
assert value["editable_production"]["schema_version"] == 1
assert value["editable_production"]["supported_schema_versions"] == [1, 2, 3]
assert value["editable_production"]["story_schema_versions"] == [3, 4, 5]
assert value["editable_production"]["supported_schema_versions"] == [1, 2, 3, 4]
assert value["editable_production"]["story_schema_versions"] == [3, 4, 5, 6]
async def test_maintenance_keeps_reads_and_login_but_blocks_draft_writes(system):

View File

@ -42,7 +42,7 @@ def test_upgrade_backfills_legacy_and_preserves_rows(tmp_path):
)
command.upgrade(config, "head")
with engine.begin() as c:
check_schema_revision(c, {"008"})
check_schema_revision(c, {"009"})
row = c.execute(
text("SELECT password_hash,must_change_password FROM visual_users WHERE id='owner'")
).one()

View File

@ -35,4 +35,4 @@ def test_v5_is_additive_and_matches_runtime_metadata(tmp_path):
# 历史升级断言仍验证 005;运行时 metadata 则在新增 006 后校验。
command.upgrade(config, "head")
with engine.begin() as connection:
check_schema_revision(connection, {"008"})
check_schema_revision(connection, {"009"})

View File

@ -34,7 +34,7 @@ def test_v6_preserves_005_assets_and_metadata(tmp_path):
assert connection.scalar(text("SELECT COUNT(*) FROM visual_asset_folders")) == 0
diff = schema_preflight(connection, Base.metadata)
assert diff.matches, diff.differences
check_schema_revision(connection, {"008"})
check_schema_revision(connection, {"009"})
for table in ("visual_jobs", "visual_drafts", "visual_workflow_runs"):
fks = inspect(connection).get_foreign_keys(table)
folder_fks = [f for f in fks if f["referred_table"] == "visual_folders"]

View File

@ -31,7 +31,7 @@ def test_007_preserves_legacy_run_and_adds_nullable_editor_fields(tmp_path):
command.upgrade(config, "007")
command.upgrade(config, "head")
with engine.begin() as c:
check_schema_revision(c, {"008"})
check_schema_revision(c, {"009"})
assert c.execute(
text("SELECT run_kind,output_goal,result_manifest FROM visual_workflow_runs")
).one() == ("legacy", "film", None)

View File

@ -11,7 +11,7 @@ from app.core.config import Settings
from app.core.database import Database
async def test_runtime_accepts_migrated_008_and_refuses_007(tmp_path):
async def test_runtime_accepts_migrated_009_and_refuses_older_schemas(tmp_path):
path = tmp_path / "v8.sqlite3"
config = Config(str(Path(__file__).parents[1] / "alembic.ini"))
config.attributes["url"] = "sqlite+aiosqlite:///" + str(path)
@ -28,6 +28,9 @@ async def test_runtime_accepts_migrated_008_and_refuses_007(tmp_path):
with pytest.raises(RuntimeError, match="[Ss]chema"):
await database.initialize()
await asyncio.to_thread(command.upgrade, config, "008")
with pytest.raises(RuntimeError, match="[Ss]chema"):
await database.initialize()
await asyncio.to_thread(command.upgrade, config, "009")
await database.initialize()
finally:
await database.close()
@ -62,7 +65,7 @@ def test_008_roundtrip_keeps_legacy_rows_and_rebuilds_metadata(tmp_path):
connection.scalar(text("SELECT password_hash FROM visual_users WHERE id='owner'"))
== "unchanged"
)
command.upgrade(config, "008")
command.upgrade(config, "head")
with engine.begin() as connection:
assert schema_preflight(connection, Base.metadata).matches
finally:

View File

@ -0,0 +1,104 @@
import json
from sqlalchemy import select
from app.models import WorkflowRun, WorkflowStep
from app.services.turn_review import POLICY, candidates, manually_accepted
from test_dialogue_workflow import asset
from test_native_dialogue_workflow import native_story, _start, capabilities
async def test_named_review_is_scoped_to_frozen_report_and_replay_safe(system):
capabilities(system)
did, draft = await native_story(system)
sid = draft["manifest"]["shot_ids"][0]
rid = await _start(system, did, draft["version"])
async with system.app.state.db.session() as session:
run = await session.get(WorkflowRun, rid)
steps = (
await session.scalars(select(WorkflowStep).where(WorkflowStep.run_id == rid))
).all()
gate = next(s for s in steps if s.kind == "dialogue.accepted")
video_step = next(s for s in steps if s.step_key == gate.recipe_json["video_key"])
video = await asset(session, system, run.owner_id, "video", b"test-video")
roles = ["a" * 32, "b" * 32]
intent = [
dict(utterance_id=str(i) * 32, speaker_id=speaker) for i, speaker in enumerate(roles)
]
turns = [
dict(
utterance_id=t["utterance_id"],
expected_speaker_id=t["speaker_id"],
listener_id=roles[1 - i],
start_sample=i * 48000,
end_sample=(i + 1) * 48000,
decision="indeterminate",
)
for i, t in enumerate(intent)
]
report = dict(
policy=POLICY,
decision="indeterminate",
turns=turns,
source_sha256={"video": video.sha256},
)
check = await asset(session, system, run.owner_id, "json", json.dumps(report).encode())
binding = dict(kind="json", asset_id=check.id, sha256=check.sha256, report=report)
video_step.result_json = {
"asset_id": video.id,
"sha256": video.sha256,
"duration_frames": 124,
}
audit = WorkflowStep(
run_id=rid,
step_key="nt_fixture",
kind="audio.dialogue.inspect",
semantic_input_hash="a" * 64,
state="succeeded",
result_json=binding,
resolved_input_json={"parameters": {"speaker_ids": roles, "turns": intent}},
)
session.add(audit)
gate.recipe_json = {**gate.recipe_json, "turn_report_key": audit.step_key}
gate.state = "awaiting_review"
gate.result_json = {"review_request": {"asset_id": check.id, "sha256": check.sha256}}
run.spec_snapshot = {**run.spec_snapshot, "schema_version": 6}
run.state, run.error_json = (
"blocked",
{"code": "native_turn_review_required", "step_key": gate.step_key},
)
await session.commit()
assert (await candidates(session, run, [*steps, audit]))[0]["can_accept"]
from app.services.turn_review import reviewable_turns
for invalid in ([], [*turns[:1], {**turns[1], "decision": "reject"}], turns[::-1]):
assert not reviewable_turns(
audit,
gate,
{**binding, "report": {**report, "turns": invalid}},
video_step.result_json,
)
body = dict(
expected_version=run.version,
report_sha256=check.sha256,
decision="accept",
note="已逐轮试听",
)
url = f"/api/editors/{did}/runs/{rid}/turns/{sid}/review"
invalid = await system.client.post(
url, json={**body, "report_sha256": "f" * 64}, headers={"Idempotency-Key": "wrong"}
)
assert invalid.status_code == 409
reply = await system.client.post(url, json=body, headers={"Idempotency-Key": "review"})
assert reply.status_code == 200, reply.text
assert reply.json()["run"]["state"] == "queued"
assert reply.json()["run"]["turn_reviews"][0]["manual_review"]["reviewer_id"]
replay = await system.client.post(url, json=body, headers={"Idempotency-Key": "review"})
assert (
replay.status_code == 200
and replay.json()["run"]["version"] == reply.json()["run"]["version"]
)
async with system.app.state.db.session() as session:
run = await session.get(WorkflowRun, rid)
assert await manually_accepted(session, run, gate, binding)
assert not await manually_accepted(session, run, gate, {**binding, "sha256": "b" * 64})

View File

@ -6,7 +6,7 @@
- 配置正式域名、HTTPS、`COOKIE_SECURE=true` 和 `PUBLIC_ACCESS=true`,更换初始管理员密码,使用专用数据库业务账号。私有配置及推理密钥不得进入前端、镜像、日志或版本库。
- 关闭本应用新准入,等待本应用在途任务和进程组完成清理。保留已排队任务;不得停止其他用户服务,也不得通过清空队列替代恢复。
- 联合备份数据库、工作空间、配置和当前部署版本,在隔离环境验证恢复及 Alembic 迁移。保留历史迁移,不用当前模型重写旧迁移。
- 连续长视频版本需要008:排空本项目运行并备份后,从007执行`alembic upgrade head`,新版API只接受008。008追加列和候选/质检表,保留旧Run和素材;不执行破坏性downgrade。回退不得用只支持007的旧API解释008,也不能覆盖上线后新增数据。迁移后再一致切换前端/API,不能仅更新页面。
- 当前业务 API 要求数据库版本 `009`。排空本项目运行并完成备份后,将已有 `008` 数据库用 `alembic upgrade head` 升级,再用 `alembic current` 确认显示 `009 (head)`。从 `007` 升级会依次经过 `008` 和 `009`。`009` 仅在草稿表增加可空的 `caption_birth_intent`,记录新故事创建时的字幕偏好;历史行取空值。先在隔离环境验证既有故事、成片与素材可读,再一致切换前端、API 和工作进程。回退按已验证的兼容程序与数据库备份执行,保护切换后的新增数据。
- 生产业务API设置`GPU_WINDOW_ENABLED=true`,本地开发保持false;先同步升级推理服务至`features.project_gpu_window=true`,再恢复准入。两类队列共用21:00–次日08:00窗口,当前阶段自然完成。两环境业务库和STATE_ROOT须隔离;历史无快照、上游结果未知的任务先核实,不自动重放或篡改幂等原包。
- 配音检查独立`SPEECH_TIMEOUT_SECONDS=330`、整体`SPEECH_TOTAL_TIMEOUT_SECONDS=360`与TTS队列/合成时限;轻量health不加载模型,部署须另验真实短句与取消清理。不得为普通回归启动真实模型。
- 一致更新业务 API、前端和需要升级的模型协议组件。业务 API 不加载 GPU 模型;GPU FIFO、外部用户优先、主存预算和 Qwen 按需预约规则继续生效。

950
docs/API使用手册.md Normal file
View File

@ -0,0 +1,950 @@
# API 接口与模型调度
[下载 OpenAPI 3.1 定义](openapi.json) · [打开故事操作手册](story.html)。本页与项目一起发布,无需外部 Swagger 服务。在 Postman 中选择 Import,导入下载的 JSON 文件,即可按接口查看方法、路径、查询参数、请求头与请求体模型,展开 components.schemas 查看字段类型、必填项和约束。导入后请按下文配置会话或 Bearer、CSRF 和幂等键。自动定义中,部分动态响应未声明字段,文件下载、事件流也可能被标成 JSON;实际返回类型和业务字段请使用对应章节。
## Postman 快速开始
1. 建立本地环境变量 `baseUrl`,值为网站地址加 `/api`。示例使用相对路径;导入的 OpenAPI 路径已包含 `/api`,避免拼接两次。
2. 发送 `POST {{baseUrl}}/auth/login`。Body 选择 raw → JSON,使用 `{"username":"{{username}}","password":"{{password}}"}`,两个变量均使用个人环境的本地值。Cookie Jar 将保存 cmvr_session。登录请求的 Post-response 脚本用下方第一行保存 CSRF。
3. 以相同会话发送 `GET {{baseUrl}}/capabilities`,按任务类型、profile、画幅检查是否可用。上传图片时用 `POST {{baseUrl}}/assets`,Body 选 form-data,键 file 类型选 File;成功后将 id 存为 imageId。
4. 发送 `POST {{baseUrl}}/jobs`,添加 `X-CSRF-Token: {{csrf}}` 与 `Idempotency-Key: {{requestKey}}`。每项新任务先生成一个新的 UUID 放入 requestKey;网络重发沿用原值。选择下文一份 JSON 作为 Body,把示例素材 ID 换成本人上传记录的 ID。提交请求的 Post-response 脚本用下方第二行保存任务 ID。
5. 用 `GET {{baseUrl}}/jobs/{{jobId}}` 查询。成功后在 result_assets 选取需要的素材并保存它的 id;`GET {{baseUrl}}/assets/{{assetId}}/content?download=1` 返回原始文件。数学推演另可从 result.text 直接读取结果。
```javascript
// 登录请求的 Post-response
if (pm.response.code === 200) pm.environment.set("csrf", pm.response.json().csrf_token);
```
```javascript
// POST /jobs 的 Post-response
if (pm.response.code === 202) pm.environment.set("jobId", pm.response.json().jobs[0].id);
```
## 1 服务地址与接口约定
### 1.1 地址
| 项目 | 值或含义 |
| --- | --- |
| 生产网站 | `https://video.svc.cmvr-iot.icu/` |
| 生产 API 根地址 | `https://video.svc.cmvr-iot.icu/api`,下文记为 `API_BASE` |
| 局域网备用网站与 API | `http://192.168.28.10:18193/` 与 `http://192.168.28.10:18193/api`;优先使用 HTTPS |
| 本地开发网站 | `http://127.0.0.1:5173` |
| 本地业务 API | `http://127.0.0.1:8000/api` |
| 下文路径 | 均相对于 `API_BASE`,例如 `/jobs` |
| 请求编码 | JSON 使用 UTF-8,`Content-Type: application/json`;上传使用 multipart |
| 时间 | ISO 8601,带 `Z` 或时区偏移;响应通常为 UTC |
| ID | 使用服务器返回的原始 ID;通常为 32 位小写十六进制字符串 |
FastAPI 在业务后端自身提供 `/openapi.json`、`/docs`;它们不带 `/api` 前缀。现有网站反代只明确代理 `/api/`,因此不能据此认定网站域名的 `/docs` 可访问,也不能把 `/api/docs`、`/api/openapi.json` 当作已经存在的接口。本文采用 Swagger 风格并不改变真实路由。
自动 OpenAPI 能描述 HTTP 外层模型;`POST /jobs` 的 `input`、`parameters` 为动态对象,模型特定字段还受业务合同校验。各任务的详细参数以下文及实时能力响应为准。示例响应为主要字段示例,实际 DTO 可能另有版本、来源和审计字段。
### 1.2 生产时段
生产保留 `GPU_WINDOW_ENABLED=true`,北京时间 `Asia/Shanghai` 的准入窗口为每天 **21:00 至次日 08:00**,交互和批量两种队列均受控。白天可登录、上传、编辑、提交排队、查询和下载已有成果;提交成功不代表立即执行。
08:00 时已经获准执行的阶段允许完成,后续阶段等待下一窗口。当前业务协调器的阶段准入也覆盖 CPU 合成和 Qwen 推演,不能假定“CPU 任务白天一定立即执行”。本地开发使用 `GPU_WINDOW_ENABLED=false`,与生产配置独立。
客户端不能传 `GPU_WINDOW_ENABLED`、`gpu_window_enabled`、`gpu_id`、`docker_id` 或任意系统命令来豁免调度。`execution_mode=interactive` 表示队列类别,不是全天算力通行证。
### 1.3 通用请求头
| 请求头 | 何时提供 | 规则 |
| --- | --- | --- |
| `Cookie` | 会话鉴权 | 登录后客户端自动保存 `cmvr_session`,不要自行构造 |
| `X-CSRF-Token` | 会话写请求 | 登录响应中的 token;用于 POST、PATCH、DELETE 等 |
| `Authorization` | 机器程序 | `Bearer cmvr_...`;与浏览器 Cookie 方案分开使用 |
| `Idempotency-Key` | 生成、运行及有关控制命令 | 建议 UUID;长度 1–128;同一业务意图保持同键、同参数 |
| `If-Match` | 使用版本 CAS 的 PATCH/DELETE | 对象最近读取到的版本;具体接口见后文 |
| `Last-Event-ID` | SSE 断线续接 | 非负整数事件游标 |
除明确标注允许外,不增加未知字段。布尔字段应传 JSON `true` / `false`,不能传字符串;整数不能用小数或布尔值冒充。素材输入使用本人已上传的素材 ID,不接受服务器绝对路径或任意外部 URL。
## 2 登录与机器鉴权
### 2.1 POST /auth/login
用途:建立浏览器或脚本会话。请求无须登录;成功返回 HTTP 200 并设置 HttpOnly Cookie。
| JSON 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `username` | string | 是 | 无 | 1–64 字符 |
| `password` | string | 是 | 无 | 1–256 字符,使用现有账户密码 |
```json
{"username":"example_user","password":"<从安全输入读取>"}
```
```json
{
"user":{"id":"11111111111111111111111111111111","username":"example_user","display_name":"示例用户","role":"user"},
"csrf_token":"<仅用于本会话的CSRF值>"
}
```
Cookie 与 CSRF 都是敏感数据,不输出到日志或文档。没有公开注册接口。管理员可新增账户;被禁用或删除的账户不能继续使用 API。`GET /auth/me` 读取当前身份;`POST /auth/logout` 注销会话,成功为 HTTP 204。修改密码、用户名使用会话接口,不使用模型推理密钥。
### 2.2 POST /auth/tokens
用途:为当前用户创建机器令牌,必须使用登录会话和 CSRF。成功 HTTP 201,明文 token 仅在创建时返回一次;不能用已有机器令牌创建新令牌。
| JSON 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `name` | string | 是 | 无 | 1–128 字符 |
| `scopes` | string[] | 是 | 无 | 最多 20 个,仅下表允许值 |
| `expires_at` | string 或 null | 否 | null | 带时区的将来时间;建议设置 |
```json
{
"name":"业务调度程序",
"scopes":["jobs:read","jobs:write","assets:read","assets:write","events:read"],
"expires_at":"2027-01-01T00:00:00+08:00"
}
```
```json
{
"token":"cmvr_<只返回一次的随机值>",
"record":{"id":"22222222222222222222222222222222","name":"业务调度程序","scopes":["jobs:read","jobs:write","assets:read","assets:write","events:read"],"expires_at":"2026-12-31T16:00:00.000Z","revoked_at":null}
}
```
| scope | 用途 |
| --- | --- |
| `jobs:read` / `jobs:write` | 查询 / 提交、取消、重试任务 |
| `assets:read` / `assets:write` | 查询、下载 / 上传、编辑素材及共享素材操作 |
| `folders:read` / `folders:write` | 分类读取 / 修改 |
| `workflows:read` / `workflows:write` | 故事、编辑器、运行的读取 / 写入 |
| `batches:read` / `batches:write` | 批次读取 / 创建和控制 |
| `events:read` | SSE 事件流 |
| `interactive:write` | 机器令牌提交交互队列时的额外权限 |
机器程序使用 `Authorization: Bearer <token>`,不要同时携带会话 Cookie 或浏览器的 `Sec-Fetch-Site` 请求头。这是本项目数据库管理的随机令牌,不是 JWT,也不是上游模型 API Key。令牌始终继承所属用户的资源隔离,不具有管理员身份。
`GET /auth/tokens` 返回当前会话用户的令牌记录,`DELETE /auth/tokens/{token_id}` 吊销,HTTP 204。即使 scope 足够,`execution_mode=interactive` 仍额外需要 `interactive:write`;生产时段限制不会因此取消。
当前版本限制:能力和状态路由在机器鉴权时会分别匹配 `capabilities:read`、`system:read`,但可创建 scope 清单不包含这两项。因此能力查询示例使用登录会话;不能通过创建不存在的权限值绕过这一限制。
### 2.3 账户管理接口
以下均使用登录会话,写操作带 CSRF。用户管理只允许管理员会话;机器令牌不会获得管理员角色。
| 方法和路径 | JSON 主要字段 | 权限与说明 |
| --- | --- | --- |
| `GET /auth/users` | 无;query page/page_size | 管理员用户列表 |
| `POST /auth/users` | username、display_name、password | 管理员新增;初始密码允许 6 位数字,用户名按服务规则校验 |
| `PATCH /auth/users/{user_id}` | disabled,可选 display_name | 管理员禁用/启用;禁用保留资源但阻止登录和操作 |
| `DELETE /auth/users/{user_id}` | 无 | 管理员永久删除用户及其受控资源,活动工作须按删除流程清理 |
| `POST /auth/password` | current_password、new_password | 当前用户改密;新密码仍要求至少 12 字符,成功后按返回提示重新登录 |
| `POST /auth/username` | username、current_password | 当前用户改用户名,核对密码并按返回提示重新登录 |
管理员不能删除最后一个可用管理员或绕过项目对自身账号的保护。删除账户属于资源清理操作,不能用“禁用账户”替代,也不要在自动模型调用脚本中默认执行。
## 3 能力与调度状态
### 3.1 GET /capabilities
鉴权:当前使用登录会话。用途:读取任务支持情况、模型 profile、默认参数、范围、原生对白门禁与调度窗口。HTTP 200。
```json
{
"items":[
{"task_type":"video.generate","available":true,"model":"MiniMax H3 原生音视频","video_profiles":[{"profile":"minimax-h3-fl2va-native-av-tp2-v1","available":true,"reason":null,"canvases":[[1344,768]],"defaults":{"width":1344,"height":768,"num_frames":124,"fps":24,"upscale":false},"constraints":{"num_frames":{"min":124,"max":158,"step":17}}},{"profile":"minimax-h3-fl2va-native-av-v1","available":false,"reason":"尚未启用或未完成独立实测认证","canvases":[]}]}
],
"dialogue":{"native_av":{"available":true,"production_available":true,"languages":["Chinese"],"supports_two_faces":false,"max_visible_speakers":1,"readiness":{"generation":true,"word_alignment":true,"visual_review":true},"reason":null}},
"execution_policy":{"timezone":"Asia/Shanghai","start":"21:00","end":"08:00","batch_window_enabled":true,"batch_open":false,"close_behavior":"finish_current","next_batch_at":"2026-11-27T13:00:00+00:00","configuration_error":null},
"workflow_limits":{"max_shots":60,"fps":24},
"scheduler":{"available":true,"state":"ready","gpus":[]}
}
```
上例为主要字段节选,其中可用状态仅说明字段形状,不代替部署后的实时状态。实际视频配置在 `items[task_type=video.generate].video_profiles[]` 中,读取目标 profile 自己的 `available`、`reason`、`canvases`、`defaults`、`constraints`。原生 `canvases` 只列实际认证的 `[width,height]` 组合;上例为 `[[1344,768]]`,未认证或关闭时为 `[]`。即使 `available=true`,也不能提交列表外的画布;分别读取 width/height 的理论数值范围不能替代组合检查。
同一模型族的静音视频、原生有声、单卡、双卡及不同画幅可能有不同验收结果。按本次提交要用的 profile 和 canvases 选择。
### 3.2 GET /system/status
HTTP 200,返回 `inference_online`、`scheduler`、`models`、`environment`、`database_backend`、`execution_policy`、`workflow_limits`、`public_access`。用于运维观察;`inference_online=true` 只代表上游健康,不保证指定模型已经完成认证。
当前没有对业务用户公开的 `POST /scheduler/run`、`POST /gpu/allocate` 或任意启动容器接口。**调用调度器的正式方式是向 `/jobs`、`/editors/{id}/runs` 或 `/batches` 提交受控业务命令**。后台依据资源阶段获得 `new_gpu`、`cpu_media`、`qwen_http` 槽位,客户端只选择任务意图与支持的参数。
### 3.3 GET /live 与 GET /ready
这两个接口不要求登录。`/live` 返回 `{"status":"ok"}`,检查进程活性;`/ready` 在数据库、协调器、上游协议与准入检查均通过时返回 HTTP 200,否则 HTTP 503。
```json
{"status":"ready","checks":{"database":true,"coordinator":true,"upstream_protocol":true,"accepting":true}}
```
GPU 忙或等待夜间窗口不是进程故障;不需要因此重启网站或重复提交任务。
## 4 通用任务提交与返回结构
### 4.1 POST /jobs
鉴权:会话及 CSRF,或 `jobs:write`;交互机器任务还需 `interactive:write`。请求为 JSON,建议始终携带 `Idempotency-Key`。成功 HTTP 202,返回 `{"jobs":[JobDTO]}`。
| 字段 | 类型 | 必填 | 默认值 | 约束和说明 |
| --- | --- | --- | --- | --- |
| `task_type` | string | 是 | 无 | 使用后续任务清单支持的名字 |
| `input` | object | 否 | `{}` | 提示词与本人素材 ID;具体必填项由任务决定 |
| `parameters` | object | 否 | `{}` | 模型参数;未知字段拒绝 |
| `execution_mode` | string | 否 | `interactive` | `interactive` 或 `batch` |
| `count` | integer | 否 | 1 | 1–4;多份仅限图片、参考图片、缺陷样本任务;各份种子递增 |
| `scheduled_at` | datetime 或 null | 否 | null | 必须带时区;将来时间会先处于 `scheduled` |
| `folder_id` | string 或 null | 否 | null | 任务记录所在本人分类 |
| `output_folder_id` | string 或 null | 否 | 未传时继承 `folder_id` | 显式 null 表示成果不继承分类 |
```json
{
"task_type":"image.generate",
"execution_mode":"batch",
"input":{"prompt":"白色背景上的蓝色陶瓷杯,自然柔光"},
"parameters":{"width":1024,"height":1024,"num_inference_steps":50,"seed":42,"guidance_scale":4.0},
"count":1
}
```
```json
{
"jobs":[{
"id":"33333333333333333333333333333333",
"task_type":"image.generate",
"state":"submitting",
"phase":"waiting_dispatch",
"version":1,
"execution_mode":"batch",
"desired_state":"run",
"hold_reasons":[],
"result_assets":[],
"result":null,
"progress":null,
"queue_position":null,
"attempt_count":0,
"preemptions":0,
"error":null,
"sync_warning":null,
"cancel_requested":false
}]
}
```
HTTP 202 只表示意图已经接纳,首个状态也可能因定时或调度推进而不同。不要把 `progress=null` 解释成 0%,也不要编造模型生成百分比。任务 ID 是业务任务 ID,不是 GPU PID。
### 4.2 JobDTO 主要字段
| 字段 | 类型 | 含义 |
| --- | --- | --- |
| `id` | string | 持久业务任务 ID |
| `task_type`、`parameters` | string、object | 已提交任务类型及公开参数 |
| `state`、`phase` | string | 生命周期状态、当前阶段 |
| `version` | integer | 对象版本,用于一致读取及有关删除控制 |
| `hold_reasons` | string[] | 等待原因,如窗口等待;不是新的生成请求 |
| `run_id`、`step_key`、`batch_id` | string 或 null | 所属故事运行或批次 |
| `result_assets` | AssetDTO[] | 已归档、可访问的成果 |
| `result` | object 或 null | 文本、识别、模型实测元数据等,随任务变化 |
| `error` | object 或 null | 失败 code/message 等,不直接向终端用户展示内部路径 |
| `sync_warning` | string 或 null | 上游查询、下载或归档恢复提示,不应自动另建任务 |
| `attempt_count` | integer | 上游尝试数 |
| `explicit_attempt` | integer | 用户明确重试代次 |
| `preemptions` | integer | 让卡次数,可能重新排队 |
| `created_at`、`scheduled_at`、`started_at`、`finished_at` | datetime 或 null | 时间线 |
常见状态包括 `scheduled`、`submitting`、`queued`、`running`、`collecting`、`cancelling`、`succeeded`、`failed`、`cancelled`、`timed_out`、`needs_attention`。`cancel_requested` 是独立布尔字段,不是这里的取消中状态名称。读取实际 `state` 和 `phase`,不要仅凭页面文字推断状态。上游结束后归档未完成时仍可能是 `collecting`;自动让卡不等于用户取消。
不同任务使用同一个 JobDTO 外层,模型结果的读取位置如下。`result_assets` 中每项都是可继续查询或下载的 AssetDTO,不能把上游文件路径当作下载地址。
| 任务 | 成功后的主要读取位置 |
| --- | --- |
| `image.generate`、`image.reference.generate` | `result_assets` 中的图片;`result` 为实际生成元数据 |
| `defect.generate` | 保存全部相关图片成果,包括生成样本和控制图;不返回缺陷真值掩膜 |
| 原生 `video.generate` | `result_assets` 中的有声 MP4 和独立 WAV;实测元数据在 `result.native_av` |
| `math.solve` | `result.text`,以及文本和 JSON 素材 |
| `media.structure` | `result.subjects/scene/ocr/tags/frames`,以及结构化 JSON 素材 |
| `audio.transcribe` | `result.text` 和 `result.segments`,以及转写成果;通用分段不是字词口型证据 |
| `video.compose` | `result_assets` 中的成片视频;完整故事验收需查父运行及质检成果 |
### 4.3 GET /jobs 与 GET /jobs/{job_id}
鉴权:会话或 `jobs:read`。列表返回 `items,total,page,page_size,cursor`;详情直接返回 JobDTO。
| 列表 query | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `page` | integer | 1 | 从 1 开始 |
| `page_size` | integer | 24 | 常规 1–100,以服务校验为准 |
| `folder_id` | string | `""` | 本人分类筛选 |
| `task_type`、`state` | string | `""` | 类型、状态筛选 |
| `root_only` | boolean | false | 排除所属运行的子任务 |
建议每 2–5 秒轮询一次目标任务,状态 `succeeded` 后读取 `result_assets`。`needs_attention` 表示执行结果或清理状态需核对,不能通过新增同类任务掩盖未知结果。
### 4.4 取消 重试 删除
| 方法和路径 | 请求 | 成功 | 行为 |
| --- | --- | --- | --- |
| `POST /jobs/{id}/cancel` | 无 JSON 必填字段;会话仍需 CSRF | 200 JobDTO | 请求取消,实际退出与清理异步确认 |
| `POST /jobs/{id}/retry` | 建议新的 `Idempotency-Key` | 202 `{"jobs":[...]}` | 对可重试的失败任务发起明确重试;不是超时恢复操作 |
| `DELETE /jobs/{id}` | 按对象要求提供 `If-Match` | 200 | 清理任务记录及其受控成果;活动任务须先取消并等清理完成 |
故事工作流子任务应由父运行控制,不要绕过父图单独重试;错误响应会提示相应父运行。删除与取消是不同操作;删除不会变成一个可安全忽略的“隐藏按钮”。
### 4.5 GET /submissions/{key}
query `operation` 必填。用于响应丢失后恢复业务意图,HTTP 200。
```text
GET /submissions/8ebc5e83-52cf-4428-a1bb-754528199212?operation=jobs.create
```
```json
{"key":"8ebc5e83-52cf-4428-a1bb-754528199212","operation":"jobs.create","status":"accepted","resource_json":{"job_ids":["33333333333333333333333333333333"]},"job_ids":["33333333333333333333333333333333"]}
```
常用 operation 有 `jobs.create`、`jobs.retry`、`editor.save`、`editor.dialogue.enable` 及接口对应的运行命令。客户端应在发请求前保存幂等键、完整 body、操作名和返回 ID。404 只表示尚未找到,重放仍必须使用原键与原 body;410 表示原结果已清理,不能用旧键强行重建;409 表示同键被用于不同参数。
## 5 素材上传与成果下载
### 5.1 POST /assets
鉴权:会话及 CSRF,或 `assets:write`。使用 multipart,成功 HTTP 201,返回 AssetDTO。
| form 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `file` | binary | 是 | 实际图片、音视频等文件,不是服务器路径 |
| `name` | string | 否 | 显示名,默认由上传文件名取得 |
| `folder_id` | string | 否 | 本人分类 ID |
默认单文件上限 512 MiB,实际还受反代、用户存储配额和格式检查约束。不要将 API Key、密码或无关服务器文件上传为素材。
```json
{
"id":"44444444444444444444444444444444",
"name":"speaker.png",
"kind":"image",
"mime_type":"image/png",
"size_bytes":350000,
"width":1344,
"height":768,
"duration_seconds":null,
"preview_url":"/api/assets/44444444444444444444444444444444/content",
"download_url":"/api/assets/44444444444444444444444444444444/content?download=1",
"source_job_id":null,
"source_output_index":null,
"origin":"upload"
}
```
### 5.2 查询与文件内容
| 接口 | 成功响应 |
| --- | --- |
| `GET /assets` | 分页 `items,total,page,page_size,cursor`;可按 `kind,q,tag,favorite,origin,folder_id` 筛选 |
| `GET /assets/{asset_id}` | 单个 AssetDTO |
| `GET /assets/{asset_id}/content` | 受鉴权保护的原始文件内容 |
| `GET /assets/{asset_id}/content?download=1` | 以下载方式返回原文件 |
| `GET /assets/{asset_id}/thumbnail` | 已生成的缩略图 |
| `PATCH /assets/{asset_id}` | 修改 `name`、`tags`、`favorite`、`folder_ids` |
| `DELETE /assets/{asset_id}` | HTTP 204;仍被草稿、任务或运行引用时可能 409 |
下载需要同一用户会话或 `assets:read`。相对 `download_url` 已包含 `/api`,拼接时使用网站根地址,避免得到 `/api/api/...`。文件接口支持单个字节范围 `Range: bytes=0-31`,合法请求 HTTP 206,越界为 416;不支持多区间请求。
素材不存在、已删除或非本人均不能访问,通常返回 404。不要把素材路由替换为绕过鉴权的公共静态目录。任务可能有多个成果,应按 `kind`、`mime_type`、名称和输出用途选择,不要无条件下载 `result_assets[0]`。
AssetDTO 和 `result_assets` 不公开 `sha256`。普通任务下载可核对 `size_bytes` 并自行计算文件摘要,但没有公开的可信预期摘要时,不能声称已与服务器 SHA 校验一致。故事成片可按 `steps[kind=video.compose].result.asset_id` 匹配素材,并与该 Step 返回的 `result.sha256` 比对;不要臆造 `asset.sha256` 字段。
## 6 图片生成接口
### 6.1 文生图 image.generate
方法:`POST /jobs`。模型意图:Qwen-Image;以能力接口实际模型标识为准。`count` 支持 1–4。
| input 字段 | 类型 | 必填 | 默认值 | 限制 |
| --- | --- | --- | --- | --- |
| `prompt` | string | 是 | 无 | 非空,最多 8000 字符 |
| `negative_prompt` | string | 否 | `""` | 最多 8000 字符 |
| parameters 字段 | 类型 | 必填 | 默认值 | 范围 |
| --- | --- | --- | --- | --- |
| `width` | integer | 否 | 1024 | 256–2048,16 的整数倍 |
| `height` | integer | 否 | 1024 | 256–2048,16 的整数倍 |
| `num_inference_steps` | integer | 否 | 50 | 1–100 |
| `guidance_scale` | number | 否 | 4.0 | 1–20 |
| `seed` | integer | 否 | 42 | 0–4294967295 |
总像素不超过 2048×2048。返回方式与通用 JobDTO 一致;成功时在 `result_assets` 取得图片。提高步数会增加计算,不是质量保证。
### 6.2 参考图生成 image.reference.generate
方法:`POST /jobs`。先上传 1–3 张参考图,保持顺序;本版默认 profile 为 `qwen-image-edit-2511-v1`,以当前配置与认证为准。缺参考图或未认证时不会自动降级文生图。
| input 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `prompt` | string | 是 | 非空,最多 8000 字符;用 Picture 1、Picture 2 对应顺序 |
| `reference_asset_ids` | string[] | 是 | 默认 1–3 张本人图片 ID,不重复;实际最大值由能力给出 |
| `negative_prompt` | string | 否 | 默认空串 |
| parameters 字段 | 类型 | 默认值 | 约束 |
| --- | --- | --- | --- |
| `profile` | string | 配置值 | 必须等于已启用且认证的 profile |
| `width`、`height` | integer | 1280、704 | 仅 1280×704、704×1280、1024×1024 |
| `num_inference_steps` | integer | 40 | 1–100 |
| `seed` | integer | 42 | 0–4294967295 |
| `guidance_scale` | number | 1.0 | 1–20 |
| `true_cfg_scale` | number | 4.0 | 1–20 |
| `max_sequence_length` | integer | 1024 | 1–1024 |
```json
{
"task_type":"image.reference.generate",
"execution_mode":"batch",
"input":{"prompt":"保持Picture 1人物的脸部、发型与服饰,人物站在温暖室内,中景,正面偏侧,表情自然。","reference_asset_ids":["44444444444444444444444444444444"]},
"parameters":{"profile":"qwen-image-edit-2511-v1","width":1280,"height":704,"num_inference_steps":40,"seed":42,"guidance_scale":1.0,"true_cfg_scale":4.0,"max_sequence_length":1024},
"count":1
}
```
生成后应检查人物身份、手部、构图和口部清晰度,再作为视频首帧。参考图是模型输入;普通文生图的提示词中写一个素材 ID 不会自动使用该图片。
## 7 H3 视频生成接口
### 7.1 先选择正确的 profile
`POST /jobs` 的 `task_type` 都是 `video.generate`,但 profile 决定参数和音轨合同。**调用 H3 时必须显式传 profile**。为兼容历史请求,省略 profile 保留旧 Wan 参数语义,不能把它理解成“自动选择服务器最新 H3”。
| profile | 条件输入字段 | 请求帧数 | 输出音轨与用途 |
| --- | --- | --- | --- |
| `minimax-h3-fl2va-bf16-v1` | `image_asset_id`,可选图生条件 | 25–337 且 4n+1 | 静音,历史常规 H3 |
| `minimax-h3-fl2va-bf16-v2` | `first_frame_asset_id`,可选尾帧 | 124–345,步长 17 | 静音完整原生帧 |
| `minimax-h3-fl2va-bf16-tp2-v1` | `image_asset_id` 必填 | 25–145 且 4n+1 | 双卡静音,最长请求约 6 秒 |
| `minimax-h3-fl2va-native-av-v1` | `first_frame_asset_id`,可选尾帧 | 124–345,步长 17 | 单卡原生音画;可用性取决于服务认证 |
| `minimax-h3-fl2va-native-av-tp2-v1` | `first_frame_asset_id` | 124、141、158 | 双卡原生音画,仅首帧;示例使用 1344×768 横屏 |
| `wan2.2-ti2v-5b-v1` | `image_asset_id` 可选 | 5–361 且 4n+1 | 保留历史配置 |
profile 是否真实可用、是否正式认证、是否暂时关闭,必须读取目标项自己的能力字段,不能只根据这个清单提交。此处示例采用 `minimax-h3-fl2va-native-av-tp2-v1` 横屏 1344×768;单卡及竖屏原生配置不因横屏 TP2 验收而自动开放。双卡需要两张符合资源策略的空闲卡,不是传 `gpu_count=2`;内存预留也按该 profile 的实际资源策略计算。
### 7.2 原生有声 H3 参数
方法:`POST /jobs`;`count=1`。下面以 `minimax-h3-fl2va-native-av-tp2-v1` 为例;须同时满足目标项实时 `available=true` 和 `[1344,768]` 在该项 `canvases` 内。
| input 字段 | 类型 | 必填 | 约束 |
| --- | --- | --- | --- |
| `prompt` | string | 是 | 最多 8000 字符,写完整画面动作、对白和声景 |
| `first_frame_asset_id` | string | 是 | 本人图片 ID |
| `last_frame_asset_id` | string | 不传 | TP2 不支持;提交此字段会拒绝 |
| `negative_prompt` | string | 否 | H3 只能为空;不要提交非空负提示词 |
| parameters 字段 | 类型 | 默认值 | 约束 |
| --- | --- | --- | --- |
| `profile` | string | 调用时显式指定 | 示例使用 `minimax-h3-fl2va-native-av-tp2-v1` |
| `width` | integer | 1344 | 示例宽度为 1344,须命中实时 canvases |
| `height` | integer | 768 | 示例画幅高度为 768;必须符合目标 profile 的 canvases |
| `num_frames` | integer | 124 | TP2 只允许 124、141、158 |
| `fps` | integer | 24 | 固定 24 |
| `num_inference_steps` | integer | 50 | 2–100 |
| `seed` | integer | 42 | 0–4294967295 |
| `conditioning_mode` | string | `first_frame` | TP2 固定 `first_frame` |
| `upscale` | boolean | false | 原生有声固定 false |
| `upscale_width`、`upscale_height` | integer | 1920、1080 | 通用兼容字段,偶数,分别 256–3840 与 256–2160;原生不执行增强,通常省略 |
| `tile_size` | integer | 128 | 通用兼容字段,64–256,16 的倍数;原生不执行增强,通常省略 |
原生模式不接收 `guidance_scale`、不支持任意 fps、不支持用 `duration=5` 替代帧数。124、141、158 帧约为 5.17、5.88、6.58 秒,台词须留出自然开口和句末闭口余量。更长内容拆成正常切镜的多镜头,再走故事流程成片,不能超过 TP2 单镜 158 帧上限。
```json
{
"task_type":"video.generate",
"execution_mode":"batch",
"count":1,
"input":{
"first_frame_asset_id":"44444444444444444444444444444444",
"prompt":"integrated_multimodal_description: [Shot 1] 一位青年正面略偏侧中景,脸部清晰,固定镜头,人物自然呼吸,轻微点头。青年(S1)用清晰自然的中文说:<d>[Chinese] 你好,欢迎来到我们的故事。</d> 说完自然闭唇,保持轻微表情动作到结尾,不再继续说话。\noverall_soundscape: 安静室内,只有这位青年说话,无其他人声。\nnon_diegetic_music: N/A"
},
"parameters":{
"profile":"minimax-h3-fl2va-native-av-tp2-v1",
"width":1344,"height":768,"num_frames":124,"fps":24,
"num_inference_steps":50,"seed":42,"conditioning_mode":"first_frame","upscale":false
}
}
```
成功时 `result_assets` 应包含带原声的视频及 32kHz 双声道 PCM WAV;按类型识别并分别保存。`result.native_av` 会提供实测帧数、样本数、采样率、音画时长差和完整输出策略等元数据,以实际响应为准。官方 40Hz 音频潜变量格点可使 WAV 比视频长或短至多约 12.5ms;不能为了让两个容器时长字符串相等而裁掉句尾。
同一段音画的精确帧数及音频样本数可从 Job.result.native_av 读取。
| `result.native_av` 字段 | 类型与单位 | 说明 |
| --- | --- | --- |
| `video_frames`、`fps` | integer | 实测完整视频帧数,固定 24fps |
| `sample_rate`、`channels` | integer | 原始 WAV 为 32000Hz、双声道 |
| `audio_samples` | integer,每声道样本数 | 完整原声音轨样本数 |
| `start_sample`、`end_sample` | integer | 原始完整区间,起点 0,终点等于 audio_samples |
| `audio_duration`、`video_duration` | number,秒 | 分别按样本数和帧数计算的时长 |
| `av_duration_delta` | number,秒 | 音频时长减视频时长;这是长度差,不是人物口型延迟 |
| `output_policy`、`audio_trimmed` | string、boolean | `full_native`、false,完整保留原生输出 |
| `audio_format` | string | `pcm_s16le`,独立 WAV 的编码 |
直接 `video.generate` 返回的是该镜头的原始生成结果,**不会自动替调用方执行故事的双路对白内容复核、字幕编译和成片验收**。需要自动检查和字幕时,走第 11 章故事原生对白流程;不能把“任务 succeeded”当作已经证明口型完全正确。
### 7.3 静音 H3 首帧示例
```json
{
"task_type":"video.generate",
"execution_mode":"batch",
"input":{"image_asset_id":"44444444444444444444444444444444","prompt":"人物缓慢转头看向窗外,肩部随呼吸轻微起伏,窗外雨水持续流动,固定镜头。"},
"parameters":{"profile":"minimax-h3-fl2va-bf16-v1","width":1344,"height":768,"num_frames":121,"fps":24,"num_inference_steps":50,"seed":42,"upscale":false},
"count":1
}
```
这个 profile 是静音合同。把“配乐”写进提示词不会改变其输出音轨合同;不要把它与 native-av profile 混用。需要首尾帧静音模式时使用 v2,输入字段改成 `first_frame_asset_id` / `last_frame_asset_id`,并传 `conditioning_mode=first_last_frame`、合法原生帧数。
## 8 缺陷条件样本接口
### 8.1 defect.generate
方法:`POST /jobs`;模型意图为 SDXL 与 Canny ControlNet。先上传本人参考图,输出合成条件样本图片及边缘控制图。它不是缺陷检测器,不返回缺陷真值标签或分割掩膜。
| input 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `prompt` | string | 是 | 非空,最多 8000 字符,写材质、缺陷类型、范围和光照 |
| `image_asset_id` | string | 是 | 参考图片 ID |
| `negative_prompt` | string | 否 | 默认空串 |
尺寸、步数、seed 范围与文生图一致;本任务默认 `guidance_scale=7.5`,另有:
| parameters 字段 | 类型 | 默认值 | 约束 |
| --- | --- | --- | --- |
| `controlnet_conditioning_scale` | number | 0.8 | 0–2 |
| `canny_low` | integer | 100 | 0–255,必须小于 canny_high |
| `canny_high` | integer | 200 | 0–255 |
| `count` | integer | 1 | 属于外层请求,最多 4,不放入 parameters |
```json
{
"task_type":"defect.generate",
"execution_mode":"batch",
"input":{"image_asset_id":"44444444444444444444444444444444","prompt":"工业检测照片,保持金属表面主体结构,一处细长不规则划痕,划痕边缘有细微反光,背景和光照自然。","negative_prompt":"文字,水印,卡通,整体结构变形"},
"parameters":{"width":1024,"height":1024,"num_inference_steps":50,"seed":100,"guidance_scale":7.5,"controlnet_conditioning_scale":0.8,"canny_low":100,"canny_high":200},
"count":2
}
```
返回两个独立业务任务,种子按 100、101 使用。每个任务成功后保存其全部相关图片,人工确认缺陷是否存在、位置和强度,再做标注;不能把 Canny 图当成缺陷掩膜。生成样本质量与是否适合训练必须通过真实检测数据验证。
## 9 推演与素材理解接口
### 9.1 math.solve
方法:`POST /jobs`。网页“推演”对应数学推演和解释,不是物理仿真、数字孪生、形式化证明或保证正确的求解器。
| 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `input.prompt` | string | 是 | 无 | 非空,最多 8000 字符 |
| `parameters.max_tokens` | integer | 否 | 2048 | 1–4096 |
| `parameters.enable_thinking` | boolean | 否 | false | 仅 JSON 布尔值 |
```json
{
"task_type":"math.solve",
"execution_mode":"batch",
"input":{"prompt":"求解方程 x²-5x+6=0,给出计算过程并代回检验。"},
"parameters":{"max_tokens":2048,"enable_thinking":false},
"count":1
}
```
成功后 `GET /jobs/{id}` 的 `result.text` 提供回答,`result_assets` 保存文本、JSON 等成果。例:`{"result":{"text":"……模型实际回答……"}}`。模型标识从能力接口读取,不能在任务里任意添加 `model_url` 或 API Key。
### 9.2 media.structure
用于先理解图片或视频画面,再把提取后的题目交给 `math.solve`。它不自动把每个模型回答当作数学事实。
| 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `input.asset_id` | string | 是 | 无 | 本人图片或视频 ID |
| `parameters.frame_count` | integer | 否 | 6 | 1–12;视频均匀抽帧数 |
```json
{"task_type":"media.structure","execution_mode":"batch","input":{"asset_id":"44444444444444444444444444444444"},"parameters":{"frame_count":6},"count":1}
```
输出 `result.subjects`、`scene`、`ocr`、`tags` 和 `frames`,并归档结构化 JSON;每帧包含 `timestamp_seconds`、`scene`、`subjects`、`ocr`、`tags`。这些是模型理解结果。对图片题目,先核对题干、符号、单位是否提取准确,再单独提交文本推演;`math.solve` 不直接接受图片 ID。
### 9.3 audio.transcribe
| 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `input.audio_asset_id` | string | 是 | 无 | 本人音频或有声视频 ID |
| `parameters.language` | string | 否 | `zh` | `zh,en,ja,ko,de,fr,es,ru,ar,pt,it,auto` |
| `parameters.max_audio_seconds` | integer | 否 | 1800 | 1–1800 |
```json
{"task_type":"audio.transcribe","execution_mode":"batch","input":{"audio_asset_id":"55555555555555555555555555555555"},"parameters":{"language":"zh","max_audio_seconds":1800},"count":1}
```
这是通用 Whisper 转写合同,时间可能是约 30 秒块边界,不能将其当作字词口型对齐证据。故事原生对白另用真实 word timestamps 和独立识别共识验收。
## 10 合成 字幕与背景音乐
### 10.1 video.compose
方法:`POST /jobs`,`count=1`。用于已有视频的按序裁剪、拼接、叠加纯文本字幕及指定一条成片音轨。复杂多层音轨和原生对白保留优先走故事混音,不通过提示词控制音量。
| 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `input.asset_ids` | string[] | 否 | 无 | 如提供,顺序必须和 clips 一致 |
| `input.audio_asset_id` | string | 否 | 无 | 本人音轨 ID;不要与参数中的音轨 ID 冲突 |
| `parameters.clips` | object[] | 是 | 无 | 1–1000,且服从实时 max_shots 与实际资源上限 |
| `clips[].asset_id` | string | 是 | 无 | 本人视频 ID |
| `clips[].start_seconds` | number | 否 | 0 | 0–86400,源片内起点 |
| `clips[].end_seconds` | number | 否 | 实际结尾 | 大于起点,不能超源片实际长度 |
| `parameters.width` | integer | 否 | 1280 | 256–3840,偶数 |
| `parameters.height` | integer | 否 | 720 | 256–2160,偶数 |
| `parameters.fps` | integer | 否 | 24 | 24、25、30、60 |
| `parameters.subtitles` | object[] | 否 | `[]` | 最多 1000 条 |
| `subtitles[].start`、`end` | number | 是 | 无 | 整片秒数,end 大于 start,不能超成片 |
| `subtitles[].text` | string | 是 | 无 | 1–2000 字符纯文本;不支持 ASS 控制语法 |
```json
{
"task_type":"video.compose","execution_mode":"batch","count":1,
"input":{"asset_ids":["66666666666666666666666666666666","77777777777777777777777777777777"],"audio_asset_id":"55555555555555555555555555555555"},
"parameters":{
"width":1920,"height":1080,"fps":24,
"clips":[{"asset_id":"66666666666666666666666666666666","start_seconds":0,"end_seconds":5},{"asset_id":"77777777777777777777777777777777","start_seconds":0,"end_seconds":5}],
"subtitles":[{"start":0.2,"end":4.5,"text":"第一段字幕"},{"start":5.2,"end":9.5,"text":"第二段字幕"}]
}
}
```
外部音轨会作为成片音轨使用,不会自动与各视频对白混合;短音轨剩余补静音,不自动循环,长音轨按成片长度结束。保留原声并叠加背景音乐时,应使用故事 `audio.layers` 混音,或上传已制作好的整片混合音轨。这里的字幕使用秒数;故事编辑器字幕用帧数,音频图层用 48kHz 整数样本,不要混用。
## 11 故事、节奏字幕与同框对白
### 11.1 使用方式
以下路径使用同一用户的登录会话。可从已有故事开始,先按[故事操作手册](story.html)准备好角色、场景、分镜和对白。需要全新故事时按下节接口创建。请求中传最新版本,保存和启动运行使用不同的幂等键。
### 11.2 创建故事或读取现有故事
`POST /stories` 返回 HTTP 201 StoryDTO。需要 `name` 和版本化 `spec`;`create_folder` 默认 true,`folder_id` 可选。已有故事使用 `GET /stories/{id}`。
以下为新建一个单人说话镜头的最小基准故事示例,ID 仅供说明,实际脚本应使用不同的 `uuid.uuid4().hex`:
```json
{
"name":"人物说话示例",
"create_folder":false,
"spec":{
"schema_version":3,
"profile":"landscape_1080_v1",
"context":{"style":"写实电影,中景人物,清晰自然面部"},
"scenes":[{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","name":"室内","location":"安静房间","time":"白天","lighting":"柔和窗光"}],
"entities":[{"id":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","kind":"person","name":"青年","description":"青年男性,短发,浅色衬衫,面部清晰"}],
"shots":[{
"id":"cccccccccccccccccccccccccccccccc","name":"青年开场",
"scene_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"cast":[{"id":"dddddddddddddddddddddddddddddddd","entity_id":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","position":"画面中央中景","action":"自然呼吸并轻微点头"}],
"visual_prompt":"青年正面略偏侧中景,头肩完整,嘴部无遮挡,背景简单,清晰自然面部。",
"motion_prompt":"固定镜头,自然说话,轻微头部与肩部动作,结束后放松闭唇。",
"edit":{"start_frame":0,"duration_frames":120}
}],
"render":{"fps":24,"total_frames":120,"fit":"contain","subtitles":[]}
}
}
```
不要通过修改同一稳定 ID 的含义冒充另一角色;删除镜头、段落或角色后应重新核对引用。
### 11.3 POST /editors/{draft_id}/dialogue/enable
用途:显式启用或升级为 H3 原生对白。JSON `expected_version` 必填、integer、至少 1;需要 `Idempotency-Key`。成功 HTTP 200 EditorDTO。
```json
{"expected_version":1}
```
```json
{
"draft_id":"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
"version":2,
"revision":2,
"name":"人物说话示例",
"editing_mode":"auto",
"manifest":{"schema_version":3,"source_kind":"story","spec":{"schema_version":5,"dialogue":{"generation":"native_av","language":"Chinese"}}},
"assets":[],"issues":[]
}
```
上例 manifest 为节选,保存时必须使用真实完整 manifest,不能将这个节选回传。此处以 V5 / V3 草稿说明字段,新建故事启用对白后可能得到 V6 / V4。请沿用响应中的实际版本;稳定镜头、素材和历史运行保留。读取旧故事不会静默升级,旧冻结运行保持原图。
### 11.4 原生作者字段
| manifest 路径 | 类型 | 说明和限制 |
| --- | --- | --- |
| `spec.dialogue.generation` | string | `native_av` |
| `spec.dialogue.language` | string | 当前故事本版允许中文 `Chinese`;实时认证仍必须通过 |
| `spec.dialogue.speakers[]` | object[] | 角色 ID、entity_id、name、native_voice;人物应在故事 entities 中 |
| `speakers[].native_voice` | string 或 null | 1–500 字符声线描述,例如“青年男性,清亮中音,语气平静” |
| `spec.dialogue.utterances[]` | object[] | 稳定 id、speaker_id、完整 text;text 为 1–2000 字符 |
| `utterances[].spoken_text` | string 或 null | 可选口播改写,识别按此实际口播目标检查 |
| `utterances[].source` | string | 文本台词沿用 `tts` 标签;native_av 下由 H3 直接生成,不创建 TTS 步骤 |
| `utterances[].delivery` | string | 最多 500 字符,语气和表演提示,不是精确采样控制 |
| `spec.dialogue.sequences[]` | object[] | 段落稳定 id、shot_ids、utterance_ids,明确镜头与台词归属 |
| `shots[].performance.native_utterance_ids` | string[] | 本镜头完整台词 ID;`[]` 明确无对白;多镜头段落必须逐镜分配 |
| `shots[].performance.visible_speaker_ids` | string[] | 画内人物须属于镜头 cast。单人模式选择一人;正式双人轮流模式的两个角色与认证条件见 11.12 |
| `shots[].performance.lip_sync` | string | `auto`、`required`、`off`;画外词时不要求画面人物开口 |
| `shots[].video_parameters.profile` | string | 示例使用横屏 TP2 profile;实际可选组合由实时能力决定 |
| `shots[].video_parameters.source_frames` | integer | 故事字段使用 source_frames;不要与 Jobs 的 num_frames 混淆 |
| `shots[].video_parameters.upscale` | boolean | 原生固定 false |
| `audio.layers[]` | object[] | 独立 BGM/SFX 图层,见下一节 |
| `captions.mode` | string | 常用 `script`;实际字幕依据验收后的原音词时间生成 |
每句台词必须且只能分配到一个镜头;单人模式通过正常切镜实现多人对白。使用同框轮流发言时要检查独立能力,按顺序分配两位角色的台词。单镜段落可自动采用全部台词,多镜段落不能猜测分配、重复播放或截断一句。
声线描述不能保证克隆参考录音或跨镜音色完全一致。旧参考录音、录音台词和人工导入视频不能冒充已验收的原生音画;需用户明确解除、转换或强制重新生成。原素材和历史绑定不会因此被删除。请分别检查同框轮流、连续动作和尾帧的计划约束;单镜支持某种输入不等于故事编排已经开放该组合。
### 11.5 POST /editors/{draft_id}/save
用途:保存完整作者 manifest 与可选故事名。成功 HTTP 200 EditorDTO。
| JSON 字段 | 类型 | 必填 | 约束 |
| --- | --- | --- | --- |
| `expected_version` | integer | 是 | 最近取得的版本,至少 1 |
| `manifest` | object | 是 | 完整 V1/V2/V3/V4 编辑器 manifest,与故事版本相符 |
| `name` | string 或 null | 否 | 1–255 字符,不允许全空格 |
原生模式不创建独立旁白或 MuseTalk 步骤。旧旁白应明确关闭或转换为画外台词,背景乐留在独立图层。服务器维护的 `native_audio`、`native_report`、`native_alignment` 等派生绑定是只读结果,客户端不得捏造审批、SHA 或质检通过记录。
保存时可在 Postman 把 GET /editors/{draft_id} 返回的完整 manifest 复制到 Body 中,加上当前 expected_version。即使只改故事名,请保留现有镜头、台词、绑定、字幕、音轨和 schema_version。服务端返回最新 EditorDTO 后再进行 plan。
### 11.6 配乐与字幕字段
故事音频以 48,000Hz 整数样本处理,24fps 下每帧为 2,000 样本。以下为整片开头进入、播放前 5 秒的 BGM 图层节选;素材必须真的有足够长度。
```json
{
"audio":{
"mode":"silent","mix_mode":"composed","segments":[],"ducking":true,
"layers":[{
"id":"ffffffffffffffffffffffffffffffff","role":"bgm","anchor":"absolute",
"asset_id":"55555555555555555555555555555555",
"offset_sample":0,"source_start_sample":0,"source_end_sample":240000,
"gain_db":-16,"fade_in_samples":12000,"fade_out_samples":24000
}]
},
"captions":{"mode":"script","cues":[]}
}
```
这里 `audio.mode=silent` 只关闭独立旧旁白,原生镜头声音仍由原生混音流程保留。每层 role 为 `bgm` 或 `sfx`,默认 bgm;gain_db 范围 -60…12。anchor 可为 `absolute`、`shot`、`scene`,选后两者必须分别提供对应 ID。每层起止、偏移和淡入淡出为整数样本;音乐短了不会被提示词自动延长。
字幕 cue 使用稳定 ID、anchor、start_frame/end_frame、text 和独立的 `text_override`、`timing_override`;对白字幕 anchor 为 `utterance` 并引用 utterance_id。保护人工文案不等于保护人工时间,改时间后仍须落在有效时间线内。只改字幕或配乐可复用有效 H3 视频,改台词、声线、画面或语言会失效对应音视频闭包。
### 11.7 POST /editors/{draft_id}/plan
先计划再执行。此接口需要会话及 CSRF,但不需要 `Idempotency-Key`;成功 HTTP 200,不启动模型生成。
| JSON 字段 | 类型 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- | --- |
| `expected_version` | integer | 是 | 无 | 草稿当前版本 |
| `output_goal` | string | 否 | `film` | `film` 生成成片;`media` 仅生成目标素材 |
| `targets` | string[] | 否 | `[]` | 原生支持 frame:id、video:id、native_alignment:id、captions |
| `force` | string[] | 否 | `[]` | 明确强制更新的目标,不为普通重连设置 |
| `execution_mode` | string | 否 | `interactive` | 两种队列仍遵守生产时段 |
| `output_folder_id` | string 或 null | 否 | 未指定 | 成果分类 |
```json
{"expected_version":3,"output_goal":"film","targets":[],"force":[],"execution_mode":"batch"}
```
```json
{
"output_goal":"film","source_version":3,
"steps":[
{"key":"frame_0001","kind":"image.generate","unit_id":"cccccccccccccccccccccccccccccccc","status":"generate"},
{"key":"nv_0001","kind":"video.generate","unit_id":"cccccccccccccccccccccccccccccccc","status":"generate"},
{"key":"na_0001","kind":"audio.dialogue.extract","unit_id":"cccccccccccccccccccccccccccccccc","status":"generate"},
{"key":"nq_0001","kind":"audio.dialogue.inspect","unit_id":"cccccccccccccccccccccccccccccccc","status":"generate"}
],
"issues":[],
"plan_hash":"<服务器返回的64位十六进制摘要>"
}
```
这里只节选步骤,实际还有视觉检查、内部验收、混音、字幕和合成。步骤 status 为 generate 或 reuse,不是 Job 的执行状态。`issues` 非空时先修复问题,不能绕过计划。原生能力缺失会明确阻止生成;首帧单独闭包不要求语音能力。
### 11.8 POST /editors/{draft_id}/runs
需要会话、CSRF 和 `Idempotency-Key`;请求与 plan 一致,再增加必填的 64hex `expected_plan_hash`。成功 HTTP 202 RunSnapshot。
```json
{
"expected_version":3,"output_goal":"film","targets":[],"force":[],
"execution_mode":"batch","expected_plan_hash":"<上一计划的plan_hash>"
}
```
```json
{
"run":{"id":"99999999999999999999999999999999","state":"queued","desired_state":"run","execution_mode":"batch","version":1,"run_kind":"story_auto","output_goal":"film","apply_state":"pending","completed_steps":0,"total_steps":9,"result_assets":[]},
"steps":[],"jobs":[],"cursor":100
}
```
实际 DTO 包含 `draft` 和按冻结顺序的 Steps。不要假定总步骤恒为 9,首帧复用、多镜头和配乐会改变数量。再次运行前须重新读取 editor 版本并计划;若在计划后改了草稿或能力证据变化,旧摘要会冲突,须重新计划,不能手写哈希。
### 11.9 查询 取消与应用
`GET /workflow-runs/{id}` 返回 RunSnapshot,重点查看 `run.state`、`run.error`、`run.apply_state`、Steps 及 `run.result_assets`。自动运行可从 `steps` 中找到 `kind=video.compose` 的 Step,再按其 `result.asset_id` 匹配输出素材;也可查看对应合成 Job 的 `result_assets`。不要把任意首帧图片当成片,也不要假定存在未定义的 `run.current_output` 响应字段。
有对白的原生镜头在首帧后由 H3 一次产生画面、声音和口型,再提取真实音轨、Whisper 逐词识别、SenseVoice 盲内容复核和视觉检查。两路内容与目标台词不一致、缺证据或词时间不可靠时阻止通过,不用作者文字填充“识别结果”。新图没有独立 TTS/MuseTalk;历史冻结图仍可按原合同读取恢复。
无对白镜头使用独立静默验收:固定版本的 Silero CPU VAD 对同一真实音轨的左右声道分别逐窗检查,覆盖完整选段,且 SenseVoice 实际识别为空,才可按 `silero-sensevoice-verified-silence-v1` 判定无语音。Whisper 在静默或音乐中可能幻觉出文字;报告仍保留原转写、内容错误率和逐词失败,不改写成空、不伪造词时间,也不声称“两路 ASR 都为空”。VAD 或第二路证据缺失、任一声道出现语音、选段或音轨 SHA 不符,仍阻止通过。该静默策略只用于期望台词确实为空的镜头,不能为有对白的错误转写兜底。
| 接口 | JSON | 成功 |
| --- | --- | --- |
| `POST /workflow-runs/{id}/cancel` | `{"expected_version":运行version}` | 200 RunSnapshot,等待实际退出清理 |
| `POST /workflow-runs/{id}/pause` | 同上 | 200,暂停后续阶段 |
| `POST /workflow-runs/{id}/resume` | 同上 | 200,仍受能力、窗口及清理状态控制 |
| `POST /editors/{draft_id}/apply` | `{"expected_version":草稿version,"run_id":"..."}` | 200 EditorDTO;成功且来源版本匹配才应用 |
这些运行控制应保存相应 `Idempotency-Key`。V5 成片成功后会尝试自动应用;`apply_state=conflict` 表示作者已有更新,结果保留但不覆盖。先查看新编辑内容与输出,再明确处理,不强行把旧结果覆盖回新草稿。
### 11.10 修改后局部重生成
| 想修改什么 | 操作 |
| --- | --- |
| 某镜头画面或台词 | 修改该镜头/对应台词并 save,再 plan + run;需要强制时用 `video:<shot_id>` |
| 发音、声线、表演 | 修改角色 native_voice、台词或 delivery;该镜头画面与声音一起重新生成 |
| 仅字幕文案/位置 | 改 cue 并 save,film 计划可复用 H3;人工保护仍检查合法性 |
| 只重测字幕时间 | force `native_alignment:<shot_id>`,重新识别与验收,不重生成 H3 |
| 背景音乐、音量、淡入淡出 | 修改 audio.layers 后生成 film,只重混音和合成 |
| 只更新首帧 | media 目标 `frame:<shot_id>`;不会自动修改全片作者时长 |
示例:只重新生成一个镜头素材时,`output_goal=media`、`targets=["video:<shot_id>"]`、`force=["video:<shot_id>"]`;之后再计划 film 复用有效素材生成新成片。不要用旧 `speech:`、`base_video:`、`synced_video:` 目标调用新原生图。
### 11.11 人工路径兼容
人工逐步制作仍使用 `/stories/{id}/candidates`、`/selections`、`/readiness`、`/renders`。自动成片不用逐镜候选确认;两条路径不能混淆批准状态。模式切换使用 `POST /editors/{id}/mode`,JSON 为 `{"expected_version":版本,"mode":"auto"或"manual"}`,需要会话、CSRF、幂等键和空闲草稿。
删除故事前先确认连带范围。DELETE /stories/{id} 携带 If-Match 版本。服务隐藏故事并清理其运行、任务和可删除的未收藏素材,保留已收藏或仍有受保护引用的素材。未收尾时返回 202 及 pending=true,协调器继续处理;处理完成时返回清理回执。
### 11.12 当前版本的成片与对白修订接口
| 方法和路径 | 参数位置、类型与要求 | 成功响应 |
| --- | --- | --- |
| GET /stories/{id}/film | path:故事 ID,string,必填。读取当前用户的故事 | 200,最新正式成片对象含 asset(AssetDTO)、draft_revision(integer)、run_id(string)、captions_srt_available(boolean);没有符合条件的正式运行时返回 null。实验视频也可在素材库按 ID 下载 |
| POST /editors/{draft_id}/captions/preview | JSON:expected_version 必填 integer;utterance_id 可选 string;manifest 可选完整对象,用于预览编辑 | 200,version、fps 为 integer,rows、issues 为数组。行中有 text、local_start_frame、local_end_frame;没有可靠时序时允许待定 |
| GET /editors/{draft_id}/runs/{run_id}/captions.srt | path:草稿和运行 ID 均为必填 string;需有冻结字幕 | 200,application/x-subrip,UTF-8 字幕附件。可先查 captions_srt_available |
| POST /editors/{draft_id}/dialogue/fork-cuts | 会话及 CSRF。JSON:expected_version(integer)、shot_id(string)必填;confirm(boolean,默认 false)、name(string)可选。确认时加 Idempotency-Key | 200,预览返回 shots、warnings、name;confirm=true 成功返回新草稿,用于改为说话人切镜 |
| POST /editors/{draft_id}/runs/{run_id}/turns/{shot_id}/review | 会话、CSRF、幂等键。JSON:expected_version(当前运行的 integer 版本)、report_sha256(64位十六进制 string)、decision(accept)、note(1–1000字符)必填 | 200 更新后运行快照,仅适用于服务判定可以人工复核的镜头 |
原生对白故事可使用 Story V6 与 Editor V4。节奏字幕在编辑清单的 `captions.presentation` 设置 `punctuation`(hide、preserve)及 `pacing`(rhythm、sentence),配套提交 `edits` 数组;当前新功能可按实际语音停顿显示无标点字幕,历史清单仍按保存的版本解析。导出 SRT 使用相应运行的冻结字幕。
只改字幕、配乐时,可在相同 plan/runs 合同中分别选择 `output_goal=caption_film`、`mix_film`,用合格已有来源生成修订。`caption_inspect` 用于补充字幕检查。根据返回的 issues 处理来源、人工锁定及能力限制,再按 plan_hash 提交。
新故事可在 POST /stories 的 JSON 中选择 captions_mode(none、manual、script、ai_script)和 caption_presentation(punctuation、pacing)。既有故事不会自动套用新建时的偏好。
正式同框轮流发言需要 `GET /capabilities` 中的 `dialogue.native_av.two_person_turns.available`。草稿可以配置、自由提示词可以试拍,正式运行仍会检查模型证据与逐轮验收。被判定需要重生成时,先修正台词、画面或绑定素材。对于可复核项,使用当前运行报告的摘要提交判断。
## 12 定时提交 批次与事件流
### 12.1 定时任务
`POST /jobs` 可在外层增加 `scheduled_at`:
```json
{"task_type":"image.generate","execution_mode":"batch","scheduled_at":"2027-01-01T21:00:00+08:00","input":{"prompt":"清晨山谷,云雾缓慢散开"},"parameters":{"width":1024,"height":1024,"seed":42},"count":1}
```
定时只是最早派发时刻,不是保证开始时刻。届时仍需窗口开放、资源可用、用户有效和能力就绪。
### 12.2 POST /batches
鉴权:会话及 CSRF,或 `batches:write`。需要 `Idempotency-Key`,成功 HTTP 202。
| 字段 | 类型 | 必填 | 默认值 | 限制 |
| --- | --- | --- | --- | --- |
| `name` | string | 否 | `夜间批次` | 1–255 字符 |
| `items` | object[] | 是 | 无 | 1–100 个清单项 |
| `items[].kind` | string | 是 | 无 | `job` 或 `workflow` |
| job 项 task_type/input/parameters/count | 同 Jobs | 按任务 | count=1 | 同任务参数合同 |
| workflow 项 draft_id/draft_revision/expected_version | string/integer/integer | 是 | 无 | 冻结指定工作流修订 |
```json
{
"name":"夜间素材批次",
"items":[
{"kind":"job","task_type":"image.generate","input":{"prompt":"写实雨夜街口"},"parameters":{"width":1024,"height":1024,"seed":42},"count":1},
{"kind":"job","task_type":"math.solve","input":{"prompt":"计算2x+3=9并检验"},"parameters":{"max_tokens":1024,"enable_thinking":false},"count":1}
]
}
```
返回 BatchSnapshot,包含批次及成员状态。`GET /batches/{id}` 查询;`POST /batches/{id}/control` 传 `{"desired_state":"run|pause|cancel","expected_version":当前版本}`,实际传其中一个枚举值。100 个清单项不等于并行使用 100 张 GPU,也不能把单任务 count 改为 100。
### 12.3 GET /events
鉴权:会话或 `events:read`。返回 `Content-Type: text/event-stream`,长连接,不是一次性 JSON。
| 参数/头 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| query `after` | integer | 0 | 非负 owner 事件游标 |
| `Last-Event-ID` | integer 字符串 | 无 | 提供时优先于 query after |
```text
: connected
id: 123
event: job.updated
data: {"job":{"id":"33333333333333333333333333333333","state":"running","version":2}}
: heartbeat
```
实际 data 结构按事件而定;收到通知后可重新 GET 对应资源。断流保存游标重新订阅,遇 `reset` 必须重新获取当前列表和详情;不重建生成请求。反代需保留 SSE 不缓冲及长超时。令牌不放在 URL 中,也不把 Session Cookie 写进事件日志。
## 13 错误码与排查
业务错误通常返回 detail.code 和 detail.message。请求模型校验失败时,HTTP 422 的 detail 也可能是含 loc、msg、type 的数组。
业务错误通常形如:
```json
{"detail":{"code":"capability_unavailable","message":"所选模型尚未启用或尚未完成认证"}}
```
Pydantic 字段验证错误可能返回 `detail` 数组,含 `loc/type/msg`。客户端应兼容这两种形状,不要只支持一个中文 message。
| HTTP | code 示例 | 处理 |
| --- | --- | --- |
| 400 | `invalid_input` | 参数不符合该任务合同,核对字段、类型、帧数与 profile |
| 401 | `not_authenticated`、`session_expired`、`token_expired` | 重新登录或检查令牌有效期/用户禁用情况 |
| 403 | `csrf_failed` | 会话写操作补正确 CSRF,不关闭校验 |
| 403 | `scope_required` | 配置实际存在且适用的 scope |
| 403 | `session_required` | 改用登录会话;不能给 token 加不存在权限绕过 |
| 404 | `asset_not_found`、`resource_not_found` | 检查 ID、归属、删除状态;管理员也不能跨私有资源读取 |
| 409 | `idempotency_conflict` | 同键参数变了;恢复用原参数,新意图才用新键 |
| 409 | `draft_version_conflict`、`run_version_conflict` | 重新读取版本,保留用户修改后重新计划 |
| 409 | `cleanup_pending`、`deletion_requires_terminal` | 独立记录需等待相关执行清理;删除整个故事使用第 11.11 节的联动清理回执 |
| 409 | `native_dialogue_upgrade_required` | 显式升级旧对白草稿,新运行不创建旧口型图 |
| 409 | `invalid_native_alignment` | 实测原声、双路文字、词时间或来源合同不匹配,不能伪造通过 |
| 409 | `locked_dependency_changed` | 依赖已变但素材锁定;明确解锁或强制重生成 |
| 410 | `resource_purged` | 原幂等结果已删除,不能复活旧意图 |
| 413 | 上传/输出超限 | 减小文件或按资源策略拆分 |
| 416 | 非法 Range | 修正字节区间,避免多范围请求 |
| 422 | `unsupported_task`、`invalid_target` 等 | 核对任务类型、字段、目标语法与素材种类 |
| 422 | `native_canvas_uncertified` | 原生 width/height 未命中该 profile 的实时 canvases;示例使用 1344×768 横屏 |
| 429 | `quota_exceeded`、频率限制 | 有界退避,减少并发或等待配额释放 |
| 503 | `capability_unavailable`、`maintenance` | 等待恢复或完成模型认证;不要换成未经授权的服务 |
| 503 | `database_unavailable` | 管理员查看真实 SQL/锁/连接原因;不要连续重发删除 |
`/capabilities` 或计划中返回的 `reason/issues` 比“服务器在线”更具体。原生模式典型计划问题包括台词遗漏/重复、超过单镜容量、录音不支持、双人同框未认证、人工视频不支持、画面或声音证据缺失。先解决对应问题再执行,不关闭门禁。
同一次网络超时不能直接视为未受理。先恢复幂等提交或查询已知 ID;上游执行结果未知时不要发另一个任务占用更多资源。
## 下载与维护
[OpenAPI JSON](openapi.json) · [故事操作手册](story.html)。在项目根目录使用业务后端 Python 环境运行 `python scripts/export_api_openapi.py` 导出完整接口定义,运行 `python scripts/render_manuals.py --only api` 发布网页与 Markdown。路径覆盖全部 HTTP 操作;部分路由由服务层直接返回动态 DTO,其成功响应没有额外声明 Pydantic 类型,请结合本文的返回字段和实际响应读取。

View File

@ -1,6 +1,6 @@
# 自动长视频与音轨操作指南
更新:2026-11-27。第 1–7 节介绍普通可编辑自动成片,以“凤凰90秒长视频+BGM”为例。第 8 节介绍切镜式多人对白、音色试听与局部返工,并以《雨夜归途》说明检查顺序。两条路径沿用同一套基准板、分镜和成片导航。
更新于 2026-12-01。第 1–7 节介绍普通可编辑自动成片,以“凤凰90秒长视频+BGM”为例。第 8 节介绍原生对白、节奏字幕和同框试拍,并以《雨夜归途》说明切镜式制作的检查顺序。两条路径沿用同一套基准板、分镜和成片导航。
返回[主操作手册](操作手册_20261111.md);需要逐镜确认候选时,使用[锚定故事工作室操作手册](锚定工作室操作手册_20261111.md)的人工流程。
@ -15,7 +15,7 @@
| 生成旁白 | 文字经TTS变成说话音频;旁白文案与字幕可按模式生成,不是音乐生成 |
| 自动生成原创配乐、无限延长同一镜头 | 当前没有这些入口;长片由多个有界镜头拼接,受镜头数、额度、存储、资源和超时限制 |
H3生成的视频本身静音。在提示词里写“恢宏配乐”不会生成音乐音轨;必须实际选择音频并重新合成。
第 1–7 节使用的普通 H3 视频配置输出静音镜头。需要配乐时,先准备音乐文件,在成片设置中选用并合成。第 8 节的 H3 原生有声配置可以生成对白同期声。
## 2. 模型、时长与环境
@ -80,7 +80,7 @@ H3 v1请求25–337帧,TP2请求25–145帧,均为`4n+1`;内部原生对
在故事中点“刷新进度”,或在版本与运行历史点“查看运行进度与成果”,也可到“任务”查看等待和失败原因。系统按计划生成首帧、视频及需要的声音/字幕,再合成MP4;不会因关闭网页而取消已接受运行。空闲GPU、其他用户、模型冷加载、窗口和失败恢复决定耗时,不能据镜头数承诺固定完工时间。
完成后到“03 成片”点“播放最新完成成片”,在预览弹窗点“下载原件”保存最终MP4;也可在“查看运行进度与成果”找到最终成片,或在“素材”查找当前成果目录内的MP4。单镜头视频与最终成片是不同素材,检查文件时长和内容后再交付。试听确认音乐确实出现在新版MP4中,检查开头、镜头连接、后半段与片尾。
完成后到“03 成片”,在顶部播放器检查最近一次成功导出的成片及版本号,点“下载成片”保存 MP4。也可在“查看运行进度与成果”找到最终视频,或在“素材”查找当前成果目录内的 MP4。单镜头视频与最终成片是不同素材,检查文件时长和内容后再交付。试听确认音乐确实出现在新版MP4中,检查开头、镜头连接、后半段与片尾。
如果只点“仅生成素材”,该运行不会生成最终影片,也不会替换最近完成的成片预览;需要成片时再点“生成修改部分并成片”。
@ -104,7 +104,7 @@ H3 v2是独立的原生帧/首末帧合同,原生帧124–345、步进17;首
### 8.1 开启对白,编写声线与语言
1. 保存现有故事,点顶部“启用对白自动成片”。新对白故事使用 Story V5 / Editor V3,由H3在同一次生成中完成画面、声音与口型。继续使用“01 基准板”“02 分镜”“03 成片”。
1. 保存现有故事,点顶部“启用对白自动成片”。H3 在同一次生成中完成画面、声音与口型。普通单人对白采用 Story V5,启用节奏字幕的编辑草稿采用 Editor V4。继续使用“01 基准板”“02 分镜”“03 成片”。
2. 历史对白故事会显示“升级为H3原生对白”。点击后只改变当前编辑中的生成方式,仍需点“保存”才提交;原有配音配置、素材绑定、运行和成片历史保留。升级不会重新生成任何素材。旧声音档案仍绑定参考录音时,原生FL2VA不使用这段录音克隆;在档案内点“解除旧参考录音约束”,只解除录音约束,录音素材与历史绑定继续保留。
3. 在“01 基准板”给人物准备清晰参考图,并在“角色声音档案”绑定说话人。在“声线描述”写年龄感、音高、质感、语气和节奏,例如“青年男声,清亮、自然,语速平稳”;在“对白语言”选择或填写支持的语言,默认Chinese。画外声音可绑定“画外旁白”。
4. 声线描述表达目标,不等同于固定音色或参考录音克隆。新流程不再选择Kokoro或VoxCPM2,不再独立生成台词试听,也不再经过MuseTalk重新对口型。音色一致性、读音和同步须通过实际生成的连续视频与原生音轨核对。
@ -114,13 +114,13 @@ H3 v2是独立的原生帧/首末帧合同,原生帧124–345、步进17;首
1. 在“02 分镜”加入镜头实际出现的人物,把画面与动作写在各自提示词中,把具体台词写进“镜头对白”的段落台词。作者台词与字幕文案分别保留;“口播改写”用于发音提示,“表演指令”用于语气、停顿和表演提示,不提供精确采样控制;历史句后停顿数据仍保留。历史台词若使用录音素材,必须明确点击“改为H3根据台词生成”才能转为原生生成;声音会重新生成,原录音素材仍保留。升级本身不会自动转换录音台词。
2. 在“本镜头台词”勾选这个镜头说的完整台词。单镜头段落默认使用该段全部台词;一个段落含多个镜头时,必须逐镜明确分配,系统不会猜测一句话如何截断,也不会把整段台词复制到每镜。
3. 当前一个镜头只支持一个发言角色。多人交流请拆为切镜,为各镜头分配对应人物的台词。人物在画面中发言时勾选“画内说话人”,画外声音不勾选;历史故事中已有的多人可见设置不会被自动删除。纯反应镜头可点“本镜头无对白”,明确设为无对白镜头;这与尚未指定台词不同。
3. “按说话人切镜”每镜安排一位发言人。多人交流时为各镜头分配对应人物的台词。同一机位需要两人轮流发言时,可按第 8.6 节准备同框试拍。人物在画面中发言时勾选“画内说话人”,画外声音不勾选;历史故事中已有的多人可见设置不会被自动删除。纯反应镜头可点“本镜头无对白”,明确设为无对白镜头;这与尚未指定台词不同。
4. 先做每位角色的单人近景小样。点击“重新生成本镜头原生对白”,同时更新该镜头的画面、声音与口型。镜头时长应容纳完整台词与停顿;过长台词应由作者拆句和拆镜。
5. 点击“预览原生音视频”和“试听实际原生音轨”,确认人物、实际说出的内容、语言、声线、节奏和音画同步。已有历史录音和口型片段仍可预览,但不能作为新原生对白已完成的证据。
### 8.3 字幕、混音与局部返工
1. 字幕时间依据实际原生音轨对齐,字幕文字保持作者原文或独立的字幕改字。在“对白字幕与音乐时间线”可修改字幕文案;时间不合适时到分镜点“重新对齐本镜头字幕”,读取已有原生音轨重新测时,再更新字幕并成片。
1. 字幕时间依据实际原生音轨对齐,字幕文字保持作者原文或独立的字幕改字。在“对白字幕与音乐时间线”可修改字幕文案;仅需处理字幕时,按第 8.5 节使用已有原声校时和字幕返修。
2. 声音、口型、表演或读音需要重做时,修改相关台词、声线或动作后,重新生成整个镜头的原生对白。新流程不提供独立配音返工、口型帧偏移或“仅重做口型”。首帧与锁定素材仍按当前编辑的保护规则处理。
3. 在“03 成片”保持“对白自动混音”,勾选“本次成片使用对白”。背景音乐与音效仍可独立添加,调整增益、淡入淡出和定位;启用“对白及旁白期间降低背景音乐音量”后,检查人声是否清楚、音乐是否适度。
4. 原生音轨已进入对白混音时,避免再把同一镜头原声叠加一次。历史独立旁白及成品音轨只读保留;原生模式请点“关闭历史独立旁白及成品音轨”,再把画外台词放入镜头对白。关闭只暂停旧声音模式,不删除文案、录音或历史绑定。背景音乐和音效继续独立编辑,点“重新混音并成片”应用修改。
@ -129,9 +129,24 @@ H3 v2是独立的原生帧/首末帧合同,原生帧124–345、步进17;首
### 8.4 《雨夜归途》的迁移检查顺序
《雨夜归途》含林晚、许舟、陈叔三名角色,原安排为22镜、19句对白、约120秒,配有无歌词背景音乐《檐灯》。原稿和历史成片继续保留;历史成片的完成状态不表示H3原生对白版本已经生成或验收。本次仅修改本地流程,没有重新制作线上成片。
《雨夜归途》含林晚、许舟、陈叔三名角色,原安排为22镜、19句对白、约120秒,配有无歌词背景音乐《檐灯》。原稿和历史成片继续保留;历史成片的完成状态不表示H3原生对白版本已经生成或验收。检查旧故事时请以当前打开的故事版本和选用素材为准。
1. 显式升级编辑版本并保存,为三人编写容易区分的声线描述。先核对页面原生音频能力是否可用。
2. 逐镜指定完整台词及单一发言角色。历史共享段落不能自动推断台词与镜头的对应关系,需人工安排。
3. 分别生成三人的单镜头小样,通过实际原生音轨与连续视频核对声音区分、完整读音、口型、静音段和人物身份;需要时调整描述并重做该镜头。
4. 小样满意后,检查实际音轨字幕对齐与BGM音量,再运行整片。完成后检查开头、中段、切镜和片尾,以新版本实际时间线为准。
### 8.5 在已有成片上试用节奏字幕,按版本下载 SRT
1. 新建故事时,在“启用中文原生对白后的字幕”选择“自动节奏字幕 · 隐藏句读”“人工字幕”或“关闭字幕”。选择自动字幕的故事在启用中文原生对白时采用节奏显示。已有故事可在“03 成片”的“字幕草稿预览”点“试用节奏字幕”,按镜头展开同一句,比较原设置与试用设置的文字、起止帧。
2. 在“出现方式”选“按节奏”或“整句”,在“标点显示”选“隐藏句读”或“保留原文”。这两个开关独立,例如可以整句显示并隐藏句读。作者台词和口播稿仍供生成原声使用。满意后点“应用并保存”;点“取消试用”可返回原设置。
3. 展开台词并“循环听本句”。只有整句起止可靠时,预览会保留整句;“待校时”表示仍需确定时间。有匹配的原视频和未混音的单人对白音轨时,可点“仅分析本镜已有原声”,检查执行计划中的音频识别任务。也可以点“试听本镜并校时”,填写镜内起止帧并锁定时间。最后一帧填字幕消失的帧号,例如填 24 到 48 会在第 24 至 47 帧显示。
4. 拆句时选择“原文断点”,将播放头移到对应声音位置,再点“按播放头拆分”。“合并下一段”用于同一句相邻片段。“锁定文字”和“锁定时间”可分别设置,点“应用片段修改”后保存草稿。删除的片段可在本句“恢复显示”。点“仅重算本句”可查看重新计算的结果;更换原声后若提示复核,试听并重新确认原时间锁。
5. 要下载已经导出的字幕,在“最新完成成片”或“版本与运行历史”找到对应版本,点“下载该版本 SRT”。文件使用该次成片冻结的字幕表。要导出刚修改的字幕,点“更新字幕并成片”。此操作使用原始无字幕镜头和匹配的成片混音,成功后生成新版本。历史混音缺失,或刚更换配乐、调整增益时,点“重新混音并成片”,用已选镜头及同源净音轨重建声音。缺少原片、净音轨或镜头时基时,计划会指出具体镜头。若只剩带烧录字幕、混合音轨的旧 MP4,可继续播放旧版和编辑草稿;根据计划提示恢复可重烧的镜头或重新混音,再进行返修。
### 8.6 制作两人同框、各说一句的候选
1. 在“02 分镜”的镜头对白中把拍摄方式切到“同框轮流对白”。在同一个横屏中文镜头指定两位画内角色,为每人分配一句完整台词。在“01 基准板”的角色声音档案中,为两人分别选清晰的独立参考脸及可辨认其声线的独立声音样本。
2. 选用或生成含两人的首帧并保存。按画面核对左、右角色,必要时点“交换左右角色”,再点“确认首帧与角色对应”。逐轮填写语气、听者动作,核对发言顺序和镜头可用时长。替换首帧后需要再次确认对应关系。
3. 保存草稿,查看“试生成本镜”的可用性。系统按实际 H3 配置、横屏画布和帧数核对双人专用认证。配置待认证时可继续编辑,也可点“预览并另存切镜版”,核对两镜分配后另存故事。配置已认证且角色、首帧和台词齐全时,点“试生成本镜”并查看该次运行。
4. 在“02 分镜”的“查看试拍运行”选择候选版本,打开“双人候选逐轮审核”。逐轮点“回放本轮原声与画面”,核对谁说了哪句、发言人口型以及听者有没有跟读。自动通过的候选按计划继续。遇到“待复核”,逐轮勾选“已核对本轮归属、内容和口型”,填写“选用说明”并点“以当前账号选用此候选”。明确失败的候选需要换选或重新试拍。人工选用记录关联当前候选和报告,更换候选后需重新核对。

View File

@ -1,14 +1,19 @@
# 锚定故事工作室操作手册
# 故事工作室操作手册
适用版本:2026-11-13 的“故事”工作室。入口为登录后的侧栏“故事”,页面路径 `/studio`;单个故事在 `/studio/故事编号` 编辑。多镜头自动生成、人工选片和“03 成片”统一在故事内进行;独立“工作流”“批量”“成片”页面已移除,既有数据和共享后端API保留。旧链接会转至故事或任务。
更新于 2026-12-01。登录后打开侧栏“故事”(`/studio`),点故事卡片可继续编辑。在“01 基准板”定人物与场景,在“02 分镜”排镜头,在“03 成片”剪辑、混音、加字幕并播放已导出的版本。
更新:2026-11-26。希望自动制作凤凰等长故事并加入BGM,优先看[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)。普通故事填好分镜后,保存并点“启用可编辑自动成片”;系统自动生成素材并合成,不要求逐镜确认。H3视频本身静音,BGM需上传已有授权音频,再在“03 成片”选择人工音轨。详细版本恢复规则见[主操作手册](操作手册_20261111.md)第12节。希望逐镜人工确认时,按本手册第0节先做完一个 **2 镜头、10 秒**的小故事,再增加镜头。实际操作顺序是:**新建并命名 → 建基准板 → 写分镜并保存 → 逐镜确认首帧 → 逐镜确认视频 → 调整时间线 → 保存并合成 → 下载成片**。只有已有视频、只需剪辑时,才可直接从视频导入开始。
| 想完成的作品 | 从哪里开始 | 在哪里看结果 |
| --- | --- | --- |
| 第一次做故事,逐镜选首帧和视频 | 按第 0 节做两镜头、十秒的小片 | 确认选片并点“冻结素材并合成”后,到“03 成片”播放 |
| 分镜已写好,希望一键生成长片,之后还能换镜头 | 保存故事,启用“可编辑自动成片”,按第 15 节设置音轨和字幕 | 点“自动生成初稿并成片”。改某镜后点“生成修改部分并成片” |
| 角色需要开口说话、保留对白与口型 | 保存故事,启用“对白自动成片”,按第 16 节填写说话人、台词和表演 | 在“02 分镜”试听原声、预览逐镜表演。在“03 成片”检查字幕、配乐和全片 |
| 已有白模预演 | 第 18 节介绍用预演构图生成首帧和用原视频保留动作两种方法 | 处理后的图片或视频可导入对应分镜 |
**历史验证状态(2026-11-11,Wan路径):**当时已通过 **1、2、3 张参考图真实生成**、**1280×704 的5秒和15秒视频及增强**,以及网站“三图首帧→确认→视频→页面选片→冻结合成”的真实闭环。当时验收环境开放了参考生成,验收故事名为“锚定模型全链路验收(真实生成)”。该记录不是本轮真实模型复验。当前H3、TP2及参考生成按钮是否开放,以当前环境返回的独立能力状态为准;通过样例不代表每种题材、身份一致性、复杂变形或长镜头质量都已验收。
对接脚本、请求参数、响应和任务查询见[API 接口使用说明](api.html)。普通长故事、原生对白和版本返修的分步示例见[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)。各环境可用的模型、队列时段和认证能力以当前页面提示为准。
## 0. 人工候选流程:两个镜头完成第一个故事
本节适用于人工候选流程;自动生成路径使用主手册第12节。已经启用自动成片时,先保存修改,再点击导航栏“返回逐步骤人工确认”,即可回到本流程;已有自动素材会作为待确认候选保留,由你逐步确认,故事和历史运行不变。存在未结束任务时,需要先完成或取消并等待清理后再切换。之后仍可点击“启用可编辑自动成片”切回。本例是“青衣旅人走向山门”:第一个镜头看旅人和山门的全景,第二个镜头看同一旅人的近景,每镜头选用 5 秒,最后合成 10 秒横屏视频。下面文字可直接照填;示例不会自动建立镜头,也不会自动替你生成或选片。
本节讲普通故事的人工候选流程。普通自动生成见第 15 节,原生对白见第 16 节。已经启用自动成片时,先保存修改,再点击导航栏“返回逐步骤人工确认”,即可回到本流程;普通故事已有自动素材会作为待确认候选保留,由你逐步确认。对白故事切到人工模式时进入“逐步骤对白制作”,仍使用原生对白编辑面板。存在未结束任务时,需要先完成或取消并等待清理后再切换。之后仍可点击“启用可编辑自动成片”切回。本例是“青衣旅人走向山门”:第一个镜头看旅人和山门的全景,第二个镜头看同一旅人的近景,每镜头选用 5 秒,最后合成 10 秒横屏视频。下面文字可直接照填;示例不会自动建立镜头,也不会自动替你生成或选片。
### 第 1 步:进入故事并命名
@ -102,7 +107,7 @@
1. 点击“03 成片”,顶部是“成片预览”。展开下方“查看镜头选片检查”,确认两个镜头逐项显示“选片已确认”。确认“画幅”为“横屏 1920 × 1080”;“适配”选“完整显示(留边)”可保留整个画面,选“填充画幅(裁边)”会裁去边缘以铺满画布。
2. 如有修改,先点“保存故事”,再点“冻结素材并合成”。系统会再次检查实际素材与选段;弹出“素材已冻结,合成任务已提交”后,等候成片历史更新。这个按钮只合成已确认视频,不会替你补生成缺少的镜头。
3. 点顶部“刷新成片”同步结果。合成成功后,最新成片以缩略图显示在顶部,无需先翻过镜头清单。点击缩略图或“播放成片”,在弹窗中检查镜头顺序、转接处、字幕和声音;可拖动播放器进度条、调整音量或全屏查看。
3. 点“刷新成片”。顶部播放器显示最近一次成功导出的成片,旁边有版本和时长。直接播放,拖动进度条查看镜头顺序、转接处、声音和字幕。
4. 想单独查看时点“新窗口播放”;保存最终文件时点“下载成片”。要查看旧版本或运行进度,展开下方“合成历史”,其中仍可播放、下载历史视频及查看冻结设定。
顶部“成片预览”可以直接播放最新完成的视频。“合成历史”记录了本次冻结版本和处理阶段。需要新版时,保存修改并再次合成。下载整个视频请点“下载成片”。
@ -131,9 +136,9 @@
“保存故事”保存你填写的设定与剪辑;“确认首帧”“确认选片”会直接把这次选择记录到服务器,成功后不必再为同一个确认重复保存。后续又修改设定、提示词或时间值时,仍需先保存。单纯切换预览、模式或当前镜头不会替你保存。
分镜和成片模式下,左栏“+”增加镜头;选中卡片后用“上移”“下移”重排,用“删除当前镜头”移除。至少保留一个镜头。镜头数量上限由当前环境配置,默认通常为 120;页面达到上限后不再允许添加。
在“02 分镜”的镜头列表点“+”或“+镜头”增加镜头。选中卡片后用“上移”“下移”重排,删除前先确认当前镜头。至少保留一个镜头,数量上限以当前故事模式和页面提示为准。
镜头名称和展示序号不是身份:重排不会把另一镜头的角色、候选或确认结果移到当前镜头。下方时间线中的镜头块也可点击,用于选中镜头;裁剪通过右侧数值输入完成。
各镜头的角色和选片按镜头编号关联,重排后仍对应原镜头。在“03 成片”的时间线上核对排序和裁剪后的时长。
## 3. 建立故事基准板
@ -432,18 +437,34 @@ HTTP/SSE 断线、关闭网页或切换页面不会取消已经保存提交的
“启用连续性制作”会升级为 V4 故事,可添加分层背景音乐和音效。V5 多人对白同样支持分层音轨。原生帧和首末帧使用 H3 v2 的独立合同;连续性质检开关 `CONTINUITY_QUALITY_CERTIFIED` 默认 `false`,H3 v2 另需上游证书。普通切镜、自动长视频和 BGM 可以在各自已开放的能力范围内制作。
旧版 Wan 路径曾验证 1–3 张参考图生成、5 秒与 15 秒视频,以及确认首帧、选片和合成的流程。查看旧故事时按其保存的配置复现,创建新故事时以当前模型的时长和能力提示为准。
完整步骤、模型对照、分镜时长与恢复操作见[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)。
## 16. 多人对白制作
## 16. 有对白的镜头怎么做
保存故事后点“启用对白自动成片”,进入 Story V5 / Editor V3。在“01 基准板”将说话人绑定到角色,分别设置并复用固定声音。在“02 分镜”按段落编辑台词,并选择镜头实际可见的说话人。为每位角色选正面、无遮挡且嘴部清晰的参考图,优先分别做一段单人近景小样,再扩为整片。正常切镜可用正面或小角度近景组织对话。当前双人同框口型尚未认证,保持关闭。
1. **建立说话人。** 保存故事,点“启用对白自动成片”。旧版对白故事若显示“升级为H3原生对白”,升级后点“保存编辑”。在“01 基准板”给每个角色绑定说话人,分别写对白语言与声线。例如女儿用“年轻普通话女声,明亮,紧张时语速稍快”,父亲用“年长普通话男低音,沉稳,句间略有停顿”。声线描述用来引导表现,实际音色请听生成的样片。
2. **分配台词。** 在“02 分镜”加入出镜角色,写清场面、动作与运镜。在“镜头对白”按段落输入台词,并勾选“本镜头台词”和对应的画内说话人。段落跨多个镜头时,为每镜分配完整句子。只拍听者反应时可选“本镜头无对白”。
3. **先做一个说话镜头。** “按说话人切镜”适合父女来回对话,每镜安排一位发言人。在动作中写清开口前的反应和说完后的状态。点“重新生成本镜头原生对白”,用“预览原生音视频”和“试听实际原生音轨”检查第一字、尾音、说话人和听者反应。H3 原生有声模式在同一次生成里产出画面、声音和口型。需要改变读音、声音或表演时改这一镜并重生。
4. **合成。** 在“03 成片”选择“对白自动混音”,启用“本次成片使用对白”。按需添加背景音乐,调整增益和淡入淡出后,在整片中听一下人声。只改配乐时可点“重新混音并成片”。若编辑器提示历史独立旁白或成品音轨与原生对白冲突,试听并确认用途后,按提示关闭旧声音模式。
5. **找回作品。** “03 成片”顶部显示本故事最近一次成功导出的版本。点“刷新成片”“新窗口播放”或“下载成片”。自动模式可在本页展开“版本与运行历史”查旧版或查看当前运行。“仅生成素材”的结果在镜头、对应任务和素材中可查。自行导入或外部总剪的 MP4 在“素材”的对应文件夹播放,故事播放器只关联该故事的成片运行。
用 Kokoro 时,在“声音工作台”以同一预设音色生成另一句话,再到角色档案“选择参考录音”。这段独立录音只用于音色核验。VoxCPM2 则在绑定参考录音后填写相应参考文本。
### 两人在同一镜头轮流说话
“03 成片”可独立改字幕和 BGM。台词锚点随实测对白移动。需要返工时可分别选择“重做此句配音”“仅重做口型”或“重做原片”。运行异常且准备结构已物化时,点“准备结构另存故事”可打开独立的新草稿。
1. 在“02 分镜”将拍摄方式切为“同框轮流对白”。使用横屏中文对白,在同一镜头指定两位画内角色,各分配一句完整台词。到“01 基准板”为两人分别选择独立参考脸和声音样本,供身份及声线核验。
2. 用含两位人物且嘴部清楚的图片作首帧,保存后按画面核对左右身份,必要时点“交换左右角色”,再点“确认首帧与角色对应”。更换首帧后重新确认。写清每轮发言时另一人的反应。
3. 保存后查看“试生成本镜”。按钮按当前环境的双人认证、模型、画幅、帧数及本镜输入判断是否可用。待认证时仍可保存同框草稿,或点“预览并另存切镜版”,核对台词分配后另存一部切镜故事。
4. 试拍后打开“双人候选逐轮审核”,逐轮回放原声与画面。重点看谁先开口、听者有无跟读、换人前后声音和脸是否对应。候选提示“待复核”时,完成逐轮核对并填写“选用说明”后才可人工选用;明确失败的候选需要重拍或换选。
质检确认是置信度高的小幅口型偏移时,系统可在原音频、字幕和镜头时间线上自动重做口型,独立复检通过后再选用。若仍未通过,已合格的素材和此前完成的成片会保留。可在任务详情区分人物身份一致性、口型同步和静音段嘴部运动等原因,再决定重做口型还是原片。
## 17. 对白字幕按说话节奏显示
人工确认口型偏移后,可在“02 分镜”选中目标镜头,在“镜头对白”调整“口型对时(帧)”。默认 0,范围为 −6 至 6 的整数。正数提前,负数延后,24 帧/秒时每帧约 41.7 毫秒。例如口型晚约 3 帧时填 3,再点“仅重做口型”。重做后查看该镜预览和复检结果,原对白和字幕保持原位。
1. 新建故事时,“启用中文原生对白后的字幕”默认选“自动节奏字幕 · 隐藏句读”,也可选择“人工字幕”或“关闭字幕”。已有作品可在“03 成片 → 字幕草稿预览”点“试用节奏字幕”,预览后再“应用并保存”。
2. 在“出现方式”选“按节奏”或“整句”,在“标点显示”选“隐藏句读”或“保留原文”。只需字幕干净时,直接改显示设置即可,台词里的问号、逗号可保留给演员表演。字幕使用台词或字幕改字,输入时无须在每句前加角色姓名。
3. 展开一句并点“循环听本句”。例如“爸,你往这儿靠靠”中间若有明显停顿,可在“原文断点”选“爸”后面,将播放头移到相应位置,点“按播放头拆分”。起止帧按左闭右开计算,24 到 48 对应第 24 到 47 帧。精细调整后可分别锁定文字、锁定时间。若预览提示“待校时”,按提示读取已有净音轨重新分析,或试听后填写镜内帧点。
4. 保存后点“更新字幕并成片”生成新版,需要匹配的无字幕原片和成片混音。若刚改过配乐或旧混音缺失,用“重新混音并成片”。完成后在播放器或“版本与运行历史”点“下载该版本 SRT”(有可导出字幕的版本才显示),该文件对应已导出版本。
三角色、22 镜、120 秒《雨夜归途》的跑样顺序和当前验收状态见[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)第 8 节。
## 18. 使用白模预演参考
- **保留构图和站位。** 从预演导出分镜首帧,到“创作 → 图生图”添加白模截图和角色参考图,提示词注明各图用途、人物左右、朝向及视线。检查生成的正式首帧,在“02 分镜”导入并选用,填写运动描述,再生成视频。人工候选流程先点“确认首帧”。H3 依选用配置接受首帧或首尾帧,双卡原生有声配置使用首帧。首帧能约束开场构图,精确动作时序和机位轨迹仍需看片核对。
- **保留已有动作和运镜。** 若预演视频中的人物能被跟踪,可到“创作 → 视频人物替换”先“识别人物”,沿时间轴检查检测框,给每人绑定一张角色参考图再生成。替换区域围绕人物,场景和道具会沿用预演画面;该入口保留源音轨时也会沿用原台词。想用这段成品参与普通故事合成,可在人工流程导入视频候选并确认选片。详细步骤见[图生图与视频人物替换操作手册](图生图与视频人物替换操作手册_20261112.md)。
- 项目的视频生成接口接收提示词和静态图像条件。整段白模动画的骨骼、深度序列或摄影机轨迹目前没有对应的 H3 输入字段。实际支持的图片、素材字段和任务类型见[API 接口使用说明](api.html)。

File diff suppressed because one or more lines are too long

950
frontend/public/help/api.md Normal file
View File

@ -0,0 +1,950 @@
# API 接口与模型调度
[下载 OpenAPI 3.1 定义](openapi.json) · [打开故事操作手册](story.html)。本页与项目一起发布,无需外部 Swagger 服务。在 Postman 中选择 Import,导入下载的 JSON 文件,即可按接口查看方法、路径、查询参数、请求头与请求体模型,展开 components.schemas 查看字段类型、必填项和约束。导入后请按下文配置会话或 Bearer、CSRF 和幂等键。自动定义中,部分动态响应未声明字段,文件下载、事件流也可能被标成 JSON;实际返回类型和业务字段请使用对应章节。
## Postman 快速开始
1. 建立本地环境变量 `baseUrl`,值为网站地址加 `/api`。示例使用相对路径;导入的 OpenAPI 路径已包含 `/api`,避免拼接两次。
2. 发送 `POST {{baseUrl}}/auth/login`。Body 选择 raw → JSON,使用 `{"username":"{{username}}","password":"{{password}}"}`,两个变量均使用个人环境的本地值。Cookie Jar 将保存 cmvr_session。登录请求的 Post-response 脚本用下方第一行保存 CSRF。
3. 以相同会话发送 `GET {{baseUrl}}/capabilities`,按任务类型、profile、画幅检查是否可用。上传图片时用 `POST {{baseUrl}}/assets`,Body 选 form-data,键 file 类型选 File;成功后将 id 存为 imageId。
4. 发送 `POST {{baseUrl}}/jobs`,添加 `X-CSRF-Token: {{csrf}}` 与 `Idempotency-Key: {{requestKey}}`。每项新任务先生成一个新的 UUID 放入 requestKey;网络重发沿用原值。选择下文一份 JSON 作为 Body,把示例素材 ID 换成本人上传记录的 ID。提交请求的 Post-response 脚本用下方第二行保存任务 ID。
5. 用 `GET {{baseUrl}}/jobs/{{jobId}}` 查询。成功后在 result_assets 选取需要的素材并保存它的 id;`GET {{baseUrl}}/assets/{{assetId}}/content?download=1` 返回原始文件。数学推演另可从 result.text 直接读取结果。
```javascript
// 登录请求的 Post-response
if (pm.response.code === 200) pm.environment.set("csrf", pm.response.json().csrf_token);
```
```javascript
// POST /jobs 的 Post-response
if (pm.response.code === 202) pm.environment.set("jobId", pm.response.json().jobs[0].id);
```
## 1 服务地址与接口约定
### 1.1 地址
| 项目 | 值或含义 |
| --- | --- |
| 生产网站 | `https://video.svc.cmvr-iot.icu/` |
| 生产 API 根地址 | `https://video.svc.cmvr-iot.icu/api`,下文记为 `API_BASE` |
| 局域网备用网站与 API | `http://192.168.28.10:18193/` 与 `http://192.168.28.10:18193/api`;优先使用 HTTPS |
| 本地开发网站 | `http://127.0.0.1:5173` |
| 本地业务 API | `http://127.0.0.1:8000/api` |
| 下文路径 | 均相对于 `API_BASE`,例如 `/jobs` |
| 请求编码 | JSON 使用 UTF-8,`Content-Type: application/json`;上传使用 multipart |
| 时间 | ISO 8601,带 `Z` 或时区偏移;响应通常为 UTC |
| ID | 使用服务器返回的原始 ID;通常为 32 位小写十六进制字符串 |
FastAPI 在业务后端自身提供 `/openapi.json`、`/docs`;它们不带 `/api` 前缀。现有网站反代只明确代理 `/api/`,因此不能据此认定网站域名的 `/docs` 可访问,也不能把 `/api/docs`、`/api/openapi.json` 当作已经存在的接口。本文采用 Swagger 风格并不改变真实路由。
自动 OpenAPI 能描述 HTTP 外层模型;`POST /jobs` 的 `input`、`parameters` 为动态对象,模型特定字段还受业务合同校验。各任务的详细参数以下文及实时能力响应为准。示例响应为主要字段示例,实际 DTO 可能另有版本、来源和审计字段。
### 1.2 生产时段
生产保留 `GPU_WINDOW_ENABLED=true`,北京时间 `Asia/Shanghai` 的准入窗口为每天 **21:00 至次日 08:00**,交互和批量两种队列均受控。白天可登录、上传、编辑、提交排队、查询和下载已有成果;提交成功不代表立即执行。
08:00 时已经获准执行的阶段允许完成,后续阶段等待下一窗口。当前业务协调器的阶段准入也覆盖 CPU 合成和 Qwen 推演,不能假定“CPU 任务白天一定立即执行”。本地开发使用 `GPU_WINDOW_ENABLED=false`,与生产配置独立。
客户端不能传 `GPU_WINDOW_ENABLED`、`gpu_window_enabled`、`gpu_id`、`docker_id` 或任意系统命令来豁免调度。`execution_mode=interactive` 表示队列类别,不是全天算力通行证。
### 1.3 通用请求头
| 请求头 | 何时提供 | 规则 |
| --- | --- | --- |
| `Cookie` | 会话鉴权 | 登录后客户端自动保存 `cmvr_session`,不要自行构造 |
| `X-CSRF-Token` | 会话写请求 | 登录响应中的 token;用于 POST、PATCH、DELETE 等 |
| `Authorization` | 机器程序 | `Bearer cmvr_...`;与浏览器 Cookie 方案分开使用 |
| `Idempotency-Key` | 生成、运行及有关控制命令 | 建议 UUID;长度 1–128;同一业务意图保持同键、同参数 |
| `If-Match` | 使用版本 CAS 的 PATCH/DELETE | 对象最近读取到的版本;具体接口见后文 |
| `Last-Event-ID` | SSE 断线续接 | 非负整数事件游标 |
除明确标注允许外,不增加未知字段。布尔字段应传 JSON `true` / `false`,不能传字符串;整数不能用小数或布尔值冒充。素材输入使用本人已上传的素材 ID,不接受服务器绝对路径或任意外部 URL。
## 2 登录与机器鉴权
### 2.1 POST /auth/login
用途:建立浏览器或脚本会话。请求无须登录;成功返回 HTTP 200 并设置 HttpOnly Cookie。
| JSON 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `username` | string | 是 | 无 | 1–64 字符 |
| `password` | string | 是 | 无 | 1–256 字符,使用现有账户密码 |
```json
{"username":"example_user","password":"<从安全输入读取>"}
```
```json
{
"user":{"id":"11111111111111111111111111111111","username":"example_user","display_name":"示例用户","role":"user"},
"csrf_token":"<仅用于本会话的CSRF值>"
}
```
Cookie 与 CSRF 都是敏感数据,不输出到日志或文档。没有公开注册接口。管理员可新增账户;被禁用或删除的账户不能继续使用 API。`GET /auth/me` 读取当前身份;`POST /auth/logout` 注销会话,成功为 HTTP 204。修改密码、用户名使用会话接口,不使用模型推理密钥。
### 2.2 POST /auth/tokens
用途:为当前用户创建机器令牌,必须使用登录会话和 CSRF。成功 HTTP 201,明文 token 仅在创建时返回一次;不能用已有机器令牌创建新令牌。
| JSON 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `name` | string | 是 | 无 | 1–128 字符 |
| `scopes` | string[] | 是 | 无 | 最多 20 个,仅下表允许值 |
| `expires_at` | string 或 null | 否 | null | 带时区的将来时间;建议设置 |
```json
{
"name":"业务调度程序",
"scopes":["jobs:read","jobs:write","assets:read","assets:write","events:read"],
"expires_at":"2027-01-01T00:00:00+08:00"
}
```
```json
{
"token":"cmvr_<只返回一次的随机值>",
"record":{"id":"22222222222222222222222222222222","name":"业务调度程序","scopes":["jobs:read","jobs:write","assets:read","assets:write","events:read"],"expires_at":"2026-12-31T16:00:00.000Z","revoked_at":null}
}
```
| scope | 用途 |
| --- | --- |
| `jobs:read` / `jobs:write` | 查询 / 提交、取消、重试任务 |
| `assets:read` / `assets:write` | 查询、下载 / 上传、编辑素材及共享素材操作 |
| `folders:read` / `folders:write` | 分类读取 / 修改 |
| `workflows:read` / `workflows:write` | 故事、编辑器、运行的读取 / 写入 |
| `batches:read` / `batches:write` | 批次读取 / 创建和控制 |
| `events:read` | SSE 事件流 |
| `interactive:write` | 机器令牌提交交互队列时的额外权限 |
机器程序使用 `Authorization: Bearer <token>`,不要同时携带会话 Cookie 或浏览器的 `Sec-Fetch-Site` 请求头。这是本项目数据库管理的随机令牌,不是 JWT,也不是上游模型 API Key。令牌始终继承所属用户的资源隔离,不具有管理员身份。
`GET /auth/tokens` 返回当前会话用户的令牌记录,`DELETE /auth/tokens/{token_id}` 吊销,HTTP 204。即使 scope 足够,`execution_mode=interactive` 仍额外需要 `interactive:write`;生产时段限制不会因此取消。
当前版本限制:能力和状态路由在机器鉴权时会分别匹配 `capabilities:read`、`system:read`,但可创建 scope 清单不包含这两项。因此能力查询示例使用登录会话;不能通过创建不存在的权限值绕过这一限制。
### 2.3 账户管理接口
以下均使用登录会话,写操作带 CSRF。用户管理只允许管理员会话;机器令牌不会获得管理员角色。
| 方法和路径 | JSON 主要字段 | 权限与说明 |
| --- | --- | --- |
| `GET /auth/users` | 无;query page/page_size | 管理员用户列表 |
| `POST /auth/users` | username、display_name、password | 管理员新增;初始密码允许 6 位数字,用户名按服务规则校验 |
| `PATCH /auth/users/{user_id}` | disabled,可选 display_name | 管理员禁用/启用;禁用保留资源但阻止登录和操作 |
| `DELETE /auth/users/{user_id}` | 无 | 管理员永久删除用户及其受控资源,活动工作须按删除流程清理 |
| `POST /auth/password` | current_password、new_password | 当前用户改密;新密码仍要求至少 12 字符,成功后按返回提示重新登录 |
| `POST /auth/username` | username、current_password | 当前用户改用户名,核对密码并按返回提示重新登录 |
管理员不能删除最后一个可用管理员或绕过项目对自身账号的保护。删除账户属于资源清理操作,不能用“禁用账户”替代,也不要在自动模型调用脚本中默认执行。
## 3 能力与调度状态
### 3.1 GET /capabilities
鉴权:当前使用登录会话。用途:读取任务支持情况、模型 profile、默认参数、范围、原生对白门禁与调度窗口。HTTP 200。
```json
{
"items":[
{"task_type":"video.generate","available":true,"model":"MiniMax H3 原生音视频","video_profiles":[{"profile":"minimax-h3-fl2va-native-av-tp2-v1","available":true,"reason":null,"canvases":[[1344,768]],"defaults":{"width":1344,"height":768,"num_frames":124,"fps":24,"upscale":false},"constraints":{"num_frames":{"min":124,"max":158,"step":17}}},{"profile":"minimax-h3-fl2va-native-av-v1","available":false,"reason":"尚未启用或未完成独立实测认证","canvases":[]}]}
],
"dialogue":{"native_av":{"available":true,"production_available":true,"languages":["Chinese"],"supports_two_faces":false,"max_visible_speakers":1,"readiness":{"generation":true,"word_alignment":true,"visual_review":true},"reason":null}},
"execution_policy":{"timezone":"Asia/Shanghai","start":"21:00","end":"08:00","batch_window_enabled":true,"batch_open":false,"close_behavior":"finish_current","next_batch_at":"2026-11-27T13:00:00+00:00","configuration_error":null},
"workflow_limits":{"max_shots":60,"fps":24},
"scheduler":{"available":true,"state":"ready","gpus":[]}
}
```
上例为主要字段节选,其中可用状态仅说明字段形状,不代替部署后的实时状态。实际视频配置在 `items[task_type=video.generate].video_profiles[]` 中,读取目标 profile 自己的 `available`、`reason`、`canvases`、`defaults`、`constraints`。原生 `canvases` 只列实际认证的 `[width,height]` 组合;上例为 `[[1344,768]]`,未认证或关闭时为 `[]`。即使 `available=true`,也不能提交列表外的画布;分别读取 width/height 的理论数值范围不能替代组合检查。
同一模型族的静音视频、原生有声、单卡、双卡及不同画幅可能有不同验收结果。按本次提交要用的 profile 和 canvases 选择。
### 3.2 GET /system/status
HTTP 200,返回 `inference_online`、`scheduler`、`models`、`environment`、`database_backend`、`execution_policy`、`workflow_limits`、`public_access`。用于运维观察;`inference_online=true` 只代表上游健康,不保证指定模型已经完成认证。
当前没有对业务用户公开的 `POST /scheduler/run`、`POST /gpu/allocate` 或任意启动容器接口。**调用调度器的正式方式是向 `/jobs`、`/editors/{id}/runs` 或 `/batches` 提交受控业务命令**。后台依据资源阶段获得 `new_gpu`、`cpu_media`、`qwen_http` 槽位,客户端只选择任务意图与支持的参数。
### 3.3 GET /live 与 GET /ready
这两个接口不要求登录。`/live` 返回 `{"status":"ok"}`,检查进程活性;`/ready` 在数据库、协调器、上游协议与准入检查均通过时返回 HTTP 200,否则 HTTP 503。
```json
{"status":"ready","checks":{"database":true,"coordinator":true,"upstream_protocol":true,"accepting":true}}
```
GPU 忙或等待夜间窗口不是进程故障;不需要因此重启网站或重复提交任务。
## 4 通用任务提交与返回结构
### 4.1 POST /jobs
鉴权:会话及 CSRF,或 `jobs:write`;交互机器任务还需 `interactive:write`。请求为 JSON,建议始终携带 `Idempotency-Key`。成功 HTTP 202,返回 `{"jobs":[JobDTO]}`。
| 字段 | 类型 | 必填 | 默认值 | 约束和说明 |
| --- | --- | --- | --- | --- |
| `task_type` | string | 是 | 无 | 使用后续任务清单支持的名字 |
| `input` | object | 否 | `{}` | 提示词与本人素材 ID;具体必填项由任务决定 |
| `parameters` | object | 否 | `{}` | 模型参数;未知字段拒绝 |
| `execution_mode` | string | 否 | `interactive` | `interactive` 或 `batch` |
| `count` | integer | 否 | 1 | 1–4;多份仅限图片、参考图片、缺陷样本任务;各份种子递增 |
| `scheduled_at` | datetime 或 null | 否 | null | 必须带时区;将来时间会先处于 `scheduled` |
| `folder_id` | string 或 null | 否 | null | 任务记录所在本人分类 |
| `output_folder_id` | string 或 null | 否 | 未传时继承 `folder_id` | 显式 null 表示成果不继承分类 |
```json
{
"task_type":"image.generate",
"execution_mode":"batch",
"input":{"prompt":"白色背景上的蓝色陶瓷杯,自然柔光"},
"parameters":{"width":1024,"height":1024,"num_inference_steps":50,"seed":42,"guidance_scale":4.0},
"count":1
}
```
```json
{
"jobs":[{
"id":"33333333333333333333333333333333",
"task_type":"image.generate",
"state":"submitting",
"phase":"waiting_dispatch",
"version":1,
"execution_mode":"batch",
"desired_state":"run",
"hold_reasons":[],
"result_assets":[],
"result":null,
"progress":null,
"queue_position":null,
"attempt_count":0,
"preemptions":0,
"error":null,
"sync_warning":null,
"cancel_requested":false
}]
}
```
HTTP 202 只表示意图已经接纳,首个状态也可能因定时或调度推进而不同。不要把 `progress=null` 解释成 0%,也不要编造模型生成百分比。任务 ID 是业务任务 ID,不是 GPU PID。
### 4.2 JobDTO 主要字段
| 字段 | 类型 | 含义 |
| --- | --- | --- |
| `id` | string | 持久业务任务 ID |
| `task_type`、`parameters` | string、object | 已提交任务类型及公开参数 |
| `state`、`phase` | string | 生命周期状态、当前阶段 |
| `version` | integer | 对象版本,用于一致读取及有关删除控制 |
| `hold_reasons` | string[] | 等待原因,如窗口等待;不是新的生成请求 |
| `run_id`、`step_key`、`batch_id` | string 或 null | 所属故事运行或批次 |
| `result_assets` | AssetDTO[] | 已归档、可访问的成果 |
| `result` | object 或 null | 文本、识别、模型实测元数据等,随任务变化 |
| `error` | object 或 null | 失败 code/message 等,不直接向终端用户展示内部路径 |
| `sync_warning` | string 或 null | 上游查询、下载或归档恢复提示,不应自动另建任务 |
| `attempt_count` | integer | 上游尝试数 |
| `explicit_attempt` | integer | 用户明确重试代次 |
| `preemptions` | integer | 让卡次数,可能重新排队 |
| `created_at`、`scheduled_at`、`started_at`、`finished_at` | datetime 或 null | 时间线 |
常见状态包括 `scheduled`、`submitting`、`queued`、`running`、`collecting`、`cancelling`、`succeeded`、`failed`、`cancelled`、`timed_out`、`needs_attention`。`cancel_requested` 是独立布尔字段,不是这里的取消中状态名称。读取实际 `state` 和 `phase`,不要仅凭页面文字推断状态。上游结束后归档未完成时仍可能是 `collecting`;自动让卡不等于用户取消。
不同任务使用同一个 JobDTO 外层,模型结果的读取位置如下。`result_assets` 中每项都是可继续查询或下载的 AssetDTO,不能把上游文件路径当作下载地址。
| 任务 | 成功后的主要读取位置 |
| --- | --- |
| `image.generate`、`image.reference.generate` | `result_assets` 中的图片;`result` 为实际生成元数据 |
| `defect.generate` | 保存全部相关图片成果,包括生成样本和控制图;不返回缺陷真值掩膜 |
| 原生 `video.generate` | `result_assets` 中的有声 MP4 和独立 WAV;实测元数据在 `result.native_av` |
| `math.solve` | `result.text`,以及文本和 JSON 素材 |
| `media.structure` | `result.subjects/scene/ocr/tags/frames`,以及结构化 JSON 素材 |
| `audio.transcribe` | `result.text` 和 `result.segments`,以及转写成果;通用分段不是字词口型证据 |
| `video.compose` | `result_assets` 中的成片视频;完整故事验收需查父运行及质检成果 |
### 4.3 GET /jobs 与 GET /jobs/{job_id}
鉴权:会话或 `jobs:read`。列表返回 `items,total,page,page_size,cursor`;详情直接返回 JobDTO。
| 列表 query | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| `page` | integer | 1 | 从 1 开始 |
| `page_size` | integer | 24 | 常规 1–100,以服务校验为准 |
| `folder_id` | string | `""` | 本人分类筛选 |
| `task_type`、`state` | string | `""` | 类型、状态筛选 |
| `root_only` | boolean | false | 排除所属运行的子任务 |
建议每 2–5 秒轮询一次目标任务,状态 `succeeded` 后读取 `result_assets`。`needs_attention` 表示执行结果或清理状态需核对,不能通过新增同类任务掩盖未知结果。
### 4.4 取消 重试 删除
| 方法和路径 | 请求 | 成功 | 行为 |
| --- | --- | --- | --- |
| `POST /jobs/{id}/cancel` | 无 JSON 必填字段;会话仍需 CSRF | 200 JobDTO | 请求取消,实际退出与清理异步确认 |
| `POST /jobs/{id}/retry` | 建议新的 `Idempotency-Key` | 202 `{"jobs":[...]}` | 对可重试的失败任务发起明确重试;不是超时恢复操作 |
| `DELETE /jobs/{id}` | 按对象要求提供 `If-Match` | 200 | 清理任务记录及其受控成果;活动任务须先取消并等清理完成 |
故事工作流子任务应由父运行控制,不要绕过父图单独重试;错误响应会提示相应父运行。删除与取消是不同操作;删除不会变成一个可安全忽略的“隐藏按钮”。
### 4.5 GET /submissions/{key}
query `operation` 必填。用于响应丢失后恢复业务意图,HTTP 200。
```text
GET /submissions/8ebc5e83-52cf-4428-a1bb-754528199212?operation=jobs.create
```
```json
{"key":"8ebc5e83-52cf-4428-a1bb-754528199212","operation":"jobs.create","status":"accepted","resource_json":{"job_ids":["33333333333333333333333333333333"]},"job_ids":["33333333333333333333333333333333"]}
```
常用 operation 有 `jobs.create`、`jobs.retry`、`editor.save`、`editor.dialogue.enable` 及接口对应的运行命令。客户端应在发请求前保存幂等键、完整 body、操作名和返回 ID。404 只表示尚未找到,重放仍必须使用原键与原 body;410 表示原结果已清理,不能用旧键强行重建;409 表示同键被用于不同参数。
## 5 素材上传与成果下载
### 5.1 POST /assets
鉴权:会话及 CSRF,或 `assets:write`。使用 multipart,成功 HTTP 201,返回 AssetDTO。
| form 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `file` | binary | 是 | 实际图片、音视频等文件,不是服务器路径 |
| `name` | string | 否 | 显示名,默认由上传文件名取得 |
| `folder_id` | string | 否 | 本人分类 ID |
默认单文件上限 512 MiB,实际还受反代、用户存储配额和格式检查约束。不要将 API Key、密码或无关服务器文件上传为素材。
```json
{
"id":"44444444444444444444444444444444",
"name":"speaker.png",
"kind":"image",
"mime_type":"image/png",
"size_bytes":350000,
"width":1344,
"height":768,
"duration_seconds":null,
"preview_url":"/api/assets/44444444444444444444444444444444/content",
"download_url":"/api/assets/44444444444444444444444444444444/content?download=1",
"source_job_id":null,
"source_output_index":null,
"origin":"upload"
}
```
### 5.2 查询与文件内容
| 接口 | 成功响应 |
| --- | --- |
| `GET /assets` | 分页 `items,total,page,page_size,cursor`;可按 `kind,q,tag,favorite,origin,folder_id` 筛选 |
| `GET /assets/{asset_id}` | 单个 AssetDTO |
| `GET /assets/{asset_id}/content` | 受鉴权保护的原始文件内容 |
| `GET /assets/{asset_id}/content?download=1` | 以下载方式返回原文件 |
| `GET /assets/{asset_id}/thumbnail` | 已生成的缩略图 |
| `PATCH /assets/{asset_id}` | 修改 `name`、`tags`、`favorite`、`folder_ids` |
| `DELETE /assets/{asset_id}` | HTTP 204;仍被草稿、任务或运行引用时可能 409 |
下载需要同一用户会话或 `assets:read`。相对 `download_url` 已包含 `/api`,拼接时使用网站根地址,避免得到 `/api/api/...`。文件接口支持单个字节范围 `Range: bytes=0-31`,合法请求 HTTP 206,越界为 416;不支持多区间请求。
素材不存在、已删除或非本人均不能访问,通常返回 404。不要把素材路由替换为绕过鉴权的公共静态目录。任务可能有多个成果,应按 `kind`、`mime_type`、名称和输出用途选择,不要无条件下载 `result_assets[0]`。
AssetDTO 和 `result_assets` 不公开 `sha256`。普通任务下载可核对 `size_bytes` 并自行计算文件摘要,但没有公开的可信预期摘要时,不能声称已与服务器 SHA 校验一致。故事成片可按 `steps[kind=video.compose].result.asset_id` 匹配素材,并与该 Step 返回的 `result.sha256` 比对;不要臆造 `asset.sha256` 字段。
## 6 图片生成接口
### 6.1 文生图 image.generate
方法:`POST /jobs`。模型意图:Qwen-Image;以能力接口实际模型标识为准。`count` 支持 1–4。
| input 字段 | 类型 | 必填 | 默认值 | 限制 |
| --- | --- | --- | --- | --- |
| `prompt` | string | 是 | 无 | 非空,最多 8000 字符 |
| `negative_prompt` | string | 否 | `""` | 最多 8000 字符 |
| parameters 字段 | 类型 | 必填 | 默认值 | 范围 |
| --- | --- | --- | --- | --- |
| `width` | integer | 否 | 1024 | 256–2048,16 的整数倍 |
| `height` | integer | 否 | 1024 | 256–2048,16 的整数倍 |
| `num_inference_steps` | integer | 否 | 50 | 1–100 |
| `guidance_scale` | number | 否 | 4.0 | 1–20 |
| `seed` | integer | 否 | 42 | 0–4294967295 |
总像素不超过 2048×2048。返回方式与通用 JobDTO 一致;成功时在 `result_assets` 取得图片。提高步数会增加计算,不是质量保证。
### 6.2 参考图生成 image.reference.generate
方法:`POST /jobs`。先上传 1–3 张参考图,保持顺序;本版默认 profile 为 `qwen-image-edit-2511-v1`,以当前配置与认证为准。缺参考图或未认证时不会自动降级文生图。
| input 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `prompt` | string | 是 | 非空,最多 8000 字符;用 Picture 1、Picture 2 对应顺序 |
| `reference_asset_ids` | string[] | 是 | 默认 1–3 张本人图片 ID,不重复;实际最大值由能力给出 |
| `negative_prompt` | string | 否 | 默认空串 |
| parameters 字段 | 类型 | 默认值 | 约束 |
| --- | --- | --- | --- |
| `profile` | string | 配置值 | 必须等于已启用且认证的 profile |
| `width`、`height` | integer | 1280、704 | 仅 1280×704、704×1280、1024×1024 |
| `num_inference_steps` | integer | 40 | 1–100 |
| `seed` | integer | 42 | 0–4294967295 |
| `guidance_scale` | number | 1.0 | 1–20 |
| `true_cfg_scale` | number | 4.0 | 1–20 |
| `max_sequence_length` | integer | 1024 | 1–1024 |
```json
{
"task_type":"image.reference.generate",
"execution_mode":"batch",
"input":{"prompt":"保持Picture 1人物的脸部、发型与服饰,人物站在温暖室内,中景,正面偏侧,表情自然。","reference_asset_ids":["44444444444444444444444444444444"]},
"parameters":{"profile":"qwen-image-edit-2511-v1","width":1280,"height":704,"num_inference_steps":40,"seed":42,"guidance_scale":1.0,"true_cfg_scale":4.0,"max_sequence_length":1024},
"count":1
}
```
生成后应检查人物身份、手部、构图和口部清晰度,再作为视频首帧。参考图是模型输入;普通文生图的提示词中写一个素材 ID 不会自动使用该图片。
## 7 H3 视频生成接口
### 7.1 先选择正确的 profile
`POST /jobs` 的 `task_type` 都是 `video.generate`,但 profile 决定参数和音轨合同。**调用 H3 时必须显式传 profile**。为兼容历史请求,省略 profile 保留旧 Wan 参数语义,不能把它理解成“自动选择服务器最新 H3”。
| profile | 条件输入字段 | 请求帧数 | 输出音轨与用途 |
| --- | --- | --- | --- |
| `minimax-h3-fl2va-bf16-v1` | `image_asset_id`,可选图生条件 | 25–337 且 4n+1 | 静音,历史常规 H3 |
| `minimax-h3-fl2va-bf16-v2` | `first_frame_asset_id`,可选尾帧 | 124–345,步长 17 | 静音完整原生帧 |
| `minimax-h3-fl2va-bf16-tp2-v1` | `image_asset_id` 必填 | 25–145 且 4n+1 | 双卡静音,最长请求约 6 秒 |
| `minimax-h3-fl2va-native-av-v1` | `first_frame_asset_id`,可选尾帧 | 124–345,步长 17 | 单卡原生音画;可用性取决于服务认证 |
| `minimax-h3-fl2va-native-av-tp2-v1` | `first_frame_asset_id` | 124、141、158 | 双卡原生音画,仅首帧;示例使用 1344×768 横屏 |
| `wan2.2-ti2v-5b-v1` | `image_asset_id` 可选 | 5–361 且 4n+1 | 保留历史配置 |
profile 是否真实可用、是否正式认证、是否暂时关闭,必须读取目标项自己的能力字段,不能只根据这个清单提交。此处示例采用 `minimax-h3-fl2va-native-av-tp2-v1` 横屏 1344×768;单卡及竖屏原生配置不因横屏 TP2 验收而自动开放。双卡需要两张符合资源策略的空闲卡,不是传 `gpu_count=2`;内存预留也按该 profile 的实际资源策略计算。
### 7.2 原生有声 H3 参数
方法:`POST /jobs`;`count=1`。下面以 `minimax-h3-fl2va-native-av-tp2-v1` 为例;须同时满足目标项实时 `available=true` 和 `[1344,768]` 在该项 `canvases` 内。
| input 字段 | 类型 | 必填 | 约束 |
| --- | --- | --- | --- |
| `prompt` | string | 是 | 最多 8000 字符,写完整画面动作、对白和声景 |
| `first_frame_asset_id` | string | 是 | 本人图片 ID |
| `last_frame_asset_id` | string | 不传 | TP2 不支持;提交此字段会拒绝 |
| `negative_prompt` | string | 否 | H3 只能为空;不要提交非空负提示词 |
| parameters 字段 | 类型 | 默认值 | 约束 |
| --- | --- | --- | --- |
| `profile` | string | 调用时显式指定 | 示例使用 `minimax-h3-fl2va-native-av-tp2-v1` |
| `width` | integer | 1344 | 示例宽度为 1344,须命中实时 canvases |
| `height` | integer | 768 | 示例画幅高度为 768;必须符合目标 profile 的 canvases |
| `num_frames` | integer | 124 | TP2 只允许 124、141、158 |
| `fps` | integer | 24 | 固定 24 |
| `num_inference_steps` | integer | 50 | 2–100 |
| `seed` | integer | 42 | 0–4294967295 |
| `conditioning_mode` | string | `first_frame` | TP2 固定 `first_frame` |
| `upscale` | boolean | false | 原生有声固定 false |
| `upscale_width`、`upscale_height` | integer | 1920、1080 | 通用兼容字段,偶数,分别 256–3840 与 256–2160;原生不执行增强,通常省略 |
| `tile_size` | integer | 128 | 通用兼容字段,64–256,16 的倍数;原生不执行增强,通常省略 |
原生模式不接收 `guidance_scale`、不支持任意 fps、不支持用 `duration=5` 替代帧数。124、141、158 帧约为 5.17、5.88、6.58 秒,台词须留出自然开口和句末闭口余量。更长内容拆成正常切镜的多镜头,再走故事流程成片,不能超过 TP2 单镜 158 帧上限。
```json
{
"task_type":"video.generate",
"execution_mode":"batch",
"count":1,
"input":{
"first_frame_asset_id":"44444444444444444444444444444444",
"prompt":"integrated_multimodal_description: [Shot 1] 一位青年正面略偏侧中景,脸部清晰,固定镜头,人物自然呼吸,轻微点头。青年(S1)用清晰自然的中文说:<d>[Chinese] 你好,欢迎来到我们的故事。</d> 说完自然闭唇,保持轻微表情动作到结尾,不再继续说话。\noverall_soundscape: 安静室内,只有这位青年说话,无其他人声。\nnon_diegetic_music: N/A"
},
"parameters":{
"profile":"minimax-h3-fl2va-native-av-tp2-v1",
"width":1344,"height":768,"num_frames":124,"fps":24,
"num_inference_steps":50,"seed":42,"conditioning_mode":"first_frame","upscale":false
}
}
```
成功时 `result_assets` 应包含带原声的视频及 32kHz 双声道 PCM WAV;按类型识别并分别保存。`result.native_av` 会提供实测帧数、样本数、采样率、音画时长差和完整输出策略等元数据,以实际响应为准。官方 40Hz 音频潜变量格点可使 WAV 比视频长或短至多约 12.5ms;不能为了让两个容器时长字符串相等而裁掉句尾。
同一段音画的精确帧数及音频样本数可从 Job.result.native_av 读取。
| `result.native_av` 字段 | 类型与单位 | 说明 |
| --- | --- | --- |
| `video_frames`、`fps` | integer | 实测完整视频帧数,固定 24fps |
| `sample_rate`、`channels` | integer | 原始 WAV 为 32000Hz、双声道 |
| `audio_samples` | integer,每声道样本数 | 完整原声音轨样本数 |
| `start_sample`、`end_sample` | integer | 原始完整区间,起点 0,终点等于 audio_samples |
| `audio_duration`、`video_duration` | number,秒 | 分别按样本数和帧数计算的时长 |
| `av_duration_delta` | number,秒 | 音频时长减视频时长;这是长度差,不是人物口型延迟 |
| `output_policy`、`audio_trimmed` | string、boolean | `full_native`、false,完整保留原生输出 |
| `audio_format` | string | `pcm_s16le`,独立 WAV 的编码 |
直接 `video.generate` 返回的是该镜头的原始生成结果,**不会自动替调用方执行故事的双路对白内容复核、字幕编译和成片验收**。需要自动检查和字幕时,走第 11 章故事原生对白流程;不能把“任务 succeeded”当作已经证明口型完全正确。
### 7.3 静音 H3 首帧示例
```json
{
"task_type":"video.generate",
"execution_mode":"batch",
"input":{"image_asset_id":"44444444444444444444444444444444","prompt":"人物缓慢转头看向窗外,肩部随呼吸轻微起伏,窗外雨水持续流动,固定镜头。"},
"parameters":{"profile":"minimax-h3-fl2va-bf16-v1","width":1344,"height":768,"num_frames":121,"fps":24,"num_inference_steps":50,"seed":42,"upscale":false},
"count":1
}
```
这个 profile 是静音合同。把“配乐”写进提示词不会改变其输出音轨合同;不要把它与 native-av profile 混用。需要首尾帧静音模式时使用 v2,输入字段改成 `first_frame_asset_id` / `last_frame_asset_id`,并传 `conditioning_mode=first_last_frame`、合法原生帧数。
## 8 缺陷条件样本接口
### 8.1 defect.generate
方法:`POST /jobs`;模型意图为 SDXL 与 Canny ControlNet。先上传本人参考图,输出合成条件样本图片及边缘控制图。它不是缺陷检测器,不返回缺陷真值标签或分割掩膜。
| input 字段 | 类型 | 必填 | 说明 |
| --- | --- | --- | --- |
| `prompt` | string | 是 | 非空,最多 8000 字符,写材质、缺陷类型、范围和光照 |
| `image_asset_id` | string | 是 | 参考图片 ID |
| `negative_prompt` | string | 否 | 默认空串 |
尺寸、步数、seed 范围与文生图一致;本任务默认 `guidance_scale=7.5`,另有:
| parameters 字段 | 类型 | 默认值 | 约束 |
| --- | --- | --- | --- |
| `controlnet_conditioning_scale` | number | 0.8 | 0–2 |
| `canny_low` | integer | 100 | 0–255,必须小于 canny_high |
| `canny_high` | integer | 200 | 0–255 |
| `count` | integer | 1 | 属于外层请求,最多 4,不放入 parameters |
```json
{
"task_type":"defect.generate",
"execution_mode":"batch",
"input":{"image_asset_id":"44444444444444444444444444444444","prompt":"工业检测照片,保持金属表面主体结构,一处细长不规则划痕,划痕边缘有细微反光,背景和光照自然。","negative_prompt":"文字,水印,卡通,整体结构变形"},
"parameters":{"width":1024,"height":1024,"num_inference_steps":50,"seed":100,"guidance_scale":7.5,"controlnet_conditioning_scale":0.8,"canny_low":100,"canny_high":200},
"count":2
}
```
返回两个独立业务任务,种子按 100、101 使用。每个任务成功后保存其全部相关图片,人工确认缺陷是否存在、位置和强度,再做标注;不能把 Canny 图当成缺陷掩膜。生成样本质量与是否适合训练必须通过真实检测数据验证。
## 9 推演与素材理解接口
### 9.1 math.solve
方法:`POST /jobs`。网页“推演”对应数学推演和解释,不是物理仿真、数字孪生、形式化证明或保证正确的求解器。
| 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `input.prompt` | string | 是 | 无 | 非空,最多 8000 字符 |
| `parameters.max_tokens` | integer | 否 | 2048 | 1–4096 |
| `parameters.enable_thinking` | boolean | 否 | false | 仅 JSON 布尔值 |
```json
{
"task_type":"math.solve",
"execution_mode":"batch",
"input":{"prompt":"求解方程 x²-5x+6=0,给出计算过程并代回检验。"},
"parameters":{"max_tokens":2048,"enable_thinking":false},
"count":1
}
```
成功后 `GET /jobs/{id}` 的 `result.text` 提供回答,`result_assets` 保存文本、JSON 等成果。例:`{"result":{"text":"……模型实际回答……"}}`。模型标识从能力接口读取,不能在任务里任意添加 `model_url` 或 API Key。
### 9.2 media.structure
用于先理解图片或视频画面,再把提取后的题目交给 `math.solve`。它不自动把每个模型回答当作数学事实。
| 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `input.asset_id` | string | 是 | 无 | 本人图片或视频 ID |
| `parameters.frame_count` | integer | 否 | 6 | 1–12;视频均匀抽帧数 |
```json
{"task_type":"media.structure","execution_mode":"batch","input":{"asset_id":"44444444444444444444444444444444"},"parameters":{"frame_count":6},"count":1}
```
输出 `result.subjects`、`scene`、`ocr`、`tags` 和 `frames`,并归档结构化 JSON;每帧包含 `timestamp_seconds`、`scene`、`subjects`、`ocr`、`tags`。这些是模型理解结果。对图片题目,先核对题干、符号、单位是否提取准确,再单独提交文本推演;`math.solve` 不直接接受图片 ID。
### 9.3 audio.transcribe
| 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `input.audio_asset_id` | string | 是 | 无 | 本人音频或有声视频 ID |
| `parameters.language` | string | 否 | `zh` | `zh,en,ja,ko,de,fr,es,ru,ar,pt,it,auto` |
| `parameters.max_audio_seconds` | integer | 否 | 1800 | 1–1800 |
```json
{"task_type":"audio.transcribe","execution_mode":"batch","input":{"audio_asset_id":"55555555555555555555555555555555"},"parameters":{"language":"zh","max_audio_seconds":1800},"count":1}
```
这是通用 Whisper 转写合同,时间可能是约 30 秒块边界,不能将其当作字词口型对齐证据。故事原生对白另用真实 word timestamps 和独立识别共识验收。
## 10 合成 字幕与背景音乐
### 10.1 video.compose
方法:`POST /jobs`,`count=1`。用于已有视频的按序裁剪、拼接、叠加纯文本字幕及指定一条成片音轨。复杂多层音轨和原生对白保留优先走故事混音,不通过提示词控制音量。
| 字段 | 类型 | 必填 | 默认值 | 约束 |
| --- | --- | --- | --- | --- |
| `input.asset_ids` | string[] | 否 | 无 | 如提供,顺序必须和 clips 一致 |
| `input.audio_asset_id` | string | 否 | 无 | 本人音轨 ID;不要与参数中的音轨 ID 冲突 |
| `parameters.clips` | object[] | 是 | 无 | 1–1000,且服从实时 max_shots 与实际资源上限 |
| `clips[].asset_id` | string | 是 | 无 | 本人视频 ID |
| `clips[].start_seconds` | number | 否 | 0 | 0–86400,源片内起点 |
| `clips[].end_seconds` | number | 否 | 实际结尾 | 大于起点,不能超源片实际长度 |
| `parameters.width` | integer | 否 | 1280 | 256–3840,偶数 |
| `parameters.height` | integer | 否 | 720 | 256–2160,偶数 |
| `parameters.fps` | integer | 否 | 24 | 24、25、30、60 |
| `parameters.subtitles` | object[] | 否 | `[]` | 最多 1000 条 |
| `subtitles[].start`、`end` | number | 是 | 无 | 整片秒数,end 大于 start,不能超成片 |
| `subtitles[].text` | string | 是 | 无 | 1–2000 字符纯文本;不支持 ASS 控制语法 |
```json
{
"task_type":"video.compose","execution_mode":"batch","count":1,
"input":{"asset_ids":["66666666666666666666666666666666","77777777777777777777777777777777"],"audio_asset_id":"55555555555555555555555555555555"},
"parameters":{
"width":1920,"height":1080,"fps":24,
"clips":[{"asset_id":"66666666666666666666666666666666","start_seconds":0,"end_seconds":5},{"asset_id":"77777777777777777777777777777777","start_seconds":0,"end_seconds":5}],
"subtitles":[{"start":0.2,"end":4.5,"text":"第一段字幕"},{"start":5.2,"end":9.5,"text":"第二段字幕"}]
}
}
```
外部音轨会作为成片音轨使用,不会自动与各视频对白混合;短音轨剩余补静音,不自动循环,长音轨按成片长度结束。保留原声并叠加背景音乐时,应使用故事 `audio.layers` 混音,或上传已制作好的整片混合音轨。这里的字幕使用秒数;故事编辑器字幕用帧数,音频图层用 48kHz 整数样本,不要混用。
## 11 故事、节奏字幕与同框对白
### 11.1 使用方式
以下路径使用同一用户的登录会话。可从已有故事开始,先按[故事操作手册](story.html)准备好角色、场景、分镜和对白。需要全新故事时按下节接口创建。请求中传最新版本,保存和启动运行使用不同的幂等键。
### 11.2 创建故事或读取现有故事
`POST /stories` 返回 HTTP 201 StoryDTO。需要 `name` 和版本化 `spec`;`create_folder` 默认 true,`folder_id` 可选。已有故事使用 `GET /stories/{id}`。
以下为新建一个单人说话镜头的最小基准故事示例,ID 仅供说明,实际脚本应使用不同的 `uuid.uuid4().hex`:
```json
{
"name":"人物说话示例",
"create_folder":false,
"spec":{
"schema_version":3,
"profile":"landscape_1080_v1",
"context":{"style":"写实电影,中景人物,清晰自然面部"},
"scenes":[{"id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa","name":"室内","location":"安静房间","time":"白天","lighting":"柔和窗光"}],
"entities":[{"id":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","kind":"person","name":"青年","description":"青年男性,短发,浅色衬衫,面部清晰"}],
"shots":[{
"id":"cccccccccccccccccccccccccccccccc","name":"青年开场",
"scene_id":"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
"cast":[{"id":"dddddddddddddddddddddddddddddddd","entity_id":"bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb","position":"画面中央中景","action":"自然呼吸并轻微点头"}],
"visual_prompt":"青年正面略偏侧中景,头肩完整,嘴部无遮挡,背景简单,清晰自然面部。",
"motion_prompt":"固定镜头,自然说话,轻微头部与肩部动作,结束后放松闭唇。",
"edit":{"start_frame":0,"duration_frames":120}
}],
"render":{"fps":24,"total_frames":120,"fit":"contain","subtitles":[]}
}
}
```
不要通过修改同一稳定 ID 的含义冒充另一角色;删除镜头、段落或角色后应重新核对引用。
### 11.3 POST /editors/{draft_id}/dialogue/enable
用途:显式启用或升级为 H3 原生对白。JSON `expected_version` 必填、integer、至少 1;需要 `Idempotency-Key`。成功 HTTP 200 EditorDTO。
```json
{"expected_version":1}
```
```json
{
"draft_id":"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee",
"version":2,
"revision":2,
"name":"人物说话示例",
"editing_mode":"auto",
"manifest":{"schema_version":3,"source_kind":"story","spec":{"schema_version":5,"dialogue":{"generation":"native_av","language":"Chinese"}}},
"assets":[],"issues":[]
}
```
上例 manifest 为节选,保存时必须使用真实完整 manifest,不能将这个节选回传。此处以 V5 / V3 草稿说明字段,新建故事启用对白后可能得到 V6 / V4。请沿用响应中的实际版本;稳定镜头、素材和历史运行保留。读取旧故事不会静默升级,旧冻结运行保持原图。
### 11.4 原生作者字段
| manifest 路径 | 类型 | 说明和限制 |
| --- | --- | --- |
| `spec.dialogue.generation` | string | `native_av` |
| `spec.dialogue.language` | string | 当前故事本版允许中文 `Chinese`;实时认证仍必须通过 |
| `spec.dialogue.speakers[]` | object[] | 角色 ID、entity_id、name、native_voice;人物应在故事 entities 中 |
| `speakers[].native_voice` | string 或 null | 1–500 字符声线描述,例如“青年男性,清亮中音,语气平静” |
| `spec.dialogue.utterances[]` | object[] | 稳定 id、speaker_id、完整 text;text 为 1–2000 字符 |
| `utterances[].spoken_text` | string 或 null | 可选口播改写,识别按此实际口播目标检查 |
| `utterances[].source` | string | 文本台词沿用 `tts` 标签;native_av 下由 H3 直接生成,不创建 TTS 步骤 |
| `utterances[].delivery` | string | 最多 500 字符,语气和表演提示,不是精确采样控制 |
| `spec.dialogue.sequences[]` | object[] | 段落稳定 id、shot_ids、utterance_ids,明确镜头与台词归属 |
| `shots[].performance.native_utterance_ids` | string[] | 本镜头完整台词 ID;`[]` 明确无对白;多镜头段落必须逐镜分配 |
| `shots[].performance.visible_speaker_ids` | string[] | 画内人物须属于镜头 cast。单人模式选择一人;正式双人轮流模式的两个角色与认证条件见 11.12 |
| `shots[].performance.lip_sync` | string | `auto`、`required`、`off`;画外词时不要求画面人物开口 |
| `shots[].video_parameters.profile` | string | 示例使用横屏 TP2 profile;实际可选组合由实时能力决定 |
| `shots[].video_parameters.source_frames` | integer | 故事字段使用 source_frames;不要与 Jobs 的 num_frames 混淆 |
| `shots[].video_parameters.upscale` | boolean | 原生固定 false |
| `audio.layers[]` | object[] | 独立 BGM/SFX 图层,见下一节 |
| `captions.mode` | string | 常用 `script`;实际字幕依据验收后的原音词时间生成 |
每句台词必须且只能分配到一个镜头;单人模式通过正常切镜实现多人对白。使用同框轮流发言时要检查独立能力,按顺序分配两位角色的台词。单镜段落可自动采用全部台词,多镜段落不能猜测分配、重复播放或截断一句。
声线描述不能保证克隆参考录音或跨镜音色完全一致。旧参考录音、录音台词和人工导入视频不能冒充已验收的原生音画;需用户明确解除、转换或强制重新生成。原素材和历史绑定不会因此被删除。请分别检查同框轮流、连续动作和尾帧的计划约束;单镜支持某种输入不等于故事编排已经开放该组合。
### 11.5 POST /editors/{draft_id}/save
用途:保存完整作者 manifest 与可选故事名。成功 HTTP 200 EditorDTO。
| JSON 字段 | 类型 | 必填 | 约束 |
| --- | --- | --- | --- |
| `expected_version` | integer | 是 | 最近取得的版本,至少 1 |
| `manifest` | object | 是 | 完整 V1/V2/V3/V4 编辑器 manifest,与故事版本相符 |
| `name` | string 或 null | 否 | 1–255 字符,不允许全空格 |
原生模式不创建独立旁白或 MuseTalk 步骤。旧旁白应明确关闭或转换为画外台词,背景乐留在独立图层。服务器维护的 `native_audio`、`native_report`、`native_alignment` 等派生绑定是只读结果,客户端不得捏造审批、SHA 或质检通过记录。
保存时可在 Postman 把 GET /editors/{draft_id} 返回的完整 manifest 复制到 Body 中,加上当前 expected_version。即使只改故事名,请保留现有镜头、台词、绑定、字幕、音轨和 schema_version。服务端返回最新 EditorDTO 后再进行 plan。
### 11.6 配乐与字幕字段
故事音频以 48,000Hz 整数样本处理,24fps 下每帧为 2,000 样本。以下为整片开头进入、播放前 5 秒的 BGM 图层节选;素材必须真的有足够长度。
```json
{
"audio":{
"mode":"silent","mix_mode":"composed","segments":[],"ducking":true,
"layers":[{
"id":"ffffffffffffffffffffffffffffffff","role":"bgm","anchor":"absolute",
"asset_id":"55555555555555555555555555555555",
"offset_sample":0,"source_start_sample":0,"source_end_sample":240000,
"gain_db":-16,"fade_in_samples":12000,"fade_out_samples":24000
}]
},
"captions":{"mode":"script","cues":[]}
}
```
这里 `audio.mode=silent` 只关闭独立旧旁白,原生镜头声音仍由原生混音流程保留。每层 role 为 `bgm` 或 `sfx`,默认 bgm;gain_db 范围 -60…12。anchor 可为 `absolute`、`shot`、`scene`,选后两者必须分别提供对应 ID。每层起止、偏移和淡入淡出为整数样本;音乐短了不会被提示词自动延长。
字幕 cue 使用稳定 ID、anchor、start_frame/end_frame、text 和独立的 `text_override`、`timing_override`;对白字幕 anchor 为 `utterance` 并引用 utterance_id。保护人工文案不等于保护人工时间,改时间后仍须落在有效时间线内。只改字幕或配乐可复用有效 H3 视频,改台词、声线、画面或语言会失效对应音视频闭包。
### 11.7 POST /editors/{draft_id}/plan
先计划再执行。此接口需要会话及 CSRF,但不需要 `Idempotency-Key`;成功 HTTP 200,不启动模型生成。
| JSON 字段 | 类型 | 必填 | 默认值 | 说明 |
| --- | --- | --- | --- | --- |
| `expected_version` | integer | 是 | 无 | 草稿当前版本 |
| `output_goal` | string | 否 | `film` | `film` 生成成片;`media` 仅生成目标素材 |
| `targets` | string[] | 否 | `[]` | 原生支持 frame:id、video:id、native_alignment:id、captions |
| `force` | string[] | 否 | `[]` | 明确强制更新的目标,不为普通重连设置 |
| `execution_mode` | string | 否 | `interactive` | 两种队列仍遵守生产时段 |
| `output_folder_id` | string 或 null | 否 | 未指定 | 成果分类 |
```json
{"expected_version":3,"output_goal":"film","targets":[],"force":[],"execution_mode":"batch"}
```
```json
{
"output_goal":"film","source_version":3,
"steps":[
{"key":"frame_0001","kind":"image.generate","unit_id":"cccccccccccccccccccccccccccccccc","status":"generate"},
{"key":"nv_0001","kind":"video.generate","unit_id":"cccccccccccccccccccccccccccccccc","status":"generate"},
{"key":"na_0001","kind":"audio.dialogue.extract","unit_id":"cccccccccccccccccccccccccccccccc","status":"generate"},
{"key":"nq_0001","kind":"audio.dialogue.inspect","unit_id":"cccccccccccccccccccccccccccccccc","status":"generate"}
],
"issues":[],
"plan_hash":"<服务器返回的64位十六进制摘要>"
}
```
这里只节选步骤,实际还有视觉检查、内部验收、混音、字幕和合成。步骤 status 为 generate 或 reuse,不是 Job 的执行状态。`issues` 非空时先修复问题,不能绕过计划。原生能力缺失会明确阻止生成;首帧单独闭包不要求语音能力。
### 11.8 POST /editors/{draft_id}/runs
需要会话、CSRF 和 `Idempotency-Key`;请求与 plan 一致,再增加必填的 64hex `expected_plan_hash`。成功 HTTP 202 RunSnapshot。
```json
{
"expected_version":3,"output_goal":"film","targets":[],"force":[],
"execution_mode":"batch","expected_plan_hash":"<上一计划的plan_hash>"
}
```
```json
{
"run":{"id":"99999999999999999999999999999999","state":"queued","desired_state":"run","execution_mode":"batch","version":1,"run_kind":"story_auto","output_goal":"film","apply_state":"pending","completed_steps":0,"total_steps":9,"result_assets":[]},
"steps":[],"jobs":[],"cursor":100
}
```
实际 DTO 包含 `draft` 和按冻结顺序的 Steps。不要假定总步骤恒为 9,首帧复用、多镜头和配乐会改变数量。再次运行前须重新读取 editor 版本并计划;若在计划后改了草稿或能力证据变化,旧摘要会冲突,须重新计划,不能手写哈希。
### 11.9 查询 取消与应用
`GET /workflow-runs/{id}` 返回 RunSnapshot,重点查看 `run.state`、`run.error`、`run.apply_state`、Steps 及 `run.result_assets`。自动运行可从 `steps` 中找到 `kind=video.compose` 的 Step,再按其 `result.asset_id` 匹配输出素材;也可查看对应合成 Job 的 `result_assets`。不要把任意首帧图片当成片,也不要假定存在未定义的 `run.current_output` 响应字段。
有对白的原生镜头在首帧后由 H3 一次产生画面、声音和口型,再提取真实音轨、Whisper 逐词识别、SenseVoice 盲内容复核和视觉检查。两路内容与目标台词不一致、缺证据或词时间不可靠时阻止通过,不用作者文字填充“识别结果”。新图没有独立 TTS/MuseTalk;历史冻结图仍可按原合同读取恢复。
无对白镜头使用独立静默验收:固定版本的 Silero CPU VAD 对同一真实音轨的左右声道分别逐窗检查,覆盖完整选段,且 SenseVoice 实际识别为空,才可按 `silero-sensevoice-verified-silence-v1` 判定无语音。Whisper 在静默或音乐中可能幻觉出文字;报告仍保留原转写、内容错误率和逐词失败,不改写成空、不伪造词时间,也不声称“两路 ASR 都为空”。VAD 或第二路证据缺失、任一声道出现语音、选段或音轨 SHA 不符,仍阻止通过。该静默策略只用于期望台词确实为空的镜头,不能为有对白的错误转写兜底。
| 接口 | JSON | 成功 |
| --- | --- | --- |
| `POST /workflow-runs/{id}/cancel` | `{"expected_version":运行version}` | 200 RunSnapshot,等待实际退出清理 |
| `POST /workflow-runs/{id}/pause` | 同上 | 200,暂停后续阶段 |
| `POST /workflow-runs/{id}/resume` | 同上 | 200,仍受能力、窗口及清理状态控制 |
| `POST /editors/{draft_id}/apply` | `{"expected_version":草稿version,"run_id":"..."}` | 200 EditorDTO;成功且来源版本匹配才应用 |
这些运行控制应保存相应 `Idempotency-Key`。V5 成片成功后会尝试自动应用;`apply_state=conflict` 表示作者已有更新,结果保留但不覆盖。先查看新编辑内容与输出,再明确处理,不强行把旧结果覆盖回新草稿。
### 11.10 修改后局部重生成
| 想修改什么 | 操作 |
| --- | --- |
| 某镜头画面或台词 | 修改该镜头/对应台词并 save,再 plan + run;需要强制时用 `video:<shot_id>` |
| 发音、声线、表演 | 修改角色 native_voice、台词或 delivery;该镜头画面与声音一起重新生成 |
| 仅字幕文案/位置 | 改 cue 并 save,film 计划可复用 H3;人工保护仍检查合法性 |
| 只重测字幕时间 | force `native_alignment:<shot_id>`,重新识别与验收,不重生成 H3 |
| 背景音乐、音量、淡入淡出 | 修改 audio.layers 后生成 film,只重混音和合成 |
| 只更新首帧 | media 目标 `frame:<shot_id>`;不会自动修改全片作者时长 |
示例:只重新生成一个镜头素材时,`output_goal=media`、`targets=["video:<shot_id>"]`、`force=["video:<shot_id>"]`;之后再计划 film 复用有效素材生成新成片。不要用旧 `speech:`、`base_video:`、`synced_video:` 目标调用新原生图。
### 11.11 人工路径兼容
人工逐步制作仍使用 `/stories/{id}/candidates`、`/selections`、`/readiness`、`/renders`。自动成片不用逐镜候选确认;两条路径不能混淆批准状态。模式切换使用 `POST /editors/{id}/mode`,JSON 为 `{"expected_version":版本,"mode":"auto"或"manual"}`,需要会话、CSRF、幂等键和空闲草稿。
删除故事前先确认连带范围。DELETE /stories/{id} 携带 If-Match 版本。服务隐藏故事并清理其运行、任务和可删除的未收藏素材,保留已收藏或仍有受保护引用的素材。未收尾时返回 202 及 pending=true,协调器继续处理;处理完成时返回清理回执。
### 11.12 当前版本的成片与对白修订接口
| 方法和路径 | 参数位置、类型与要求 | 成功响应 |
| --- | --- | --- |
| GET /stories/{id}/film | path:故事 ID,string,必填。读取当前用户的故事 | 200,最新正式成片对象含 asset(AssetDTO)、draft_revision(integer)、run_id(string)、captions_srt_available(boolean);没有符合条件的正式运行时返回 null。实验视频也可在素材库按 ID 下载 |
| POST /editors/{draft_id}/captions/preview | JSON:expected_version 必填 integer;utterance_id 可选 string;manifest 可选完整对象,用于预览编辑 | 200,version、fps 为 integer,rows、issues 为数组。行中有 text、local_start_frame、local_end_frame;没有可靠时序时允许待定 |
| GET /editors/{draft_id}/runs/{run_id}/captions.srt | path:草稿和运行 ID 均为必填 string;需有冻结字幕 | 200,application/x-subrip,UTF-8 字幕附件。可先查 captions_srt_available |
| POST /editors/{draft_id}/dialogue/fork-cuts | 会话及 CSRF。JSON:expected_version(integer)、shot_id(string)必填;confirm(boolean,默认 false)、name(string)可选。确认时加 Idempotency-Key | 200,预览返回 shots、warnings、name;confirm=true 成功返回新草稿,用于改为说话人切镜 |
| POST /editors/{draft_id}/runs/{run_id}/turns/{shot_id}/review | 会话、CSRF、幂等键。JSON:expected_version(当前运行的 integer 版本)、report_sha256(64位十六进制 string)、decision(accept)、note(1–1000字符)必填 | 200 更新后运行快照,仅适用于服务判定可以人工复核的镜头 |
原生对白故事可使用 Story V6 与 Editor V4。节奏字幕在编辑清单的 `captions.presentation` 设置 `punctuation`(hide、preserve)及 `pacing`(rhythm、sentence),配套提交 `edits` 数组;当前新功能可按实际语音停顿显示无标点字幕,历史清单仍按保存的版本解析。导出 SRT 使用相应运行的冻结字幕。
只改字幕、配乐时,可在相同 plan/runs 合同中分别选择 `output_goal=caption_film`、`mix_film`,用合格已有来源生成修订。`caption_inspect` 用于补充字幕检查。根据返回的 issues 处理来源、人工锁定及能力限制,再按 plan_hash 提交。
新故事可在 POST /stories 的 JSON 中选择 captions_mode(none、manual、script、ai_script)和 caption_presentation(punctuation、pacing)。既有故事不会自动套用新建时的偏好。
正式同框轮流发言需要 `GET /capabilities` 中的 `dialogue.native_av.two_person_turns.available`。草稿可以配置、自由提示词可以试拍,正式运行仍会检查模型证据与逐轮验收。被判定需要重生成时,先修正台词、画面或绑定素材。对于可复核项,使用当前运行报告的摘要提交判断。
## 12 定时提交 批次与事件流
### 12.1 定时任务
`POST /jobs` 可在外层增加 `scheduled_at`:
```json
{"task_type":"image.generate","execution_mode":"batch","scheduled_at":"2027-01-01T21:00:00+08:00","input":{"prompt":"清晨山谷,云雾缓慢散开"},"parameters":{"width":1024,"height":1024,"seed":42},"count":1}
```
定时只是最早派发时刻,不是保证开始时刻。届时仍需窗口开放、资源可用、用户有效和能力就绪。
### 12.2 POST /batches
鉴权:会话及 CSRF,或 `batches:write`。需要 `Idempotency-Key`,成功 HTTP 202。
| 字段 | 类型 | 必填 | 默认值 | 限制 |
| --- | --- | --- | --- | --- |
| `name` | string | 否 | `夜间批次` | 1–255 字符 |
| `items` | object[] | 是 | 无 | 1–100 个清单项 |
| `items[].kind` | string | 是 | 无 | `job` 或 `workflow` |
| job 项 task_type/input/parameters/count | 同 Jobs | 按任务 | count=1 | 同任务参数合同 |
| workflow 项 draft_id/draft_revision/expected_version | string/integer/integer | 是 | 无 | 冻结指定工作流修订 |
```json
{
"name":"夜间素材批次",
"items":[
{"kind":"job","task_type":"image.generate","input":{"prompt":"写实雨夜街口"},"parameters":{"width":1024,"height":1024,"seed":42},"count":1},
{"kind":"job","task_type":"math.solve","input":{"prompt":"计算2x+3=9并检验"},"parameters":{"max_tokens":1024,"enable_thinking":false},"count":1}
]
}
```
返回 BatchSnapshot,包含批次及成员状态。`GET /batches/{id}` 查询;`POST /batches/{id}/control` 传 `{"desired_state":"run|pause|cancel","expected_version":当前版本}`,实际传其中一个枚举值。100 个清单项不等于并行使用 100 张 GPU,也不能把单任务 count 改为 100。
### 12.3 GET /events
鉴权:会话或 `events:read`。返回 `Content-Type: text/event-stream`,长连接,不是一次性 JSON。
| 参数/头 | 类型 | 默认值 | 说明 |
| --- | --- | --- | --- |
| query `after` | integer | 0 | 非负 owner 事件游标 |
| `Last-Event-ID` | integer 字符串 | 无 | 提供时优先于 query after |
```text
: connected
id: 123
event: job.updated
data: {"job":{"id":"33333333333333333333333333333333","state":"running","version":2}}
: heartbeat
```
实际 data 结构按事件而定;收到通知后可重新 GET 对应资源。断流保存游标重新订阅,遇 `reset` 必须重新获取当前列表和详情;不重建生成请求。反代需保留 SSE 不缓冲及长超时。令牌不放在 URL 中,也不把 Session Cookie 写进事件日志。
## 13 错误码与排查
业务错误通常返回 detail.code 和 detail.message。请求模型校验失败时,HTTP 422 的 detail 也可能是含 loc、msg、type 的数组。
业务错误通常形如:
```json
{"detail":{"code":"capability_unavailable","message":"所选模型尚未启用或尚未完成认证"}}
```
Pydantic 字段验证错误可能返回 `detail` 数组,含 `loc/type/msg`。客户端应兼容这两种形状,不要只支持一个中文 message。
| HTTP | code 示例 | 处理 |
| --- | --- | --- |
| 400 | `invalid_input` | 参数不符合该任务合同,核对字段、类型、帧数与 profile |
| 401 | `not_authenticated`、`session_expired`、`token_expired` | 重新登录或检查令牌有效期/用户禁用情况 |
| 403 | `csrf_failed` | 会话写操作补正确 CSRF,不关闭校验 |
| 403 | `scope_required` | 配置实际存在且适用的 scope |
| 403 | `session_required` | 改用登录会话;不能给 token 加不存在权限绕过 |
| 404 | `asset_not_found`、`resource_not_found` | 检查 ID、归属、删除状态;管理员也不能跨私有资源读取 |
| 409 | `idempotency_conflict` | 同键参数变了;恢复用原参数,新意图才用新键 |
| 409 | `draft_version_conflict`、`run_version_conflict` | 重新读取版本,保留用户修改后重新计划 |
| 409 | `cleanup_pending`、`deletion_requires_terminal` | 独立记录需等待相关执行清理;删除整个故事使用第 11.11 节的联动清理回执 |
| 409 | `native_dialogue_upgrade_required` | 显式升级旧对白草稿,新运行不创建旧口型图 |
| 409 | `invalid_native_alignment` | 实测原声、双路文字、词时间或来源合同不匹配,不能伪造通过 |
| 409 | `locked_dependency_changed` | 依赖已变但素材锁定;明确解锁或强制重生成 |
| 410 | `resource_purged` | 原幂等结果已删除,不能复活旧意图 |
| 413 | 上传/输出超限 | 减小文件或按资源策略拆分 |
| 416 | 非法 Range | 修正字节区间,避免多范围请求 |
| 422 | `unsupported_task`、`invalid_target` 等 | 核对任务类型、字段、目标语法与素材种类 |
| 422 | `native_canvas_uncertified` | 原生 width/height 未命中该 profile 的实时 canvases;示例使用 1344×768 横屏 |
| 429 | `quota_exceeded`、频率限制 | 有界退避,减少并发或等待配额释放 |
| 503 | `capability_unavailable`、`maintenance` | 等待恢复或完成模型认证;不要换成未经授权的服务 |
| 503 | `database_unavailable` | 管理员查看真实 SQL/锁/连接原因;不要连续重发删除 |
`/capabilities` 或计划中返回的 `reason/issues` 比“服务器在线”更具体。原生模式典型计划问题包括台词遗漏/重复、超过单镜容量、录音不支持、双人同框未认证、人工视频不支持、画面或声音证据缺失。先解决对应问题再执行,不关闭门禁。
同一次网络超时不能直接视为未受理。先恢复幂等提交或查询已知 ID;上游执行结果未知时不要发另一个任务占用更多资源。
## 下载与维护
[OpenAPI JSON](openapi.json) · [故事操作手册](story.html)。在项目根目录使用业务后端 Python 环境运行 `python scripts/export_api_openapi.py` 导出完整接口定义,运行 `python scripts/render_manuals.py --only api` 发布网页与 Markdown。路径覆盖全部 HTTP 操作;部分路由由服务层直接返回动态 DTO,其成功响应没有额外声明 Pydantic 类型,请结合本文的返回字段和实际响应读取。

File diff suppressed because one or more lines are too long

View File

@ -1,6 +1,6 @@
# 自动长视频与音轨操作指南
更新:2026-11-27。第 1–7 节介绍普通可编辑自动成片,以“凤凰90秒长视频+BGM”为例。第 8 节介绍H3原生多人对白、实际音视频检查与局部返工,并以《雨夜归途》说明检查顺序。两条路径沿用同一套基准板、分镜和成片导航。
更新于 2026-12-01。第 1–7 节介绍普通可编辑自动成片,以“凤凰90秒长视频+BGM”为例。第 8 节介绍原生对白、节奏字幕和同框试拍,并以《雨夜归途》说明切镜式制作的检查顺序。两条路径沿用同一套基准板、分镜和成片导航。
返回[主操作手册](操作手册_20261111.md);需要逐镜确认候选时,使用[锚定故事工作室操作手册](锚定工作室操作手册_20261111.md)的人工流程。
@ -15,7 +15,7 @@
| 生成旁白 | 文字经TTS变成说话音频;旁白文案与字幕可按模式生成,不是音乐生成 |
| 自动生成原创配乐、无限延长同一镜头 | 当前没有这些入口;长片由多个有界镜头拼接,受镜头数、额度、存储、资源和超时限制 |
H3生成的视频本身静音。在提示词里写“恢宏配乐”不会生成音乐音轨;必须实际选择音频并重新合成。
第 1–7 节使用的普通 H3 视频配置输出静音镜头。需要配乐时,先准备音乐文件,在成片设置中选用并合成。第 8 节的 H3 原生有声配置可以生成对白同期声。
## 2. 模型、时长与环境
@ -80,7 +80,7 @@ H3 v1请求25–337帧,TP2请求25–145帧,均为`4n+1`;内部原生对
在故事中点“刷新进度”,或在版本与运行历史点“查看运行进度与成果”,也可到“任务”查看等待和失败原因。系统按计划生成首帧、视频及需要的声音/字幕,再合成MP4;不会因关闭网页而取消已接受运行。空闲GPU、其他用户、模型冷加载、窗口和失败恢复决定耗时,不能据镜头数承诺固定完工时间。
完成后到“03 成片”点“播放最新完成成片”,在预览弹窗点“下载原件”保存最终MP4;也可在“查看运行进度与成果”找到最终成片,或在“素材”查找当前成果目录内的MP4。单镜头视频与最终成片是不同素材,检查文件时长和内容后再交付。试听确认音乐确实出现在新版MP4中,检查开头、镜头连接、后半段与片尾。
完成后到“03 成片”,在顶部播放器检查最近一次成功导出的成片及版本号,点“下载成片”保存 MP4。也可在“查看运行进度与成果”找到最终视频,或在“素材”查找当前成果目录内的 MP4。单镜头视频与最终成片是不同素材,检查文件时长和内容后再交付。试听确认音乐确实出现在新版MP4中,检查开头、镜头连接、后半段与片尾。
如果只点“仅生成素材”,该运行不会生成最终影片,也不会替换最近完成的成片预览;需要成片时再点“生成修改部分并成片”。
@ -104,7 +104,7 @@ H3 v2是独立的原生帧/首末帧合同,原生帧124–345、步进17;首
### 8.1 开启对白,编写声线与语言
1. 保存现有故事,点顶部“启用对白自动成片”。新对白故事使用 Story V5 / Editor V3,由H3在同一次生成中完成画面、声音与口型。继续使用“01 基准板”“02 分镜”“03 成片”。
1. 保存现有故事,点顶部“启用对白自动成片”。H3 在同一次生成中完成画面、声音与口型。普通单人对白采用 Story V5,启用节奏字幕的编辑草稿采用 Editor V4。继续使用“01 基准板”“02 分镜”“03 成片”。
2. 历史对白故事会显示“升级为H3原生对白”。点击后只改变当前编辑中的生成方式,仍需点“保存”才提交;原有配音配置、素材绑定、运行和成片历史保留。升级不会重新生成任何素材。旧声音档案仍绑定参考录音时,原生FL2VA不使用这段录音克隆;在档案内点“解除旧参考录音约束”,只解除录音约束,录音素材与历史绑定继续保留。
3. 在“01 基准板”给人物准备清晰参考图,并在“角色声音档案”绑定说话人。在“声线描述”写年龄感、音高、质感、语气和节奏,例如“青年男声,清亮、自然,语速平稳”;在“对白语言”选择或填写支持的语言,默认Chinese。画外声音可绑定“画外旁白”。
4. 声线描述表达目标,不等同于固定音色或参考录音克隆。新流程不再选择Kokoro或VoxCPM2,不再独立生成台词试听,也不再经过MuseTalk重新对口型。音色一致性、读音和同步须通过实际生成的连续视频与原生音轨核对。
@ -114,13 +114,13 @@ H3 v2是独立的原生帧/首末帧合同,原生帧124–345、步进17;首
1. 在“02 分镜”加入镜头实际出现的人物,把画面与动作写在各自提示词中,把具体台词写进“镜头对白”的段落台词。作者台词与字幕文案分别保留;“口播改写”用于发音提示,“表演指令”用于语气、停顿和表演提示,不提供精确采样控制;历史句后停顿数据仍保留。历史台词若使用录音素材,必须明确点击“改为H3根据台词生成”才能转为原生生成;声音会重新生成,原录音素材仍保留。升级本身不会自动转换录音台词。
2. 在“本镜头台词”勾选这个镜头说的完整台词。单镜头段落默认使用该段全部台词;一个段落含多个镜头时,必须逐镜明确分配,系统不会猜测一句话如何截断,也不会把整段台词复制到每镜。
3. 当前一个镜头只支持一个发言角色。多人交流请拆为切镜,为各镜头分配对应人物的台词。人物在画面中发言时勾选“画内说话人”,画外声音不勾选;历史故事中已有的多人可见设置不会被自动删除。纯反应镜头可点“本镜头无对白”,明确设为无对白镜头;这与尚未指定台词不同。
3. “按说话人切镜”每镜安排一位发言人。多人交流时为各镜头分配对应人物的台词。同一机位需要两人轮流发言时,可按第 8.6 节准备同框试拍。人物在画面中发言时勾选“画内说话人”,画外声音不勾选;历史故事中已有的多人可见设置不会被自动删除。纯反应镜头可点“本镜头无对白”,明确设为无对白镜头;这与尚未指定台词不同。
4. 先做每位角色的单人近景小样。点击“重新生成本镜头原生对白”,同时更新该镜头的画面、声音与口型。镜头时长应容纳完整台词与停顿;过长台词应由作者拆句和拆镜。
5. 点击“预览原生音视频”和“试听实际原生音轨”,确认人物、实际说出的内容、语言、声线、节奏和音画同步。已有历史录音和口型片段仍可预览,但不能作为新原生对白已完成的证据。
### 8.3 字幕、混音与局部返工
1. 字幕时间依据实际原生音轨对齐,字幕文字保持作者原文或独立的字幕改字。在“对白字幕与音乐时间线”可修改字幕文案;时间不合适时到分镜点“重新对齐本镜头字幕”,读取已有原生音轨重新测时,再更新字幕并成片。
1. 字幕时间依据实际原生音轨对齐,字幕文字保持作者原文或独立的字幕改字。在“对白字幕与音乐时间线”可修改字幕文案;仅需处理字幕时,按第 8.5 节使用已有原声校时和字幕返修。
2. 声音、口型、表演或读音需要重做时,修改相关台词、声线或动作后,重新生成整个镜头的原生对白。新流程不提供独立配音返工、口型帧偏移或“仅重做口型”。首帧与锁定素材仍按当前编辑的保护规则处理。
3. 在“03 成片”保持“对白自动混音”,勾选“本次成片使用对白”。背景音乐与音效仍可独立添加,调整增益、淡入淡出和定位;启用“对白及旁白期间降低背景音乐音量”后,检查人声是否清楚、音乐是否适度。
4. 原生音轨已进入对白混音时,避免再把同一镜头原声叠加一次。历史独立旁白及成品音轨只读保留;原生模式请点“关闭历史独立旁白及成品音轨”,再把画外台词放入镜头对白。关闭只暂停旧声音模式,不删除文案、录音或历史绑定。背景音乐和音效继续独立编辑,点“重新混音并成片”应用修改。
@ -129,9 +129,24 @@ H3 v2是独立的原生帧/首末帧合同,原生帧124–345、步进17;首
### 8.4 《雨夜归途》的迁移检查顺序
《雨夜归途》含林晚、许舟、陈叔三名角色,原安排为22镜、19句对白、约120秒,配有无歌词背景音乐《檐灯》。原稿和历史成片继续保留;历史成片的完成状态不表示H3原生对白版本已经生成或验收。本次仅修改本地流程,没有重新制作线上成片。
《雨夜归途》含林晚、许舟、陈叔三名角色,原安排为22镜、19句对白、约120秒,配有无歌词背景音乐《檐灯》。原稿和历史成片继续保留;历史成片的完成状态不表示H3原生对白版本已经生成或验收。检查旧故事时请以当前打开的故事版本和选用素材为准。
1. 显式升级编辑版本并保存,为三人编写容易区分的声线描述。先核对页面原生音频能力是否可用。
2. 逐镜指定完整台词及单一发言角色。历史共享段落不能自动推断台词与镜头的对应关系,需人工安排。
3. 分别生成三人的单镜头小样,通过实际原生音轨与连续视频核对声音区分、完整读音、口型、静音段和人物身份;需要时调整描述并重做该镜头。
4. 小样满意后,检查实际音轨字幕对齐与BGM音量,再运行整片。完成后检查开头、中段、切镜和片尾,以新版本实际时间线为准。
### 8.5 在已有成片上试用节奏字幕,按版本下载 SRT
1. 新建故事时,在“启用中文原生对白后的字幕”选择“自动节奏字幕 · 隐藏句读”“人工字幕”或“关闭字幕”。选择自动字幕的故事在启用中文原生对白时采用节奏显示。已有故事可在“03 成片”的“字幕草稿预览”点“试用节奏字幕”,按镜头展开同一句,比较原设置与试用设置的文字、起止帧。
2. 在“出现方式”选“按节奏”或“整句”,在“标点显示”选“隐藏句读”或“保留原文”。这两个开关独立,例如可以整句显示并隐藏句读。作者台词和口播稿仍供生成原声使用。满意后点“应用并保存”;点“取消试用”可返回原设置。
3. 展开台词并“循环听本句”。只有整句起止可靠时,预览会保留整句;“待校时”表示仍需确定时间。有匹配的原视频和未混音的单人对白音轨时,可点“仅分析本镜已有原声”,检查执行计划中的音频识别任务。也可以点“试听本镜并校时”,填写镜内起止帧并锁定时间。最后一帧填字幕消失的帧号,例如填 24 到 48 会在第 24 至 47 帧显示。
4. 拆句时选择“原文断点”,将播放头移到对应声音位置,再点“按播放头拆分”。“合并下一段”用于同一句相邻片段。“锁定文字”和“锁定时间”可分别设置,点“应用片段修改”后保存草稿。删除的片段可在本句“恢复显示”。点“仅重算本句”可查看重新计算的结果;更换原声后若提示复核,试听并重新确认原时间锁。
5. 要下载已经导出的字幕,在“最新完成成片”或“版本与运行历史”找到对应版本,点“下载该版本 SRT”。文件使用该次成片冻结的字幕表。要导出刚修改的字幕,点“更新字幕并成片”。此操作使用原始无字幕镜头和匹配的成片混音,成功后生成新版本。历史混音缺失,或刚更换配乐、调整增益时,点“重新混音并成片”,用已选镜头及同源净音轨重建声音。缺少原片、净音轨或镜头时基时,计划会指出具体镜头。若只剩带烧录字幕、混合音轨的旧 MP4,可继续播放旧版和编辑草稿;根据计划提示恢复可重烧的镜头或重新混音,再进行返修。
### 8.6 制作两人同框、各说一句的候选
1. 在“02 分镜”的镜头对白中把拍摄方式切到“同框轮流对白”。在同一个横屏中文镜头指定两位画内角色,为每人分配一句完整台词。在“01 基准板”的角色声音档案中,为两人分别选清晰的独立参考脸及可辨认其声线的独立声音样本。
2. 选用或生成含两人的首帧并保存。按画面核对左、右角色,必要时点“交换左右角色”,再点“确认首帧与角色对应”。逐轮填写语气、听者动作,核对发言顺序和镜头可用时长。替换首帧后需要再次确认对应关系。
3. 保存草稿,查看“试生成本镜”的可用性。系统按实际 H3 配置、横屏画布和帧数核对双人专用认证。配置待认证时可继续编辑,也可点“预览并另存切镜版”,核对两镜分配后另存故事。配置已认证且角色、首帧和台词齐全时,点“试生成本镜”并查看该次运行。
4. 在“02 分镜”的“查看试拍运行”选择候选版本,打开“双人候选逐轮审核”。逐轮点“回放本轮原声与画面”,核对谁说了哪句、发言人口型以及听者有没有跟读。自动通过的候选按计划继续。遇到“待复核”,逐轮勾选“已核对本轮归属、内容和口型”,填写“选用说明”并点“以当前账号选用此候选”。明确失败的候选需要换选或重新试拍。人工选用记录关联当前候选和报告,更换候选后需重新核对。

File diff suppressed because it is too large Load Diff

File diff suppressed because one or more lines are too long

View File

@ -1,14 +1,19 @@
# 锚定故事工作室操作手册
# 故事工作室操作手册
适用版本:2026-11-13 的“故事”工作室。入口为登录后的侧栏“故事”,页面路径 `/studio`;单个故事在 `/studio/故事编号` 编辑。多镜头自动生成、人工选片和“03 成片”统一在故事内进行;独立“工作流”“批量”“成片”页面已移除,既有数据和共享后端API保留。旧链接会转至故事或任务。
更新于 2026-12-01。登录后打开侧栏“故事”(`/studio`),点故事卡片可继续编辑。在“01 基准板”定人物与场景,在“02 分镜”排镜头,在“03 成片”剪辑、混音、加字幕并播放已导出的版本。
更新:2026-11-26。希望自动制作凤凰等长故事并加入BGM,优先看[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)。普通故事填好分镜后,保存并点“启用可编辑自动成片”;系统自动生成素材并合成,不要求逐镜确认。H3视频本身静音,BGM需上传已有授权音频,再在“03 成片”选择人工音轨。详细版本恢复规则见[主操作手册](操作手册_20261111.md)第12节。希望逐镜人工确认时,按本手册第0节先做完一个 **2 镜头、10 秒**的小故事,再增加镜头。实际操作顺序是:**新建并命名 → 建基准板 → 写分镜并保存 → 逐镜确认首帧 → 逐镜确认视频 → 调整时间线 → 保存并合成 → 下载成片**。只有已有视频、只需剪辑时,才可直接从视频导入开始。
| 想完成的作品 | 从哪里开始 | 在哪里看结果 |
| --- | --- | --- |
| 第一次做故事,逐镜选首帧和视频 | 按第 0 节做两镜头、十秒的小片 | 确认选片并点“冻结素材并合成”后,到“03 成片”播放 |
| 分镜已写好,希望一键生成长片,之后还能换镜头 | 保存故事,启用“可编辑自动成片”,按第 15 节设置音轨和字幕 | 点“自动生成初稿并成片”。改某镜后点“生成修改部分并成片” |
| 角色需要开口说话、保留对白与口型 | 保存故事,启用“对白自动成片”,按第 16 节填写说话人、台词和表演 | 在“02 分镜”试听原声、预览逐镜表演。在“03 成片”检查字幕、配乐和全片 |
| 已有白模预演 | 第 18 节介绍用预演构图生成首帧和用原视频保留动作两种方法 | 处理后的图片或视频可导入对应分镜 |
**历史验证状态(2026-11-11,Wan路径):**当时已通过 **1、2、3 张参考图真实生成**、**1280×704 的5秒和15秒视频及增强**,以及网站“三图首帧→确认→视频→页面选片→冻结合成”的真实闭环。当时验收环境开放了参考生成,验收故事名为“锚定模型全链路验收(真实生成)”。该记录不是本轮真实模型复验。当前H3、TP2及参考生成按钮是否开放,以当前环境返回的独立能力状态为准;通过样例不代表每种题材、身份一致性、复杂变形或长镜头质量都已验收。
对接脚本、请求参数、响应和任务查询见[API 接口使用说明](api.html)。普通长故事、原生对白和版本返修的分步示例见[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)。各环境可用的模型、队列时段和认证能力以当前页面提示为准。
## 0. 人工候选流程:两个镜头完成第一个故事
本节适用于人工候选流程;自动生成路径使用主手册第12节。已经启用自动成片时,先保存修改,再点击导航栏“返回逐步骤人工确认”,即可回到本流程;已有自动素材会作为待确认候选保留,由你逐步确认,故事和历史运行不变。存在未结束任务时,需要先完成或取消并等待清理后再切换。之后仍可点击“启用可编辑自动成片”切回。本例是“青衣旅人走向山门”:第一个镜头看旅人和山门的全景,第二个镜头看同一旅人的近景,每镜头选用 5 秒,最后合成 10 秒横屏视频。下面文字可直接照填;示例不会自动建立镜头,也不会自动替你生成或选片。
本节讲普通故事的人工候选流程。普通自动生成见第 15 节,原生对白见第 16 节。已经启用自动成片时,先保存修改,再点击导航栏“返回逐步骤人工确认”,即可回到本流程;普通故事已有自动素材会作为待确认候选保留,由你逐步确认。对白故事切到人工模式时进入“逐步骤对白制作”,仍使用原生对白编辑面板。存在未结束任务时,需要先完成或取消并等待清理后再切换。之后仍可点击“启用可编辑自动成片”切回。本例是“青衣旅人走向山门”:第一个镜头看旅人和山门的全景,第二个镜头看同一旅人的近景,每镜头选用 5 秒,最后合成 10 秒横屏视频。下面文字可直接照填;示例不会自动建立镜头,也不会自动替你生成或选片。
### 第 1 步:进入故事并命名
@ -102,7 +107,7 @@
1. 点击“03 成片”,顶部是“成片预览”。展开下方“查看镜头选片检查”,确认两个镜头逐项显示“选片已确认”。确认“画幅”为“横屏 1920 × 1080”;“适配”选“完整显示(留边)”可保留整个画面,选“填充画幅(裁边)”会裁去边缘以铺满画布。
2. 如有修改,先点“保存故事”,再点“冻结素材并合成”。系统会再次检查实际素材与选段;弹出“素材已冻结,合成任务已提交”后,等候成片历史更新。这个按钮只合成已确认视频,不会替你补生成缺少的镜头。
3. 点顶部“刷新成片”同步结果。合成成功后,最新成片以缩略图显示在顶部,无需先翻过镜头清单。点击缩略图或“播放成片”,在弹窗中检查镜头顺序、转接处、字幕和声音;可拖动播放器进度条、调整音量或全屏查看。
3. 点“刷新成片”。顶部播放器显示最近一次成功导出的成片,旁边有版本和时长。直接播放,拖动进度条查看镜头顺序、转接处、声音和字幕。
4. 想单独查看时点“新窗口播放”;保存最终文件时点“下载成片”。要查看旧版本或运行进度,展开下方“合成历史”,其中仍可播放、下载历史视频及查看冻结设定。
顶部“成片预览”可以直接播放最新完成的视频。“合成历史”记录了本次冻结版本和处理阶段。需要新版时,保存修改并再次合成。下载整个视频请点“下载成片”。
@ -131,9 +136,9 @@
“保存故事”保存你填写的设定与剪辑;“确认首帧”“确认选片”会直接把这次选择记录到服务器,成功后不必再为同一个确认重复保存。后续又修改设定、提示词或时间值时,仍需先保存。单纯切换预览、模式或当前镜头不会替你保存。
分镜和成片模式下,左栏“+”增加镜头;选中卡片后用“上移”“下移”重排,用“删除当前镜头”移除。至少保留一个镜头。镜头数量上限由当前环境配置,默认通常为 120;页面达到上限后不再允许添加。
在“02 分镜”的镜头列表点“+”或“+镜头”增加镜头。选中卡片后用“上移”“下移”重排,删除前先确认当前镜头。至少保留一个镜头,数量上限以当前故事模式和页面提示为准。
镜头名称和展示序号不是身份:重排不会把另一镜头的角色、候选或确认结果移到当前镜头。下方时间线中的镜头块也可点击,用于选中镜头;裁剪通过右侧数值输入完成。
各镜头的角色和选片按镜头编号关联,重排后仍对应原镜头。在“03 成片”的时间线上核对排序和裁剪后的时长。
## 3. 建立故事基准板
@ -432,18 +437,34 @@ HTTP/SSE 断线、关闭网页或切换页面不会取消已经保存提交的
“启用连续性制作”会升级为 V4 故事,可添加分层背景音乐和音效。V5 多人对白同样支持分层音轨。原生帧和首末帧使用 H3 v2 的独立合同;连续性质检开关 `CONTINUITY_QUALITY_CERTIFIED` 默认 `false`,H3 v2 另需上游证书。普通切镜、自动长视频和 BGM 可以在各自已开放的能力范围内制作。
旧版 Wan 路径曾验证 1–3 张参考图生成、5 秒与 15 秒视频,以及确认首帧、选片和合成的流程。查看旧故事时按其保存的配置复现,创建新故事时以当前模型的时长和能力提示为准。
完整步骤、模型对照、分镜时长与恢复操作见[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)。
## 16. 多人对白制作
## 16. 有对白的镜头怎么做
保存故事后点“启用对白自动成片”,进入 Story V5 / Editor V3。在“01 基准板”将说话人绑定到角色,分别设置并复用固定声音。在“02 分镜”按段落编辑台词,并选择镜头实际可见的说话人。为每位角色选正面、无遮挡且嘴部清晰的参考图,优先分别做一段单人近景小样,再扩为整片。正常切镜可用正面或小角度近景组织对话。当前双人同框口型尚未认证,保持关闭。
1. **建立说话人。** 保存故事,点“启用对白自动成片”。旧版对白故事若显示“升级为H3原生对白”,升级后点“保存编辑”。在“01 基准板”给每个角色绑定说话人,分别写对白语言与声线。例如女儿用“年轻普通话女声,明亮,紧张时语速稍快”,父亲用“年长普通话男低音,沉稳,句间略有停顿”。声线描述用来引导表现,实际音色请听生成的样片。
2. **分配台词。** 在“02 分镜”加入出镜角色,写清场面、动作与运镜。在“镜头对白”按段落输入台词,并勾选“本镜头台词”和对应的画内说话人。段落跨多个镜头时,为每镜分配完整句子。只拍听者反应时可选“本镜头无对白”。
3. **先做一个说话镜头。** “按说话人切镜”适合父女来回对话,每镜安排一位发言人。在动作中写清开口前的反应和说完后的状态。点“重新生成本镜头原生对白”,用“预览原生音视频”和“试听实际原生音轨”检查第一字、尾音、说话人和听者反应。H3 原生有声模式在同一次生成里产出画面、声音和口型。需要改变读音、声音或表演时改这一镜并重生。
4. **合成。** 在“03 成片”选择“对白自动混音”,启用“本次成片使用对白”。按需添加背景音乐,调整增益和淡入淡出后,在整片中听一下人声。只改配乐时可点“重新混音并成片”。若编辑器提示历史独立旁白或成品音轨与原生对白冲突,试听并确认用途后,按提示关闭旧声音模式。
5. **找回作品。** “03 成片”顶部显示本故事最近一次成功导出的版本。点“刷新成片”“新窗口播放”或“下载成片”。自动模式可在本页展开“版本与运行历史”查旧版或查看当前运行。“仅生成素材”的结果在镜头、对应任务和素材中可查。自行导入或外部总剪的 MP4 在“素材”的对应文件夹播放,故事播放器只关联该故事的成片运行。
用 Kokoro 时,在“声音工作台”以同一预设音色生成另一句话,再到角色档案“选择参考录音”。这段独立录音只用于音色核验。VoxCPM2 则在绑定参考录音后填写相应参考文本。
### 两人在同一镜头轮流说话
“03 成片”可独立改字幕和 BGM。台词锚点随实测对白移动。需要返工时可分别选择“重做此句配音”“仅重做口型”或“重做原片”。运行异常且准备结构已物化时,点“准备结构另存故事”可打开独立的新草稿。
1. 在“02 分镜”将拍摄方式切为“同框轮流对白”。使用横屏中文对白,在同一镜头指定两位画内角色,各分配一句完整台词。到“01 基准板”为两人分别选择独立参考脸和声音样本,供身份及声线核验。
2. 用含两位人物且嘴部清楚的图片作首帧,保存后按画面核对左右身份,必要时点“交换左右角色”,再点“确认首帧与角色对应”。更换首帧后重新确认。写清每轮发言时另一人的反应。
3. 保存后查看“试生成本镜”。按钮按当前环境的双人认证、模型、画幅、帧数及本镜输入判断是否可用。待认证时仍可保存同框草稿,或点“预览并另存切镜版”,核对台词分配后另存一部切镜故事。
4. 试拍后打开“双人候选逐轮审核”,逐轮回放原声与画面。重点看谁先开口、听者有无跟读、换人前后声音和脸是否对应。候选提示“待复核”时,完成逐轮核对并填写“选用说明”后才可人工选用;明确失败的候选需要重拍或换选。
质检确认是置信度高的小幅口型偏移时,系统可在原音频、字幕和镜头时间线上自动重做口型,独立复检通过后再选用。若仍未通过,已合格的素材和此前完成的成片会保留。可在任务详情区分人物身份一致性、口型同步和静音段嘴部运动等原因,再决定重做口型还是原片。
## 17. 对白字幕按说话节奏显示
人工确认口型偏移后,可在“02 分镜”选中目标镜头,在“镜头对白”调整“口型对时(帧)”。默认 0,范围为 −6 至 6 的整数。正数提前,负数延后,24 帧/秒时每帧约 41.7 毫秒。例如口型晚约 3 帧时填 3,再点“仅重做口型”。重做后查看该镜预览和复检结果,原对白和字幕保持原位。
1. 新建故事时,“启用中文原生对白后的字幕”默认选“自动节奏字幕 · 隐藏句读”,也可选择“人工字幕”或“关闭字幕”。已有作品可在“03 成片 → 字幕草稿预览”点“试用节奏字幕”,预览后再“应用并保存”。
2. 在“出现方式”选“按节奏”或“整句”,在“标点显示”选“隐藏句读”或“保留原文”。只需字幕干净时,直接改显示设置即可,台词里的问号、逗号可保留给演员表演。字幕使用台词或字幕改字,输入时无须在每句前加角色姓名。
3. 展开一句并点“循环听本句”。例如“爸,你往这儿靠靠”中间若有明显停顿,可在“原文断点”选“爸”后面,将播放头移到相应位置,点“按播放头拆分”。起止帧按左闭右开计算,24 到 48 对应第 24 到 47 帧。精细调整后可分别锁定文字、锁定时间。若预览提示“待校时”,按提示读取已有净音轨重新分析,或试听后填写镜内帧点。
4. 保存后点“更新字幕并成片”生成新版,需要匹配的无字幕原片和成片混音。若刚改过配乐或旧混音缺失,用“重新混音并成片”。完成后在播放器或“版本与运行历史”点“下载该版本 SRT”(有可导出字幕的版本才显示),该文件对应已导出版本。
三角色、22 镜、120 秒《雨夜归途》的跑样顺序和当前验收状态见[自动长视频与音轨操作指南](自动长视频与音轨操作指南_20261126.md)第 8 节。
## 18. 使用白模预演参考
- **保留构图和站位。** 从预演导出分镜首帧,到“创作 → 图生图”添加白模截图和角色参考图,提示词注明各图用途、人物左右、朝向及视线。检查生成的正式首帧,在“02 分镜”导入并选用,填写运动描述,再生成视频。人工候选流程先点“确认首帧”。H3 依选用配置接受首帧或首尾帧,双卡原生有声配置使用首帧。首帧能约束开场构图,精确动作时序和机位轨迹仍需看片核对。
- **保留已有动作和运镜。** 若预演视频中的人物能被跟踪,可到“创作 → 视频人物替换”先“识别人物”,沿时间轴检查检测框,给每人绑定一张角色参考图再生成。替换区域围绕人物,场景和道具会沿用预演画面;该入口保留源音轨时也会沿用原台词。想用这段成品参与普通故事合成,可在人工流程导入视频候选并确认选片。详细步骤见[图生图与视频人物替换操作手册](图生图与视频人物替换操作手册_20261112.md)。
- 项目的视频生成接口接收提示词和静态图像条件。整段白模动画的骨骼、深度序列或摄影机轨迹目前没有对应的 H3 输入字段。实际支持的图片、素材字段和任务类型见[API 接口使用说明](api.html)。

View File

@ -85,6 +85,7 @@ function clearSession() {
useSharedAssetsStore().clear()
drafts.clear()
caps.items = []
caps.editorV4 = false
useWorkflowsStore().reset()
useStoriesStore().reset()
clearInterval(poll)

View File

@ -1,6 +1,8 @@
import { request } from './client'
import { durable } from './durable'
import type {
CaptionPreview,
CutPreview,
EditorDTO,
EditorManifest,
EditorPlan,
@ -10,7 +12,21 @@ import type {
} from '../types/editors'
import type { RunSnapshot } from '../types/workflows'
const path = (id: string) => `/editors/${encodeURIComponent(id)}`
export const captionSrtUrl = (id: string, runId: string) =>
`/api${path(id)}/runs/${encodeURIComponent(runId)}/captions.srt`
export const editorsApi = {
previewCuts: (id: string, expected_version: number, shot_id: string) =>
request<CutPreview>(`${path(id)}/dialogue/fork-cuts`, {
method: 'POST',
body: JSON.stringify({ expected_version, shot_id, confirm: false }),
}),
forkCuts: (id: string, expected_version: number, shot_id: string, name: string) =>
durable<EditorDTO>('editor.dialogue.fork_cuts', `${path(id)}/dialogue/fork-cuts`, {
expected_version,
shot_id,
confirm: true,
name,
}),
forkPreparedDialogue: (id: string, expected_version: number, run_id: string, name: string) =>
durable<PreparedDialogueFork>(
'editor.dialogue.fork_prepared',
@ -37,10 +53,33 @@ export const editorsApi = {
}),
editorFromRun: (id: string, expected_version: number, run_id: string) =>
durable<EditorDTO>('editor.from_run', `${path(id)}/from-run`, { expected_version, run_id }),
previewCaptions: (
id: string,
expected_version: number,
manifest?: EditorManifest,
utterance_id?: string,
) =>
request<CaptionPreview>(`${path(id)}/captions/preview`, {
method: 'POST',
body: JSON.stringify({ expected_version, manifest, utterance_id }),
}),
planEditor: (id: string, input: EditorPlanInput) =>
request<EditorPlan>(`${path(id)}/plan`, { method: 'POST', body: JSON.stringify(input) }),
runEditor: (id: string, input: EditorPlanInput & { expected_plan_hash: string }) =>
durable<RunSnapshot>('editor.run', `${path(id)}/runs`, input),
reviewTurnCandidate: (
id: string,
runId: string,
shotId: string,
expected_version: number,
report_sha256: string,
note: string,
) =>
durable<RunSnapshot>(
'editor.turn_review',
`${path(id)}/runs/${encodeURIComponent(runId)}/turns/${encodeURIComponent(shotId)}/review`,
{ expected_version, report_sha256, decision: 'accept', note },
),
applyEditor: (id: string, expected_version: number, run_id: string) =>
durable<EditorDTO>('editor.apply', `${path(id)}/apply`, { expected_version, run_id }),
}

View File

@ -24,11 +24,26 @@ export const storiesApi = {
request<Page<StoryDTO>>(`/stories${queryString(filters)}`),
story: (id: string) => request<StoryDTO>(path(id)),
storyFilm: (id: string) =>
request<{ asset: Asset; draft_revision: number } | null>(`${path(id)}/film`),
createStory: (name: string, spec: StorySpec, folders: FolderOptions = {}) =>
request<{
asset: Asset
draft_revision: number
run_id?: string
captions_srt_available?: boolean
} | null>(`${path(id)}/film`),
createStory: (
name: string,
spec: StorySpec,
folders: FolderOptions = {},
captionsMode?: 'script' | 'manual' | 'none',
) =>
request<StoryDTO>('/stories', {
method: 'POST',
body: JSON.stringify({ name, spec, ...folders }),
body: JSON.stringify({
name,
spec,
...folders,
...(captionsMode ? { captions_mode: captionsMode } : {}),
}),
}),
saveStory: (story: StoryDTO, name: string, spec: StorySpec, folders: FolderOptions = {}) =>
request<StoryDTO>(path(story.id), {

View File

@ -445,3 +445,24 @@ it('opens the fork using the saved title and version without adopting it into th
expect(v.bindings.dto.value.version).toBe(5)
expect(v.bindings.preparedForks.value[run.id]).toBe('new')
})
it('routes native remix through existing media on V4 and preserves legacy film certification', async () => {
const { dialogueFixture } = await import('../utils/dialogueFixture')
const state = dialogueFixture()
if (state.manifest.schema_version !== 3) throw Error('fixture')
state.manifest.spec.dialogue.generation = 'native_av'
const ui = await view()
const vm = ui.bindings
vm.editor.adopt(state)
const submit = vi.spyOn(vm.editor, 'generate').mockResolvedValue(undefined)
vm.capabilities.editorV4 = true
expect(vm.remixGoal.value).toBe('mix_film')
expect(vm.remixBlocked.value).toBe(false)
await vm.generate(vm.remixGoal.value)
expect(submit).toHaveBeenCalledWith('mix_film', [], false)
vm.capabilities.editorV4 = false
expect(vm.remixGoal.value).toBe('film')
expect(vm.remixBlocked.value).toBe(true)
await vm.generate(vm.remixGoal.value)
expect(submit).toHaveBeenCalledTimes(1)
})

View File

@ -1,7 +1,10 @@
<script setup lang="ts">
import { isDialogueManifest } from '../domain/creation/continuity'
import { upgradeContinuity } from '../domain/creation/continuity'
import { useCapabilitiesStore } from '../stores/capabilities'
import { computed, onBeforeUnmount, ref, watch } from 'vue'
import { captionSrtUrl } from '../api/editors'
import { api, errorMessage } from '../api'
import { getSessionGeneration } from '../api/client'
import { useAuthStore } from '../stores/auth'
@ -32,7 +35,7 @@ import {
H3_NATIVE_LANDSCAPE_ONLY_DESCRIPTION,
H3_NATIVE_AV_PROFILE,
} from '../domain/creation/videoProfile'
import type { EditorDTO, EditorCue } from '../types/editors'
import type { EditorDTO, EditorCue, EditorOutputGoal } from '../types/editors'
import type { Asset, AssetKind } from '../types/assets'
import type { RunDTO } from '../types/workflows'
import AssetPicker from './AssetPicker.vue'
@ -41,8 +44,16 @@ import RunCard from './RunCard.vue'
import StoryBaselineBoard from './studio/StoryBaselineBoard.vue'
import StoryFilmPreview from './studio/StoryFilmPreview.vue'
import StoryShotEditor from './studio/StoryShotEditor.vue'
import CutForkPreview from './studio/CutForkPreview.vue'
import TurnReviewPanel from './studio/TurnReviewPanel.vue'
import RhythmCaptions from './studio/RhythmCaptions.vue'
import DialogueEditor from './studio/DialogueEditor.vue'
import { canChangeSequence, NATIVE_DIALOGUE_UNAVAILABLE } from '../domain/creation/dialogue'
import {
canChangeSequence,
NATIVE_DIALOGUE_UNAVAILABLE,
nativeUtterancesForShot,
twoPersonCertificateIssue,
} from '../domain/creation/dialogue'
import { secondsToSamples, samplesToSeconds } from '../domain/creation/nativeTiming'
const props = withDefaults(
defineProps<{
@ -68,7 +79,7 @@ const editor = useEditableProduction(
const { dto, manifest, busy, notice, dirty, plan, snapshot, executionMode } = editor
const capabilities = useCapabilitiesStore()
const dialogueManifest = computed(() =>
manifest.value?.schema_version === 3 ? manifest.value : undefined,
isDialogueManifest(manifest.value) ? manifest.value : undefined,
)
const nativeDialogue = computed(
() => dialogueManifest.value?.spec.dialogue.generation === 'native_av',
@ -118,6 +129,15 @@ const filmBlocked = computed(() => {
(m.audio.mix_mode === 'manual_mix' || m.audio.mode === 'manual_track')
)
})
const remixGoal = computed(() => (capabilities.editorV4 ? 'mix_film' : 'film'))
const remixBlocked = computed(
() =>
busy.value ||
filmBlocked.value ||
(remixGoal.value === 'film' && (dialogueNeedsCertification.value || !!nativeFilmIssue.value)),
)
const sourceOnlyGoal = (goal: EditorOutputGoal) =>
goal === 'caption_film' || goal === 'caption_inspect' || goal === 'mix_film'
const visibleLimit = computed(() => capabilities.dialogue?.native_av?.max_visible_speakers ?? 1)
const preparedForks = ref<Record<string, string>>({})
let forkEpoch = 0
@ -159,6 +179,13 @@ const auth = useAuthStore(),
let dialoguePicker: { draftId: string; version: number; session: number } | undefined
const shot = computed(() => manifest.value?.spec.shots[index.value]),
shotId = computed(() => manifest.value?.shot_ids[index.value] || '')
const previewCutShot = ref('')
watch(
() => [props.draftId, dto.value?.version, shotId.value, auth.user?.id],
() => {
previewCutShot.value = ''
},
)
const dialogueShot = computed(() => dialogueManifest.value?.spec.shots[index.value])
const total = computed(() => (manifest.value ? editorFrames(manifest.value) : 0))
const selectedSegments = computed(
@ -287,6 +314,10 @@ async function syncFromServer() {
}
async function save() {
if (busy.value) return
if (manifest.value?.schema_version === 4 && !capabilities.editorV4) {
notice.value = '此草稿需要支持编辑器 V4 的服务才能保存。'
return
}
const session = getSessionGeneration(),
id = props.draftId,
submittedName = props.draftName
@ -301,8 +332,12 @@ async function save() {
if (current()) busy.value = false
}
}
async function generate(goal: 'media' | 'film', targets: string[] = [], force = false) {
async function generate(goal: EditorOutputGoal, targets: string[] = [], force = false) {
if (!manifest.value || busy.value) return
if (!capabilities.editorV4 && (manifest.value.schema_version === 4 || sourceOnlyGoal(goal))) {
notice.value = '此操作需要支持编辑器 V4 的服务。'
return
}
if (
nativeDialogue.value &&
targets.some((target) => target === 'script' || target.startsWith('audio:'))
@ -320,6 +355,7 @@ async function generate(goal: 'media' | 'film', targets: string[] = [], force =
return
}
if (
!sourceOnlyGoal(goal) &&
(!targets.length || targets.some((target) => /^(video|native_alignment):/.test(target))) &&
dialogueNeedsCertification.value
) {
@ -344,7 +380,10 @@ async function generate(goal: 'media' | 'film', targets: string[] = [], force =
notice.value = '成片贡献帧超过服务端上限'
return
}
if (targets.includes('captions') && manifest.value.captions.mode === 'none') {
if (
(goal === 'caption_film' || targets.includes('captions')) &&
manifest.value.captions.mode === 'none'
) {
notice.value = '请先启用字幕模式,再更新字幕并成片'
return
}
@ -355,9 +394,9 @@ async function generate(goal: 'media' | 'film', targets: string[] = [], force =
if (saved) emit('saved', saved, submittedName)
await refresh()
}
function nativeGenerationIssue(goal: 'media' | 'film', targets: string[]) {
function nativeGenerationIssue(goal: EditorOutputGoal, targets: string[]) {
const m = dialogueManifest.value
if (!nativeDialogue.value || !m) return
if (sourceOnlyGoal(goal) || !nativeDialogue.value || !m) return
if (goal !== 'film' && targets.length && !targets.some((target) => target.startsWith('video:')))
return
if (!dialogueAvailable.value) return dialogueGenerationReason.value
@ -366,6 +405,12 @@ function nativeGenerationIssue(goal: 'media' | 'film', targets: string[]) {
? m.spec.shots
: m.spec.shots.filter((shot) => targets.includes('video:' + shot.id))
for (const current of selected) {
const contract = twoPersonCertificateIssue(
current,
nativeUtterancesForShot(m.spec, current),
capabilities.dialogue?.native_av?.two_person_turns,
)
if (contract) return contract
const capability = nativeStoryVideoCapability(
current.video_parameters,
m.spec.profile,
@ -440,7 +485,7 @@ async function forkPrepared(run: RunDTO) {
result.draft_id === draftId ||
result.origin?.source_draft_id !== draftId ||
result.origin.source_run_id !== run.id ||
result.manifest.schema_version !== 3 ||
!isDialogueManifest(result.manifest) ||
result.manifest.base_run_id !== null
)
throw new Error('准备稿返回的来源或版本无效,请重新读取后检查')
@ -466,7 +511,7 @@ function add() {
: createWorkflowShot(m.spec.shots.length)
const id = 'id' in s ? s.id : editorId()
addEditorShot(m, s, id)
if (m.schema_version !== 3) m.audio.segments.push({ id: editorId(), shot_id: id, text: '' })
if (!isDialogueManifest(m)) m.audio.segments.push({ id: editorId(), shot_id: id, text: '' })
index.value = m.shot_ids.length - 1
}
function remove() {
@ -520,7 +565,7 @@ function selected(asset: Asset) {
const m = manifest.value
if (!m) return
if (
m.schema_version === 3 &&
isDialogueManifest(m) &&
(dialoguePicker?.draftId !== props.draftId ||
dialoguePicker.version !== dto.value?.version ||
dialoguePicker.session !== getSessionGeneration())
@ -529,8 +574,27 @@ function selected(asset: Asset) {
return
}
const [role, id] = pickerKey.value.split(':')
if (role === 'voice' || role === 'utterance') {
if (m.schema_version !== 3 || asset.kind !== 'audio') return
if (role === 'face_reference_asset_id' || role === 'voice_reference_asset_id') {
if (
!isDialogueManifest(m) ||
m.spec.schema_version !== 6 ||
asset.kind !== (role === 'face_reference_asset_id' ? 'image' : 'audio')
)
return
const speaker = m.spec.dialogue.speakers.find((s) => s.id === id)
if (!speaker) return
if (
role === 'face_reference_asset_id' &&
!m.spec.entities
.find((e) => e.id === speaker.entity_id)
?.reference_asset_ids.includes(asset.id)
) {
notice.value = '请在该人物的独立参考图中选择参考脸。'
return
}
speaker[role] = asset.id
} else if (role === 'voice' || role === 'utterance') {
if (!isDialogueManifest(m) || asset.kind !== 'audio') return
if (role === 'voice') {
const speaker = m.spec.dialogue.speakers.find((item) => item.id === id)
if (!speaker) return
@ -575,7 +639,7 @@ function selected(asset: Asset) {
short_policy: 'silence',
}
m.audio.mode = 'manual_track'
if (m.schema_version === 3) m.audio.mix_mode = 'manual_mix'
if (isDialogueManifest(m)) m.audio.mix_mode = 'manual_mix'
} else
m.bindings[pickerKey.value] = {
asset_id: asset.id,
@ -755,6 +819,12 @@ defineExpose({ save, dirty, busy, syncFromServer })
>
</p>
<template v-if="manifest && dto">
<p
v-if="manifest.schema_version === 4 && !capabilities.editorV4 && !capabilities.loading"
class="notice warning"
>
此草稿使用编辑器 V4。当前服务可查看已保存内容,保存修改和新版操作需要支持 V4 的服务。
</p>
<p
v-for="(issue, i) in dto.issues"
:key="i"
@ -784,6 +854,7 @@ defineExpose({ save, dirty, busy, syncFromServer })
:identity="`${draftId}:${dto.version}`"
>
<DialogueEditor
:editor-v4="capabilities.editorV4"
v-if="dialogueManifest"
section="baseline"
:manifest="dialogueManifest"
@ -792,6 +863,8 @@ defineExpose({ save, dirty, busy, syncFromServer })
:native-available="dialogueAvailable"
:native-reason="dialogueGenerationReason"
:languages="capabilities.dialogue?.native_av?.languages"
@pick-reference="pick"
@preview="preview = $event"
:visible-limit="visibleLimit"
/>
</StoryBaselineBoard>
@ -897,8 +970,12 @@ defineExpose({ save, dirty, busy, syncFromServer })
type="number" /></label
></template>
<DialogueEditor
:editor-v4="capabilities.editorV4"
v-if="dialogueManifest && dialogueShot"
section="shots"
:two-person="capabilities.dialogue?.native_av?.two_person_turns"
:dirty="dirty"
@preview-cuts="previewCutShot = shotId"
:manifest="dialogueManifest"
:shot="dialogueShot"
:assets="dto.assets"
@ -909,6 +986,64 @@ defineExpose({ save, dirty, busy, syncFromServer })
@preview="preview = $event"
@target="runDialogueTarget"
/>
<CutForkPreview
v-if="
capabilities.editorV4 &&
previewCutShot === shotId &&
!!shotId &&
dialogueShot?.performance.dialogue_staging === 'two_person_turns'
"
:key="draftId + ':' + dto.version + ':' + shotId"
:draft-id="draftId"
:version="dto.version"
:shot-id="shotId"
:dirty="dirty"
:name="dto.name"
@cancel="previewCutShot = ''"
@forked="emit('forked', $event)"
/>
<section
v-if="
dialogueShot?.performance.dialogue_staging === 'two_person_turns' && history.length
"
aria-label="本镜候选"
>
<label
>查看试拍运行<select
:value="snapshot?.run.id ?? ''"
@change="openRun(($event.target as HTMLSelectElement).value)"
>
<option
value=""
disabled
>
选择运行版本
</option>
<option
v-for="r in history"
:key="r.id"
:value="r.id"
>
r{{ r.draft_revision }} · {{ r.id.slice(-8) }} · {{ r.state }}
</option>
</select></label
>
<template v-if="snapshot"
><TurnReviewPanel
v-for="review in (snapshot.run.turn_reviews ?? []).filter(
(r) => r.shot_id === shotId,
)"
:key="snapshot.run.id + review.shot_id + review.report_sha256"
:run="snapshot.run"
:review="review"
:video="snapshot.run.result_assets.find((a) => a.id === review.video_asset_id)"
@updated="snapshot = $event"
/>
<small v-if="!snapshot.run.turn_reviews?.some((r) => r.shot_id === shotId)"
>此运行尚无本镜已绑定的逐轮报告。</small
>
</template>
</section>
<div
v-for="kind in manifest.schema_version === 2
? ['frame', 'end_frame', 'video']
@ -1004,6 +1139,7 @@ defineExpose({ save, dirty, busy, syncFromServer })
>
<h3>成片 · 音轨与字幕</h3>
<DialogueEditor
:editor-v4="capabilities.editorV4"
v-if="dialogueManifest"
section="render"
:manifest="dialogueManifest"
@ -1154,8 +1290,8 @@ defineExpose({ save, dirty, busy, syncFromServer })
</div>
<el-button
v-if="nativeDialogue"
:disabled="busy || filmBlocked || dialogueNeedsCertification || !!nativeFilmIssue"
@click="generate('film')"
:disabled="remixBlocked"
@click="generate(remixGoal)"
>重新混音并成片</el-button
>
<p>贡献帧共 {{ total }} 帧 · 混音最多 128 段,音乐和音效最多 32 层</p>
@ -1350,10 +1486,29 @@ defineExpose({ save, dirty, busy, syncFromServer })
><el-button @click="addCue">添加字幕</el-button
><el-button
:disabled="busy || manifest.captions.mode === 'none'"
@click="generate('film', ['captions'], true)"
@click="
capabilities.editorV4 && nativeDialogue
? generate('caption_film')
: generate('film', ['captions'], true)
"
>更新字幕并成片</el-button
>
</div>
<RhythmCaptions
v-if="
capabilities.editorV4 &&
nativeDialogue &&
dialogueManifest &&
manifest.captions.mode === 'script'
"
:draft-id="draftId"
:version="dto.version"
:manifest="dialogueManifest"
:assets="dto.assets"
:busy="busy"
@apply="save"
@inspect="generate('caption_inspect', ['native_report:' + $event])"
/>
<p
v-if="manifest.captions.mode === 'none'"
class="muted"
@ -1486,7 +1641,16 @@ defineExpose({ save, dirty, busy, syncFromServer })
v-for="s in plan.steps"
:key="s.key"
>
{{ s.key }} · {{ s.status }}
{{ s.key }} ·
{{
{
reuse: '复用',
generate: '生成',
pending_dependency: '等待前序步骤',
analyze: '分析',
manual: '需人工处理',
}[s.status] || s.status
}}<span v-if="s.reason"> · {{ s.reason }}</span>
</p>
</div>
</details>
@ -1536,6 +1700,11 @@ defineExpose({ save, dirty, busy, syncFromServer })
<span
>{{ r.output_goal === 'media' ? '素材' : '成片' }} · {{ r.id.slice(-8) }} ·
{{ r.state }} · r{{ r.draft_revision }}</span
><a
v-if="r.state === 'succeeded' && r.captions_srt_available"
:href="captionSrtUrl(draftId, r.id)"
download
>下载该版本 SRT</a
><el-button
:disabled="busy || dirty"
@click="restore(r.id)"

View File

@ -1,4 +1,5 @@
<script setup lang="ts">
import TurnReviewPanel from './studio/TurnReviewPanel.vue'
import FolderAssignment from './FolderAssignment.vue'
import { computed, ref } from 'vue'
import { ElMessage } from 'element-plus'
@ -132,6 +133,14 @@ const assetKindLabel: Record<string, string> = {
</script>
<template>
<article class="surface v2-panel">
<TurnReviewPanel
v-for="review in run.turn_reviews ?? []"
:key="run.id + review.shot_id + review.report_sha256"
:review="review"
:run="run"
:video="assetIndex.get(review.video_asset_id)"
@updated="publish"
/>
<details v-if="run.quality">
<summary>
质量检查 {{ run.quality.accepted_shots }}/{{ run.quality.total_shots }} · 修复

View File

@ -0,0 +1,203 @@
<script setup lang="ts">
import { computed, ref, watch } from 'vue'
import type { CaptionEdit, CaptionRow } from '../../types/editors'
import { editCaption, mergeCaption, splitCaption } from '../../domain/creation/captionEdits'
const props = defineProps<{
row: CaptionRow
next?: CaptionRow
playhead: number | null
disabled: boolean
duration: number
}>()
const emit = defineEmits<{ change: [range: CaptionRow, edits: CaptionEdit[]] }>()
const text = ref(''),
start = ref<number | ''>(''),
end = ref<number | ''>(''),
cut = ref(0),
textLock = ref(false),
timeLock = ref(false),
warning = ref('')
const source = computed(() => Array.from(props.row.source_text))
watch(
() => props.row,
(r) => {
text.value = r.text
start.value = r.local_start_frame ?? ''
end.value = r.local_end_frame ?? ''
cut.value = r.source_start + 1
textLock.value = r.text_override
timeLock.value = r.timing_override
warning.value = ''
},
{ immediate: true },
)
function save() {
if (!text.value.trim() || /[\r\n]/.test(text.value)) {
warning.value = '请填写单行显示文案。'
return
}
if (
timeLock.value &&
(typeof start.value !== 'number' ||
typeof end.value !== 'number' ||
!Number.isInteger(start.value) ||
!Number.isInteger(end.value) ||
start.value < 0 ||
end.value <= start.value ||
end.value > props.duration)
) {
warning.value = '请填写镜头范围内的起止帧,结束帧须晚于开始帧。'
return
}
const e = editCaption(props.row)
delete e.text
delete e.start_frame
delete e.end_frame
e.text_override = textLock.value
e.timing_override = timeLock.value
if (e.text_override) e.text = text.value
if (e.timing_override) {
e.start_frame = Number(start.value)
e.end_frame = Number(end.value)
}
warning.value = ''
emit('change', props.row, [e])
}
function split() {
try {
emit('change', props.row, splitCaption(props.row, cut.value, props.playhead ?? NaN))
} catch (e) {
warning.value = (e as Error).message
}
}
function merge() {
if (!props.next) return
try {
const e = mergeCaption(props.row, props.next)
emit('change', { ...props.row, source_end: e.source_end }, [e])
} catch (e) {
warning.value = (e as Error).message
}
}
</script>
<template>
<fieldset
:disabled="disabled"
class="segment"
>
<legend>
{{
{ automatic: '自动', sentence_fallback: '整句回退', manual: '人工', pending: '待校时' }[
row.status
]
}}
· {{ row.start_frame ?? '—' }}–{{ row.end_frame ?? '—' }} 全片帧
</legend>
<label
>显示文案<input
v-model="text"
maxlength="2000"
@input="textLock = true"
/></label>
<div class="options">
<label
><input
v-model="textLock"
type="checkbox"
/>锁定文字</label
>
<label
>镜内开始帧<input
v-model.number="start"
type="number"
min="0"
:max="duration - 1"
@input="timeLock = true"
/></label>
<label
>结束帧<input
v-model.number="end"
type="number"
min="1"
:max="duration"
@input="timeLock = true"
/></label>
<label
><input
v-model="timeLock"
type="checkbox"
/>锁定时间</label
>
<button
type="button"
@click="save"
>
应用片段修改
</button>
</div>
<div class="options">
<label v-if="row.source_end - row.source_start > 1"
>原文断点<select v-model.number="cut">
<option
v-for="n in row.source_end - row.source_start - 1"
:key="n"
:value="row.source_start + n"
>
第 {{ n }} 字「{{ source[row.source_start + n - 1] }}」后
</option>
</select></label
>
<button
type="button"
:disabled="row.source_end - row.source_start < 2 || playhead === null"
@click="split"
>
按播放头拆分
</button>
<button
type="button"
:disabled="!next || next.source_start !== row.source_end"
@click="merge"
>
合并下一段
</button>
<button
type="button"
@click="
emit('change', row, [
{ ...editCaption(row), deleted: true, text_override: false, timing_override: false },
])
"
>
删除片段
</button>
</div>
<p
v-if="warning"
role="alert"
>
{{ warning }}
</p>
</fieldset>
</template>
<style scoped>
.segment {
min-width: 0;
display: grid;
gap: 0.5rem;
border: 1px solid var(--el-border-color);
padding: 0.6rem;
}
.segment > label {
display: grid;
}
.options {
display: flex;
gap: 0.6rem;
align-items: center;
flex-wrap: wrap;
}
.options input[type='number'] {
width: 5rem;
}
</style>

View File

@ -0,0 +1,130 @@
<script setup lang="ts">
import { onBeforeUnmount, ref } from 'vue'
import { api, errorMessage } from '../../api'
import { getSessionGeneration } from '../../api/client'
import type { CutPreview } from '../../types/editors'
const props = defineProps<{
draftId: string
version: number
shotId: string
dirty: boolean
name: string
}>()
const emit = defineEmits<{ cancel: []; forked: [id: string] }>()
const preview = ref<CutPreview>(),
name = ref(''),
message = ref(''),
busy = ref(false),
copyId = ref('')
const identity = [props.draftId, props.version, props.shotId, getSessionGeneration()]
let mounted = true
onBeforeUnmount(() => {
mounted = false
})
function current() {
return (
mounted &&
identity[0] === props.draftId &&
identity[1] === props.version &&
identity[2] === props.shotId &&
identity[3] === getSessionGeneration()
)
}
async function load() {
busy.value = true
message.value = ''
try {
const data = await api.previewCuts(props.draftId, props.version, props.shotId)
if (!current()) return
preview.value = data
name.value = data.name || Array.from(props.name).slice(0, 250).join('') + '·切镜版'
} catch (e) {
if (current()) message.value = errorMessage(e)
} finally {
if (current()) busy.value = false
}
}
async function fork() {
if (
!current() ||
!preview.value ||
busy.value ||
props.dirty ||
!name.value.trim() ||
copyId.value
)
return
busy.value = true
message.value = ''
try {
const copy = await api.forkCuts(props.draftId, props.version, props.shotId, name.value.trim())
if (!current()) return
if (!copy.draft_id || copy.draft_id === props.draftId) throw new Error('服务端未返回切镜副本')
copyId.value = copy.draft_id
if (!props.dirty) emit('forked', copy.draft_id)
} catch (e) {
if (current()) message.value = errorMessage(e)
} finally {
if (current()) busy.value = false
}
}
void load()
</script>
<template>
<section aria-label="切镜副本预览">
<h4>切镜副本的镜头与台词</h4>
<template v-if="preview"
><ol>
<li
v-for="(s, i) in preview.shots"
:key="i"
>
{{ s.speaker_name }}「{{ s.text }}」· {{ s.duration_frames }} 帧
</li>
</ol>
<p
v-for="warning in preview.warnings"
:key="warning"
>
{{ warning }}
</p>
<template v-if="!copyId"
><label
>副本名称<input
v-model="name"
maxlength="255"
/></label>
<button
type="button"
:disabled="busy || dirty || !name.trim()"
@click="fork"
>
确认另存切镜副本
</button> </template
><router-link
v-else
:to="'/studio/' + encodeURIComponent(copyId)"
>打开切镜副本</router-link
></template
>
<p
v-if="message"
role="alert"
>
{{ message
}}<button
v-if="!preview"
@click="load"
>
重新预览
</button>
</p>
<button
type="button"
:disabled="busy"
@click="emit('cancel')"
>
关闭预览
</button>
</section>
</template>

View File

@ -2,6 +2,8 @@
import { computed, ref, watch } from 'vue'
import {
addSpeaker,
estimatedSpeechSeconds,
twoPersonCertificateIssue,
addUtterance,
audioTimelineEntries,
adjacentSequences,
@ -20,22 +22,28 @@ import {
utterancesForShot,
} from '../../domain/creation/dialogue'
import { samplesToSeconds, secondsToSamples } from '../../domain/creation/nativeTiming'
import type { DialogueCapability } from '../../types/capabilities'
import type { Asset } from '../../types/assets'
import type { EditorManifestV3 } from '../../types/editors'
import type { DialogueEditorManifest } from '../../types/editors'
import type { DialogueSpeaker, DialogueUtterance, StoryShotV5 } from '../../types/stories'
const props = defineProps<{
manifest: EditorManifestV3
manifest: DialogueEditorManifest
section: 'baseline' | 'shots' | 'render'
shot?: StoryShotV5
busy: boolean
editorV4?: boolean
nativeAvailable: boolean
nativeReason?: string | null
twoPerson?: NonNullable<DialogueCapability['native_av']>['two_person_turns']
languages?: string[]
dirty?: boolean
visibleLimit: number
assets: Asset[]
}>()
const emit = defineEmits<{
previewCuts: []
pickReference: [key: string, kind: 'audio' | 'image']
preview: [asset: Asset]
target: [kind: 'video' | 'native_alignment', id: string, force: boolean]
}>()
@ -69,8 +77,111 @@ const historicalVideo = computed(
(bindingAsset('synced_video', props.shot.id) ?? bindingAsset('base_video', props.shot.id)),
)
const nativeReport = computed(() => props.shot && bindingAsset('native_report', props.shot.id))
const isDuo = computed(() => props.shot?.performance.dialogue_staging === 'two_person_turns')
const shotVisibleLimit = computed(() => (isDuo.value ? 2 : Math.min(1, props.visibleLimit)))
const utteranceEstimate = computed(() => estimatedSpeechSeconds(nativeLines.value))
const visibleCast = computed(() =>
speakers.value.filter(
(s) => s.entity_id && props.shot?.cast.some((c) => c.entity_id === s.entity_id),
),
)
const frameBinding = computed(() => props.shot && props.manifest.bindings['frame:' + props.shot.id])
const refFaces = computed(
() =>
spec.value.entities.find((e) => e.id === speaker.value?.entity_id)?.reference_asset_ids ?? [],
)
const duoIssue = computed(() => {
if (!isDuo.value || !props.shot) return ''
const contract = twoPersonCertificateIssue(props.shot, nativeLines.value, props.twoPerson)
if (contract) return contract
if (
spec.value.profile === 'portrait_1080_v1' ||
(spec.value.dialogue.language || 'Chinese') !== 'Chinese'
)
return '同框试点使用横屏中文对白。'
const perf = props.shot.performance
if (
perf.visible_speaker_ids.length !== 2 ||
nativeLines.value.length !== 2 ||
new Set(nativeLines.value.map((l) => l.speaker_id)).size !== 2 ||
!nativeLines.value.every((l) => perf.visible_speaker_ids.includes(l.speaker_id))
)
return '请为两位画内角色各分配一句台词。'
if (!perf.first_frame_sha256 || perf.first_frame_sha256 !== frameBinding.value?.sha256)
return '请确认当前双人首帧和左右角色对应。'
if (
!perf.visible_speaker_ids.every((id) => {
const s = speakerFor(id)
return s?.face_reference_asset_id && s.voice_reference_asset_id
})
)
return '请在基准板为两位角色分别选用参考脸与声音样本。'
return ''
})
function stage(value: string) {
if (
!props.editorV4 ||
!props.shot ||
props.busy ||
!native.value ||
props.shot.performance.structure_locked
)
return
const perf = props.shot.performance
if (value !== 'two_person_turns') {
if (perf.dialogue_staging === 'two_person_turns' && !props.dirty) emit('previewCuts')
return
}
props.manifest.schema_version = 4
spec.value.schema_version = 6
perf.dialogue_staging = 'two_person_turns'
perf.native_utterance_ids ??= nativeLines.value.map((l) => l.id)
assignNumbers()
}
function assignNumbers() {
const used = new Set(
speakers.value.flatMap((s) => (s.model_speaker_number ? [s.model_speaker_number] : [])),
)
for (const id of props.shot?.performance.visible_speaker_ids ?? []) {
const s = speakerFor(id)
if (!s || s.model_speaker_number) continue
let n = 1
while (used.has(n)) n++
s.model_speaker_number = n
used.add(n)
}
}
function visiblePerson(item: DialogueSpeaker, on: boolean) {
if (!props.shot) return
setSpeakerVisible(spec.value, props.shot, item.id, on, shotVisibleLimit.value)
if (isDuo.value) {
delete props.shot.performance.first_frame_sha256
assignNumbers()
}
}
function swapSides() {
if (props.shot) {
props.shot.performance.visible_speaker_ids.reverse()
delete props.shot.performance.first_frame_sha256
}
}
function reaction(id: string, value: string) {
if (!props.shot) return
const perf = props.shot.performance
perf.listener_reactions ??= {}
perf.listener_reactions[id] = value
}
function silent() {
if (props.shot) {
props.shot.performance.native_utterance_ids = []
delete props.shot.performance.listener_reactions
}
}
const generationIssue = computed(() => {
if (isDuo.value && !props.editorV4)
return '此同框草稿需要支持编辑器 V4 的服务。可以查看已保存内容。'
if (!native.value) return '请先升级为H3原生对白,再保存当前修改。'
if (duoIssue.value) return duoIssue.value
if (!props.nativeAvailable) return props.nativeReason || NATIVE_DIALOGUE_UNAVAILABLE
if (
lines.value.length &&
@ -78,7 +189,7 @@ const generationIssue = computed(() => {
props.shot?.performance.native_utterance_ids == null
)
return '请指定本镜头台词;多镜头段落不会自动截句或重复配音。'
if (new Set(nativeLines.value.map((item) => item.speaker_id)).size > 1)
if (!isDuo.value && new Set(nativeLines.value.map((item) => item.speaker_id)).size > 1)
return '一个镜头只支持一个发言角色,请拆成切镜并分别分配台词。'
if (nativeLines.value.some((item) => !item.text.trim())) return '请填写本镜头台词原文。'
return ''
@ -151,6 +262,16 @@ function newLine() {
}
function selectNativeLine(item: DialogueUtterance, included: boolean) {
if (!props.shot || props.busy || !native.value) return
if (isDuo.value) {
const ids = (props.shot.performance.native_utterance_ids ??= [])
if (included && ids.length < 2 && !ids.includes(item.id)) ids.push(item.id)
if (!included) {
props.shot.performance.native_utterance_ids = ids.filter((id) => id !== item.id)
if (props.shot.performance.listener_reactions)
delete props.shot.performance.listener_reactions[item.id]
}
return
}
const ids = new Set(nativeLines.value.map((line) => line.id))
if (included) ids.add(item.id)
else ids.delete(item.id)
@ -292,6 +413,49 @@ const checked = (event: Event) => (event.target as HTMLInputElement).checked
@input="setVoiceDescription(speaker, input($event))"
/>
</label>
<template v-if="editorV4 && spec.schema_version === 6 && native && speaker.entity_id">
<label
>独立参考脸<select
:value="speaker.face_reference_asset_id ?? ''"
@change="speaker.face_reference_asset_id = input($event) || null"
>
<option value="">从人物参考图选择</option>
<option
v-for="id in refFaces"
:key="id"
:value="id"
>
{{ asset(id)?.name ?? id }}
</option>
</select></label
>
<button
type="button"
@click="emit('pickReference', 'voice_reference_asset_id:' + speaker.id, 'audio')"
>
选择已认可的验声样本
</button>
<span v-if="speaker.voice_reference_asset_id">{{
asset(speaker.voice_reference_asset_id)?.name ?? speaker.voice_reference_asset_id
}}</span>
<button
v-if="asset(speaker.voice_reference_asset_id)"
type="button"
@click="emit('preview', asset(speaker.voice_reference_asset_id)!)"
>
试听样本
</button>
<button
v-if="speaker.voice_reference_asset_id"
type="button"
@click="speaker.voice_reference_asset_id = null"
>
解除验声样本
</button>
<small v-if="speaker.model_speaker_number"
>模型角色 {{ speaker.model_speaker_number }}</small
>
</template>
<small class="muted"
>H3根据描述生成声音。声线描述用于表达目标,不等同于固定音色或录音克隆;请以本镜头实际音轨检查一致性。</small
>
@ -328,6 +492,21 @@ const checked = (event: Event) => (event.target as HTMLInputElement).checked
>段落含 {{ sequence.shot_ids.length }} 个镜头</span
>
</header>
<label v-if="native && editorV4"
>拍摄方式<select
:disabled="busy || shot.performance.structure_locked"
:value="shot.performance.dialogue_staging ?? ''"
@change="stage(input($event))"
>
<option
value=""
:disabled="isDuo"
>
按说话人切镜
</option>
<option value="two_person_turns">同框轮流对白</option>
</select></label
>
<fieldset :disabled="busy">
<label
>对白段落<select
@ -382,15 +561,20 @@ const checked = (event: Event) => (event.target as HTMLInputElement).checked
><input
type="checkbox"
:checked="nativeLines.some((line) => line.id === item.id)"
:disabled="
isDuo && nativeLines.length >= 2 && !nativeLines.some((l) => l.id === item.id)
"
@change="selectNativeLine(item, checked($event))"
/>{{ speakerFor(item.speaker_id)?.name }} · {{ item.text || '待填写' }}</label
>
<small class="muted"
>按完整台词分配镜头。多镜头段落需逐镜指定,每镜只安排一个发言角色;不会自动截句。</small
>
<small class="muted">{{
isDuo
? '按发言顺序选择两句台词。'
: '按完整台词分配镜头。多镜头段落需逐镜指定,每镜只安排一个发言角色;不会自动截句。'
}}</small>
<button
type="button"
@click="shot.performance.native_utterance_ids = []"
@click="silent"
>
本镜头无对白
</button>
@ -401,9 +585,7 @@ const checked = (event: Event) => (event.target as HTMLInputElement).checked
>
<legend>画内说话人</legend>
<label
v-for="item in speakers.filter(
(s) => s.entity_id && shot?.cast.some((c) => c.entity_id === s.entity_id),
)"
v-for="item in visibleCast"
:key="item.id"
class="dialogue-checkbox"
><input
@ -411,13 +593,81 @@ const checked = (event: Event) => (event.target as HTMLInputElement).checked
:checked="shot.performance.visible_speaker_ids.includes(item.id)"
:disabled="
!shot.performance.visible_speaker_ids.includes(item.id) &&
shot.performance.visible_speaker_ids.length >= visibleLimit
shot.performance.visible_speaker_ids.length >= shotVisibleLimit
"
@change="setSpeakerVisible(spec, shot, item.id, checked($event), visibleLimit)"
@change="visiblePerson(item, checked($event))"
/>{{ item.name }}</label
>
<small class="muted">在画面中发言的人物需先加入镜头;画外声音不选画内说话人。</small>
</fieldset>
<fieldset
v-if="isDuo && editorV4"
:disabled="busy"
>
<legend>双人首帧与逐轮表演</legend>
<button
type="button"
:disabled="busy || dirty"
@click="emit('previewCuts')"
>
预览并另存切镜版
</button>
<small v-if="dirty">请先保存同框草稿,再预览切镜分配。</small>
<img
v-if="asset(frameBinding?.asset_id)"
:src="asset(frameBinding?.asset_id)?.preview_url"
alt="待确认左右角色的双人首帧"
style="max-width: 18rem; width: 100%"
/>
<span
>左侧 {{ speakerFor(shot.performance.visible_speaker_ids[0] ?? '')?.name ?? '待选' }} ·
右侧 {{ speakerFor(shot.performance.visible_speaker_ids[1] ?? '')?.name ?? '待选' }}</span
>
<button
type="button"
:disabled="shot.performance.visible_speaker_ids.length !== 2"
@click="swapSides"
>
交换左右角色
</button>
<button
type="button"
:disabled="!frameBinding?.sha256 || shot.performance.visible_speaker_ids.length !== 2"
@click="shot.performance.first_frame_sha256 = frameBinding?.sha256"
>
确认首帧与角色对应
</button>
<small>{{
frameBinding?.sha256 && shot.performance.first_frame_sha256 === frameBinding.sha256
? '已确认当前首帧'
: '请先选用或生成双人首帧并保存,然后确认左右角色。'
}}</small>
<label
v-for="(item, n) in nativeLines"
:key="item.id"
>第 {{ n + 1 }} 轮 · {{ speakerFor(item.speaker_id)?.name }}「{{ item.text }}」<span
>听者动作</span
><input
maxlength="500"
:value="shot.performance.listener_reactions?.[item.id] ?? ''"
placeholder="例如抬眼倾听"
@input="reaction(item.id, input($event))"
/></label>
<button
type="button"
:disabled="nativeLines.length !== 2"
@click="shot.performance.native_utterance_ids?.reverse()"
>
交换发言轮次
</button>
<small v-if="utteranceEstimate > shot.edit.duration_frames / 24"
>按当前文本预计需要约 {{ utteranceEstimate.toFixed(1) }} 秒,请缩短对白或调整镜头。</small
>
<small
>两人各说一句,发言间留出交接停顿,句尾预留约 0.75 秒观察闭口。镜头长
{{ (shot.edit.duration_frames / 24).toFixed(2) }} 秒。</small
>
</fieldset>
<p
v-if="native && manifest.bindings[`video:${shot.id}`]?.source === 'manual'"
class="muted"
@ -458,7 +708,7 @@ const checked = (event: Event) => (event.target as HTMLInputElement).checked
:disabled="busy || !!generationIssue || videoLocked"
@click="runTarget('video')"
>
重新生成本镜头原生对白
{{ isDuo ? '试生成本镜' : '重新生成本镜头原生对白' }}
</button>
<button
type="button"
@ -616,13 +866,18 @@ const checked = (event: Event) => (event.target as HTMLInputElement).checked
在分镜中添加台词后可编辑对白字幕。
</p>
<div
v-if="timeline.some((group) => group.lines.length) || audioTimeline.length"
v-if="
(!manifest.captions.presentation && timeline.some((group) => group.lines.length)) ||
audioTimeline.length
"
class="dialogue-timeline"
tabindex="0"
aria-label="全片对白时间线"
>
<section
v-for="group in timeline.filter((item) => item.lines.length)"
v-for="group in manifest.captions.presentation
? []
: timeline.filter((item) => item.lines.length)"
:key="group.id"
>
<h4>

View File

@ -0,0 +1,117 @@
<script setup lang="ts">
import { ref, watch } from 'vue'
const props = defineProps<{ src: string; time: number }>()
const emit = defineEmits<{ seek: [seconds: number] }>()
const points = ref(''),
duration = ref(0),
notice = ref('')
watch(
() => props.src,
async (src, _, cleanup) => {
points.value = ''
duration.value = 0
notice.value = ''
if (!src || typeof AudioContext === 'undefined') return
const controller = new AbortController()
let ctx: AudioContext | undefined
cleanup(() => {
controller.abort()
if (ctx && ctx.state !== 'closed') void ctx.close()
})
try {
const response = await fetch(src, { credentials: 'same-origin', signal: controller.signal })
if (!response.ok) throw new Error('音轨读取失败')
const bytes = await response.arrayBuffer()
if (controller.signal.aborted) return
ctx = new AudioContext()
const buffer = await ctx.decodeAudioData(bytes)
if (controller.signal.aborted) return
const channels = Array.from({ length: buffer.numberOfChannels }, (_, i) =>
buffer.getChannelData(i),
)
const width = 480,
commands: string[] = []
for (let x = 0; x < width; x++) {
let peak = 0
const start = Math.floor((x * buffer.length) / width),
end = Math.floor(((x + 1) * buffer.length) / width)
for (const samples of channels)
for (let i = start; i < end; i++) peak = Math.max(peak, Math.abs(samples[i]!))
const half = Math.min(1, peak) * 22
commands.push('M' + x + ' ' + (24 - half).toFixed(1) + 'v' + (half * 2).toFixed(1))
}
duration.value = buffer.duration
points.value = commands.join('')
} catch {
if (!controller.signal.aborted) notice.value = '波形暂不可读,可用播放器定位。'
} finally {
if (ctx && ctx.state !== 'closed') void ctx.close()
}
},
{ immediate: true },
)
function scrub(e: MouseEvent) {
const rect = (e.currentTarget as SVGSVGElement).getBoundingClientRect()
if (rect.width)
emit(
'seek',
Math.min(
duration.value,
Math.max(0, ((e.clientX - rect.left) / rect.width) * duration.value),
),
)
}
</script>
<template>
<div
v-if="points"
class="waveform"
>
<svg
viewBox="0 0 480 48"
preserveAspectRatio="none"
role="img"
aria-label="镜头独立原声波形"
@click="scrub"
>
<path
:d="points"
stroke="currentColor"
/>
<line
:x1="(time / duration) * 480"
:x2="(time / duration) * 480"
y1="0"
y2="48"
stroke="var(--el-color-danger)"
stroke-width="2"
/>
</svg>
<label
>原声播放头(秒)<input
type="range"
:min="0"
:max="duration"
:step="1 / 24"
:value="time"
@input="emit('seek', Number(($event.target as HTMLInputElement).value))"
/></label>
</div>
<small v-else-if="notice">{{ notice }}</small>
</template>
<style scoped>
.waveform svg {
width: 100%;
height: 3rem;
cursor: crosshair;
background: var(--el-fill-color-light);
}
.waveform label {
display: flex;
gap: 0.5rem;
align-items: center;
}
.waveform input {
flex: 1;
}
</style>

View File

@ -0,0 +1,570 @@
<script setup lang="ts">
import { computed, nextTick, onBeforeUnmount, ref, watch } from 'vue'
import { api, errorMessage } from '../../api'
import { getSessionGeneration } from '../../api/client'
import type { Asset } from '../../types/assets'
import type {
CaptionEdit,
CaptionPresentation,
CaptionPreview,
CaptionRow,
DialogueEditorManifest,
} from '../../types/editors'
import { nativeUtterancesForShot } from '../../domain/creation/dialogue'
import { updateCaptionEdits } from '../../domain/creation/captionEdits'
import DialogueWaveform from './DialogueWaveform.vue'
import CaptionSegment from './CaptionSegment.vue'
const props = defineProps<{
draftId: string
version: number
manifest: DialogueEditorManifest
assets: Asset[]
busy: boolean
}>()
const emit = defineEmits<{ apply: []; inspect: [shotId: string] }>()
const enabled = computed(() => !!props.manifest.captions.presentation)
const options = ref<CaptionPresentation>({ punctuation: 'hide', pacing: 'rhythm' })
const shown = ref<CaptionPreview>(),
previous = ref<CaptionPreview>(),
trial = ref(false),
loading = ref(false),
message = ref('')
const clone = <T,>(value: T): T => JSON.parse(JSON.stringify(value))
const key = computed(() => JSON.stringify([props.draftId, props.version, props.manifest]))
let serial = 0,
accepted = ''
function requestGuard() {
const token = ++serial,
session = getSessionGeneration(),
original = key.value
return () => token === serial && session === getSessionGeneration() && key.value === original
}
function proposal() {
const doc = clone(props.manifest)
doc.schema_version = 4
doc.captions.presentation = clone(options.value)
doc.captions.edits ??= []
return doc
}
async function reload() {
const current = requestGuard()
loading.value = true
message.value = ''
try {
const result = await api.previewCaptions(props.draftId, props.version, props.manifest)
if (current()) shown.value = result
} catch (e) {
if (current()) message.value = errorMessage(e)
} finally {
if (current()) loading.value = false
}
}
watch(
key,
() => {
if (key.value === accepted) return
serial++
loading.value = false
trial.value = false
previous.value = undefined
shown.value = undefined
message.value = ''
options.value = clone(
props.manifest.captions.presentation ?? { punctuation: 'hide', pacing: 'rhythm' },
)
stopListening()
if (enabled.value) void reload()
},
{ flush: 'post' },
)
async function compare() {
const current = requestGuard()
trial.value = true
loading.value = true
message.value = ''
shown.value = undefined
previous.value = undefined
stopListening()
try {
const [before, after] = await Promise.all([
api.previewCaptions(props.draftId, props.version),
api.previewCaptions(props.draftId, props.version, proposal()),
])
if (current()) {
previous.value = before
shown.value = after
}
} catch (e) {
if (current()) message.value = errorMessage(e)
} finally {
if (current()) loading.value = false
}
}
function apply() {
if (!shown.value || !trial.value || loading.value || props.busy) return
props.manifest.schema_version = 4
props.manifest.captions.presentation = clone(options.value)
props.manifest.captions.edits ??= []
accepted = key.value
trial.value = false
previous.value = undefined
emit('apply')
}
function cancel() {
serial++
trial.value = false
loading.value = false
shown.value = undefined
previous.value = undefined
message.value = ''
options.value = clone(
props.manifest.captions.presentation ?? { punctuation: 'hide', pacing: 'rhythm' },
)
if (enabled.value) void reload()
}
async function recalculate(id: string, edits?: CaptionEdit[]) {
if (!enabled.value || trial.value || loading.value || props.busy) return
const current = requestGuard(),
doc = clone(props.manifest)
if (edits) doc.captions.edits = edits
loading.value = true
message.value = ''
try {
const update = await api.previewCaptions(props.draftId, props.version, doc, id)
if (!current()) return
loading.value = false
if (edits) {
props.manifest.captions.edits = edits
accepted = key.value
}
const issues = [
...(shown.value?.issues ?? []).filter((i) => i.unit_id !== id),
...update.issues,
]
shown.value = {
rows: [
...(shown.value?.rows ?? []).filter((r) => r.utterance_id !== id),
...update.rows.filter((r) => r.utterance_id === id),
],
issues: Array.from(new Map(issues.map((i) => [JSON.stringify(i), i])).values()),
}
} catch (e) {
if (current()) message.value = errorMessage(e)
} finally {
if (current()) loading.value = false
}
}
function undoEdit(edit: CaptionEdit) {
const records = props.manifest.captions.edits ?? []
return recalculate(
edit.utterance_id,
records.filter((e) => e.id !== edit.id),
)
}
function change(range: CaptionRow, edits: CaptionEdit[]) {
const replaced = (shown.value?.rows ?? [])
.filter(
(r) =>
r.utterance_id === range.utterance_id &&
r.shot_id === range.shot_id &&
r.source_text === range.source_text &&
r.source_start >= range.source_start &&
r.source_end <= range.source_end,
)
.map((r) => r.id)
return recalculate(
range.utterance_id,
updateCaptionEdits(props.manifest.captions.edits ?? [], range, edits, replaced),
)
}
function lineRows(data: CaptionPreview | undefined, sid: string, uid: string) {
return (data?.rows ?? [])
.filter((r) => r.shot_id === sid && (r.utterance_id || 'cue:' + r.id) === uid)
.sort((a, b) => a.source_start - b.source_start)
}
const groups = computed(() =>
props.manifest.spec.shots
.map((shot, index) => {
const cueKey = (r: CaptionRow) => r.utterance_id || 'cue:' + r.id
const ids = new Set([
...nativeUtterancesForShot(props.manifest.spec, shot).map((u) => u.id),
...[...(shown.value?.rows ?? []), ...(previous.value?.rows ?? [])]
.filter((r) => r.shot_id === shot.id)
.map(cueKey),
])
return {
shot,
index,
lines: [...ids].map((id) => {
const line = props.manifest.spec.dialogue.utterances.find((u) => u.id === id)
return {
id,
label: line?.text || '人工字幕',
author: !!line,
edits: (props.manifest.captions.edits ?? []).filter((e) => e.utterance_id === id),
rows: lineRows(shown.value, shot.id, id),
before: lineRows(previous.value, shot.id, id),
}
}),
}
})
.filter((group) => group.lines.length),
)
const currentTime = ref(0),
audio = ref<HTMLAudioElement>(),
source = ref(''),
liveShot = ref(''),
liveLine = ref(''),
head = ref<number | null>(null)
let origin = 0,
boundary: [number, number] | undefined,
looping = false
const nowText = computed(
() =>
shown.value?.rows.find(
(r) =>
r.shot_id === liveShot.value &&
head.value !== null &&
r.local_start_frame !== null &&
r.local_end_frame !== null &&
head.value >= r.local_start_frame &&
head.value < r.local_end_frame,
)?.text ?? '',
)
let animation = 0
function stopClock() {
if (animation && typeof cancelAnimationFrame !== 'undefined') cancelAnimationFrame(animation)
animation = 0
}
function startClock() {
stopClock()
if (typeof requestAnimationFrame === 'undefined') return
const tick = () => {
moveHead()
if (audio.value && !audio.value.paused) animation = requestAnimationFrame(tick)
}
animation = requestAnimationFrame(tick)
}
function stopListening() {
stopClock()
audio.value?.pause()
liveShot.value = ''
liveLine.value = ''
source.value = ''
head.value = null
boundary = undefined
looping = false
}
function media(shot: string) {
const binding = props.manifest.bindings['native_audio:' + shot]
return props.assets.find((a) => a.id === binding?.asset_id && a.kind === 'audio')
}
function moveHead() {
if (!audio.value) return
if (looping && boundary && audio.value.currentTime >= boundary[1])
audio.value.currentTime = boundary[0]
currentTime.value = audio.value.currentTime
head.value = Math.floor((audio.value.currentTime - origin) * 24 + 1e-6)
}
async function listen(shotId: string, id: string, rows: CaptionRow[]) {
const shot = props.manifest.spec.shots.find((s) => s.id === shotId),
asset = media(shotId)
if (!shot || !asset) return
if (liveLine.value === id && liveShot.value === shotId && looping) {
stopListening()
return
}
const binding = props.manifest.bindings['native_audio:' + shotId]
origin =
(shot.edit.start_frame + (shot.edit.dedup_frames ?? 0)) / 24 -
(binding?.provenance?.audio_offset_samples ?? 0) / 48000
const timed = rows.filter((r) => r.local_start_frame !== null && r.local_end_frame !== null)
looping = timed.length === rows.length && timed.length > 0
const begin = looping ? Math.min(...timed.map((r) => r.local_start_frame!)) : 0
const end = looping
? Math.max(...timed.map((r) => r.local_end_frame!))
: shot.edit.duration_frames
boundary = [Math.max(0, origin + begin / 24), Math.max(0, origin + end / 24)]
liveShot.value = shotId
liveLine.value = id
source.value = asset.preview_url
await nextTick()
if (!audio.value || liveLine.value !== id) return
const player = audio.value
const play = async () => {
if (player !== audio.value || liveLine.value !== id || !boundary) return
try {
player.currentTime = boundary[0]
await player.play()
} catch (e) {
message.value = errorMessage(e)
}
}
if (player.readyState >= 1) await play()
else player.addEventListener('loadedmetadata', play, { once: true })
}
function seek(seconds: number) {
if (!audio.value) return
if (boundary && (seconds < boundary[0] || seconds >= boundary[1])) looping = false
audio.value.currentTime = seconds
moveHead()
}
function replay() {
if (looping && audio.value && boundary) {
audio.value.currentTime = boundary[0]
void audio.value.play().catch((e) => {
message.value = errorMessage(e)
})
}
}
onBeforeUnmount(() => {
serial++
stopListening()
})
if (enabled.value) {
options.value = clone(props.manifest.captions.presentation!)
void reload()
}
</script>
<template>
<section
class="rhythm"
aria-label="节奏字幕草稿预览"
>
<h4>字幕草稿预览</h4>
<div class="controls">
<label
>出现方式<select
v-model="options.pacing"
:disabled="busy"
@change="compare"
>
<option value="rhythm">按节奏</option>
<option value="sentence">整句</option>
</select></label
>
<label
>标点显示<select
v-model="options.punctuation"
:disabled="busy"
@change="compare"
>
<option value="hide">隐藏句读</option>
<option value="preserve">保留原文</option>
</select></label
>
<button
v-if="!trial"
type="button"
:disabled="busy || loading"
@click="compare"
>
{{ enabled ? '对比当前设置' : '试用节奏字幕' }}
</button>
<template v-else
><button
type="button"
:disabled="busy || loading || !shown"
@click="apply"
>
应用并保存</button
><button
type="button"
@click="cancel"
>
取消试用
</button></template
>
<button
v-if="enabled && !trial"
type="button"
:disabled="busy || loading"
@click="reload"
>
刷新草稿预览
</button>
</div>
<p
v-if="loading"
role="status"
>
正在读取字幕证据…
</p>
<p
v-if="message"
role="alert"
>
{{ message }}
</p>
<div
v-if="shown || previous"
class="captions-scroll"
tabindex="0"
aria-label="逐镜字幕差异与时间"
>
<p
v-for="issue in shown?.issues"
:key="issue.unit_id + ':' + issue.code + issue.message"
role="status"
>
{{ issue.unit_id }} {{ issue.message }}
</p>
<p v-if="!groups.length">当前草稿没有对白字幕。</p>
<div
v-for="{ shot, index, lines } in groups"
:key="shot.id"
>
<h5>镜头 {{ index + 1 }} · {{ shot.name }}</h5>
<button
v-if="!trial && lines.some((l) => l.rows.some((r) => r.status === 'pending'))"
type="button"
:disabled="busy || loading"
@click="emit('inspect', shot.id)"
>
仅分析本镜已有原声
</button>
<details
v-for="line in lines"
:key="line.id"
:open="trial || undefined"
>
<summary>{{ line.label }} · {{ line.rows.length }} 段</summary>
<template v-if="trial"
><p>
原设置 ·
{{
line.before
.map(
(r) =>
r.text + '(' + (r.start_frame ?? '—') + '–' + (r.end_frame ?? '—') + ' 帧)',
)
.join(' / ') || '无'
}}
</p>
<p>
试用设置 ·
{{
line.rows
.map(
(r) =>
r.text + '(' + (r.start_frame ?? '—') + '–' + (r.end_frame ?? '—') + ' 帧)',
)
.join(' / ') || '无'
}}
</p></template
>
<template v-else-if="line.author"
><div class="controls">
<button
type="button"
:disabled="busy || loading"
@click="recalculate(line.id)"
>
仅重算本句
</button>
<button
type="button"
:disabled="!media(shot.id)"
@click="listen(shot.id, line.id, line.rows)"
>
{{
liveLine === line.id && looping
? '停止循环'
: line.rows.length &&
line.rows.every(
(r) => r.local_start_frame !== null && r.local_end_frame !== null,
)
? '循环听本句'
: '试听本镜并校时'
}}
</button>
</div>
<small v-if="!media(shot.id)">本镜还没有可试听的独立原声。</small>
<details v-if="line.edits.length">
<summary>人工调整记录({{ line.edits.length }})</summary>
<p
v-for="e in line.edits"
:key="e.id"
>
「{{ Array.from(e.source_text).slice(e.source_start, e.source_end).join('') }}」·
{{ e.deleted ? '已删除' : '人工调整' }}
<button
type="button"
:disabled="busy || loading"
@click="undoEdit(e)"
>
{{ e.deleted ? '恢复显示' : '撤除此调整' }}
</button>
</p>
</details>
<CaptionSegment
v-for="(row, i) in line.rows"
:key="row.id"
:row="row"
:next="line.rows[i + 1]"
:disabled="busy || loading"
:duration="shot.edit.duration_frames - (shot.edit.dedup_frames ?? 0)"
:playhead="liveShot === shot.id ? head : null"
@change="change"
/></template>
<p v-else>{{ line.rows.map((r) => r.text).join(' / ') }} · 可在字幕文案与锚点中修改</p>
</details>
</div>
</div>
<div
v-if="source"
class="player"
>
<audio
ref="audio"
:src="source"
controls
@play="startClock"
@pause="stopClock"
@timeupdate="moveHead"
@seeked="moveHead"
@ended="replay"
/><DialogueWaveform
:src="source"
:time="currentTime"
@seek="seek"
/><output aria-live="off">镜内第 {{ head ?? '—' }} 帧 {{ nowText }}</output>
</div>
</section>
</template>
<style scoped>
.rhythm {
display: grid;
gap: 0.6rem;
min-width: 0;
}
.rhythm h4,
.rhythm h5 {
margin: 0.3rem 0;
}
.controls {
display: flex;
flex-wrap: wrap;
gap: 0.6rem;
align-items: center;
}
.captions-scroll {
height: clamp(12rem, 36vh, 26rem);
overflow: auto;
border: 1px solid var(--el-border-color);
padding: 0.6rem;
}
details {
padding: 0.35rem 0;
}
summary {
cursor: pointer;
}
.player {
display: grid;
gap: 0.3rem;
}
audio {
max-width: 100%;
}
</style>

View File

@ -1,11 +1,13 @@
<script setup lang="ts">
import { isDialogueStory } from '../../domain/creation/continuity'
import type { StorySpec, StoryEntity } from '../../types/stories'
import { createEntity, createScene, createVariant } from '../../domain/stories/rules'
import StoryReferences from './StoryReferences.vue'
import { bindSpeaker } from '../../domain/creation/dialogue'
const props = defineProps<{ spec: StorySpec; identity: string }>()
function unlinkVoice(entityId: string) {
if (props.spec.schema_version === 5)
if (isDialogueStory(props.spec))
for (const speaker of props.spec.dialogue.speakers)
if (speaker.entity_id === entityId) bindSpeaker(props.spec, speaker, null)
}
@ -20,7 +22,7 @@ function removeEntity(entity: StoryEntity) {
shot.cast = shot.cast.filter((c) => c.entity_id !== entity.id)
}
function removeScene(id: string) {
if (props.spec.schema_version === 5)
if (isDialogueStory(props.spec))
for (const sequence of props.spec.dialogue.sequences)
if (sequence.scene_id === id) sequence.scene_id = null
props.spec.scenes = props.spec.scenes.filter((s) => s.id !== id)

View File

@ -1,5 +1,6 @@
<script setup lang="ts">
import { onBeforeUnmount, ref, watch } from 'vue'
import { captionSrtUrl } from '../../api/editors'
import { api, errorMessage } from '../../api'
import { getSessionGeneration } from '../../api/client'
import { useAuthStore } from '../../stores/auth'
@ -71,7 +72,7 @@ onBeforeUnmount(() => {
/>
<div class="story-film-details">
<p class="story-preview-hint">
最新完成成片 · r{{ film.draft_revision }}
最新完成成片 · 已导出版本 r{{ film.draft_revision }}
<template v-if="film.asset.duration_seconds">
· {{ film.asset.duration_seconds.toFixed(2) }} 秒</template
>
@ -93,6 +94,13 @@ onBeforeUnmount(() => {
:download="film.asset.name"
>下载成片</a
>
<a
v-if="film.run_id && film.captions_srt_available"
class="el-button"
:href="captionSrtUrl(draftId, film.run_id)"
download
>下载该版本 SRT</a
>
</div>
</div>
</div>

View File

@ -1,4 +1,6 @@
<script setup lang="ts">
import { isDialogueStory } from '../../domain/creation/continuity'
import { computed, ref } from 'vue'
import type { StorySpec, StoryShot, SelectionDTO } from '../../types/stories'
import { addCast, effectiveScene, videoGenerationIssue } from '../../domain/stories/rules'
@ -42,7 +44,7 @@ const effective = computed(() => effectiveScene(props.spec, props.shot))
const selectedVideoSeconds = computed(() => props.videoSelection?.asset?.duration_seconds)
const h3Video = computed(() => isH3Video(props.shot.video_parameters))
const nativeDialogue = computed(
() => props.spec.schema_version === 5 && props.spec.dialogue.generation === 'native_av',
() => isDialogueStory(props.spec) && props.spec.dialogue.generation === 'native_av',
)
const tp2Video = computed(() =>
[H3_TP2_VIDEO_PROFILE, H3_NATIVE_AV_TP2_PROFILE].includes(
@ -80,9 +82,7 @@ const nativeSingleCapability = computed(() =>
const tp2UnavailableReason = computed(() => props.tp2Reason || H3_TP2_UNAVAILABLE_REASON)
const sourceBounds = computed(() => storySourceBounds(props.shot.video_parameters))
const dialogueSequence = computed(() =>
props.spec.schema_version === 5
? sequenceForShot(props.spec, props.shot as StoryShotV5)
: undefined,
isDialogueStory(props.spec) ? sequenceForShot(props.spec, props.shot as StoryShotV5) : undefined,
)
function setScene(sceneId: string | null) {
if (dialogueSequence.value && dialogueSequence.value.shot_ids.length > 1) return
@ -92,7 +92,7 @@ function setScene(sceneId: string | null) {
function removeCast(id: string) {
const member = props.shot.cast.find((item) => item.id === id)
props.shot.cast = props.shot.cast.filter((item) => item.id !== id)
if (props.spec.schema_version === 5 && member) {
if (isDialogueStory(props.spec) && member) {
for (const speaker of props.spec.dialogue.speakers)
if (speaker.entity_id === member.entity_id)
setSpeakerVisible(props.spec, props.shot as StoryShotV5, speaker.id, false, 0)
@ -154,7 +154,7 @@ function mentionEntity(id: string) {
<h3>当前镜头</h3>
<div
v-if="
(spec.schema_version === 4 || (spec.schema_version === 5 && continuityAvailable)) &&
(spec.schema_version === 4 || (isDialogueStory(spec) && continuityAvailable)) &&
shot.continuity
"
class="ui-form-grid"

View File

@ -0,0 +1,199 @@
<script setup lang="ts">
import { computed, onBeforeUnmount, ref } from 'vue'
import { api, errorMessage } from '../../api'
import { getSessionGeneration } from '../../api/client'
import type { Asset } from '../../types/assets'
import type { RunDTO, RunSnapshot, TurnReview, TurnVerdict } from '../../types/workflows'
const props = defineProps<{ review: TurnReview; run: RunDTO; video?: Asset }>()
const emit = defineEmits<{ updated: [value: RunSnapshot] }>()
const watched = ref<string[]>([]),
note = ref(''),
busy = ref(false),
message = ref(''),
player = ref<HTMLVideoElement>()
const end = ref<number | null>(null)
const dialogue = computed(() => {
const spec = props.run.frozen_spec ?? props.run.editor_manifest?.spec
return spec && 'dialogue' in spec ? spec.dialogue : undefined
})
const name = (id?: string | null) =>
dialogue.value?.speakers.find((s) => s.id === id)?.name ?? id ?? '证据不足'
const words = (id: string) => dialogue.value?.utterances.find((u) => u.id === id)?.text
const verdict = (v?: TurnVerdict) => (v === 'pass' ? '通过' : v === 'reject' ? '失败' : '待复核')
const mayAccept = computed(
() =>
props.review.can_accept === true &&
props.review.report.decision === 'indeterminate' &&
!props.review.manual_review &&
props.review.report.turns.length === 2 &&
props.review.report.turns.every((t) => t.decision !== 'reject'),
)
let mounted = true
onBeforeUnmount(() => {
mounted = false
player.value?.pause()
})
async function play(start: number, stop: number) {
if (!player.value) return
end.value = stop / 48000
try {
player.value.currentTime = start / 48000
await player.value.play()
} catch (e) {
message.value = errorMessage(e)
}
}
function pauseAtEnd() {
if (player.value && end.value !== null && player.value.currentTime >= end.value) {
player.value.pause()
end.value = null
}
}
async function accept() {
const review = props.review,
run = props.run,
session = getSessionGeneration()
if (
!mayAccept.value ||
!note.value.trim() ||
busy.value ||
!review.report.turns.every((t) => watched.value.includes(t.utterance_id))
)
return
busy.value = true
message.value = ''
const current = () =>
mounted &&
props.review.report_sha256 === review.report_sha256 &&
props.run.id === run.id &&
session === getSessionGeneration()
try {
const result = await api.reviewTurnCandidate(
run.draft_id,
run.id,
review.shot_id,
run.version,
review.report_sha256,
note.value.trim(),
)
if (current()) emit('updated', result)
} catch (e) {
if (current()) message.value = errorMessage(e)
} finally {
if (current()) busy.value = false
}
}
</script>
<template>
<section
aria-label="同框对白逐轮审核"
class="turn-review"
>
<h4>
双人候选逐轮审核 · {{ review.manual_review ? '人工选用' : verdict(review.report.decision) }}
</h4>
<small>镜头 {{ review.shot_id }} · {{ review.report.policy }}</small>
<video
v-if="video?.kind === 'video'"
ref="player"
controls
playsinline
preload="metadata"
:src="video.preview_url"
@timeupdate="pauseAtEnd"
/>
<ol>
<li
v-for="turn in review.report.turns"
:key="turn.utterance_id"
>
<strong
>{{ name(turn.expected_speaker_id) }} ·
{{ words(turn.utterance_id) ?? turn.utterance_id }}</strong
>
<p>
{{ (turn.start_sample / 48000).toFixed(2) }}–{{ (turn.end_sample / 48000).toFixed(2) }} 秒
· {{ verdict(turn.decision) }}
</p>
<p>
实测声线 {{ name(turn.voice?.observed_speaker_id) }} · 发言人口型
{{ verdict(turn.speaker_sync?.decision) }} · 听者 {{ name(turn.listener_id) }} · 听者跟读
{{
turn.listener_sync?.decision === 'pass'
? '检出'
: turn.listener_sync?.decision === 'reject'
? '未检出'
: '待复核'
}}
· 听者闭口 {{ verdict(turn.listener_rest?.decision) }}
</p>
<small v-if="turn.reason">{{
turn.reason === 'short_turn_no_borrowing' ? '本轮有效语音太短' : turn.reason
}}</small>
<button
v-if="video?.kind === 'video'"
type="button"
@click="play(turn.start_sample, turn.end_sample)"
>
回放本轮原声与画面
</button>
<label v-if="mayAccept"
><input
v-model="watched"
type="checkbox"
:value="turn.utterance_id"
/>已核对本轮归属、内容和口型</label
>
</li>
</ol>
<p v-if="review.manual_review">
{{ review.manual_review.reviewer_name }} · {{ review.manual_review.reviewed_at }} ·
{{ review.manual_review.note }}
</p>
<template v-if="mayAccept"
><label
>选用说明<input
v-model="note"
maxlength="500"
placeholder="记录听审结论"
/></label>
<button
type="button"
:disabled="
busy ||
!note.trim() ||
!review.report.turns.every((t) => watched.includes(t.utterance_id))
"
@click="accept"
>
以当前账号选用此候选
</button></template
>
<p
v-if="message"
role="alert"
>
{{ message }}
</p>
</section>
</template>
<style scoped>
.turn-review {
padding: 0.7rem;
border: 1px solid var(--el-border-color);
overflow-wrap: anywhere;
}
.turn-review video {
display: block;
width: min(100%, 32rem);
}
.turn-review li {
margin-bottom: 0.8rem;
}
.turn-review p {
margin: 0.25rem 0;
}
.turn-review label {
display: block;
}
</style>

View File

@ -0,0 +1,375 @@
import CutForkPreview from './CutForkPreview.vue'
import { afterEach, expect, it, vi } from 'vitest'
import { createSSRApp } from 'vue'
import { renderToString } from 'vue/server-renderer'
import { dialogueFixture } from '../../utils/dialogueFixture'
import { writableManifest } from '../../domain/creation/continuity'
import { reactive } from 'vue'
import { setupHarness, settle } from '../../utils/setupHarness'
import { api } from '../../api'
import RhythmCaptions from './RhythmCaptions.vue'
import TurnReviewPanel from './TurnReviewPanel.vue'
import type { TurnReview, RunDTO } from '../../types/workflows'
import DialogueEditor from './DialogueEditor.vue'
it('keeps upgraded dialogue manifests writable only with supported version pairs', () => {
expect(writableManifest(4, 5, 'story')).toBe(true)
expect(writableManifest(4, 6, 'story')).toBe(true)
expect(writableManifest(3, 6, 'story')).toBe(false)
expect(writableManifest(4, 6, 'workflow')).toBe(false)
})
it('offers staging before a two-person certificate exists and keeps legacy documents intact', async () => {
const { manifest } = dialogueFixture()
if (manifest.schema_version !== 3) throw new Error('fixture')
manifest.spec.dialogue.generation = 'native_av'
const before = JSON.stringify(manifest)
const html = await renderToString(
createSSRApp(DialogueEditor, {
manifest,
section: 'shots',
shot: manifest.spec.shots[0]!,
busy: false,
editorV4: true,
nativeAvailable: true,
visibleLimit: 1,
assets: [],
}),
)
expect(html).toContain('同框轮流对白')
expect(JSON.stringify(manifest)).toBe(before)
})
afterEach(() => vi.restoreAllMocks())
it('previews a legacy draft without writing its cues and upgrades only after applying', async () => {
const { manifest: m } = dialogueFixture()
if (m.schema_version !== 3) throw new Error('expected dialogue fixture')
const manifest = reactive(m)
manifest.captions.mode = 'script'
const before = JSON.stringify(manifest)
const call = vi.spyOn(api, 'previewCaptions').mockResolvedValue({ rows: [], issues: [] })
const ui = setupHarness(RhythmCaptions, {
draftId: 'draft',
version: 7,
manifest,
assets: [],
busy: false,
})
try {
expect(call).not.toHaveBeenCalled()
await ui.bindings.compare()
expect(call.mock.calls[0]).toEqual(['draft', 7])
expect(call.mock.calls[1]?.[2]).toMatchObject({
schema_version: 4,
captions: { presentation: { pacing: 'rhythm', punctuation: 'hide' }, edits: [] },
})
expect(JSON.stringify(manifest)).toEqual(before)
ui.bindings.cancel()
expect(ui.events).toEqual([])
await ui.bindings.compare()
ui.bindings.apply()
expect(manifest.schema_version).toBe(4)
expect(manifest.captions.cues).toEqual(JSON.parse(before).captions.cues)
expect(ui.events).toEqual([['apply']])
} finally {
ui.unmount()
}
})
it('recalculates only the selected utterance and retains a deleted segment exception', async () => {
const { manifest: m } = dialogueFixture()
if (m.schema_version !== 3) throw new Error('expected dialogue fixture')
const manifest = reactive(m)
const uid = manifest.spec.dialogue.utterances[0]!.id
manifest.schema_version = 4
manifest.captions.mode = 'script'
manifest.captions.presentation = { pacing: 'rhythm', punctuation: 'hide' }
manifest.captions.edits = [
{
id: 'a'.repeat(32),
utterance_id: uid,
source_text: '灯亮了。',
source_start: 0,
source_end: 2,
deleted: true,
text_override: false,
timing_override: false,
},
]
const call = vi.spyOn(api, 'previewCaptions').mockResolvedValue({ rows: [], issues: [] })
const ui = setupHarness(RhythmCaptions, {
draftId: 'draft',
version: 8,
manifest,
assets: [],
busy: false,
})
try {
await settle()
await ui.bindings.recalculate(uid)
expect(call.mock.lastCall?.[3]).toBe(uid)
expect(call.mock.lastCall?.[2]?.captions.edits).toEqual(manifest.captions.edits)
expect(manifest.captions.edits[0]?.deleted).toBe(true)
} finally {
ui.unmount()
}
})
it('makes explicit staging upgrades, respects per-turn order and clears outdated face confirmations', () => {
const { manifest } = dialogueFixture()
if (manifest.schema_version !== 3) throw new Error('expected dialogue fixture')
manifest.spec.dialogue.generation = 'native_av'
const shot = manifest.spec.shots[0]!
const ui = setupHarness(DialogueEditor, {
manifest,
shot,
assets: [],
section: 'shots',
visibleLimit: 1,
editorV4: true,
nativeAvailable: true,
busy: false,
})
try {
ui.bindings.stage('two_person_turns')
expect(manifest.schema_version).toBe(4)
expect(manifest.spec.schema_version).toBe(6)
expect(shot.performance.dialogue_staging).toBe('two_person_turns')
shot.performance.visible_speaker_ids = ['left', 'right']
shot.performance.first_frame_sha256 = 'f'.repeat(64)
ui.bindings.swapSides()
expect(shot.performance.visible_speaker_ids).toEqual(['right', 'left'])
expect(shot.performance.first_frame_sha256).toBeUndefined()
} finally {
ui.unmount()
}
})
it('offers manual selection only for a server-authorized reviewable candidate', async () => {
const r: TurnReview = {
shot_id: 'shot',
report_sha256: 'f'.repeat(64),
video_asset_id: 'video',
can_accept: true,
report: {
policy: 'policy',
decision: 'indeterminate',
turns: ['a', 'b'].map((id, i) => ({
utterance_id: id,
expected_speaker_id: id,
listener_id: i ? 'a' : 'b',
start_sample: i * 48000,
end_sample: (i + 1) * 48000,
decision: 'indeterminate',
})),
},
}
const run = { id: 'run', draft_id: 'draft', version: 3 } as RunDTO
const render = () => renderToString(createSSRApp(TurnReviewPanel, { review: r, run }))
expect(await render()).toContain('以当前账号选用此候选')
r.can_accept = false
expect(await render()).not.toContain('以当前账号选用此候选')
r.can_accept = true
r.report.turns[1]!.decision = 'reject'
expect(await render()).not.toContain('以当前账号选用此候选')
})
it('previews the cut allocation before an explicit fork and keeps the original draft id', async () => {
const { manifest } = dialogueFixture()
const rows = [{ speaker_id: 's1', speaker_name: '甲', text: '早。', duration_frames: 124 }]
vi.spyOn(api, 'previewCuts').mockResolvedValue({ shots: rows, warnings: [], name: '副本' })
const fork = vi
.spyOn(api, 'forkCuts')
.mockResolvedValue({ ...dialogueFixture(), draft_id: 'copy', manifest })
const ui = setupHarness(CutForkPreview, {
draftId: 'original',
version: 4,
shotId: 'shot',
dirty: false,
name: '故事',
})
try {
await settle()
expect(ui.bindings.preview.value.shots).toEqual(rows)
expect(fork).not.toHaveBeenCalled()
await ui.bindings.fork()
expect(fork).toHaveBeenCalledWith('original', 4, 'shot', '副本')
expect(ui.events).toEqual([['forked', 'copy']])
} finally {
ui.unmount()
}
})
it('dispatches the selected shot on an exact dual certificate and refuses an adjacent frame count', () => {
const { manifest } = dialogueFixture()
if (manifest.schema_version !== 3) throw Error('fixture')
manifest.schema_version = 4
manifest.spec.schema_version = 6
const d = manifest.spec.dialogue,
shot = manifest.spec.shots[0]!
d.generation = 'native_av'
d.language = 'Chinese'
const first = d.speakers[0]!,
second = { ...first, id: 'b'.repeat(32), entity_id: 'c'.repeat(32), name: '陈叔' }
first.face_reference_asset_id = '1'.repeat(32)
first.voice_reference_asset_id = '2'.repeat(32)
first.model_speaker_number = 3
second.face_reference_asset_id = '3'.repeat(32)
second.voice_reference_asset_id = '4'.repeat(32)
second.model_speaker_number = 4
d.speakers.push(second)
const a = d.utterances[0]!,
b = { ...a, id: 'd'.repeat(32), speaker_id: second.id, text: '好。' }
d.utterances.push(b)
d.sequences[0]!.utterance_ids = [a.id, b.id]
manifest.bindings['frame:' + shot.id] = {
asset_id: 'frame',
source: 'manual',
kind: 'image',
sha256: 'e'.repeat(64),
}
shot.video_parameters.profile = 'minimax-h3-fl2va-native-av-tp2-v1'
shot.video_parameters.source_frames = 158
shot.edit.duration_frames = 158
Object.assign(shot.performance, {
duration_mode: 'fixed',
dialogue_staging: 'two_person_turns',
first_frame_sha256: 'e'.repeat(64),
native_utterance_ids: [a.id, b.id],
visible_speaker_ids: [first.id, second.id],
})
const cap = {
supported: true,
available: true,
profile: shot.video_parameters.profile,
num_frames: 158,
reason: null,
}
const ui = setupHarness(DialogueEditor, {
manifest,
shot,
section: 'shots',
busy: false,
editorV4: true,
nativeAvailable: true,
twoPerson: cap,
visibleLimit: 2,
assets: [],
})
try {
ui.bindings.runTarget('video')
expect(ui.events).toEqual([['target', 'video', shot.id, true]])
ui.setProps({ twoPerson: { ...cap, num_frames: 141 } })
ui.bindings.runTarget('video')
expect(ui.events).toHaveLength(1)
} finally {
ui.unmount()
}
})
it('labels a candidate with its frozen dialogue and submits the run version and report digest', async () => {
const { manifest } = dialogueFixture()
if (manifest.schema_version !== 3) throw Error('fixture')
const dialogue = manifest.spec.dialogue,
a = dialogue.utterances[0]!,
speaker = dialogue.speakers[0]!
const run = {
id: 'run',
draft_id: 'draft',
version: 14,
frozen_spec: manifest.spec,
} as unknown as RunDTO
const review: TurnReview = {
shot_id: 'shot',
report_sha256: 'e'.repeat(64),
video_asset_id: 'video',
can_accept: true,
report: {
policy: 'h3-two-person-turns-screen-v1',
decision: 'indeterminate',
turns: [a.id, 'reply'].map((id, i) => ({
utterance_id: id,
expected_speaker_id: i ? 'other' : speaker.id,
listener_id: i ? speaker.id : 'other',
start_sample: i * 48000,
end_sample: (i + 1) * 48000,
decision: 'indeterminate',
})),
},
}
const video = { id: 'video', kind: 'video', preview_url: '/api/assets/video/content' }
const ui = setupHarness(TurnReviewPanel, { run, review, video })
try {
expect(ui.bindings.name(speaker.id)).toBe(speaker.name)
expect(ui.bindings.words(a.id)).toBe(a.text)
const submit = vi
.spyOn(api, 'reviewTurnCandidate')
.mockResolvedValue({ run, steps: [], jobs: [] })
ui.bindings.note.value = '复核通过'
ui.bindings.watched.value = [a.id, 'reply']
await ui.bindings.accept()
expect(submit).toHaveBeenCalledWith(
'draft',
'run',
'shot',
14,
review.report_sha256,
'复核通过',
)
expect(ui.events[0]?.[0]).toBe('updated')
} finally {
ui.unmount()
}
})
it('keeps the single-speaker shot limit when the global capability also certifies two-person staging', () => {
const { manifest } = dialogueFixture()
if (manifest.schema_version !== 3) throw Error('fixture')
manifest.spec.dialogue.generation = 'native_av'
const d = manifest.spec.dialogue,
one = d.speakers[0]!,
two = { ...one, id: 'b'.repeat(32), entity_id: 'c'.repeat(32) }
d.speakers.push(two)
const shot = manifest.spec.shots[0]!
shot.performance.visible_speaker_ids = [one.id]
shot.cast = [one, two].map((s, i) => ({
id: String(i + 1).repeat(32),
entity_id: s.entity_id!,
form_id: null,
appearance_id: null,
position: '',
action: '',
}))
const v = setupHarness(DialogueEditor, {
manifest,
shot,
section: 'shots',
busy: false,
editorV4: true,
nativeAvailable: true,
visibleLimit: 2,
assets: [],
})
try {
v.bindings.visiblePerson(two, true)
expect(shot.performance.visible_speaker_ids).toEqual([one.id])
} finally {
v.unmount()
}
})
it('does not offer staging upgrades on a server which only accepts V1–V3 editors', async () => {
const { manifest } = dialogueFixture()
if (manifest.schema_version !== 3) throw Error('fixture')
manifest.spec.dialogue.generation = 'native_av'
const html = await renderToString(
createSSRApp(DialogueEditor, {
manifest,
shot: manifest.spec.shots[0],
section: 'shots',
busy: false,
nativeAvailable: true,
visibleLimit: 1,
editorV4: false,
assets: [],
}),
)
expect(html).not.toContain('同框轮流对白')
expect(html).toContain('重新生成本镜头原生对白')
})

View File

@ -96,7 +96,11 @@ export function useEditableProduction(
if (JSON.stringify(manifest.value) === serialized) manifest.value = clone(value.manifest)
return value
}
async function generate(goal: 'media' | 'film', targets: string[] = [], force = false) {
async function generate(
goal: EditorPlanInput['output_goal'],
targets: string[] = [],
force = false,
) {
if (!dto.value || busy.value) return
const current = capture()
busy.value = true
@ -131,7 +135,16 @@ export function useEditableProduction(
const run = await api.runEditor(draftId(), { ...input, expected_plan_hash: p.plan_hash })
if (current()) {
snapshot.value = run
notice.value = goal === 'film' ? '自动成片任务已提交' : '素材任务已提交'
notice.value =
goal === 'mix_film'
? '混音成片任务已提交'
: goal === 'caption_inspect'
? '本镜原声分析已提交'
: goal === 'caption_film'
? '字幕成片任务已提交'
: goal === 'film'
? '自动成片任务已提交'
: '素材任务已提交'
}
} catch (e) {
if (current()) notice.value = errorMessage(e)

View File

@ -0,0 +1,74 @@
import { expect, it } from 'vitest'
import type { CaptionEdit, CaptionRow } from '../../types/editors'
import { editCaption, mergeCaption, splitCaption, updateCaptionEdits } from './captionEdits'
const row: CaptionRow = {
id: '1'.repeat(32),
utterance_id: 'u',
shot_id: 's',
source_text: '喂𠮷君。',
source_start: 0,
source_end: 4,
text: '喂𠮷君',
start_frame: 151,
end_frame: 180,
local_start_frame: 7,
local_end_frame: 36,
status: 'automatic',
text_override: false,
timing_override: false,
}
it('uses Unicode source ranges and local frame boundaries when splitting, preserving other lines', () => {
const [a, b] = splitCaption(row, 2, 20)
expect(a).toMatchObject({
source_start: 0,
source_end: 2,
start_frame: 7,
end_frame: 20,
timing_override: true,
})
expect(b).toMatchObject({ source_start: 2, source_end: 4, start_frame: 20, end_frame: 36 })
expect(a!.id).not.toEqual(b!.id)
const old: CaptionEdit = { ...a!, utterance_id: 'v', deleted: true }
expect(updateCaptionEdits([old], row, [a!, b!])).toEqual([old, a, b])
expect(() => splitCaption(row, 4, 20)).toThrow()
expect(() => splitCaption(row, 2, 36)).toThrow()
})
it('never merges across a turn or across a suppressed source range', () => {
const next = {
...row,
source_start: 4,
source_end: 5,
local_start_frame: 38,
local_end_frame: 47,
}
expect(() => mergeCaption(row, { ...next, utterance_id: 'other' })).toThrow()
expect(() => mergeCaption(row, { ...next, source_start: 5 })).toThrow()
})
it('replaces confirmed remapped edits by persistent ID without dropping an unrelated ambiguous record', () => {
const base = {
id: 'old-left',
utterance_id: 'u',
source_start: 2,
source_end: 4,
source_text: '上个版本',
deleted: false,
timing_override: false,
text_override: true,
text: '改字',
}
const right = { ...base, id: 'old-right' },
ambiguous = { ...base, id: 'unmatched' }
const newEdit = { ...base, id: 'merged', source_text: row.source_text }
expect(
updateCaptionEdits([base, right, ambiguous], row, [newEdit], ['old-left', 'old-right']),
).toEqual([ambiguous, newEdit])
})
it('binds a newly locked or split time span to the current source audio hash', () => {
const source = { ...row, audio_sha256: 'a'.repeat(64) }
expect(editCaption(source)).toMatchObject({ audio_sha256: source.audio_sha256 })
expect(splitCaption(source, 2, 20).every((e) => e.audio_sha256 === source.audio_sha256)).toBe(
true,
)
})

View File

@ -0,0 +1,91 @@
import type { CaptionEdit, CaptionRow } from '../../types/editors'
import { editorId } from './editor'
export function editCaption(row: CaptionRow): CaptionEdit {
return {
id: /^[a-f0-9]{32}$/.test(row.id) ? row.id : editorId(),
utterance_id: row.utterance_id,
source_start: row.source_start,
source_end: row.source_end,
source_text: row.source_text,
...(row.audio_sha256 ? { audio_sha256: row.audio_sha256 } : {}),
deleted: false,
text_override: row.text_override,
timing_override: row.timing_override,
...(row.text_override ? { text: row.text } : {}),
...(row.timing_override && row.local_start_frame !== null && row.local_end_frame !== null
? { start_frame: row.local_start_frame, end_frame: row.local_end_frame }
: {}),
}
}
export function updateCaptionEdits(
edits: CaptionEdit[],
range: Pick<CaptionRow, 'utterance_id' | 'source_start' | 'source_end' | 'source_text'>,
replacements: CaptionEdit[],
replacedIds: string[] = [],
) {
// Stale author text records and tombstones outside this explicit edit remain reviewable.
const others = edits.filter(
(edit) =>
edit.utterance_id !== range.utterance_id ||
(!replacedIds.includes(edit.id) &&
(edit.source_text !== range.source_text ||
edit.source_end <= range.source_start ||
edit.source_start >= range.source_end)),
)
return [...others, ...replacements]
}
export function splitCaption(row: CaptionRow, source: number, frame: number) {
if (row.text_override) throw new Error('请先解除文字锁,再按原文拆分。')
if (!Number.isInteger(source) || source <= row.source_start || source >= row.source_end)
throw new Error('请选择片段内部的原文断点。')
if (
row.local_start_frame === null ||
row.local_end_frame === null ||
!Number.isInteger(frame) ||
frame <= row.local_start_frame ||
frame >= row.local_end_frame
)
throw new Error('请将播放头移到本段内部,再拆分字幕。')
const base = { ...editCaption(row), timing_override: true }
return [
{
...base,
id: editorId(),
source_end: source,
start_frame: row.local_start_frame,
end_frame: frame,
},
{
...base,
id: editorId(),
source_start: source,
start_frame: frame,
end_frame: row.local_end_frame,
},
]
}
export function mergeCaption(first: CaptionRow, next: CaptionRow): CaptionEdit {
if (
first.utterance_id !== next.utterance_id ||
first.shot_id !== next.shot_id ||
first.source_end !== next.source_start ||
first.source_text !== next.source_text ||
first.local_start_frame === null ||
next.local_end_frame === null
)
throw new Error('只能合并同一句内已有时间且原文相邻的字幕。')
const keepText = first.text_override || next.text_override
return {
...editCaption(first),
id: editorId(),
source_end: next.source_end,
timing_override: true,
start_frame: first.local_start_frame,
end_frame: next.local_end_frame,
text_override: keepText,
...(keepText ? { text: first.text + next.text } : {}),
}
}

View File

@ -1,5 +1,14 @@
import type { EditorManifest } from '../../types/editors'
import type { StorySpec, DialogueStorySpec } from '../../types/stories'
import type { DialogueEditorManifest, EditorManifest } from '../../types/editors'
export function isDialogueManifest(
manifest?: EditorManifest | null,
): manifest is DialogueEditorManifest {
return manifest?.schema_version === 3 || manifest?.schema_version === 4
}
export function isDialogueStory(spec?: StorySpec | null): spec is DialogueStorySpec {
return spec?.schema_version === 5 || spec?.schema_version === 6
}
export function upgradeContinuity(manifest: EditorManifest) {
if (
manifest.schema_version !== 1 ||
@ -16,6 +25,7 @@ export function upgradeContinuity(manifest: EditorManifest) {
}
export function writableManifest(editor: number, spec: number, kind: string) {
if (editor === 4) return kind === 'story' && [5, 6].includes(spec)
if (editor === 3) return kind === 'story' && spec === 5
if (editor !== 1 && editor !== 2) return false
return kind === 'story'

View File

@ -1,4 +1,10 @@
import type { EditorManifestV3 } from '../../types/editors'
import type { DialogueCapability } from '../../types/capabilities'
import {
H3_NATIVE_AV_PROFILE,
H3_NATIVE_AV_TP2_PROFILE,
H3_TP2_VIDEO_PROFILE,
} from './videoProfile'
import type { DialogueEditorManifest } from '../../types/editors'
import type {
DialogueSequence,
DialogueSpeaker,
@ -6,14 +12,14 @@ import type {
DialogueVoice,
ShotPerformance,
StoryShotV5,
StorySpecV5,
DialogueStorySpec,
} from '../../types/stories'
import { newRequestId } from '../../utils/requestId'
const id = () => newRequestId().replaceAll('-', '')
export const NATIVE_DIALOGUE_UNAVAILABLE = '上游H3原生音频尚未升级'
export function upgradeNativeDialogue(spec: StorySpecV5) {
export function upgradeNativeDialogue(spec: DialogueStorySpec) {
if (spec.dialogue.generation === 'native_av') return false
// 只修改作者正在编辑的版本;历史素材与旧配音配置留给保存时的兼容处理。
spec.dialogue.generation = 'native_av'
@ -21,14 +27,50 @@ export function upgradeNativeDialogue(spec: StorySpecV5) {
return true
}
export function nativeUtterancesForShot(spec: StorySpecV5, shot: StoryShotV5) {
export function nativeUtterancesForShot(spec: DialogueStorySpec, shot: StoryShotV5) {
const sequence = sequenceForShot(spec, shot)
const lines = utterancesForSequence(spec, sequence)
const selected = shot.performance.native_utterance_ids
if (selected == null) return sequence?.shot_ids.length === 1 ? lines : []
return lines.filter((line) => selected.includes(line.id))
const byId = new Map(lines.map((line) => [line.id, line]))
return selected.flatMap((id) => {
const line = byId.get(id)
return line ? [line] : []
})
}
export function estimatedSpeechSeconds(lines: DialogueUtterance[]) {
return lines.reduce((sum, line) => {
const text = line.spoken_text || line.text
const cjk = /[\u3400-\u9fff\u3040-\u30ff\uac00-\ud7af]/gu
const characters = (text.match(cjk) ?? []).length
const words = (text.replace(cjk, ' ').match(/[\p{L}\p{N}]+/gu) ?? []).length
return sum + characters / 4 + words / 2.4 + 0.25
}, 1)
}
export function twoPersonCertificateIssue(
shot: StoryShotV5,
lines: DialogueUtterance[],
cap?: NonNullable<DialogueCapability['native_av']>['two_person_turns'],
) {
if (shot.performance.dialogue_staging !== 'two_person_turns') return ''
if (cap?.available !== true)
return cap?.reason || '当前配置尚未通过双人同框实测,支持编辑并保存。'
const source = shot.video_parameters
const profile = [H3_NATIVE_AV_TP2_PROFILE, H3_TP2_VIDEO_PROFILE].includes(source.profile ?? '')
? H3_NATIVE_AV_TP2_PROFILE
: H3_NATIVE_AV_PROFILE
const required = Math.max(
124,
source.source_frames ?? Math.ceil((source.source_seconds ?? 5) * 24),
shot.edit.start_frame + shot.edit.duration_frames,
shot.performance.duration_mode === 'auto' ? Math.ceil(estimatedSpeechSeconds(lines) * 24) : 0,
)
const frames = 124 + 17 * Math.ceil((required - 124) / 17)
if (cap.profile !== profile || cap.num_frames !== frames)
return '当前镜头的模型或 ' + frames + ' 帧配置未命中同框证书。'
return ''
}
export const defaultPerformance = (): ShotPerformance => ({
sequence_id: null,
visible_speaker_ids: [],
@ -53,7 +95,7 @@ export function defaultVoice(provider: DialogueVoice['provider'] = 'kokoro'): Di
}
}
export function addSpeaker(spec: StorySpecV5, entityId: string | null) {
export function addSpeaker(spec: DialogueStorySpec, entityId: string | null) {
const entity = spec.entities.find((item) => item.id === entityId && item.kind === 'person')
const speaker: DialogueSpeaker = {
id: id(),
@ -66,7 +108,12 @@ export function addSpeaker(spec: StorySpecV5, entityId: string | null) {
return speaker
}
export function bindSpeaker(spec: StorySpecV5, speaker: DialogueSpeaker, entityId: string | null) {
export function bindSpeaker(
spec: DialogueStorySpec,
speaker: DialogueSpeaker,
entityId: string | null,
) {
if (speaker.entity_id !== entityId) delete speaker.face_reference_asset_id
speaker.entity_id = entityId
for (const shot of spec.shots) {
if (!entityId || !shot.cast.some((member) => member.entity_id === entityId))
@ -74,11 +121,11 @@ export function bindSpeaker(spec: StorySpecV5, speaker: DialogueSpeaker, entityI
}
}
export function sequenceForShot(spec: StorySpecV5, shot: StoryShotV5) {
export function sequenceForShot(spec: DialogueStorySpec, shot: StoryShotV5) {
return spec.dialogue.sequences.find((item) => item.id === shot.performance.sequence_id)
}
export function utterancesForSequence(spec: StorySpecV5, sequence?: DialogueSequence) {
export function utterancesForSequence(spec: DialogueStorySpec, sequence?: DialogueSequence) {
const lines = new Map(spec.dialogue.utterances.map((line) => [line.id, line]))
return (sequence?.utterance_ids ?? []).flatMap((lineId) => {
const line = lines.get(lineId)
@ -86,11 +133,11 @@ export function utterancesForSequence(spec: StorySpecV5, sequence?: DialogueSequ
})
}
export function utterancesForShot(spec: StorySpecV5, shot: StoryShotV5) {
export function utterancesForShot(spec: DialogueStorySpec, shot: StoryShotV5) {
return utterancesForSequence(spec, sequenceForShot(spec, shot))
}
export function beginSequence(spec: StorySpecV5, shot: StoryShotV5) {
export function beginSequence(spec: DialogueStorySpec, shot: StoryShotV5) {
const sequence: DialogueSequence = {
id: id(),
scene_id: shot.scene_id,
@ -100,12 +147,14 @@ export function beginSequence(spec: StorySpecV5, shot: StoryShotV5) {
}
shot.performance.sequence_id = sequence.id
shot.performance.visible_speaker_ids = []
delete shot.performance.listener_reactions
delete shot.performance.first_frame_sha256
delete shot.performance.native_utterance_ids
spec.dialogue.sequences.push(sequence)
return sequence
}
export function detachShot(spec: StorySpecV5, shot: StoryShotV5) {
export function detachShot(spec: DialogueStorySpec, shot: StoryShotV5) {
const sequence = sequenceForShot(spec, shot)
if (!sequence) return
sequence.shot_ids = sequence.shot_ids.filter((shotId) => shotId !== shot.id)
@ -113,10 +162,12 @@ export function detachShot(spec: StorySpecV5, shot: StoryShotV5) {
spec.dialogue.sequences = spec.dialogue.sequences.filter((item) => item !== sequence)
shot.performance.sequence_id = null
shot.performance.visible_speaker_ids = []
delete shot.performance.listener_reactions
delete shot.performance.first_frame_sha256
delete shot.performance.native_utterance_ids
}
export function canChangeSequence(spec: StorySpecV5, shot: StoryShotV5) {
export function canChangeSequence(spec: DialogueStorySpec, shot: StoryShotV5) {
const sequence = sequenceForShot(spec, shot)
return (
!shot.performance.structure_locked &&
@ -127,7 +178,7 @@ export function canChangeSequence(spec: StorySpecV5, shot: StoryShotV5) {
)
}
export function adjacentSequences(spec: StorySpecV5, shot: StoryShotV5) {
export function adjacentSequences(spec: DialogueStorySpec, shot: StoryShotV5) {
const index = spec.shots.indexOf(shot)
return [spec.shots[index - 1], spec.shots[index + 1]].flatMap((neighbor) => {
const sequence = neighbor && sequenceForShot(spec, neighbor)
@ -137,7 +188,7 @@ export function adjacentSequences(spec: StorySpecV5, shot: StoryShotV5) {
})
}
export function setShotSequence(spec: StorySpecV5, shot: StoryShotV5, sequenceId: string) {
export function setShotSequence(spec: DialogueStorySpec, shot: StoryShotV5, sequenceId: string) {
if (!canChangeSequence(spec, shot)) return
if (!sequenceId) {
detachShot(spec, shot)
@ -154,7 +205,7 @@ export function setShotSequence(spec: StorySpecV5, shot: StoryShotV5, sequenceId
}
export function setSpeakerVisible(
spec: StorySpecV5,
spec: DialogueStorySpec,
shot: StoryShotV5,
speakerId: string,
visible: boolean,
@ -162,6 +213,7 @@ export function setSpeakerVisible(
) {
const speakers = shot.performance.visible_speaker_ids
if (!visible) {
if (speakers.includes(speakerId)) delete shot.performance.first_frame_sha256
shot.performance.visible_speaker_ids = speakers.filter((item) => item !== speakerId)
return true
}
@ -173,7 +225,11 @@ export function setSpeakerVisible(
return true
}
export function addUtterance(spec: StorySpecV5, sequence: DialogueSequence, speakerId: string) {
export function addUtterance(
spec: DialogueStorySpec,
sequence: DialogueSequence,
speakerId: string,
) {
const line: DialogueUtterance = {
id: id(),
speaker_id: speakerId,
@ -191,7 +247,7 @@ export function addUtterance(spec: StorySpecV5, sequence: DialogueSequence, spea
sequence.utterance_ids.push(line.id)
}
export function removeUtterance(manifest: EditorManifestV3, lineId: string) {
export function removeUtterance(manifest: DialogueEditorManifest, lineId: string) {
const line = manifest.spec.dialogue.utterances.find((item) => item.id === lineId)
if (!line || line.locked) return
manifest.spec.dialogue.utterances = manifest.spec.dialogue.utterances.filter(
@ -199,6 +255,10 @@ export function removeUtterance(manifest: EditorManifestV3, lineId: string) {
)
for (const sequence of manifest.spec.dialogue.sequences)
sequence.utterance_ids = sequence.utterance_ids.filter((item) => item !== lineId)
for (const shot of manifest.spec.shots)
if (shot.performance.listener_reactions) delete shot.performance.listener_reactions[lineId]
if (manifest.captions.edits)
manifest.captions.edits = manifest.captions.edits.filter((e) => e.utterance_id !== lineId)
for (const shot of manifest.spec.shots)
if (shot.performance.native_utterance_ids)
shot.performance.native_utterance_ids = shot.performance.native_utterance_ids.filter(
@ -208,7 +268,7 @@ export function removeUtterance(manifest: EditorManifestV3, lineId: string) {
}
export function setUtteranceCaption(
manifest: EditorManifestV3,
manifest: DialogueEditorManifest,
line: DialogueUtterance,
text: string,
) {
@ -232,7 +292,7 @@ export function setUtteranceCaption(
})
}
export function audioTimelineEntries(manifest: EditorManifestV3) {
export function audioTimelineEntries(manifest: DialogueEditorManifest) {
const shots = new Map<string, number>()
const scenes = new Map<string, { start: number; end: number } | null>()
let sample = 0

View File

@ -1,5 +1,6 @@
import { isDialogueManifest, isDialogueStory } from './continuity'
import { replaceWorkflowShots } from '../workflows/timeline'
import type { StoryShot, StoryShotV5, StorySpecV5 } from '../../types/stories'
import type { StoryShot, StoryShotV5, DialogueStorySpec } from '../../types/stories'
import type { WorkflowShot } from '../../types/workflows'
import type { EditorManifest, EditorSegment } from '../../types/editors'
import { newRequestId } from '../../utils/requestId'
@ -9,13 +10,13 @@ function renumber(m: EditorManifest) {
// 显式修改结构或时长才升级历史 v1;稳定 ID 与素材绑定不参与旧 key 编号。
if (m.source_kind === 'workflow' && (m.spec.schema_version === 1 || m.spec.schema_version === 2))
m.spec = replaceWorkflowShots(m.spec, m.spec.shots)
else if (m.spec.schema_version === 4 || m.spec.schema_version === 5)
else if (m.spec.schema_version === 4 || (m.source_kind === 'story' && isDialogueStory(m.spec)))
m.spec.render.total_frames = editorFrames(m)
}
export function addEditorShot(m: EditorManifest, shot: StoryShot | WorkflowShot, id: string) {
m.spec.shots.push(shot as never)
m.shot_ids.push(id)
if (m.schema_version === 3 && 'performance' in shot) beginSequence(m.spec, shot as StoryShotV5)
if (isDialogueManifest(m) && 'performance' in shot) beginSequence(m.spec, shot as StoryShotV5)
renumber(m)
}
export function setEditorShotDuration(m: EditorManifest, index: number, frames: number) {
@ -31,7 +32,7 @@ export function moveEditorShot(m: EditorManifest, index: number, target: number)
shot = m.spec.shots.splice(index, 1)[0]!
m.shot_ids.splice(target, 0, id)
m.spec.shots.splice(target, 0, shot as never)
if (m.schema_version === 3)
if (isDialogueManifest(m))
for (const sequence of m.spec.dialogue.sequences)
sequence.shot_ids = m.shot_ids.filter((shotId) => sequence.shot_ids.includes(shotId))
renumber(m)
@ -39,8 +40,8 @@ export function moveEditorShot(m: EditorManifest, index: number, target: number)
}
export function canMoveEditorShot(m: EditorManifest, index: number, target: number) {
if (target < 0 || target >= m.shot_ids.length || !m.shot_ids[index]) return false
if (m.schema_version !== 3) return true
const spec: StorySpecV5 = m.spec
if (!isDialogueManifest(m)) return true
const spec: DialogueStorySpec = m.spec
if (
spec.shots[index]?.performance.structure_locked ||
spec.shots[target]?.performance.structure_locked
@ -54,7 +55,7 @@ export function canMoveEditorShot(m: EditorManifest, index: number, target: numb
})
}
export function removeEditorShot(m: EditorManifest, index: number) {
if (m.schema_version === 3) {
if (isDialogueManifest(m)) {
const shot = m.spec.shots[index]
if (!shot || !canChangeSequence(m.spec, shot)) return false
detachShot(m.spec, shot)

View File

@ -1,3 +1,4 @@
import { isDialogueStory } from '../creation/continuity'
import type {
StorySpec,
StoryShot,
@ -33,7 +34,7 @@ export function createScene(): StoryScene {
}
import { continuityState } from '../creation/continuity'
import { defaultPerformance } from '../creation/dialogue'
export function createShot(version: 5): StoryShotV5
export function createShot(version: 5 | 6): StoryShotV5
export function createShot(version?: number): StoryShot
export function createShot(version: number = 3): StoryShot {
const shot: StoryShot = {
@ -58,7 +59,7 @@ export function createShot(version: number = 3): StoryShot {
shot.continuity = continuityState()
selectNativeProfile(shot)
}
if (version === 5)
if (version === 5 || version === 6)
return {
...shot,
continuity: continuityState(),
@ -173,7 +174,7 @@ function integer(value: number, min: number, max: number, label: string) {
throw new Error(`${label}须为 ${min}–${max} 的整数`)
}
export function validateStory(spec: StorySpec, maxShots = 120) {
const hasSampleTiming = spec.schema_version === 4 || spec.schema_version === 5
const hasSampleTiming = spec.schema_version === 4 || isDialogueStory(spec)
keys(
spec,
[
@ -184,12 +185,12 @@ export function validateStory(spec: StorySpec, maxShots = 120) {
'entities',
'shots',
'render',
...(spec.schema_version === 5 ? ['dialogue'] : []),
...(isDialogueStory(spec) ? ['dialogue'] : []),
],
'故事',
)
if (
![3, 4, 5].includes(spec.schema_version) ||
![3, 4, 5, 6].includes(spec.schema_version) ||
!Array.isArray(spec.shots) ||
!Array.isArray(spec.entities) ||
!Array.isArray(spec.scenes)
@ -245,7 +246,7 @@ export function validateStory(spec: StorySpec, maxShots = 120) {
'video_parameters',
'edit',
...(hasSampleTiming ? ['continuity'] : []),
...(spec.schema_version === 5 ? ['performance'] : []),
...(isDialogueStory(spec) ? ['performance'] : []),
],
'镜头',
)

View File

@ -1,6 +1,7 @@
import { defineStore } from 'pinia'
import { ref } from 'vue'
import { api } from '../api'
import { getSessionGeneration } from '../api/client'
import type { Capability, Scheduler, TaskType, ExecutionPolicy, WorkflowLimits } from '../types'
import type { DialogueCapability } from '../types/capabilities'
@ -22,6 +23,7 @@ export const useCapabilitiesStore = defineStore('capabilities', () => {
max_total_frames: number
}>()
const editableProduction = ref(false)
const editorV4 = ref(false)
const dialogue = ref<DialogueCapability>()
const items = ref<Capability[]>([])
const scheduler = ref<Scheduler | null>(null)
@ -32,16 +34,22 @@ export const useCapabilitiesStore = defineStore('capabilities', () => {
const workflowLimits = ref<WorkflowLimits>({ ...legacyWorkflowLimits })
const environment = ref<'production' | 'preview' | 'test' | null>(null)
const databaseBackend = ref<'mysql' | 'sqlite' | null>(null)
let capabilityRequest = 0
async function load() {
const request = ++capabilityRequest,
session = getSessionGeneration()
const current = () => request === capabilityRequest && session === getSessionGeneration()
continuity.value = undefined
dialogue.value = undefined
editableProduction.value = false
loading.value = true
try {
const [response, status] = await Promise.all([api.capabilities(), api.systemStatus()])
if (!current()) return
items.value = response.items
editableProduction.value = response.editable_production?.schema_version === 1
const editor = response.editable_production
editorV4.value = editor?.supported_schema_versions?.includes(4) === true
dialogue.value = response.dialogue ?? editor?.dialogue
if (
editor?.supported_schema_versions?.includes(2) &&
@ -59,9 +67,10 @@ export const useCapabilitiesStore = defineStore('capabilities', () => {
}
error.value = ''
} catch (caught) {
if (!current()) return
error.value = caught instanceof Error ? caught.message : '无法读取模型能力'
} finally {
loading.value = false
if (current()) loading.value = false
}
}
function forTask(type: TaskType) {
@ -71,6 +80,7 @@ export const useCapabilitiesStore = defineStore('capabilities', () => {
continuity,
dialogue,
editableProduction,
editorV4,
inferenceOnline,
executionPolicy,
workflowLimits,

View File

@ -187,6 +187,7 @@ export const useStoriesStore = defineStore('stories', () => {
spec: StorySpec,
session = epoch,
folders: import('../types/folders').FolderOptions = {},
captionsMode?: 'script' | 'manual' | 'none',
) {
// 请求使用冻结副本;提交期间继续输入不会偷偷改变这次保存/生成的意图。
const frozen = JSON.parse(JSON.stringify(spec)) as StorySpec
@ -194,7 +195,7 @@ export const useStoriesStore = defineStore('stories', () => {
() =>
current
? api.saveStory(current, name, frozen, folders)
: api.createStory(name, frozen, folders),
: api.createStory(name, frozen, folders, captionsMode),
session,
)
if (!value || deleted.value[value.id]) return

View File

@ -78,6 +78,13 @@ export interface DialogueCapability {
supports_single_face?: boolean
supports_two_faces?: boolean
native_av?: {
two_person_turns?: {
supported: boolean
available: boolean
reason?: string | null
profile?: string | null
num_frames?: number | null
}
available: boolean
reason?: string | null
languages?: string[]

View File

@ -1,5 +1,5 @@
import type { Asset } from './assets'
import type { StorySpecV3, StorySpecV4, StorySpecV5, StoryDTO } from './stories'
import type { StorySpecV3, StorySpecV4, DialogueStorySpec, StoryDTO } from './stories'
import type { WorkflowSpec } from './workflows'
export interface EditorBinding {
asset_id: string
@ -9,6 +9,7 @@ export interface EditorBinding {
locked?: boolean
input_hash?: string
context_hash?: string
provenance?: { audio_offset_samples?: number }
generation_parameters?: Record<string, unknown>
}
export interface AudioPosition {
@ -33,6 +34,45 @@ export interface EditorSegment extends AudioPosition {
voice?: string
speed?: number
}
export interface CaptionPresentation {
punctuation: 'hide' | 'preserve'
pacing: 'rhythm' | 'sentence'
}
export interface CaptionEdit {
audio_sha256?: string
id: string
utterance_id: string
source_start: number
source_end: number
source_text: string
deleted: boolean
text_override: boolean
timing_override: boolean
text?: string
start_frame?: number
end_frame?: number
}
export interface CaptionRow {
audio_sha256?: string | null
id: string
utterance_id: string
shot_id: string
source_start: number
source_end: number
source_text: string
text: string
start_frame: number | null
end_frame: number | null
local_start_frame: number | null
local_end_frame: number | null
status: 'automatic' | 'sentence_fallback' | 'manual' | 'pending'
text_override: boolean
timing_override: boolean
}
export interface CaptionPreview {
rows: CaptionRow[]
issues: { code: string; unit_id?: string; message: string }[]
}
export interface EditorCue {
id: string
anchor: 'absolute' | 'shot' | 'audio_segment' | 'utterance'
@ -75,19 +115,29 @@ interface EditorManifestBase {
ducking?: boolean
segments: EditorSegment[]
}
captions: { mode: 'none' | 'manual' | 'script' | 'ai_script'; cues: EditorCue[] }
captions: {
mode: 'none' | 'manual' | 'script' | 'ai_script'
cues: EditorCue[]
presentation?: CaptionPresentation | null
edits?: CaptionEdit[]
}
}
export type EditorManifestLegacy = EditorManifestBase & { schema_version: 1 | 2 } & (
| { source_kind: 'story'; spec: StorySpecV3 | StorySpecV4 }
| { source_kind: 'workflow'; spec: WorkflowSpec }
)
export interface EditorManifestV3 extends EditorManifestBase {
schema_version: 3
export interface DialogueEditorManifest extends EditorManifestBase {
schema_version: 3 | 4
source_kind: 'story'
spec: StorySpecV5
spec: DialogueStorySpec
audio: EditorManifestBase['audio'] & { mix_mode: 'composed' | 'manual_mix' }
}
export type EditorManifest = EditorManifestLegacy | EditorManifestV3
export type EditorManifestV3 = DialogueEditorManifest & {
schema_version: 3
spec: import('./stories').StorySpecV5
}
export type EditorManifestV4 = DialogueEditorManifest & { schema_version: 4 }
export type EditorManifest = EditorManifestLegacy | DialogueEditorManifest
export interface EditorDTO {
editing_mode?: EditingMode
capabilities?: EditingCapabilities
@ -100,12 +150,18 @@ export interface EditorDTO {
issues: { code: string; message: string; shot_id?: string }[]
assets: Asset[]
}
export interface CutPreview {
warnings: string[]
name: string
shots: { speaker_id: string; speaker_name: string; text: string; duration_frames: number }[]
}
export interface PreparedDialogueFork extends EditorDTO {
origin: { source_draft_id: string; source_run_id: string }
}
export type EditorOutputGoal = 'media' | 'film' | 'caption_film' | 'caption_inspect' | 'mix_film'
export interface EditorPlanInput {
expected_version: number
output_goal: 'media' | 'film'
output_goal: EditorOutputGoal
targets: string[]
force: string[]
execution_mode: 'interactive' | 'batch'
@ -113,13 +169,14 @@ export interface EditorPlanInput {
}
export interface EditorPlan {
plan_hash: string
output_goal: 'media' | 'film'
output_goal: EditorOutputGoal
source_version: number
steps: {
key: string
kind: string
unit_id: string
status: 'reuse' | 'generate' | 'pending_dependency'
reason?: string
status: 'reuse' | 'generate' | 'pending_dependency' | 'analyze' | 'manual'
}[]
issues: EditorDTO['issues']
}

View File

@ -64,6 +64,9 @@ export interface DialogueSpeaker {
entity_id: string | null
name: string
voice: DialogueVoice
model_speaker_number?: number | null
face_reference_asset_id?: string | null
voice_reference_asset_id?: string | null
native_voice?: string | null
}
export interface DialogueUtterance {
@ -94,6 +97,9 @@ export interface ShotPerformance {
duration_mode: 'auto' | 'fixed'
structure_locked: boolean
original_audio: 'discard' | 'preserve'
dialogue_staging?: 'two_person_turns' | null
listener_reactions?: Record<string, string>
first_frame_sha256?: string | null
native_utterance_ids?: string[] | null
}
export interface DialogueSpec {
@ -127,12 +133,14 @@ export interface StorySpecV3 extends StorySpecBase {
export interface StorySpecV4 extends StorySpecBase {
schema_version: 4
}
export interface StorySpecV5 extends Omit<StorySpecV4, 'schema_version' | 'shots'> {
schema_version: 5
export interface DialogueStorySpec extends Omit<StorySpecV4, 'schema_version' | 'shots'> {
schema_version: 5 | 6
shots: StoryShotV5[]
dialogue: DialogueSpec
}
export type StorySpec = StorySpecV3 | StorySpecV4 | StorySpecV5
export type StorySpecV5 = DialogueStorySpec & { schema_version: 5 }
export type StorySpecV6 = DialogueStorySpec & { schema_version: 6 }
export type StorySpec = StorySpecV3 | StorySpecV4 | DialogueStorySpec
export type CandidateKind = 'frame' | 'end_frame' | 'video'
export interface StoryIssue {
shot_id?: string

View File

@ -1,4 +1,4 @@
import type { EditorManifest } from './editors'
import type { EditorManifest, EditorOutputGoal } from './editors'
import type { Asset } from './assets'
import type { Job, JobRequest } from './jobs'
export interface WorkflowShot {
@ -44,7 +44,39 @@ export interface DraftDTO {
updated_at: string
}
export type TurnVerdict = 'pass' | 'reject' | 'indeterminate'
export interface TurnReview {
shot_id: string
report_sha256: string
video_asset_id: string
can_accept: boolean
manual_review?: {
note?: string
reviewer_name?: string
reviewed_at?: string
decision?: string
} | null
report: {
policy: string
decision: TurnVerdict
turns: {
utterance_id: string
expected_speaker_id: string
listener_id: string
start_sample: number
end_sample: number
decision: TurnVerdict
voice?: { observed_speaker_id?: string | null }
speaker_sync?: { decision?: TurnVerdict }
listener_sync?: { decision?: TurnVerdict }
listener_rest?: { decision?: TurnVerdict }
reason?: string
}[]
}
}
export interface RunDTO {
frozen_spec?: WorkflowSpec | import('./stories').StorySpec
turn_reviews?: TurnReview[]
phase?: string
quality?: {
accepted_shots: number
@ -59,7 +91,9 @@ export interface RunDTO {
}[]
}
run_kind?: string
output_goal?: 'media' | 'film'
output_goal?: EditorOutputGoal
current_output_asset_id?: string | null
captions_srt_available?: boolean
apply_state?: string | null
production_materialized?: boolean
editor_manifest?: EditorManifest | null

View File

@ -73,12 +73,15 @@ it('story list creates a named automatic folder, existing folder, or explicit un
const v = await mount(StoriesView)
v.storyName.value = 'named'
await v.create()
expect(request.mock.calls[0]?.[3]).toBeUndefined()
useCapabilitiesStore().editorV4 = true
expect(request.mock.calls[0]?.[0]).toBe('named')
expect(request.mock.calls[0]?.[2]).toEqual({ create_folder: true })
v.autoFolder.value = false
v.createFolder.value = 'existing'
await v.create()
expect(request.mock.calls[1]?.[2]).toEqual({ folder_id: 'existing' })
expect(request.mock.calls[1]?.[3]).toBe('script')
v.createFolder.value = null
await v.create()
expect(request.mock.calls[2]?.[2]).toEqual({ folder_id: null })

View File

@ -2,6 +2,7 @@
import { computed, onMounted, ref, watch } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useCapabilitiesStore } from '../stores/capabilities'
import { useStoriesStore } from '../stores/stories'
import { api, errorMessage } from '../api'
import { emptyStory } from '../domain/stories/rules'
@ -10,10 +11,12 @@ import FolderSelect from '../components/FolderSelect.vue'
import FolderManager from '../components/FolderManager.vue'
import FolderAssignment from '../components/FolderAssignment.vue'
import { useFoldersStore } from '../stores/folders'
const production = useCapabilitiesStore()
const folders = useFoldersStore(),
folderFilter = ref<string | null>(''),
storyName = ref('未命名故事'),
autoFolder = ref(true),
dialogueCaptions = ref<'script' | 'manual' | 'none'>('script'),
createFolder = ref<string | null>(null)
const router = useRouter(),
store = useStoriesStore(),
@ -55,6 +58,7 @@ async function create() {
emptyStory(),
store.sessionId(),
autoFolder.value ? { create_folder: true } : { folder_id: createFolder.value },
production.editorV4 ? dialogueCaptions.value : undefined,
)
void folders.refresh()
if (story) await router.push(`/studio/${story.id}`)
@ -148,6 +152,13 @@ onMounted(load)
placeholder="新故事名称"
maxlength="255"
/>
<label v-if="production.editorV4"
>启用中文原生对白后的字幕<select v-model="dialogueCaptions">
<option value="script">自动节奏字幕 · 隐藏句读</option>
<option value="manual">人工字幕</option>
<option value="none">关闭字幕</option>
</select></label
>
<el-checkbox v-model="autoFolder">自动新建同名文件夹</el-checkbox>
<FolderSelect
v-if="!autoFolder"

View File

@ -385,7 +385,7 @@ describe('story studio session and staged editing', () => {
it('keeps a removed mirror shot removed when a queued candidate arrives', async () => {
const initial = story(),
removed = createShot()
if (initial.spec.schema_version === 5) throw new Error('historical story required')
if ('dialogue' in initial.spec) throw new Error('historical story required')
initial.spec.shots.push(removed)
initial.spec.render.total_frames = 240
const view = await editor(initial)

View File

@ -1,4 +1,6 @@
<script setup lang="ts">
import { isDialogueManifest, isDialogueStory } from '../domain/creation/continuity'
import { computed, nextTick, onBeforeUnmount, onMounted, ref, watch } from 'vue'
import { onBeforeRouteLeave, onBeforeRouteUpdate, useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
@ -86,7 +88,7 @@ const editorEnabled = ref(false),
editable = ref<InstanceType<typeof EditableProduction>>()
const canSwitchEditingMode = computed(() => base.value?.capabilities?.mode_switch === true)
const usesDialogue = computed(
() => base.value?.spec.schema_version === 5 || base.value?.editor_manifest?.schema_version === 3,
() => isDialogueStory(base.value?.spec) || isDialogueManifest(base.value?.editor_manifest),
)
const useEditorSurface = computed(() => editorEnabled.value || usesDialogue.value)
const dialogueAuthoringAvailable = computed(
@ -126,7 +128,7 @@ async function enableDialogue() {
return
if (
result.draft_id !== storyId ||
result.manifest.schema_version !== 3 ||
!isDialogueManifest(result.manifest) ||
result.version < base.value!.version
)
throw new Error('对白启用未返回完整编辑版本,请重新读取')
@ -140,7 +142,7 @@ async function enableDialogue() {
editing_mode: result.editing_mode ?? result.manifest.editing_mode ?? 'auto',
capabilities: result.capabilities ?? base.value!.capabilities,
}
if (story.id !== storyId || story.version !== result.version || story.spec.schema_version !== 5)
if (story.id !== storyId || story.version !== result.version || !isDialogueStory(story.spec))
throw new Error('对白启用未返回完整故事,请重新读取')
adopt(story)
store.applyStory(story)
@ -214,7 +216,7 @@ function editorSaved(value: EditorDTO, submittedName?: string) {
revision: value.revision,
name: value.name ?? base.value.name,
editor_manifest: value.manifest,
...(value.manifest.schema_version === 3 ? { spec: value.manifest.spec } : {}),
...(isDialogueManifest(value.manifest) ? { spec: value.manifest.spec } : {}),
editing_mode:
value.editing_mode ?? value.manifest.editing_mode ?? base.value.editing_mode ?? 'auto',
capabilities: value.capabilities ?? base.value.capabilities,
@ -597,14 +599,14 @@ async function selectedAsset(asset: Asset) {
)
}
function addShot() {
if (spec.value.schema_version === 5 || spec.value.shots.length >= (caps.value?.max_shots || 120))
if (isDialogueStory(spec.value) || spec.value.shots.length >= (caps.value?.max_shots || 120))
return
const shot = createShot(spec.value.schema_version)
spec.value = replaceShots(spec.value, [...spec.value.shots, shot])
shotId.value = shot.id
}
function moveShot(offset: number) {
if (spec.value.schema_version === 5) return
if (isDialogueStory(spec.value)) return
const index = spec.value.shots.findIndex((s) => s.id === shotId.value),
target = index + offset
if (index < 0 || target < 0 || target >= spec.value.shots.length) return
@ -613,7 +615,7 @@ function moveShot(offset: number) {
spec.value = replaceShots(spec.value, shots)
}
function removeShot() {
if (spec.value.schema_version === 5 || spec.value.shots.length <= 1) return
if (isDialogueStory(spec.value) || spec.value.shots.length <= 1) return
spec.value = replaceShots(
spec.value,
spec.value.shots.filter((s) => s.id !== shotId.value),
@ -696,7 +698,7 @@ watch(
(story.editor_manifest ? 'auto' : 'manual')) === 'auto'
if (
useEditorSurface.value &&
(serverAuto || story.spec.schema_version === 5) &&
(serverAuto || isDialogueStory(story.spec)) &&
editable.value?.syncFromServer
) {
const storyId = id.value,

Some files were not shown because too many files have changed in this diff Show More