"""通过本地正式API准备H3原生对白验收故事与首帧,不提交视频任务。""" import argparse import json import os import tempfile import time 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 .create_dialogue_example import local_session, response_json, write_json else: from create_dialogue_example import local_session, response_json, write_json ROOT = Path(__file__).resolve().parents[1] OUTPUT = ROOT / "outputs" / "H3原生对白验收_20261127" STATE = OUTPUT / "production-state.json" NAME = "H3原生对白验收 20261127" PROFILE = "minimax-h3-fl2va-native-av-tp2-v1" TEXT = "你好,很高兴见到你。" VOICE = "年轻成年女性,清亮自然的中音,标准普通话,语速从容,咬字清楚,友善轻松。" APPEARANCE = ( "一名26岁的原创中国成年女性,黑色齐肩直发,整洁自然的发型,穿纯色米色上衣," "神情温和自然,五官清晰匀称,自然皮肤纹理,不对应现实公众人物。" ) VISUAL = ( "写实电影近景,横构图,成年女性正面胸口以上近景,镜头与眼睛等高。" "脸部清晰锐利,双眼清楚可见,双颊和下颌无遮挡,嘴唇轻轻闭合," "头发和手不遮挡脸,头部基本正面,米色上衣,柔和稳定的摄影棚光线," "简单温暖浅灰背景略虚化。全画面只有一个成年人,没有文字、字幕、水印。" ) MOTION = ( "同一位原创成年女性面向镜头,用清亮自然的普通话微笑问候;" "说话时保持脸部清晰、口腔结构自然,双眼轻微交流,肩颈有细微呼吸和自然眨眼," "身体和摄影机保持稳定,避免大幅转头。说完后双唇自然闭合,保持安静友善的表情" "直到镜头结束。不添加额外台词、背景说话人、歌声、背景音乐或镜头切换。" ) def stable_id(role): return uuid5(NAMESPACE_URL, "cmvr:native-dialogue-acceptance:20261127:" + role).hex def initial_story(): return { "schema_version": 3, "profile": "landscape_1080_v1", "context": { "style": "写实电影人物近景", "lighting": "稳定柔和的摄影棚主光", "negative_prompt": "多人,遮脸,模糊,畸形面部,张嘴定格,文字,字幕,水印", }, "entities": [ { "id": stable_id("entity"), "name": "小晴", "kind": "person", "description": APPEARANCE, } ], "scenes": [ { "id": stable_id("scene"), "name": "柔光摄影棚", "description": "简单浅灰背景,稳定柔光", } ], "shots": [ { "id": stable_id("shot"), "name": "正面问候", "scene_id": stable_id("scene"), "cast": [ { "id": stable_id("cast"), "entity_id": stable_id("entity"), "position": "画面中央胸上近景", } ], "visual_prompt": VISUAL, "motion_prompt": MOTION, "frame_parameters": {"seed": 261127}, "video_parameters": { "profile": "minimax-h3-fl2va-bf16-tp2-v1", "source_seconds": 6, "num_inference_steps": 50, "seed": 261127, "upscale": False, }, "edit": {"start_frame": 0, "duration_frames": 144}, } ], "render": {"fps": 24, "total_frames": 144}, } def native_manifest(editor): m = deepcopy(editor["manifest"]) d = m["spec"]["dialogue"] d.update( generation="native_av", language="Chinese", enabled=True, speakers=[ { "id": stable_id("speaker"), "entity_id": stable_id("entity"), "name": "小晴", "native_voice": VOICE, } ], utterances=[ { "id": stable_id("line"), "speaker_id": stable_id("speaker"), "text": TEXT, "source": "tts", "delivery": "自然轻声问候,句末完整收音后闭唇安静,不加任何额外语句。", } ], sequences=[ { "id": stable_id("sequence"), "scene_id": stable_id("scene"), "shot_ids": [stable_id("shot")], "utterance_ids": [stable_id("line")], } ], ) shot = m["spec"]["shots"][0] shot["video_parameters"] = { "profile": PROFILE, "source_frames": 158, "num_inference_steps": 50, "seed": 261127, "upscale": False, } shot["edit"].update(start_frame=0, duration_frames=158, dedup_frames=0) shot["performance"].update( sequence_id=stable_id("sequence"), native_utterance_ids=[stable_id("line")], visible_speaker_ids=[stable_id("speaker")], lip_sync="required", duration_mode="auto", original_audio="preserve", ) m["spec"]["render"]["total_frames"] = 158 m["audio"].update( mode="silent", mix_mode="composed", segments=[], layers=[], track=None ) m["captions"] = {"mode": "script", "cues": []} return m def load_state(): OUTPUT.mkdir(parents=True, exist_ok=True) config = { "story": initial_story(), "text": TEXT, "voice": VOICE, "profile": PROFILE, "frames": 158, } fingerprint = sha256( json.dumps(config, ensure_ascii=False, sort_keys=True).encode() ).hexdigest() state = ( json.loads(STATE.read_text(encoding="utf-8")) if STATE.exists() else {"name": NAME, "commands": {}} ) if state.get("config_sha256", fingerprint) != fingerprint: raise RuntimeError( "验收配置已改变,不能复用已冻结意图;请明确建立另一份验收版本" ) state["config_sha256"] = fingerprint write_json(STATE, state) return state @contextmanager def production_lock(): OUTPUT.mkdir(parents=True, exist_ok=True) with (OUTPUT / ".production.lock").open("a+b") as handle: handle.seek(0, 2) if handle.tell() == 0: handle.write(b"0") handle.flush() handle.seek(0) try: if os.name == "nt": import msvcrt msvcrt.locking(handle.fileno(), msvcrt.LK_NBLCK, 1) else: import fcntl fcntl.flock(handle.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB) except OSError as exc: raise RuntimeError("其他进程正在维护同一验收故事,禁止并发提交") from exc try: yield finally: handle.seek(0) if os.name == "nt": msvcrt.locking(handle.fileno(), msvcrt.LK_UNLCK, 1) else: fcntl.flock(handle.fileno(), fcntl.LOCK_UN) def post_once(client, state, slot, path, make_body): """先落盘再POST;重启与HTTP超时只重放同一个key和精确body。""" item = state.setdefault("commands", {}).get(slot) if item is None: item = {"path": path, "body": make_body(), "key": stable_id("command:" + slot)} state["commands"][slot] = item write_json(STATE, state) if item["path"] != path: raise RuntimeError("保存的命令属于其他资源,禁止更换请求路径") if "response" not in item: item["response"] = response_json( client.post( path, json=item["body"], headers={"Idempotency-Key": item["key"]}, ) ) write_json(STATE, state) return item["response"] def find_story(client): matches = [] page = 1 while True: data = response_json( client.get("/stories", params={"page": page, "page_size": 100}) ) for row in data["items"]: if row["name"] == NAME: detail = response_json(client.get("/stories/" + row["id"])) if [s["id"] for s in detail["spec"]["shots"]] == [stable_id("shot")]: matches.append(detail) if page * 100 >= data["total"]: break page += 1 if len(matches) > 1: raise RuntimeError("存在多个同名同镜头的验收故事,禁止猜测或重复创建") return matches[0] if matches else None def prepare(client, state): story = state.get("story") if not story: story = find_story(client) if not story: if state.get("story_create") == "pending": raise RuntimeError("故事创建结果未知且未能对账,暂停重复创建") state.update(story_create="pending") write_json(STATE, state) story = response_json( client.post("/stories", json={"name": NAME, "spec": initial_story()}) ) state.update( story=story, story_create="confirmed", story_id=story["id"], studio_url="http://127.0.0.1:5173/studio/" + story["id"], ) write_json(STATE, state) path = "/editors/" + story["id"] enabled = post_once( client, state, "enable", path + "/dialogue/enable", lambda: {"expected_version": response_json(client.get(path))["version"]}, ) saved = post_once( client, state, "save", path + "/save", lambda: { "expected_version": enabled["version"], "manifest": native_manifest(enabled), }, ) write_json(OUTPUT / "editor-v3.json", saved["manifest"]) write_json(OUTPUT / "story-v5.json", saved["manifest"]["spec"]) return saved def frame(client, state): editor = prepare(client, state) path = "/editors/" + state["story_id"] if "frame_run" not in state: body = { "expected_version": editor["version"], "output_goal": "media", "targets": ["frame:" + stable_id("shot")], "force": [], "execution_mode": "interactive", } if "frame_plan" not in state: plan = response_json(client.post(path + "/plan", json=body)) if plan["issues"]: raise RuntimeError( "首帧计划未通过:" + json.dumps(plan["issues"], ensure_ascii=False) ) state["frame_plan"] = {"body": body, "plan": plan} write_json(STATE, state) frozen = state["frame_plan"] result = post_once( client, state, "frame-run", path + "/runs", lambda: { **frozen["body"], "expected_plan_hash": frozen["plan"]["plan_hash"], }, ) state["frame_run"] = result["run"]["id"] write_json(STATE, state) return poll(client, state) def poll(client, state): if not state.get("frame_run"): raise RuntimeError("尚未提交首帧任务") snapshot = response_json(client.get("/workflow-runs/" + state["frame_run"])) state["frame_snapshot"] = snapshot write_json(STATE, state) run = snapshot["run"] jobs = snapshot["jobs"] if any(job["task_type"] != "image.generate" for job in jobs): raise RuntimeError("首帧闭包出现非图像任务,立即停止继续提交") print( json.dumps( { "run_id": run["id"], "state": run["state"], "jobs": [ {"id": j["id"], "state": j["state"], "type": j["task_type"]} for j in jobs ], }, ensure_ascii=False, ), flush=True, ) return snapshot def export(client, state, snapshot): from PIL import Image run = snapshot["run"] if run["state"] != "succeeded": raise RuntimeError("首帧任务尚未成功,保留回执继续查询") binding = run["editor_manifest"]["bindings"]["frame:" + stable_id("shot")] path = "/editors/" + state["story_id"] current = response_json(client.get(path)) if ( current["manifest"]["bindings"] .get("frame:" + stable_id("shot"), {}) .get("asset_id") != binding["asset_id"] ): if run.get("apply_state") == "conflict": raise RuntimeError("故事已有后续修改,首帧保留但不覆盖新版本") post_once( client, state, "apply-frame", path + "/apply", lambda: {"expected_version": current["version"], "run_id": run["id"]}, ) current = response_json(client.get(path)) write_json(OUTPUT / "editor-v3.json", current["manifest"]) write_json(OUTPUT / "story-v5.json", current["manifest"]["spec"]) target = OUTPUT / "人物说话验收首帧.png" with tempfile.TemporaryDirectory(prefix="native-frame-", dir=OUTPUT) as temporary: download = Path(temporary) / "frame.png" digest = sha256() with client.stream( "GET", "/assets/" + binding["asset_id"] + "/content" ) as response: response.raise_for_status() with download.open("wb") as stream: for part in response.iter_bytes(): stream.write(part) digest.update(part) if digest.hexdigest() != binding["sha256"]: raise RuntimeError("下载首帧与归档SHA不一致") with Image.open(download) as image: actual_width, actual_height = image.size download.replace(target) job = next(j for j in snapshot["jobs"] if j["id"] == binding["source_job_id"]) state["frame"] = { "asset_id": binding["asset_id"], "sha256": binding["sha256"], "file": target.name, "job_id": binding.get("source_job_id"), "run_id": run["id"], "prompt": job["prompt"], "parameters": job["parameters"], "width": actual_width, "height": actual_height, "seed": job["parameters"]["seed"], "steps": job["parameters"]["num_inference_steps"], } write_json(STATE, state) (OUTPUT / "制作说明.md").write_text( "# H3 原生对白验收首帧\n\n" + f"故事:[{NAME}]({state['studio_url']})\n\n" + f"台词:{TEXT}\n\n原生视频计划为158帧、24fps,本脚本只创建故事和首帧,不提交视频任务。\n\n" + f"首帧意图:{APPEARANCE}{VISUAL}\n\n实际编译后的提示词保存在 production-state.json 的任务输入中。\n\n" + f"首帧原始尺寸:{actual_width}×{actual_height},保持原始像素及SHA,不做本地缩放。" + "H3视频的目标画布为1344×768,由模型条件输入预处理适配。\n\n" + f"素材ID:`{binding['asset_id']}`\n\nSHA256:`{binding['sha256']}`\n", encoding="utf-8", ) print( json.dumps( { "story_id": state["story_id"], "studio_url": state["studio_url"], "frame": state["frame"], "output": str(OUTPUT), }, ensure_ascii=False, ), flush=True, ) def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("action", choices=("prepare", "frame", "status", "export")) parser.add_argument( "--wait", action="store_true", help="每20秒查询,直到首帧成功;不提交视频" ) args = parser.parse_args() with production_lock(): execute(args) def execute(args): state = load_state() with local_session() as client: if args.action == "prepare": editor = prepare(client, state) print( json.dumps( { "story_id": state["story_id"], "version": editor["version"], "studio_url": state["studio_url"], }, ensure_ascii=False, ) ) return snapshot = ( frame(client, state) if args.action == "frame" else poll(client, state) ) while args.wait and snapshot["run"]["state"] not in { "succeeded", "failed", "cancelled", "blocked", }: time.sleep(20) snapshot = poll(client, state) if args.action == "export" or snapshot["run"]["state"] == "succeeded": export(client, state, snapshot) if __name__ == "__main__": main()