1528 lines
56 KiB
Python
1528 lines
56 KiB
Python
"""Prepare the original '雨夜归途' production through the local business API."""
|
||
|
||
import argparse
|
||
import json
|
||
import math
|
||
import sys
|
||
import time
|
||
import wave
|
||
from array import array
|
||
from contextlib import contextmanager
|
||
from copy import deepcopy
|
||
from hashlib import sha256
|
||
from pathlib import Path
|
||
from uuid import NAMESPACE_URL, uuid5
|
||
|
||
if __package__:
|
||
from .local_dev import read_env
|
||
else:
|
||
from local_dev import read_env
|
||
|
||
|
||
ROOT = Path(__file__).resolve().parents[1]
|
||
OUTPUT = ROOT / "outputs" / "雨夜归途_多人对白示例_20261126"
|
||
STATE = OUTPUT / "production-state.json"
|
||
BASE_URL = "http://127.0.0.1:8000/api"
|
||
STUDIO_URL = "http://127.0.0.1:5173/studio"
|
||
TP2 = "minimax-h3-fl2va-bf16-tp2-v1"
|
||
TERMINAL = {"succeeded", "failed", "cancelled", "timed_out"}
|
||
CHARACTERS = {
|
||
"lin": (
|
||
"林晚",
|
||
(
|
||
"27岁中国女性,深棕齐肩直发自然中分,右耳后夹一枚小黑发夹,"
|
||
"穿深墨绿色防水通勤外套,米白针织领,肩上少量雨珠,神情克制而疲惫。"
|
||
),
|
||
261101,
|
||
),
|
||
"xu": (
|
||
"许舟",
|
||
(
|
||
"28岁中国男青年,短黑发侧分,略方下颌,上唇与下巴刮得干净光滑,"
|
||
"穿深蓝工装外套和浅灰衬衫,袖口有少许雨痕,神情平和而专注。"
|
||
),
|
||
261102,
|
||
),
|
||
"chen": (
|
||
"陈叔",
|
||
(
|
||
"58岁中国男性,灰黑短发,额头有浅浅纹路,方形面孔,"
|
||
"穿棕色厚毛衣和洗旧的深灰帆布围裙,神情稳重亲切。"
|
||
),
|
||
261103,
|
||
),
|
||
}
|
||
SETTING = (
|
||
"秋季雨夜,老居民区临街的旧修鞋铺,墨绿木门框,琥珀色台灯"
|
||
"和窗外蓝灰冷光,窗玻璃上有细雨,柜台后虚化的旧木抽屉,无可读文字。"
|
||
)
|
||
FRAMING = (
|
||
"写实中国城市生活电影剧照,横构图,胸口以上近景,脸在画面中部靠上,清晰对焦。"
|
||
"摄影机与眼睛平齐,脸朝摄影机偏侧不超过十五度,双眼都可见,两颊直到下颌无遮挡,"
|
||
"嘴唇自然闭合,室内暖色柔和主光和自然皮肤纹理,头发和手不挡脸。画面只有一个成年人。"
|
||
)
|
||
BASE_MOTION = (
|
||
"同一名原创年轻女性在雨夜修鞋铺门口的连续六秒电影近景,保持参考图里同一张脸、发型和墨绿外套,"
|
||
"取景从胸口到发顶,面部完整清晰。她轻吸一口气,目光短暂转向画面右侧的店主,"
|
||
"保持近正面的安静倾听姿态,双唇放松自然合拢,目光回到前方。"
|
||
"她用一只手轻松握住胸口下方的背包带,肩膀慢慢放下,眨一次眼。窗外雨滴真实滑落,"
|
||
"室内暖灯恒定,镜头轻缓向前,眼睛和嘴唇保持清晰,始终只有一个人入镜。"
|
||
"不出现道具遮挡脸、台词字样、第二张脸、镜头切换、冻结画面和夸张表情。"
|
||
)
|
||
VOICES = {
|
||
"lin": (
|
||
"lin_wan",
|
||
"年轻成年女性,中低音区,标准普通话,略带疲倦,气息轻柔,语气克制,字头清楚。",
|
||
"雨还没停,我在门边等一会儿。你慢慢来,别把钥匙掉在水里。",
|
||
),
|
||
"xu": (
|
||
"xu_zhou",
|
||
"年轻成年男性,温和清亮的中音,标准普通话,自然短停顿,平静干练。",
|
||
"你把伞往这边收一收。路口有积水,我们从台阶这边过去。",
|
||
),
|
||
"chen": (
|
||
"chen_shu",
|
||
"近六十岁的成年男性,沉稳的低男声,声音稍厚稍沙,标准普通话,亲切舒缓。",
|
||
"灯我给你留着。鞋跟慢慢踩,等雨再小一点,过了门口就是干路。",
|
||
),
|
||
}
|
||
SHOTS = (
|
||
(
|
||
"檐下借步",
|
||
"lin",
|
||
6,
|
||
"老板,我能在这里站一会儿吗?",
|
||
"从画面左侧朝暖光处微微探身,抬眼看向柜台,用手在胸下轻握肩带。",
|
||
),
|
||
(
|
||
"门里暖灯",
|
||
"chen",
|
||
5,
|
||
"往里走吧,门口风大。",
|
||
"抬起眼睛并轻轻点头,右手在桌面高度招呼来人。",
|
||
),
|
||
(
|
||
"接过纸袋",
|
||
"xu",
|
||
6,
|
||
"袋子给我吧,柜台这边是干的。",
|
||
"以自然幅度探身接纸袋,纸袋从画面下缘入镜,视线随袋子回到对面。",
|
||
),
|
||
(
|
||
"只是避雨",
|
||
"lin",
|
||
6,
|
||
"谢谢,我只是来躲雨的,等雨小一点就走。",
|
||
"抿一下嘴角,扫一眼门外的落雨,肩膀小幅放松。",
|
||
),
|
||
(
|
||
"松动的鞋跟",
|
||
"chen",
|
||
6,
|
||
"鞋跟都开了,下个台阶就得掉。",
|
||
"短暂垂眼看向柜台外地面,掌心朝下比一个小间隙,然后看回前方。",
|
||
),
|
||
(
|
||
"收回半步",
|
||
"lin",
|
||
5,
|
||
"",
|
||
"保持嘴唇闭合,试探性低头又收住身体,呼吸稍停,握肩带的指尖放松。",
|
||
),
|
||
(
|
||
"右手边有凳子",
|
||
"xu",
|
||
6,
|
||
"别踩了。把脚抬一点,凳子在右手边。",
|
||
"从画面下部把小凳推到一侧,身体回正,眼睛看向画外正前方。",
|
||
),
|
||
(
|
||
"路变了",
|
||
"lin",
|
||
5,
|
||
"我刚搬回来,路都认不全。",
|
||
"靠在凳背,把头转回轻微右侧,窗上蓝光从侧脸滑过。",
|
||
),
|
||
(
|
||
"哪栋楼",
|
||
"chen",
|
||
5,
|
||
"住哪里?这条街我守了大半辈子。",
|
||
"手中小刷子停下,抬起目光询问,眉尖有轻微变化。",
|
||
),
|
||
(
|
||
"小时候的灰楼",
|
||
"lin",
|
||
5,
|
||
"五号楼。小时候叫它灰楼。",
|
||
"眼睛看向门外片刻,声音回到近处,后半句带一点迟疑的微笑。",
|
||
),
|
||
(
|
||
"槐树还在",
|
||
"chen",
|
||
6,
|
||
"那栋楼还在。楼下那棵槐树,比我还老。",
|
||
"手指在柜台边轻敲两下,笑一下,眼神仍然朝向画外来客。",
|
||
),
|
||
(
|
||
"把灯转近",
|
||
"xu",
|
||
5,
|
||
"",
|
||
"嘴唇闭合,把台灯灯座在胸下推近一点,观察画面外柜台上的工具,随后抬眼。",
|
||
),
|
||
(
|
||
"同路",
|
||
"xu",
|
||
5,
|
||
"我也住五号楼,一起过马路吧。",
|
||
"抬头跟画外来客打个手势,转回接近正面后轻声说话。",
|
||
),
|
||
(
|
||
"那扇旧门",
|
||
"lin",
|
||
5,
|
||
"那扇旧门,推开还是从前的声音吗?",
|
||
"微偏头,抬起眉毛询问,视线落在镜头外左侧,手指在膝上轻虚点一下。",
|
||
),
|
||
(
|
||
"声音也装回来了",
|
||
"xu",
|
||
6,
|
||
"以前装过新门。大家更喜欢现在这一扇。",
|
||
"嘴角带笑,掌心在胸下比一下推门动作,肩膀轻微起伏。",
|
||
),
|
||
(
|
||
"先踩稳",
|
||
"chen",
|
||
5,
|
||
"抬脚试试。慢一点,先别急着走。",
|
||
"放下工具,抬眼示意,轻轻往前点头,手在画面下方退开。",
|
||
),
|
||
(
|
||
"三次折返",
|
||
"lin",
|
||
6,
|
||
"我今天想了三次,到了路口又折回去。",
|
||
"摊开手掌又握住,短暂垂眼,句尾重新把视线落到画外听者。",
|
||
),
|
||
(
|
||
"鞋能走就往前",
|
||
"chen",
|
||
5,
|
||
"回来就好。路还长,慢慢往前走。",
|
||
"整理一下围裙后把手放下,眼睛温和地看向门边。",
|
||
),
|
||
(
|
||
"绕开积水",
|
||
"xu",
|
||
6,
|
||
"雨小了。门口有积水,我带你绕过去。",
|
||
"瞥了一眼窗外,重新转回浅角度,手指在身体下侧指向门边。",
|
||
),
|
||
(
|
||
"雨声变轻",
|
||
"lin",
|
||
5,
|
||
"",
|
||
"闭着嘴看窗外雨滴,呼吸缓下来,眨眼后露出轻微微笑,双手在胸口以下提起包带。",
|
||
),
|
||
(
|
||
"第三扇窗",
|
||
"lin",
|
||
5,
|
||
"走吧。第三扇窗,我还认得。",
|
||
"站直但维持胸像构图,目光往窗外抬一点,脸保持接近正面。",
|
||
),
|
||
(
|
||
"把伞拿上",
|
||
"chen",
|
||
6,
|
||
"等一下,伞拿上。进门了再收,别着急。",
|
||
"把一把合上的旧布伞从腰间递出画面,伞尖低于肩部,不遮脸,句末望着门外。",
|
||
),
|
||
)
|
||
SAMPLE_RATE = 48000
|
||
BGM_NAME = "檐灯_原创配乐.wav"
|
||
|
||
|
||
def write_json(path, value):
|
||
temporary = path.with_suffix(path.suffix + ".tmp")
|
||
with temporary.open("w", encoding="utf-8", newline="\n") as handle:
|
||
json.dump(value, handle, ensure_ascii=False, indent=2)
|
||
handle.write("\n")
|
||
temporary.replace(path)
|
||
|
||
|
||
def read_state():
|
||
if STATE.exists():
|
||
return json.loads(STATE.read_text(encoding="utf-8"))
|
||
return {"project": "雨夜归途", "api": BASE_URL, "jobs": {}, "artifacts": {}}
|
||
|
||
|
||
def stable_id(key):
|
||
return uuid5(NAMESPACE_URL, "cmvr:dialogue:rainy-way-home:20261126:" + key).hex
|
||
|
||
|
||
def requested_frames(constraints, seconds, fps):
|
||
minimum, maximum, step = (constraints[name] for name in ("min", "max", "step"))
|
||
target = seconds * fps + 1
|
||
if not minimum <= target <= maximum or (target - minimum) % step:
|
||
raise ValueError("请求时长不符合已认证模型的原生帧数网格")
|
||
return target
|
||
|
||
|
||
@contextmanager
|
||
def local_session():
|
||
import httpx
|
||
|
||
config = read_env(ROOT / ".env.local")
|
||
with httpx.Client(base_url=BASE_URL, timeout=30, trust_env=False) as client:
|
||
login = client.post(
|
||
"/auth/login",
|
||
json={
|
||
"username": config["ADMIN_USERNAME"],
|
||
"password": config["ADMIN_PASSWORD"],
|
||
},
|
||
)
|
||
login.raise_for_status()
|
||
client.headers["X-CSRF-Token"] = login.json()["csrf_token"]
|
||
try:
|
||
yield client
|
||
finally:
|
||
try:
|
||
client.post("/auth/logout")
|
||
except httpx.RequestError:
|
||
pass
|
||
|
||
|
||
def announce(*parts):
|
||
print(*parts, flush=True)
|
||
|
||
|
||
def response_json(response):
|
||
if not response.is_success:
|
||
try:
|
||
payload = response.json()
|
||
except ValueError:
|
||
payload = {}
|
||
error = (
|
||
(payload.get("error") or payload.get("detail"))
|
||
if isinstance(payload, dict)
|
||
else None
|
||
)
|
||
if isinstance(error, dict):
|
||
code, message = (
|
||
error.get("code", "request_failed"),
|
||
error.get("message", ""),
|
||
)
|
||
elif isinstance(error, str):
|
||
code, message = "request_failed", error
|
||
else:
|
||
code, message = "request_failed", ""
|
||
retry = response.headers.get("Retry-After")
|
||
context = f" (Retry-After: {retry})" if retry else ""
|
||
raise RuntimeError(
|
||
f"HTTP {response.status_code}: {code} {message}{context}".strip()
|
||
)
|
||
return response.json()
|
||
|
||
|
||
def submit_job(client, state, name, payload):
|
||
jobs = state["jobs"]
|
||
if name not in jobs:
|
||
jobs[name] = {
|
||
"idempotency_key": stable_id("job:" + name),
|
||
"request": payload,
|
||
"state": "submitting",
|
||
}
|
||
write_json(STATE, state)
|
||
entry = jobs[name]
|
||
if entry.get("id"):
|
||
return entry
|
||
result = response_json(
|
||
client.post(
|
||
"/jobs",
|
||
json=entry["request"],
|
||
headers={"Idempotency-Key": entry["idempotency_key"]},
|
||
)
|
||
)
|
||
(job,) = result["jobs"]
|
||
entry.update(id=job["id"], state=job["state"])
|
||
write_json(STATE, state)
|
||
announce(name, "job", entry["id"], entry["state"])
|
||
return entry
|
||
|
||
|
||
def poll_job(client, state, name):
|
||
entry = state["jobs"][name]
|
||
if entry.get("asset_id"):
|
||
return entry
|
||
job = response_json(client.get("/jobs/" + entry["id"]))
|
||
status = job["state"]
|
||
if status != entry["state"]:
|
||
entry["state"] = status
|
||
write_json(STATE, state)
|
||
announce(name, "job", entry["id"], status)
|
||
if status == "succeeded":
|
||
expected_kind = (
|
||
"image"
|
||
if name.startswith("reference-")
|
||
else "audio"
|
||
if entry["request"]["task_type"].startswith("audio.")
|
||
else "video"
|
||
)
|
||
asset = next(
|
||
item for item in job["result_assets"] if item["kind"] == expected_kind
|
||
)
|
||
entry.update(
|
||
asset_id=asset["id"],
|
||
kind=asset["kind"],
|
||
mime_type=asset["mime_type"],
|
||
duration_seconds=asset["duration_seconds"],
|
||
)
|
||
write_json(STATE, state)
|
||
announce(name, "asset", asset["id"], asset["duration_seconds"])
|
||
elif status in TERMINAL:
|
||
error = job.get("error") or {}
|
||
entry["error"] = {"code": error.get("code"), "message": error.get("message")}
|
||
write_json(STATE, state)
|
||
return entry
|
||
|
||
|
||
def export_asset(client, state, name, *, basename=None):
|
||
entry = state["jobs"][name]
|
||
suffix = {
|
||
"image/png": ".png",
|
||
"image/jpeg": ".jpg",
|
||
"image/webp": ".webp",
|
||
"video/mp4": ".mp4",
|
||
"audio/wav": ".wav",
|
||
"audio/x-wav": ".wav",
|
||
}[entry["mime_type"]]
|
||
target = OUTPUT / ((basename or name) + suffix)
|
||
if (
|
||
target.exists()
|
||
and entry.get("file") == target.name
|
||
and entry.get("exported_asset_id") == entry["asset_id"]
|
||
and sha256(target.read_bytes()).hexdigest() == entry.get("sha256")
|
||
):
|
||
return
|
||
temporary = target.with_suffix(suffix + ".tmp")
|
||
checksum = sha256()
|
||
with client.stream("GET", f"/assets/{entry['asset_id']}/content") as response:
|
||
response.raise_for_status()
|
||
with temporary.open("wb") as output:
|
||
for chunk in response.iter_bytes():
|
||
checksum.update(chunk)
|
||
output.write(chunk)
|
||
temporary.replace(target)
|
||
entry.update(
|
||
file=target.name,
|
||
exported_asset_id=entry["asset_id"],
|
||
sha256=checksum.hexdigest(),
|
||
size_bytes=target.stat().st_size,
|
||
)
|
||
write_json(STATE, state)
|
||
|
||
|
||
def queue_samples():
|
||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||
state = read_state()
|
||
with local_session() as client:
|
||
capabilities = {
|
||
item["task_type"]: item
|
||
for item in response_json(client.get("/capabilities"))["items"]
|
||
}
|
||
image = capabilities["image.generate"]
|
||
profile = next(
|
||
item
|
||
for item in capabilities["video.generate"]["video_profiles"]
|
||
if item["profile"] == TP2
|
||
)
|
||
if not image["available"] or not profile["available"]:
|
||
raise RuntimeError("本地业务队列还未开放人物图或 H3 双卡视频能力")
|
||
fps = profile["defaults"]["fps"]
|
||
frames = requested_frames(profile["constraints"]["num_frames"], 6, fps)
|
||
reference_names = []
|
||
for character, (_, appearance, seed) in CHARACTERS.items():
|
||
name = "reference-" + character
|
||
reference_names.append(name)
|
||
submit_job(
|
||
client,
|
||
state,
|
||
name,
|
||
{
|
||
"task_type": "image.generate",
|
||
"input": {"prompt": f"{FRAMING}{appearance}{SETTING}"},
|
||
"parameters": {
|
||
"width": 1344,
|
||
"height": 768,
|
||
"num_inference_steps": 30,
|
||
"guidance_scale": 4.0,
|
||
"seed": seed,
|
||
},
|
||
"execution_mode": "batch",
|
||
},
|
||
)
|
||
sample = "sample-01-h3-tp2"
|
||
while True:
|
||
for name in reference_names:
|
||
entry = poll_job(client, state, name)
|
||
if entry.get("asset_id"):
|
||
export_asset(client, state, name)
|
||
lin = state["jobs"]["reference-lin"]
|
||
if lin.get("asset_id"):
|
||
submit_job(
|
||
client,
|
||
state,
|
||
sample,
|
||
{
|
||
"task_type": "video.generate",
|
||
"input": {
|
||
"prompt": BASE_MOTION,
|
||
"image_asset_id": lin["asset_id"],
|
||
},
|
||
"parameters": {
|
||
"profile": TP2,
|
||
"width": profile["defaults"]["width"],
|
||
"height": profile["defaults"]["height"],
|
||
"num_frames": frames,
|
||
"fps": fps,
|
||
"num_inference_steps": 20,
|
||
"seed": 261201,
|
||
"upscale": False,
|
||
},
|
||
"execution_mode": "batch",
|
||
},
|
||
)
|
||
if poll_job(client, state, sample).get("asset_id"):
|
||
export_asset(client, state, sample)
|
||
jobs = state["jobs"]
|
||
references_done = all(
|
||
jobs[name]["state"] in TERMINAL for name in reference_names
|
||
)
|
||
sample_done = (
|
||
lin["state"] != "succeeded"
|
||
or jobs.get(sample, {}).get("state") in TERMINAL
|
||
)
|
||
if references_done and sample_done:
|
||
break
|
||
time.sleep(12)
|
||
for name in [*reference_names, sample]:
|
||
if jobs.get(name, {}).get("state") != "succeeded":
|
||
raise RuntimeError(f"{name} 未成功。保留任务回执供检查。")
|
||
|
||
|
||
def build_story(state):
|
||
scene_id = stable_id("scene:shoe-repair-shop")
|
||
entities = {}
|
||
speakers = {}
|
||
for key, (name, appearance, seed) in CHARACTERS.items():
|
||
image = state["jobs"].get("reference-" + key, {}).get("asset_id")
|
||
alias, style, reference_text = VOICES[key]
|
||
voice_asset = state.get("voice_references", {}).get(key, {})
|
||
voice_id = voice_asset.get("asset_id")
|
||
entities[key] = {
|
||
"id": stable_id("entity:" + key),
|
||
"name": name,
|
||
"kind": "person",
|
||
"description": appearance,
|
||
"reference_asset_ids": [image] if image else [],
|
||
"forms": [],
|
||
"appearances": [],
|
||
}
|
||
speakers[key] = {
|
||
"id": stable_id("speaker:" + key),
|
||
"entity_id": entities[key]["id"],
|
||
"name": name,
|
||
"voice": {
|
||
"provider": "kokoro" if key == "xu" else "voxcpm2",
|
||
"model": "kokoro-82m" if key == "xu" else "voxcpm2",
|
||
"voice": "zm_yunxi" if key == "xu" else alias,
|
||
"reference_asset_id": voice_id,
|
||
"reference_text": voice_asset.get("reference_text")
|
||
or voice_asset.get("text", reference_text)
|
||
if voice_id and key != "xu"
|
||
else "",
|
||
"style": "" if key == "xu" else style,
|
||
"speed": {"lin": 1.04, "xu": 1.04, "chen": 1.0}[key],
|
||
"seed": 42 if key == "xu" else seed,
|
||
"revision": 1,
|
||
},
|
||
}
|
||
|
||
shots, lines, sequences = [], [], []
|
||
angles = (
|
||
"镜头靠门,人物位于画面偏右,望向左侧柜台,近正面。",
|
||
"镜头在柜台高度,人物位于画面偏左,望向右侧来客,另一眼完整可见。",
|
||
"镜头在台灯旁略靠前,为双眼到肩部的较紧近景,眼神稍偏镜头外。",
|
||
)
|
||
for i, (title, speaker, seconds, line, action) in enumerate(SHOTS, 1):
|
||
entity = entities[speaker]
|
||
uid = f"{i:02d}"
|
||
shot_id = stable_id("shot:" + uid)
|
||
seq_id = stable_id("sequence:" + uid)
|
||
line_ids = []
|
||
if line:
|
||
line_id = stable_id("line:" + uid)
|
||
take = (
|
||
state.get("production", {})
|
||
.get("selected_speech_takes", {})
|
||
.get(line_id, {})
|
||
)
|
||
line_ids.append(line_id)
|
||
lines.append(
|
||
{
|
||
"id": line_id,
|
||
"speaker_id": speakers[speaker]["id"],
|
||
"text": line,
|
||
"spoken_text": None,
|
||
"source": "asset" if take.get("asset_id") else "tts",
|
||
"asset_id": take.get("asset_id"),
|
||
"source_start_sample": 0,
|
||
"source_end_sample": None,
|
||
"gap_after_sample": 9600,
|
||
"delivery": "",
|
||
"locked": False,
|
||
}
|
||
)
|
||
angle = (
|
||
"正面固定胸像,双眼与双唇完整清晰,双肩水平,目光稍偏镜头外,脸部大小稳定。"
|
||
if speaker == "xu"
|
||
else angles[(i - 1) % len(angles)]
|
||
)
|
||
camera = (
|
||
"。固定摄影机和取景范围,始终近正面,只用轻微目光变化表达,不抬高下巴。"
|
||
if speaker == "xu"
|
||
else ",镜头轻缓自然。"
|
||
)
|
||
shots.append(
|
||
{
|
||
"id": shot_id,
|
||
"name": title,
|
||
"scene_id": scene_id,
|
||
"cast": [
|
||
{
|
||
"id": stable_id("cast:" + uid),
|
||
"entity_id": entity["id"],
|
||
"form_id": None,
|
||
"appearance_id": None,
|
||
"position": "胸像近景,双眼及双唇完整可见。",
|
||
"action": action,
|
||
}
|
||
],
|
||
"visual_prompt": (
|
||
f"{FRAMING}{entity['description']}{SETTING}{angle}"
|
||
f"镜头情节是「{title}」,画面选在动作刚开始时,脸部始终完整。{action}"
|
||
),
|
||
"motion_prompt": BASE_MOTION
|
||
if i == 1
|
||
else (
|
||
f"连续{seconds}秒写实电影近景,同一张参考脸、发型和服装,清晰对焦。{action}"
|
||
"只有一位成年人,面部接近正面;不遮嘴、不换脸、无字幕"
|
||
+ camera
|
||
+ ("她" if speaker == "lin" else "他")
|
||
+ (
|
||
"保持放松闭唇,只表演上述肢体与眼神动作,头部不过度转动。"
|
||
if line
|
||
else "保持合嘴,自然呼吸与眨眼。"
|
||
)
|
||
),
|
||
"overrides": {},
|
||
"frame_parameters": {"seed": 261300 + i},
|
||
"video_parameters": {
|
||
"profile": TP2,
|
||
"seed": 261200 + i,
|
||
"source_seconds": seconds,
|
||
"num_inference_steps": 20,
|
||
"upscale": False,
|
||
},
|
||
"edit": {
|
||
"start_frame": 0,
|
||
"duration_frames": seconds * 24,
|
||
"dedup_frames": 0,
|
||
},
|
||
"continuity": {"transition": "cut"},
|
||
"performance": {
|
||
"sequence_id": seq_id,
|
||
"visible_speaker_ids": [speakers[speaker]["id"]] if line else [],
|
||
"lip_sync": "required" if line else "off",
|
||
"duration_mode": "fixed",
|
||
"structure_locked": False,
|
||
"original_audio": "discard",
|
||
},
|
||
}
|
||
)
|
||
sequences.append(
|
||
{
|
||
"id": seq_id,
|
||
"scene_id": scene_id,
|
||
"shot_ids": [shot_id],
|
||
"utterance_ids": line_ids,
|
||
"timing_mode": "fixed",
|
||
}
|
||
)
|
||
|
||
return {
|
||
"schema_version": 5,
|
||
"profile": "landscape_1080_v1",
|
||
"context": {
|
||
"era": "当代旧居民区",
|
||
"style": "低调写实都市生活短片",
|
||
"palette": "暖琥珀与靛青,保留自然肤色",
|
||
"lighting": "顶部柔光,门外侧逆光",
|
||
"negative_prompt": "卡通、第二张脸、面部遮挡、可读文字、静帧、冻结、夸张表情",
|
||
},
|
||
"scenes": [
|
||
{
|
||
"id": scene_id,
|
||
"name": "雨夜修鞋铺",
|
||
"description": SETTING,
|
||
"reference_asset_ids": [],
|
||
"location": "老居民区临街修鞋铺门廊及柜台",
|
||
"time": "秋夜约八点",
|
||
"weather": "由急促细雨转为轻微滴雨",
|
||
"lighting": "台灯暖光与湿街蓝灰反射",
|
||
}
|
||
],
|
||
"entities": list(entities.values()),
|
||
"shots": shots,
|
||
"render": {
|
||
"fps": 24,
|
||
"total_frames": sum(s["edit"]["duration_frames"] for s in shots),
|
||
"fit": "contain",
|
||
"audio": None,
|
||
"subtitles": [],
|
||
"template_version": "plain-v1",
|
||
},
|
||
"dialogue": {
|
||
"enabled": True,
|
||
"speakers": list(speakers.values()),
|
||
"utterances": lines,
|
||
"sequences": sequences,
|
||
},
|
||
}
|
||
|
||
|
||
def bgm_layer(seconds, asset_id):
|
||
return {
|
||
"id": stable_id("bgm:eaves-light"),
|
||
"role": "bgm",
|
||
"asset_id": asset_id,
|
||
"anchor": "absolute",
|
||
"offset_sample": 0,
|
||
"source_start_sample": 0,
|
||
"source_end_sample": seconds * SAMPLE_RATE,
|
||
"gain_db": -4,
|
||
"fade_in_samples": 2 * SAMPLE_RATE,
|
||
"fade_out_samples": 3 * SAMPLE_RATE,
|
||
}
|
||
|
||
|
||
def build_manifest(story, bgm_asset_id=None):
|
||
return {
|
||
"schema_version": 3,
|
||
"source_kind": "story",
|
||
"editing_mode": "auto",
|
||
"spec": story,
|
||
"shot_ids": [shot["id"] for shot in story["shots"]],
|
||
"bindings": {},
|
||
"audio": {
|
||
"mode": "silent",
|
||
"voice": "",
|
||
"speed": 1,
|
||
"track": None,
|
||
"segments": [],
|
||
"mix_mode": "composed",
|
||
"ducking": True,
|
||
"layers": [bgm_layer(story["render"]["total_frames"] // 24, bgm_asset_id)]
|
||
if bgm_asset_id
|
||
else [],
|
||
},
|
||
"captions": {"mode": "script", "cues": []},
|
||
}
|
||
|
||
|
||
def synthesize_bgm(target, seconds):
|
||
"""《檐灯》原创音高与节奏,单声道 48 kHz PCM,无样本库和外部采样。"""
|
||
total = seconds * SAMPLE_RATE
|
||
samples = array("f", [0.0]) * total
|
||
|
||
def note(midi, start, length, amplitude, decay):
|
||
first = int(start * SAMPLE_RATE)
|
||
count = min(int(length * SAMPLE_RATE), total - first)
|
||
phase_step = 2 * math.pi * 440 * 2 ** ((midi - 69) / 12) / SAMPLE_RATE
|
||
for i in range(count):
|
||
position = i / SAMPLE_RATE
|
||
attack = min(1.0, position / 0.085)
|
||
release = min(1.0, (count - i) / (0.7 * SAMPLE_RATE))
|
||
envelope = amplitude * attack * release * math.exp(-position / decay)
|
||
phase = phase_step * i
|
||
samples[first + i] += envelope * (
|
||
math.sin(phase)
|
||
+ 0.18 * math.sin(phase * 2.001)
|
||
+ 0.06 * math.sin(phase * 3.003)
|
||
)
|
||
|
||
harmonies = (
|
||
(45, 57, 60, 64, 71),
|
||
(41, 57, 60, 64, 69),
|
||
(48, 55, 62, 64, 67),
|
||
(43, 55, 57, 62, 69),
|
||
(45, 57, 60, 64, 72),
|
||
(41, 57, 60, 65, 69),
|
||
(43, 55, 59, 62, 69),
|
||
(48, 55, 60, 64, 67),
|
||
)
|
||
for bar, start in enumerate(range(0, seconds, 6)):
|
||
chord = harmonies[(bar + bar // 8) % len(harmonies)]
|
||
note(chord[0], start, 5.9, 0.024, 4.1)
|
||
for offset, pitch in zip((0.32, 1.1, 2.42, 3.74), chord[1:]):
|
||
note(pitch, start + offset, 3.05, 0.015, 1.1)
|
||
if bar % 4 in (0, 3):
|
||
note(chord[-1] + 12, start + 4.38, 1.9, 0.007, 0.74)
|
||
|
||
pcm = array(
|
||
"h",
|
||
(
|
||
round(
|
||
sample
|
||
* 32767
|
||
* min(1.0, i / (2 * SAMPLE_RATE), (total - i) / (3 * SAMPLE_RATE))
|
||
)
|
||
for i, sample in enumerate(samples)
|
||
),
|
||
)
|
||
if sys.byteorder != "little":
|
||
pcm.byteswap()
|
||
temporary = target.with_suffix(".wav.tmp")
|
||
with wave.open(str(temporary), "wb") as track:
|
||
track.setparams((1, 2, SAMPLE_RATE, total, "NONE", "not compressed"))
|
||
track.writeframes(pcm.tobytes())
|
||
temporary.replace(target)
|
||
|
||
|
||
def story_speakers(story):
|
||
speakers = {speaker["id"]: speaker for speaker in story["dialogue"]["speakers"]}
|
||
return {key: speakers[stable_id("speaker:" + key)] for key in CHARACTERS}
|
||
|
||
|
||
def recorded_reference_text(reference):
|
||
for key in ("reference_text", "text"):
|
||
value = reference.get(key)
|
||
if isinstance(value, str) and value.strip():
|
||
return value.strip()
|
||
return ""
|
||
|
||
|
||
def voice_reference_notes(story, references):
|
||
for key, speaker in story_speakers(story).items():
|
||
voice = speaker["voice"]
|
||
if voice["provider"] == "kokoro":
|
||
provider = "Kokoro"
|
||
purpose = "使用固定预设配音。独立参考录音仅用于音色核验。"
|
||
else:
|
||
provider = "VoxCPM2"
|
||
purpose = "使用固定参考录音配音和核验。" + voice["style"]
|
||
text = recorded_reference_text(references.get(key, {}))
|
||
if not voice["reference_asset_id"]:
|
||
transcript = "参考录音待登记。"
|
||
elif text:
|
||
transcript = f"参考录音原文「{text}」"
|
||
else:
|
||
transcript = "参考录音原文待核对。"
|
||
yield f"- {speaker['name']}({provider} `{voice['voice']}`)。{purpose}{transcript}"
|
||
|
||
|
||
def prepare_story():
|
||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||
state = read_state()
|
||
story = build_story(state)
|
||
seconds = story["render"]["total_frames"] // 24
|
||
write_json(OUTPUT / "story-v5.json", story)
|
||
bgm = OUTPUT / BGM_NAME
|
||
if not bgm.exists():
|
||
synthesize_bgm(bgm, seconds)
|
||
bgm_id = state.get("artifacts", {}).get("bgm", {}).get("asset_id")
|
||
write_json(OUTPUT / "editor-v3.json", build_manifest(story, bgm_id))
|
||
write_json(OUTPUT / "bgm-placement.json", bgm_layer(seconds, bgm_id))
|
||
|
||
lines = [
|
||
"# 雨夜归途",
|
||
"",
|
||
"林晚搬回旧街,雨中在修鞋铺停脚。陈叔补好她的鞋,刚好同路的许舟和她一起回五号楼。",
|
||
"",
|
||
f"横屏 24fps,{len(SHOTS)} 镜,作者时间线 {seconds} 秒。全片普通切镜,写实单人近景。",
|
||
"",
|
||
"| 镜头 | 秒 | 人物 | 台词或反应 |",
|
||
"| --- | ---: | --- | --- |",
|
||
]
|
||
for i, (title, person, length, dialogue, action) in enumerate(SHOTS, 1):
|
||
lines.append(
|
||
f"| {i:02d} {title} | {length} | {CHARACTERS[person][0]} | {dialogue or action} |"
|
||
)
|
||
lines += [
|
||
"",
|
||
"## 人物与声音",
|
||
"",
|
||
"角色是为本片原创生成的虚构人物。来源回执、队列任务、素材 ID 与下载校验值见 production-state.json。",
|
||
"每个角色沿用固定声线。提交整片前,应在 V5 作者稿中登记人物参考图和独立参考录音。",
|
||
*voice_reference_notes(story, state.get("voice_references", {})),
|
||
"",
|
||
"## 音乐与字幕",
|
||
"",
|
||
"《檐灯》是本片程序合成的原创无歌词配乐。波形从音高与节奏合成,未调用外部采样库。",
|
||
"源码位于仓库 scripts/create_dialogue_example.py。WAV 采用 48 kHz 单声道 PCM,成片可在对白时压低音乐音量。",
|
||
"bgm-placement.json 指定全片锚点、淡入淡出与取样范围。上传音乐后填入对应的业务素材 ID。",
|
||
"中文字幕由实测对白生成,作者清单保留台词锚点。正式字幕时间码随项目运行产生。",
|
||
"",
|
||
"## 制作阶段",
|
||
"",
|
||
"story-v5.json 与 editor-v3.json 是可编辑作者稿。请以 production-state.json 中的真实任务状态为准。",
|
||
"全部生成由本地项目的业务队列调度。源视频、固定参考音色、最终口型与成片须分别验收。",
|
||
]
|
||
studio_url = state.get("production", {}).get("studio_url")
|
||
if studio_url:
|
||
lines.extend(["", f"本地可编辑故事见[雨夜归途工作室]({studio_url})。"])
|
||
(OUTPUT / "制作说明.md").write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||
announce(
|
||
len(SHOTS),
|
||
"shots;",
|
||
seconds,
|
||
"seconds;",
|
||
len(story["dialogue"]["utterances"]),
|
||
"lines",
|
||
)
|
||
|
||
|
||
@contextmanager
|
||
def production_lock():
|
||
OUTPUT.mkdir(parents=True, exist_ok=True)
|
||
with (OUTPUT / ".production.lock").open("a+b") as handle:
|
||
if sys.platform == "win32":
|
||
import msvcrt
|
||
|
||
handle.seek(0)
|
||
msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1)
|
||
else:
|
||
import fcntl
|
||
|
||
fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||
yield
|
||
|
||
|
||
def rows(client, path, **filters):
|
||
page = 1
|
||
while True:
|
||
result = response_json(
|
||
client.get(path, params={**filters, "page_size": 100, "page": page})
|
||
)
|
||
yield from result["items"]
|
||
if page * 100 >= result["total"]:
|
||
return
|
||
page += 1
|
||
|
||
|
||
def create_or_reconcile(state, key, find, create):
|
||
resources = state.setdefault("production", {}).setdefault("resources", {})
|
||
entry = resources.get(key)
|
||
if entry and entry.get("id"):
|
||
return entry["id"]
|
||
matches = list(find())
|
||
if len(matches) > 1:
|
||
raise RuntimeError(f"{key} 有多个符合的业务对象,须确认所用对象后再继续")
|
||
if matches:
|
||
resources[key] = {"id": matches[0], "state": "reconciled"}
|
||
write_json(STATE, state)
|
||
return matches[0]
|
||
if entry and entry.get("state") == "pending":
|
||
raise RuntimeError(f"{key} 的上次创建结果尚未确认,已暂停重复创建,请重新对账")
|
||
# 故事和上传路由没有提交回执。在请求前落盘,只有已知拒绝或精确对账后才继续。
|
||
resources[key] = {"state": "pending"}
|
||
write_json(STATE, state)
|
||
response = create()
|
||
if 400 <= response.status_code < 500 and response.status_code != 408:
|
||
resources[key]["state"] = "rejected"
|
||
write_json(STATE, state)
|
||
item = response_json(response)
|
||
resources[key] = {"state": "created", "id": item["id"]}
|
||
write_json(STATE, state)
|
||
return item["id"]
|
||
|
||
|
||
def post_once(client, state, slot, path, body=None):
|
||
commands = state.setdefault("production", {}).setdefault("commands", {})
|
||
if slot not in commands:
|
||
if body is None:
|
||
raise RuntimeError(f"{slot} 缺少首次提交内容")
|
||
commands[slot] = {
|
||
"path": path,
|
||
"body": body,
|
||
"key": stable_id("production:" + slot),
|
||
}
|
||
write_json(STATE, state)
|
||
item = commands[slot]
|
||
if item["path"] != path:
|
||
raise RuntimeError("提交回执属于另一个资源")
|
||
return response_json(
|
||
client.post(path, json=item["body"], headers={"Idempotency-Key": item["key"]})
|
||
)
|
||
|
||
|
||
def asset_digest(client, asset_id):
|
||
digest = sha256()
|
||
with client.stream("GET", f"/assets/{asset_id}/content") as response:
|
||
response.raise_for_status()
|
||
for chunk in response.iter_bytes():
|
||
digest.update(chunk)
|
||
return digest.hexdigest()
|
||
|
||
|
||
def upload_bgm(client, state):
|
||
path = OUTPUT / BGM_NAME
|
||
checksum = sha256(path.read_bytes()).hexdigest()
|
||
name = "雨夜归途 · 檐灯 · " + checksum[:12]
|
||
|
||
def find():
|
||
return (
|
||
item["id"]
|
||
for item in rows(client, "/assets", kind="audio", origin="upload", q=name)
|
||
if item["name"] == name and asset_digest(client, item["id"]) == checksum
|
||
)
|
||
|
||
def upload():
|
||
with path.open("rb") as handle:
|
||
return client.post(
|
||
"/assets",
|
||
data={"name": name},
|
||
files={"file": (path.name, handle, "audio/wav")},
|
||
)
|
||
|
||
asset_id = create_or_reconcile(state, "bgm:" + checksum, find, upload)
|
||
if asset_digest(client, asset_id) != checksum:
|
||
raise RuntimeError("已登记的配乐与本地原创 WAV 内容不一致")
|
||
state.setdefault("artifacts", {})["bgm"] = {
|
||
"asset_id": asset_id,
|
||
"sha256": checksum,
|
||
"file": path.name,
|
||
}
|
||
write_json(STATE, state)
|
||
return asset_id
|
||
|
||
|
||
def voice_reference_request(speaker, text, capabilities):
|
||
voice = speaker["voice"]
|
||
provider = voice["provider"]
|
||
name = speaker["name"]
|
||
if not text.strip() or not voice["voice"].strip():
|
||
raise RuntimeError(f"{name}缺少独立录音文案或音色配置")
|
||
if provider == "kokoro":
|
||
task = "audio.speech"
|
||
capability = capabilities.get(task, {})
|
||
presets = capability.get("constraints", {}).get("voice", {}).get("values") or []
|
||
if (
|
||
capability.get("available") is not True
|
||
or capability.get("model") != voice["model"]
|
||
or voice["voice"] not in presets
|
||
):
|
||
raise RuntimeError(f"{name}需要已开放的 Kokoro 模型及预设 {voice['voice']}")
|
||
parameters = {"voice": voice["voice"], "speed": 1}
|
||
elif provider == "voxcpm2":
|
||
task = "audio.dialogue.speech"
|
||
capability = capabilities.get(task, {})
|
||
profile = "voxcpm2-v1"
|
||
if (
|
||
capability.get("available") is not True
|
||
or capability.get("defaults", {}).get("profile") != profile
|
||
):
|
||
raise RuntimeError(f"{name}需要已开放的 VoxCPM2 配音配置 {profile}")
|
||
parameters = {
|
||
"profile": profile,
|
||
"voice": voice["voice"],
|
||
"style": voice["style"],
|
||
"seed": voice["seed"],
|
||
"speed": 1,
|
||
"reference_text": "",
|
||
}
|
||
else:
|
||
raise RuntimeError(f"{name}的参考录音提供方未配置")
|
||
return {
|
||
"task_type": task,
|
||
"input": {"prompt": text},
|
||
"parameters": parameters,
|
||
"execution_mode": "batch",
|
||
}
|
||
|
||
|
||
def production_voices(client, state):
|
||
refs = state.setdefault("voice_references", {})
|
||
missing = [key for key in CHARACTERS if not refs.get(key, {}).get("asset_id")]
|
||
if not missing:
|
||
announce("复用三条已登记的参考音色")
|
||
return
|
||
capabilities = {
|
||
item["task_type"]: item
|
||
for item in response_json(client.get("/capabilities"))["items"]
|
||
}
|
||
speakers = story_speakers(build_story(state))
|
||
requests = {
|
||
key: voice_reference_request(speakers[key], VOICES[key][2], capabilities)
|
||
for key in missing
|
||
}
|
||
# 先校验所有待补参考的合同,再提交。不能把旧的 Vox 任务当成 Kokoro 核验素材。
|
||
for key, payload in requests.items():
|
||
recorded = state["jobs"].get("voice-reference-" + key)
|
||
if recorded and recorded.get("request") != payload:
|
||
raise RuntimeError(
|
||
f"{speakers[key]['name']}已有不同的参考录音任务,请核对其来源"
|
||
)
|
||
for key, payload in requests.items():
|
||
job_name = "voice-reference-" + key
|
||
submit_job(client, state, job_name, payload)
|
||
result = poll_job(client, state, job_name)
|
||
if result.get("asset_id"):
|
||
export_asset(client, state, job_name)
|
||
refs[key] = {
|
||
"asset_id": result["asset_id"],
|
||
"text": payload["input"]["prompt"],
|
||
}
|
||
write_json(STATE, state)
|
||
elif result["state"] in TERMINAL:
|
||
raise RuntimeError(f"{job_name} 终止,已保留任务回执")
|
||
if any(not refs.get(key, {}).get("asset_id") for key in missing):
|
||
announce("音色任务仍在队列中。再次运行 production-voices 可读取结果。")
|
||
|
||
|
||
def production_prepare(client, state):
|
||
capabilities = response_json(client.get("/capabilities"))
|
||
if capabilities.get("dialogue", {}).get("authoring_available") is not True:
|
||
raise RuntimeError("本地 API 尚不支持 V5 作者稿")
|
||
story = build_story(state)
|
||
speakers = story_speakers(story)
|
||
voices = [speaker["voice"] for speaker in speakers.values()]
|
||
reference_ids = {voice["reference_asset_id"] for voice in voices}
|
||
if not all(reference_ids) or len(reference_ids) != len(voices):
|
||
raise RuntimeError("请先为三个角色分别登记独立的参考录音")
|
||
for key, speaker in speakers.items():
|
||
voice = speaker["voice"]
|
||
reference = state.get("voice_references", {}).get(key, {})
|
||
text = voice["reference_text"]
|
||
if voice["provider"] == "voxcpm2" and not (
|
||
isinstance(text, str)
|
||
and text.strip()
|
||
and recorded_reference_text(reference)
|
||
):
|
||
raise RuntimeError(f"请填写{speaker['name']}的 VoxCPM2 参考录音原文")
|
||
if any(not entity["reference_asset_ids"] for entity in story["entities"]):
|
||
raise RuntimeError("请先完成三个角色的原创人物参考")
|
||
for voice in voices:
|
||
if (
|
||
response_json(client.get(f"/assets/{voice['reference_asset_id']}"))["kind"]
|
||
!= "audio"
|
||
):
|
||
raise RuntimeError("登记的声线参考不是可访问的音频素材")
|
||
production = state.setdefault("production", {})
|
||
title = state["project"]
|
||
first_id = story["shots"][0]["id"]
|
||
|
||
def find_story():
|
||
return (
|
||
item["id"]
|
||
for item in rows(client, "/stories")
|
||
if item["name"] == title
|
||
and item["spec"]["schema_version"] == 5
|
||
and any(shot["id"] == first_id for shot in item["spec"]["shots"])
|
||
)
|
||
|
||
draft_id = create_or_reconcile(
|
||
state,
|
||
"draft",
|
||
find_story,
|
||
lambda: client.post("/stories", json={"name": title, "spec": story}),
|
||
)
|
||
path = f"/editors/{draft_id}"
|
||
current = response_json(client.get(path))
|
||
if "studio_url" not in production:
|
||
production["studio_url"] = f"{STUDIO_URL}/{draft_id}"
|
||
write_json(STATE, state)
|
||
if "prepared_version" in production:
|
||
announce("已配置的故事", draft_id, "当前版本", current["version"])
|
||
return
|
||
bgm_id = upload_bgm(client, state)
|
||
if current["editing_mode"] != "auto":
|
||
current = post_once(
|
||
client,
|
||
state,
|
||
"mode",
|
||
path + "/mode",
|
||
{"expected_version": current["version"], "mode": "auto"},
|
||
)
|
||
manifest = deepcopy(current["manifest"])
|
||
layer = bgm_layer(story["render"]["total_frames"] // 24, bgm_id)
|
||
layers = manifest["audio"].setdefault("layers", [])
|
||
if not any(item["id"] == layer["id"] for item in layers):
|
||
layers.append(layer)
|
||
if manifest["captions"]["mode"] == "none":
|
||
manifest["captions"]["mode"] = "script"
|
||
# 采用已核验的首镜原片及其实际生成输入;已有手工选择优先。
|
||
sample = state["jobs"].get("sample-01-h3-tp2", {})
|
||
reference = state["jobs"].get("reference-lin", {})
|
||
first = manifest["spec"]["shots"][0]
|
||
bindings = manifest["bindings"]
|
||
frame_key, video_key = "frame:" + first_id, "video:" + first_id
|
||
image_id = sample.get("request", {}).get("input", {}).get("image_asset_id")
|
||
video_id = sample.get("asset_id")
|
||
if (
|
||
first["id"] == first_id
|
||
and first["edit"]["start_frame"] == 0
|
||
and first["edit"]["duration_frames"] == 144
|
||
and sample.get("verification", {}).get("decoded_frames") == 145
|
||
and image_id
|
||
and video_id
|
||
and reference.get("asset_id") == image_id
|
||
and bindings.get(frame_key, {}).get("asset_id", image_id) == image_id
|
||
and bindings.get(video_key, {}).get("asset_id", video_id) == video_id
|
||
):
|
||
bindings.setdefault(
|
||
frame_key,
|
||
{
|
||
"asset_id": image_id,
|
||
"sha256": reference["sha256"],
|
||
"kind": "image",
|
||
"source": "manual",
|
||
"locked": True,
|
||
},
|
||
)
|
||
bindings.setdefault(
|
||
video_key,
|
||
{
|
||
"asset_id": video_id,
|
||
"sha256": sample["sha256"],
|
||
"kind": "video",
|
||
"source": "manual",
|
||
"locked": True,
|
||
},
|
||
)
|
||
current = post_once(
|
||
client,
|
||
state,
|
||
"save",
|
||
path + "/save",
|
||
{"expected_version": current["version"], "manifest": manifest},
|
||
)
|
||
production["prepared_version"] = current["version"]
|
||
write_json(STATE, state)
|
||
write_json(OUTPUT / "local-editor-v3.json", current["manifest"])
|
||
announce("故事", draft_id, "版本", current["version"])
|
||
|
||
|
||
def production_run(client, state, stage):
|
||
production = state.get("production", {})
|
||
if "prepared_version" not in production:
|
||
raise RuntimeError("请先执行 production-prepare")
|
||
runs = production.setdefault("runs", {})
|
||
if stage in runs:
|
||
announce("已提交", stage, runs[stage]["id"])
|
||
return
|
||
draft_id = production["resources"]["draft"]["id"]
|
||
path = f"/editors/{draft_id}"
|
||
if stage in production.get("commands", {}):
|
||
result = post_once(client, state, stage, path + "/runs")
|
||
else:
|
||
current = response_json(client.get(path))
|
||
if current["editing_mode"] != "auto":
|
||
raise RuntimeError("故事已切到逐步骤模式,请检查当前草稿")
|
||
targets = []
|
||
if stage == "pilot":
|
||
first_two = current["manifest"]["shot_ids"][:2]
|
||
if len(first_two) != 2:
|
||
raise RuntimeError("两镜小样需要两个有效镜头")
|
||
targets = ["synced_video:" + sid for sid in first_two]
|
||
else:
|
||
if "pilot" not in runs:
|
||
raise RuntimeError("请先完成两镜口型小样")
|
||
pilot = response_json(client.get("/workflow-runs/" + runs["pilot"]["id"]))[
|
||
"run"
|
||
]
|
||
if pilot["state"] != "succeeded" or pilot.get("apply_state") != "applied":
|
||
raise RuntimeError("两镜小样尚未成功并应用到作者稿")
|
||
body = {
|
||
"expected_version": current["version"],
|
||
"output_goal": "media" if targets else "film",
|
||
"targets": targets,
|
||
"force": [],
|
||
"execution_mode": "batch",
|
||
}
|
||
plan = response_json(client.post(path + "/plan", json=body))
|
||
if plan["issues"]:
|
||
raise RuntimeError(";".join(issue["message"] for issue in plan["issues"]))
|
||
result = post_once(
|
||
client,
|
||
state,
|
||
stage,
|
||
path + "/runs",
|
||
{**body, "expected_plan_hash": plan["plan_hash"]},
|
||
)
|
||
run = result["run"]
|
||
runs[stage] = {"id": run["id"], "state": run["state"]}
|
||
write_json(STATE, state)
|
||
announce("已提交", stage, run["id"])
|
||
|
||
|
||
def production_preview_pilot(client, state):
|
||
rid = state["production"]["runs"]["pilot"]["id"]
|
||
snapshot = response_json(client.get("/workflow-runs/" + rid))
|
||
run = snapshot["run"]
|
||
if run["state"] != "succeeded" or run.get("apply_state") != "applied":
|
||
raise RuntimeError("请先完成并应用两镜小样")
|
||
manifest = run["editor_manifest"]
|
||
bindings = manifest["bindings"]
|
||
steps = {step["step_key"]: step for step in snapshot["steps"]}
|
||
lines = {line["id"]: line for line in manifest["spec"]["dialogue"]["utterances"]}
|
||
clips, segments, captions = [], [], []
|
||
frames = 0
|
||
for sid in manifest["shot_ids"][:2]:
|
||
video = bindings["synced_video:" + sid]
|
||
report = bindings["dialogue_report:" + sid]
|
||
if video["provenance"]["quality_asset_id"] != report["asset_id"]:
|
||
raise RuntimeError("小样镜头与验收报告不匹配")
|
||
lip = next(
|
||
step
|
||
for step in steps.values()
|
||
if step["kind"] == "video.lipsync" and step["recipe"]["unit_id"] == sid
|
||
)
|
||
for stem in lip["recipe"]["stems"]:
|
||
source = steps[stem["stem_key"]]["resolved_input"]["input"]
|
||
for original in source["segments"]:
|
||
segment = dict(
|
||
original, offset_sample=frames * 2000 + original["offset_sample"]
|
||
)
|
||
uid = segment["segment_id"]
|
||
if (
|
||
bindings["normalized_speech:" + uid]["asset_id"]
|
||
!= segment["asset_id"]
|
||
):
|
||
raise RuntimeError("干声与已选用的归一化对白不匹配")
|
||
segments.append(segment)
|
||
start = segment["offset_sample"]
|
||
end = (
|
||
start
|
||
+ segment["source_end_sample"]
|
||
- segment["source_start_sample"]
|
||
)
|
||
captions.append(
|
||
{
|
||
"start": start / 48000,
|
||
"end": end / 48000,
|
||
"text": lines[uid]["text"],
|
||
}
|
||
)
|
||
count = video["duration_frames"]
|
||
meta = response_json(client.get("/assets/" + video["asset_id"]))
|
||
clips.append(
|
||
{
|
||
"shot_id": sid,
|
||
"asset_id": video["asset_id"],
|
||
"sha256": video["sha256"],
|
||
"width": meta["width"],
|
||
"height": meta["height"],
|
||
"fps": 24,
|
||
"source_frames": count,
|
||
"start_frame": 0,
|
||
"duration_frames": count,
|
||
}
|
||
)
|
||
frames += count
|
||
if len(clips) != 2 or len(captions) != 2:
|
||
raise RuntimeError("样例需要两个验收镜头与两句对白")
|
||
(bgm,) = [layer for layer in manifest["audio"]["layers"] if layer["role"] == "bgm"]
|
||
offset, start = bgm["offset_sample"], bgm["source_start_sample"]
|
||
end = min(bgm["source_end_sample"], start + frames * 2000 - offset)
|
||
segments.append(
|
||
{
|
||
"role": "bgm",
|
||
"asset_id": bgm["asset_id"],
|
||
"segment_id": bgm["id"],
|
||
"offset_sample": offset,
|
||
"source_start_sample": start,
|
||
"source_end_sample": end,
|
||
"gain_db": bgm["gain_db"],
|
||
"fade_in_samples": bgm["fade_in_samples"],
|
||
"fade_out_samples": bgm["fade_out_samples"],
|
||
}
|
||
)
|
||
|
||
def render(tag, task, inputs, parameters):
|
||
name = f"pilot-{tag}-{rid}"
|
||
submit_job(
|
||
client,
|
||
state,
|
||
name,
|
||
{
|
||
"task_type": task,
|
||
"input": inputs,
|
||
"parameters": parameters,
|
||
"execution_mode": "batch",
|
||
},
|
||
)
|
||
while True:
|
||
entry = poll_job(client, state, name)
|
||
if entry.get("asset_id"):
|
||
return name, entry["asset_id"]
|
||
if entry["state"] in TERMINAL:
|
||
raise RuntimeError(f"{tag} 失败:{entry.get('error')}")
|
||
time.sleep(3)
|
||
|
||
_, mixed = render(
|
||
"mix",
|
||
"audio.mix",
|
||
{"segments": segments, "total_frames": frames},
|
||
{"ducking": manifest["audio"].get("ducking", True)},
|
||
)
|
||
spec = deepcopy(manifest["spec"])
|
||
spec["schema_version"] = 4
|
||
spec.pop("dialogue")
|
||
spec["shots"] = spec["shots"][:2]
|
||
for shot, clip in zip(spec["shots"], clips, strict=True):
|
||
shot.pop("performance")
|
||
shot["edit"].update(
|
||
start_frame=0, dedup_frames=0, duration_frames=clip["duration_frames"]
|
||
)
|
||
shot["continuity"].update(transition="cut", endpoint_mode="first_frame")
|
||
audio = {
|
||
"asset_id": mixed,
|
||
"source_start_sample": 0,
|
||
"source_end_sample": frames * 2000,
|
||
"offset_sample": 0,
|
||
"sample_rate": 48000,
|
||
"short_policy": "silence",
|
||
}
|
||
spec["render"].update(
|
||
total_frames=frames,
|
||
audio=audio,
|
||
subtitles=[
|
||
{
|
||
"start_frame": math.floor(cue["start"] * 24),
|
||
"end_frame": math.ceil(cue["end"] * 24),
|
||
"text": cue["text"],
|
||
}
|
||
for cue in captions
|
||
],
|
||
)
|
||
frozen = {
|
||
"clips": clips,
|
||
"fps": 24,
|
||
"canvas": [1920, 1080],
|
||
"audio": {**audio, "sha256": asset_digest(client, mixed)},
|
||
}
|
||
name, _ = render(
|
||
"compose-frames",
|
||
"video.compose",
|
||
{"asset_ids": [clip["asset_id"] for clip in clips], "audio_asset_id": mixed},
|
||
{
|
||
"clips": [{"asset_id": clip["asset_id"]} for clip in clips],
|
||
"story_spec": spec,
|
||
"render_inputs": frozen,
|
||
},
|
||
)
|
||
export_asset(client, state, name, basename="雨夜归途_两镜小样")
|
||
for cue in captions:
|
||
announce(f"{cue['start']:.3f}–{cue['end']:.3f}", cue["text"])
|
||
|
||
|
||
def write_subtitles(path, cues):
|
||
def timestamp(frame):
|
||
milliseconds = (int(frame) * 1000 + 12) // 24
|
||
sec, ms = divmod(milliseconds, 1000)
|
||
minutes, second = divmod(sec, 60)
|
||
hours, minute = divmod(minutes, 60)
|
||
return f"{hours:02d}:{minute:02d}:{second:02d},{ms:03d}"
|
||
|
||
rows = [
|
||
f"{index}\n{timestamp(cue['start_frame'])} --> {timestamp(cue['end_frame'])}\n{cue['text']}"
|
||
for index, cue in enumerate(cues, 1)
|
||
]
|
||
path.write_text("\n\n".join(rows) + "\n", encoding="utf-8")
|
||
|
||
|
||
def production_status(client, state):
|
||
for stage, receipt in state.get("production", {}).get("runs", {}).items():
|
||
snapshot = response_json(client.get("/workflow-runs/" + receipt["id"]))
|
||
run = snapshot["run"]
|
||
receipt.update(state=run["state"], apply_state=run.get("apply_state"))
|
||
announce(
|
||
stage, run["id"], run["state"], run.get("apply_state"), run.get("error")
|
||
)
|
||
if (
|
||
stage != "film"
|
||
or run["state"] != "succeeded"
|
||
or run.get("apply_state") != "applied"
|
||
):
|
||
continue
|
||
steps = {step["step_key"]: step for step in snapshot["steps"]}
|
||
# The run also retains its referenced source clips. Export the output of
|
||
# the successful compositor, rather than treating every video as a film.
|
||
compose = [
|
||
step for step in steps.values()
|
||
if step["kind"] == "video.compose" and step["state"] == "succeeded"
|
||
]
|
||
if len(compose) != 1:
|
||
raise RuntimeError("运行未返回唯一的正式合成步骤")
|
||
final_id = (compose[0].get("result") or {}).get("asset_id")
|
||
videos = [
|
||
asset for asset in run["result_assets"]
|
||
if asset["id"] == final_id and asset["kind"] == "video"
|
||
and asset.get("source_job_id") == compose[0].get("selected_job_id")
|
||
]
|
||
if len(videos) != 1:
|
||
raise RuntimeError("正式成片素材与合成步骤不一致")
|
||
cues = (steps.get("dialogue_captions", {}).get("result") or {}).get("cues", [])
|
||
mix_id = (steps.get("dialogue_mix", {}).get("result") or {}).get("asset_id")
|
||
if not cues or not mix_id:
|
||
raise RuntimeError("最终声音或字幕尚未出现在成功运行的回执中")
|
||
write_subtitles(OUTPUT / "雨夜归途.srt", cues)
|
||
mix = response_json(client.get(f"/assets/{mix_id}"))
|
||
for key, asset in (("雨夜归途", videos[0]), ("雨夜归途_最终混音", mix)):
|
||
state["jobs"].setdefault(key, {}).update(
|
||
asset_id=asset["id"], mime_type=asset["mime_type"]
|
||
)
|
||
export_asset(client, state, key)
|
||
write_json(OUTPUT / "final-editor-v3.json", run["editor_manifest"])
|
||
write_json(STATE, state)
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
commands = {
|
||
"production-voices": production_voices,
|
||
"production-prepare": production_prepare,
|
||
"production-preview-pilot": production_preview_pilot,
|
||
"production-pilot": lambda client, state: production_run(
|
||
client, state, "pilot"
|
||
),
|
||
"production-render": lambda client, state: production_run(
|
||
client, state, "film"
|
||
),
|
||
"production-status": production_status,
|
||
}
|
||
parser.add_argument("command", choices=["prepare", "samples", *commands])
|
||
args = parser.parse_args()
|
||
if args.command == "prepare":
|
||
prepare_story()
|
||
return
|
||
with production_lock():
|
||
if args.command == "samples":
|
||
queue_samples()
|
||
else:
|
||
state = read_state()
|
||
with local_session() as client:
|
||
commands[args.command](client, state)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
try:
|
||
main()
|
||
except KeyboardInterrupt:
|
||
sys.exit("监控已停止。任务仍在业务队列,请用同一命令恢复。")
|