1325 lines
74 KiB
Python
1325 lines
74 KiB
Python
"""提示词组装:把角色设定、场景、景别/运镜、台词与全局风格拼成供应商提示词。
|
||
|
||
镜头提示词 = 全局风格 + 角色一致性描述 + 场景 + 画面描述 + 摄影语言 + 时长/画幅 + 台词情绪。
|
||
每次重新生成都会写入 PromptRevision,满足「调整提示词或重新生成」的可追溯要求。
|
||
"""
|
||
from __future__ import annotations
|
||
|
||
import re
|
||
|
||
from sqlalchemy.orm import Session
|
||
|
||
from app.constants import (AssetKind, CameraAngle, CameraMovement, ShotSize,
|
||
drop_topic, is_audio_topic, split_phrases)
|
||
from app.models import Character, Project, PromptRevision, Scene, Shot
|
||
from app.services import storage
|
||
|
||
_SIZE_HINT = {
|
||
ShotSize.EXTREME_WIDE: "大远景,强调环境与空间关系",
|
||
ShotSize.WIDE: "远景,人物小于环境",
|
||
ShotSize.FULL: "全景,人物全身入镜",
|
||
ShotSize.MEDIUM: "中景,膝盖以上",
|
||
ShotSize.CLOSE_UP: "近景,胸部以上,突出表情",
|
||
ShotSize.EXTREME_CLOSE_UP: "特写,局部细节",
|
||
}
|
||
_MOVE_HINT = {
|
||
CameraMovement.STATIC: "固定机位,画面稳定",
|
||
CameraMovement.PUSH_IN: "缓慢推镜,逐步靠近主体",
|
||
CameraMovement.PULL_OUT: "缓慢拉镜,逐步展开环境",
|
||
CameraMovement.PAN_LEFT: "机位向左摇",
|
||
CameraMovement.PAN_RIGHT: "机位向右摇",
|
||
CameraMovement.TILT_UP: "机位上摇",
|
||
CameraMovement.TILT_DOWN: "机位下摇",
|
||
CameraMovement.DOLLY_IN: "轨道推进",
|
||
CameraMovement.DOLLY_OUT: "轨道后拉",
|
||
CameraMovement.TRACK: "横向移镜跟随",
|
||
CameraMovement.ORBIT: "环绕主体",
|
||
CameraMovement.HANDHELD: "手持轻微晃动,纪实感",
|
||
CameraMovement.CRANE: "升降机大幅垂直运动",
|
||
CameraMovement.ZOOM_IN: "推焦放大",
|
||
CameraMovement.ZOOM_OUT: "拉焦缩小",
|
||
}
|
||
_ANGLE_HINT = {
|
||
CameraAngle.EYE_LEVEL: "平视视角", CameraAngle.HIGH: "俯拍视角", CameraAngle.LOW: "仰拍视角",
|
||
CameraAngle.BIRD_EYE: "鸟瞰视角", CameraAngle.DUTCH: "倾斜构图", CameraAngle.OVER_SHOULDER: "过肩镜头",
|
||
}
|
||
|
||
# 联合音视频专用**极简**镜头语言:首帧关键帧已经把景别锁死(``<Picture 1>`` 就是这一镜的第一帧),
|
||
# 「膝盖以上」「胸部以上,突出表情」「画面稳定」「逐步展开环境」这些解释性尾巴
|
||
# 既和图重复,又是最容易被念出来的词——S03 实测开头乱语里就出现了「中景,膝盖」。
|
||
# 只留模型必须知道的两个动词:什么景别、怎么运动。
|
||
_SIZE_TERSE = {ShotSize.FULL: "全景", ShotSize.MEDIUM: "中景", ShotSize.CLOSE_UP: "近景",
|
||
ShotSize.EXTREME_CLOSE_UP: "特写"}
|
||
_MOVE_TERSE = {CameraMovement.STATIC: "固定机位", CameraMovement.PUSH_IN: "缓慢推镜",
|
||
CameraMovement.PULL_OUT: "缓慢拉镜", CameraMovement.PAN_LEFT: "机位向左摇",
|
||
CameraMovement.PAN_RIGHT: "机位向右摇", CameraMovement.TILT_UP: "机位上摇",
|
||
CameraMovement.TILT_DOWN: "机位下摇", CameraMovement.DOLLY_IN: "轨道推进",
|
||
CameraMovement.DOLLY_OUT: "轨道后拉", CameraMovement.TRACK: "横向移镜跟随",
|
||
CameraMovement.ORBIT: "环绕主体", CameraMovement.HANDHELD: "手持轻晃",
|
||
CameraMovement.CRANE: "升降机垂直运动", CameraMovement.ZOOM_IN: "推焦放大",
|
||
CameraMovement.ZOOM_OUT: "拉焦缩小"}
|
||
|
||
|
||
def camera_terms(shot: Shot, *, with_lens_note: bool = True, terse: bool = False) -> list[str]:
|
||
"""把景别/机位/运镜翻成中文说法,**认不出的值一律不进提示词**。
|
||
|
||
数据库里存着写错列的脏枚举(project 11 S03 的景别是机位 over_shoulder)。
|
||
普通模型多一个英文词无所谓,联合音视频模型会把它照念一遍——
|
||
上一版每段开头那段杂音里就有这种英文原值。宁可少一个镜头语言描述,
|
||
也不能让脏数据变成画外音。
|
||
"""
|
||
from app.constants import normalize_camera_fields
|
||
|
||
size, angle, move = normalize_camera_fields(shot.shot_size, shot.camera_angle,
|
||
shot.camera_movement)
|
||
if terse:
|
||
size_hint, move_hint = _SIZE_TERSE, _MOVE_TERSE
|
||
else:
|
||
size_hint, move_hint = _SIZE_HINT, _MOVE_HINT
|
||
terms = [size_hint.get(size, ""), _ANGLE_HINT.get(angle, ""), move_hint.get(move, "")]
|
||
if with_lens_note and shot.lens_note:
|
||
terms.append(str(shot.lens_note).strip())
|
||
return [t for t in terms if t]
|
||
|
||
# 每个人物送进模型的「身份参照图」只取一张,优先级如下。
|
||
# 项目 9 实测的第 7 个根因:把同一人物的三视图(一张纸上并排站着正面/侧面/背面
|
||
# 三个全身像)和定妆图一起喂给 qwen-image / MiniMax H3,模型不会理解「这是同一个人
|
||
# 的多角度」,而是照着多出来的人再画一遍——成片里主角身后就多出一名穿同款西装的
|
||
# 背景同事,自动质检怎么返工都改不掉(返工话术是文字,毛病是从参考图里克隆来的)。
|
||
IDENTITY_KINDS = ("portrait", "costume", "expression", "turnaround")
|
||
CHAR_BUDGET = 6
|
||
SIZE_BUDGET = 9
|
||
MOVE_BUDGET = 7
|
||
ANGLE_BUDGET = 5
|
||
|
||
|
||
# 与定妆照冲突的文字描述:模型对「文字」的服从度高于「参考图」,
|
||
# 人物描述卡里写着「白色短款 T 恤 + 黑丝袜」,参考图换成西装,出片仍然是 T 恤。
|
||
# 因此当本镜头真的带上了这个人的定妆图/三视图时,衣着、发型、妆造与影棚摄影类
|
||
# 文字必须让位给参考图,只保留年龄气质这类不冲突的信息。
|
||
_COSTUME_MARKERS = ("衣", "服", "装", "穿", "裙", "裤", "袜", "鞋", "帽", "衫", "袄", "外套", "西装",
|
||
"夹克", "t恤", "T恤", "卫衣", "制服", "校服", "盔甲", "披风", "围巾", "手套",
|
||
"领带", "腰带", "印花", "图案", "布料", "面料", "丝绸", "牛仔", "礼服", "马甲",
|
||
"背心", "胸下", "截断", "露", "配饰", "项链", "耳环", "眼镜", "墨镜")
|
||
_HAIR_MARKERS = ("发型", "头发", "长发", "短发", "卷发", "直发", "大波浪", "波浪", "刘海", "盘发",
|
||
"辫", "染发", "发色", "头饰", "发饰", "松散黑色")
|
||
_STUDIO_MARKERS = ("柔光", "打光", "布光", "影棚", "背景虚化", "构图", "大片", "写真", "人像",
|
||
"中全景", "全景", "特写", "景深", "光影", "超清", "杰作", "8k", "4k", "高清")
|
||
|
||
|
||
def conflicting_traits(text: str) -> list[str]:
|
||
"""挑出会与定妆照打架的短语(衣着/发型/影棚风格)。"""
|
||
hits: list[str] = []
|
||
for phrase in re.split(r"[,、。;;\n]+", str(text or "")):
|
||
clean = phrase.strip()
|
||
if not clean:
|
||
continue
|
||
probe = clean.lower()
|
||
if any(marker in probe for marker in _COSTUME_MARKERS + _HAIR_MARKERS + _STUDIO_MARKERS):
|
||
hits.append(clean)
|
||
return hits
|
||
|
||
|
||
def non_conflicting_traits(text: str) -> str:
|
||
drop = set(conflicting_traits(text))
|
||
kept = [phrase.strip() for phrase in re.split(r"[,、。;;\n]+", str(text or ""))
|
||
if phrase.strip() and phrase.strip() not in drop]
|
||
return ",".join(kept)
|
||
|
||
|
||
# ================================================================ 联合音视频(joint_av)
|
||
# MiniMax H3 这类模型一次前向同时出画面和音轨,**整段提示词既是画面脚本也是声音脚本**。
|
||
# 实测(项目 11「告诉你个小秘密第1期」,逐段 ASR 对齐 + A/B 复现):
|
||
# · 「……以定妆图/三视图为准,不得按文字另行改写衣着」→ 成片 0-2.8s 念出「拒绝按摩另行改写移拙」;
|
||
# · 「这一段没有人说话」→ 片尾真的冒出一句「没有人说话」;
|
||
# · 「俊杰说:“…”」→ 开头先念三遍「俊杰 俊杰 俊杰」;
|
||
# · 纯视觉 caption + 「{名}台词:「…」」→ 从 0.00s 正常开口,无乱语。
|
||
# 所以给这类模型的提示词必须遵守三条硬规则:
|
||
# 1. 只写**看得见的东西**(名词短语优先),关于说话/声音/下指令的句子一律不进;
|
||
# 2. 一致性约束靠 **<Picture n> 官方标签**锚定参考图,不靠「必须/严禁」这类话;
|
||
# 3. 环境声用「听得见的名词短语」(键盘敲击声、安静的房间底噪),不写成句子;
|
||
# 4. 台词只写官方语音标记 <d>…</d> 里的原文,音色靠 <Audio n> 引用随附参考音频,
|
||
# 不写「俊杰台词:」这种自造约定(模型会连前后描述一起念)。
|
||
JOINT_PICTURE_MARK = "<Picture " # 缓存提示词里出现它 = 这一版是按 joint_av 写的
|
||
|
||
# 参考图标签的写法:
|
||
# inline = 「<Picture 2>中的俊杰」——标签当定语,紧跟名词;
|
||
# prefix = 「<Picture 2>是俊杰」——旧写法,提示词开头是若干条陈述整句。
|
||
# 为什么默认改成 inline(v2 成片逐镜 ASR 实测):H3 会把开头那几条
|
||
# 「<Picture 1>是这一镜的画面。<Picture 2>是俊杰,高大,和蔼。」**原样念出来**,
|
||
# 于是每个有声镜头前面都多出 2.0~2.7s 谁也听不懂的话,后面台词反而正常。
|
||
# 陈述句「X 是 Y」在联合音视频模型眼里就是旁白文本,而定语「Y 中的 X」不是句子,
|
||
# 没有可读性,模型就不会张嘴。留 prefix 开关是为了随时回退做 A/B。
|
||
JOINT_REF_STYLE = "inline"
|
||
|
||
# 官方 tokenizer 里「说出口的话」有专用边界:comfy/text_encoders/minimax.py 的
|
||
# MINIMAX_EXTRA_TOKENS 注册了 ``<d>``=151669、``</d>``=151670(还有 caption/lyrics 起止)。
|
||
# ComfyUI 只把它们加进词表、**不会自动插**,所以这一段格式得由提示词自己写。
|
||
# 之前用散文「俊杰台词:「…」」是自造约定,模型只能猜哪一段是话——猜错的代价就是
|
||
# 把前后的画面描述当台词念出来(项目 11 每一镜开头那段乱语)。
|
||
JOINT_SPEECH_MARK = "<d>"
|
||
JOINT_SPEECH_OPEN, JOINT_SPEECH_CLOSE = "<d>", "</d>"
|
||
# 参考音色的官方引用写法(MiniMaxH3ReferenceToVideo docstring:
|
||
# "the prompt refers to them as <Picture i> / <Video k> / <Audio j>")。
|
||
# 只喂 ref_audio 不在文字里引用 = 这条嗓子没有挂靠点,take5 实测开头冒出 13 个音节、
|
||
# F0 128Hz,而声线样本「你好,我是俊杰,是公司的产品专家。」正好 14 个音节。
|
||
JOINT_AUDIO_MARK = "<Audio "
|
||
# 旧版 joint caption 的指纹:时长/画幅是 length/width/height 结构化入参,写进文字里
|
||
# 只会多一句可被念出来的话,已删;靠它把老缓存顶掉重算。
|
||
JOINT_LEGACY_MARK = "时长约 "
|
||
# H3 实测语速(项目 11 两组独立 ASR 对齐:19 字/3.9s=4.9、35 字/6.8s=5.16)。
|
||
# TTS 用的 audio.CPS_CJK=4.3 偏慢,拿它排 H3 的镜头会多留 1.5~2.4s 空档;
|
||
# 而**音轨长度 = 请求帧数**,空档必须被填满,填什么模型自己挑 ⇒ 又是开头乱语。
|
||
JOINT_CPS_CJK = 5.0
|
||
JOINT_WPS_LATIN = 2.6
|
||
JOINT_SPEECH_PAD_SECONDS = 0.25 # 起音留白,避免第一个字被切在 0 帧上
|
||
|
||
# joint 专用剔除词:不是「关于声音」,但同样容易被念出来的口水句。
|
||
# **不是画面内容**的元指令:画幅/分辨率/帧率是 width/height/fps 结构化入参,
|
||
# 「无水印无字幕」是给生图看的要求,「跨镜头严格一致」视频模型没能力执行——
|
||
# 它们出现在任何字段(项目 style_guide、场景描述、人物外观、分镜文案)里都只会
|
||
# 被 H3 当台词念。挂在 sanitize_visual 这一层,四类来源一次管住。
|
||
_JOINT_STRIP_MARKERS = ("符合", "以上传", "随附", "保持造型", "参考图", "定妆图", "三视图",
|
||
"为准", "按文字", "第1轮", "第2轮", "轮】", "自动质检", "判定不合格",
|
||
"无字幕", "无水印", "水印", "9:16", "16:9", "竖屏", "横屏", "画幅",
|
||
"分辨率", "帧率", "跨镜头", "严格一致", "保持一致", "完全一致")
|
||
# 「长相、发型与服装完全以定妆图为准」这种整句被剔掉后剩下的词根:留着没有信息量,
|
||
# 只会被模型当成一句没说完的话念出来。
|
||
_JOINT_FRAGMENT_DROP = {"长相", "发型", "服装", "衣着", "妆造", "造型", "五官", "着装",
|
||
"人物五官", "人物长相", "肤色", "人物", "细节", "材质", "纹理", "光影",
|
||
"透视", "构图", "氛围", "质感", "主角"}
|
||
|
||
|
||
# 联合音视频模型的调用方式决定了文字预算很贵:人物的长相/发型/衣着由**定妆图**
|
||
# (``<Picture n>`` 参照图)锁死,场景由**场景图**锁死,构图由**首帧关键帧**锁死。
|
||
# 项目/人物资料里那些为「文生图」写的描述词因此全是重复劳动,
|
||
# 而 H3 的文本入口只有一个 prompt、没有 negative、没有 chat 模板
|
||
# ——重复的每一段都是「可能被念出来的候选台词」。以下三组按这个前提取消:
|
||
#
|
||
# * 看不见的气质/性格词:定妆图演不出来,文字也演不出来,只会被念(「轻熟纯欲气质」);
|
||
# * 妆造词:图里已经有妆,文字复述纯属占位(「精致淡妆」);
|
||
# * 一致性元指令:persona_prompt 里那一大段「跨镜头严格一致/固定面部骨骼/8k」
|
||
# 是写给**出图**环节看的,模型读了只会当台词(且它并没有能力“一致”)。
|
||
_JOINT_LOOK_DROP_MARKERS = ("气质", "纯欲", "气场", "人设", "性格", "和蔼", "温柔", "善良", "沉稳",
|
||
"给人", "感觉", "可靠", "亲切", "专业", "稳重", "内敛", "活泼", "稚气",
|
||
"正义", "勇敢", "冷酷", "高冷", "神秘", "羞涩", "坚毅", "耿直", "侠女",
|
||
"憨厚", "开朗", "自信", "认真", "执着", "俏皮", "灵动", "优雅", "帅气",
|
||
"美丽", "漂亮", "可爱", "轻熟", "成熟", "大方", "干练")
|
||
_JOINT_MAKEUP_MARKERS = ("妆", "眉形", "口红", "腮红", "淡颜")
|
||
_JOINT_PERSONA_DROP_MARKERS = ("一致性", "跨镜头", "锚点", "锁定", "固定面", "面部骨骼", "骨骼",
|
||
"五官比例", "8k", "80k", "4k", "极高细节", "超清", "杰作", "写实人像",
|
||
"无字幕", "无水印", "不做动画", "电影级", "胶片颗粒", "分辨率")
|
||
# 项目 style_guide 常混进「不是画面」的东西:画幅/时长是 length/width/height 结构化入参,
|
||
# 「环境音:…」是声音内容(写在这儿等于要求模型把这几个字念出来,环境声有专门通道
|
||
# —— shot.ambience)。
|
||
_JOINT_STYLE_DROP_MARKERS = ("环境音", "画幅", "竖屏", "横屏", "分辨率", "帧率", "9:16", "16:9",
|
||
"无字幕", "无水印", "秒", "水印",
|
||
"一致", "锁定", "跨镜头", "动作连贯")
|
||
|
||
|
||
def drop_phrases(text: str, markers) -> str:
|
||
"""按短语粒度丢弃命中 markers 的片段(保留其余片段原序)。"""
|
||
kept = [piece for piece in split_phrases(text)
|
||
if piece.strip() and not any(marker in piece for marker in markers)]
|
||
return ",".join(kept)
|
||
|
||
|
||
# 「嘴/唇」是发声器官词,写进 H3 的文字里就会被念出来(见 AUDIO_TOPIC_MARKERS),
|
||
# 于是「嘴角带笑」这类**纯表情**描述会被 sanitize_visual 整条丢掉、白白损失内容。
|
||
# 这里先把常见说法原地换成不带发声器官的等价写法,剩下的(「嘴唇微张」「张口说话」)
|
||
# 仍然交给 drop_topic 删掉——那种句子本来就不该出现在 joint caption 里。
|
||
_MOUTH_IDIOMS: list[tuple[re.Pattern, str]] = [
|
||
(re.compile(r"嘴角[^,。;、]{0,4}?(笑意|微笑|笑|弧度|上扬|微扬)"), "面带笑意"),
|
||
(re.compile(r"嘴角"), "脸颊"),
|
||
(re.compile(r"(抿|咧|张|张开的)嘴(?:巴)?(?=[笑咧])"), "脸"),
|
||
(re.compile(r"嘴唇?[^,。;、]{0,3}?(微笑|含笑|带笑|上扬)"), "面带笑意"),
|
||
(re.compile(r"唇角"), "脸侧"),
|
||
]
|
||
|
||
|
||
def rewrite_mouth_idioms(text: str) -> str:
|
||
"""表情类「嘴」字说法 → 不含发声器官的同义写法(只服务 joint caption)。"""
|
||
out = str(text or "")
|
||
for pattern, repl in _MOUTH_IDIOMS:
|
||
out = pattern.sub(repl, out)
|
||
return out
|
||
|
||
|
||
def sanitize_visual(text: str) -> str:
|
||
"""把任意来源的文案洗成「可以放心喂给联合音视频模型」的视觉描述。
|
||
|
||
先把表情惯用语里的「嘴角/唇角」改写掉(否则整句会被误删),再按标点拆短语,
|
||
丢掉三类内容:讲声音/说话的、给系统下指令的、
|
||
以及 joint 专属的口水句(「符合都市轻松风格」这种被 ASR 抓到念出来过)。
|
||
"""
|
||
kept: list[str] = []
|
||
for piece in drop_topic(rewrite_mouth_idioms(text)).split(","):
|
||
clean = piece.strip()
|
||
if not clean:
|
||
continue
|
||
probe = clean.lower()
|
||
if clean in _JOINT_FRAGMENT_DROP or any(marker in probe for marker in _JOINT_STRIP_MARKERS):
|
||
continue
|
||
kept.append(clean)
|
||
return ",".join(kept)
|
||
|
||
|
||
def joint_cast_brief(char: Character, *, portrait_bound: bool) -> str:
|
||
"""joint caption 里的人物描述:**不带名字**(名字由 <Picture n> 锚定句给出),
|
||
不带「长相发型以定妆图为准」这类指令句,只留看得见的人物特征。"""
|
||
bits = []
|
||
if char.appearance:
|
||
bits.append(non_conflicting_traits(char.appearance) if portrait_bound else char.appearance)
|
||
# persona_prompt **整条不进联合音视频提示词**:它是写给定妆图的一致性元指令
|
||
# (「同一位……五官、发型和服装跨镜头严格一致」「8k分辨率,电影级光影,masterpiece」
|
||
# 「【真实大模型 qwen/qwen3.7-plus】」),全库角色里没有一个人靠它提供独有外貌
|
||
# (appearance 为空而 persona_prompt 非空的角色 = 0 个),它却动辄 300~400 字,
|
||
# 而 H3 会把这一整段当台词念出来。出图路径照旧使用它,这里只是不再进视频提示词;
|
||
# 万一将来有人只填了 persona_prompt,仍按兜底放行,避免人物变成无名氏。
|
||
if char.persona_prompt and not (char.appearance or "").strip():
|
||
bits.append(char.persona_prompt)
|
||
text = sanitize_visual(",".join(b for b in bits if b))
|
||
# 一致性元指令(「跨镜头严格一致」「固定面部骨骼」「8k」)与影棚出图行话
|
||
# (「杰作/柔光/背景虚化/中全景/构图高级」)对视频模型既无法执行又会被念出来,
|
||
# 有没有定妆图都得删。非 portrait_bound 这条分支以前没人管:实测漏出
|
||
# 「柔和影棚柔光,背景虚化,中全景,时尚大片,构图高级」,其中「中全景」
|
||
# 还和本镜自己的「中景」直接打架。
|
||
text = drop_phrases(text, _JOINT_LOOK_DROP_MARKERS + _JOINT_MAKEUP_MARKERS
|
||
+ _JOINT_PERSONA_DROP_MARKERS + _STUDIO_MARKERS)
|
||
name = str(char.name or "").strip()
|
||
if text.startswith(name + ","):
|
||
text = text[len(name) + 1:]
|
||
return text
|
||
|
||
|
||
def joint_av_mode(db: Session | None, project: Project, shot: Shot) -> bool:
|
||
"""这一镜要用的视频模型是不是「音画一次成片」的联合音视频模型。
|
||
|
||
判定只看模型能力位(``Capabilities.joint_av``):时间线设置管的是「台词交给谁」,
|
||
而提示词该怎么写取决于「模型会不会把文字念出来」,两者必须分开判断。
|
||
"""
|
||
if db is None:
|
||
return False
|
||
from app.providers import registry as model_registry
|
||
|
||
try:
|
||
spec, _adapter = model_registry.resolve_video(db, shot.provider or project.default_provider,
|
||
shot.model or None)
|
||
return bool(model_registry.capabilities_of(spec).joint_av)
|
||
except Exception: # noqa: BLE001 - 判不出就当普通模型
|
||
return False
|
||
|
||
|
||
def joint_plan_stale(prompt_text: str, *, joint: bool, has_dialogue: bool = False) -> bool:
|
||
"""缓存的提示词是按另一种模型形态(或旧版 joint 格式)写的。
|
||
|
||
joint -> 普通:文字里全是「<Picture 3>」这种标签,普通模型看不懂;
|
||
普通 -> joint:留着「必须/严禁/为准」的指令句,模型会照着念出一段乱语。
|
||
joint -> joint(改版格式):老 caption 带着「时长约 9 秒」这类**会被念出来**的冗余句,
|
||
或者台词还没进 ``<d>`` 官方标记,都必须重算,否则改了格式却仍在下发旧文案。
|
||
"""
|
||
text = prompt_text or ""
|
||
if not text.strip():
|
||
return False
|
||
if (JOINT_PICTURE_MARK in text) != bool(joint):
|
||
return True
|
||
if not joint:
|
||
return JOINT_SPEECH_MARK in text
|
||
if JOINT_LEGACY_MARK in text:
|
||
return True
|
||
return bool(has_dialogue) and JOINT_SPEECH_MARK not in text
|
||
|
||
def picture_roles(db: Session, shot: Shot, *, first_frame: str = "", last_frame: str = "",
|
||
limit: int = 0) -> list[dict]:
|
||
"""把「模型实际收到的参考图顺序」翻译成 ``<Picture n>`` 的身份标签。
|
||
|
||
H3 的官方标签按下发顺序计数,所以这里必须复用适配器那一份选图逻辑
|
||
(``comfyui.reference_inputs``),否则提示词里的「<Picture 2> 是俊杰」
|
||
指的其实是场景图,身份锚定反而比不加标签更糟。
|
||
"""
|
||
from app.providers.comfyui import reference_inputs
|
||
from app.providers.base import VideoGenRequest
|
||
|
||
details = collect_reference_details(db, shot)
|
||
by_path = {str(row["path"]): row for row in details}
|
||
ranked = [str(row["path"]) for row in details]
|
||
explicit = [path for path in ranked if by_path.get(path, {}).get("owner_type") == "shot"]
|
||
probe = VideoGenRequest(prompt="", duration_seconds=0, reference_images=ranked,
|
||
explicit_reference_images=explicit)
|
||
used = reference_inputs(probe, first_frame or "", int(limit or 99), last=last_frame or "")
|
||
kind_labels = {"portrait": "定妆照", "turnaround": "三视图", "costume": "服装照",
|
||
"expression": "表情参考", "scene_image": "场景", "keyframe": "首帧画面",
|
||
"last_frame": "尾帧画面", "reference_image": "参考图", "reference": "参考图"}
|
||
roles: list[dict] = []
|
||
for idx, path in enumerate(used, start=1):
|
||
row = by_path.get(str(path))
|
||
if row is None:
|
||
if str(path) == str(first_frame or ""):
|
||
roles.append({"index": idx, "path": str(path), "label": "这一镜的首帧画面",
|
||
"owner_type": "frame", "owner_id": None, "name": ""})
|
||
continue
|
||
roles.append({"index": idx, "path": str(path), "label": "参考图",
|
||
"owner_type": "other", "owner_id": None, "name": ""})
|
||
continue
|
||
name = str(row.get("owner_name") or "")
|
||
kind = str(row.get("kind") or "")
|
||
roles.append({"index": idx, "path": str(path), "owner_type": row.get("owner_type"),
|
||
"owner_id": row.get("owner_id"), "kind": kind, "name": name,
|
||
"label": (f"{name}的{kind_labels.get(kind, kind)}" if name
|
||
else kind_labels.get(kind, "参考图"))})
|
||
return roles
|
||
|
||
|
||
def joint_dialogue_lines(shot: Shot) -> list[dict]:
|
||
"""joint 台词行:``{speaker, text, character_id}``。
|
||
|
||
``speaker`` **不再写进 caption**(「俊杰台词:」这种前缀实测会被一起念出来),
|
||
只用来把这一行绑到正确的 ``<Audio n>`` 参考音色上;「谁在说话」由首帧的
|
||
镜头调度决定,见 :func:`keyframe_speech_note`。
|
||
"""
|
||
lines = shot.all_lines()
|
||
out: list[dict] = []
|
||
for line in lines:
|
||
name = shot.line_speaker_name(line) or "角色"
|
||
out.append({"speaker": name, "text": line["text"], "character_id": line.get("character_id")})
|
||
return out
|
||
|
||
def character_brief(char: Character, *, portrait_bound: bool = False) -> str:
|
||
bits = [char.name.strip()]
|
||
if char.appearance:
|
||
# 有定妆照入模时只保留不冲突的部分(年龄、气质、体型观感),避免文字盖过参考图
|
||
bits.append(non_conflicting_traits(char.appearance) if portrait_bound
|
||
else char.appearance.strip())
|
||
if char.persona_prompt:
|
||
bits.append(char.persona_prompt.strip())
|
||
if portrait_bound:
|
||
bits.append("长相、发型与服装完全以随附的定妆图/三视图为准")
|
||
brief = ",".join(b for b in bits if b)
|
||
return brief or char.name
|
||
|
||
|
||
def multi_view_characters(db: Session, shot: Shot) -> list[str]:
|
||
"""本镜头只能拿三视图当参照的人物名(这类图上一个人在纸上出现三次,最容易克隆)。"""
|
||
if db is None:
|
||
return []
|
||
return sorted({str(row.get("owner_name") or "")
|
||
for row in collect_reference_details(db, shot)
|
||
if row.get("owner_type") == "human" and row.get("multi_view")})
|
||
|
||
|
||
def portrait_bound_ids(db: Session, shot: Shot) -> set[int]:
|
||
"""本镜头的参考素材里已经有定妆图/三视图的人物 id。"""
|
||
return {int(row["owner_id"]) for row in collect_reference_details(db, shot)
|
||
if row.get("owner_type") == "human" and row.get("kind") in ("portrait", "turnaround")}
|
||
|
||
|
||
def voice_timbre_hint(db: Session, project: Project, shot: Shot) -> str:
|
||
"""说话人绑定声线的音色描述:MiniMax H3 这类原生音画同步模型会自己挑嗓子,
|
||
不给提示就用通用嗓,于是「同一个陌生人」反复出现在不同角色嘴里。"""
|
||
from app.services import audio
|
||
|
||
voice, _info = audio.resolve_voice(db, project, shot)
|
||
if voice is None:
|
||
return ""
|
||
bits = [audio.GENDER_LABELS.get(str(voice.gender or ""), ""),
|
||
audio.AGE_BAND_LABELS.get(audio.voice_age_band(voice), ""),
|
||
str(voice.description or "").strip()]
|
||
text = ",".join(b for b in bits if b)
|
||
return text[:80]
|
||
|
||
|
||
# 走「模型直出语音」时给台词段的硬约束:口型必须对得上,且不许有旁白/字幕抢戏。
|
||
NATIVE_SPEECH_NOTE = ("人物开口说出这句台词,语音与口型严格同步,音色以随附的参考音频为准;"
|
||
"除台词与必要环境声外不要背景音乐,不要旁白,不要画面字幕")
|
||
|
||
|
||
# 判断缓存提示词是按哪种语音方案写的:文字音色描述 vs 随附参考音频。
|
||
TEXT_VOICE_MARK = "说话音色:"
|
||
NATIVE_VOICE_MARK = "音色以随附的参考音频为准"
|
||
|
||
|
||
def native_voice_mode(db: Session, project: Project, shot: Shot) -> bool:
|
||
"""这一镜的台词是否该由视频模型直出(时间线设置 + 模型能力)。"""
|
||
from app.services import timeline as timeline_service
|
||
|
||
try:
|
||
return timeline_service.native_voice_wanted(db, project, shot)
|
||
except Exception: # noqa: BLE001 - 判定失败退回「按文字描述音色」
|
||
return False
|
||
|
||
|
||
def voice_plan_stale(prompt_text: str, *, native: bool) -> bool:
|
||
"""缓存的提示词还在按另一种语音方案说话(改了时间线设置或换了模型后必然发生)。
|
||
|
||
留着「说话音色:男声,中年声」而同时又喂参考音频更糟:模型对文字的服从度高于
|
||
参考输入,角色一开口就换人。命中冲突时由调用方按当前方案重算整段提示词。
|
||
"""
|
||
text = prompt_text or ""
|
||
if not text.strip():
|
||
return False
|
||
if native:
|
||
return TEXT_VOICE_MARK in text and NATIVE_VOICE_MARK not in text
|
||
return NATIVE_VOICE_MARK in text
|
||
|
||
|
||
def line_speaker_character(shot: Shot, line: dict) -> Character | None:
|
||
"""某一行的说话人角色对象(``character_id`` 优先,其次行上的名字)。"""
|
||
cid = line.get("character_id")
|
||
try:
|
||
cid = int(cid) if cid else None
|
||
except (TypeError, ValueError):
|
||
cid = None
|
||
chars = list(shot.characters or [])
|
||
if cid:
|
||
for char in chars:
|
||
if char.id == cid:
|
||
return char
|
||
if shot.speaker is not None and shot.speaker.id == cid:
|
||
return shot.speaker
|
||
name = str(line.get("name") or "").strip()
|
||
if name:
|
||
for char in chars:
|
||
if str(char.name or "").strip() == name:
|
||
return char
|
||
return None
|
||
|
||
|
||
def dialogue_voices(db: Session, project: Project, shot: Shot) -> list:
|
||
"""本镜头台词可能用到的声线,**按台词出现的顺序**排列。
|
||
|
||
顺序就是 ``<Audio n>`` 的序号::func:`compose_joint_caption` 给某句台词打标签时
|
||
查的是这同一条列表(``ref_audios.ref_audio_{n-1}`` 由 ComfyUI 按输入顺序编号),
|
||
所以「谁的嗓子排在第几条」必须由「谁先开口」决定。
|
||
|
||
只收「有明确依据」的声音:逐句说话人自己的默认声线,加上镜头级解析出的主声线、
|
||
以及台词文案里点了名的出镜角色自带声线。没有依据的角色不塞,否则 H3 会在
|
||
3 条参考里随机挑,反而更容易串音。
|
||
|
||
旧实现只按 ``shot.speaker_character_id`` 收 1 条,再靠「台词文字里出现名字」补人:
|
||
双人对白镜头(``shot.lines`` 两个 ``character_id``)通常只下发一条参考音频,
|
||
第二个人根本拿不到自己的 ``<Audio n>``,于是整段话由第一个人的嗓子念完。
|
||
"""
|
||
from app.models import VoiceAsset
|
||
from app.services import audio
|
||
|
||
out: list = []
|
||
seen: set[int] = set()
|
||
|
||
def push(voice) -> bool:
|
||
if voice is None or getattr(voice, "id", None) in seen:
|
||
return False
|
||
seen.add(voice.id)
|
||
out.append(voice)
|
||
return True
|
||
|
||
unvoiced = False
|
||
for line in shot.all_lines():
|
||
char = line_speaker_character(shot, line)
|
||
voice = db.get(VoiceAsset, char.default_voice_id) if (
|
||
char is not None and char.default_voice_id) else None
|
||
if voice is None:
|
||
unvoiced = True
|
||
continue
|
||
push(voice)
|
||
|
||
# 有人没绑自己的声线时才补镜头级声线:那可能是运营在分镜上手工指定的音色,
|
||
# 也可能是老数据(只有 dialogue + speaker)。逐句全都绑好了就别再塞,多一条
|
||
# 无关音色进参考池,模型就多一个可以挑错的嗓子。
|
||
if unvoiced or not out:
|
||
push(audio.resolve_voice_asset(db, project, shot))
|
||
dialogue = str(shot.dialogue or "")
|
||
for char in list(shot.characters or []):
|
||
if char.default_voice_id and char.name and char.name in dialogue:
|
||
push(db.get(VoiceAsset, char.default_voice_id))
|
||
return out
|
||
|
||
|
||
def reference_voice_audios(db: Session, project: Project, shot: Shot, *, limit: int,
|
||
allow: bool = True) -> tuple[list[str], list]:
|
||
"""把声线的克隆样本换成「能上传给模型的参考音频」绝对路径列表。
|
||
|
||
返回 (音频路径, 对应声线)。取不到文件不是错误:少了参考只会让模型自己挑嗓子,
|
||
口型仍然是对的,绝不能因此挡住整条生成链路。
|
||
"""
|
||
from app.services import audio, storage
|
||
|
||
if not allow or limit <= 0 or not str(shot.dialogue or "").strip():
|
||
return [], []
|
||
paths: list[str] = []
|
||
used: list = []
|
||
for voice in dialogue_voices(db, project, shot)[:limit]:
|
||
rel = audio.current_voice_audio(db, voice)
|
||
if not rel:
|
||
continue
|
||
absolute = str(storage.to_absolute(rel))
|
||
if not storage.exists(rel):
|
||
continue
|
||
# 同一个样本文件被两条声线共用时只算一条:适配器上传前会按路径去重,
|
||
# 这里不去重就会比 caption 里的 <Audio n> 少一个槽位,序号集体错位,
|
||
# 台词就安到别人的嗓子上。宁可少一条参考,也不能错绑。
|
||
if absolute in paths:
|
||
continue
|
||
paths.append(absolute)
|
||
used.append(voice)
|
||
return paths, used
|
||
|
||
|
||
# 过肩/越肩机位 + 推镜是「凭空多出一只手」的高发组合:摄像机绕到人物背后时,
|
||
# 模型会把原本属于主角的那只手保留成前景元素,再给主角补一只,于是同一镜头里
|
||
# 出现三只手(项目 9 镜头 03 实测:第 4 帧三只手 → 自动质检连拒 2 轮,调度判失败)。
|
||
OTS_HINTS = ("over_shoulder", "过肩", "越肩", "ots")
|
||
|
||
|
||
def hand_ownership_note(shot: Shot) -> str:
|
||
"""镜头语言带过肩/越肩时,给画面加一条「每只手都必须有主人」的硬约束。"""
|
||
text = " ".join(str(v or "") for v in (
|
||
shot.camera_angle, shot.camera_movement, shot.lens_note, shot.description)).lower()
|
||
if not any(hint in text for hint in OTS_HINTS):
|
||
return ""
|
||
return ("过肩镜头的前景肩膀与手臂必须属于画面中已出镜的人物之一,"
|
||
"不得为了过肩而引入画面外的第三人;画面里每一只手都要能连到某位出镜人物身上,"
|
||
"同一个人任何时候都不得超过两只手,严禁出现第三只手或悬空的手")
|
||
|
||
|
||
def dialogue_speakers(shot: Shot, lines: list[dict] | None = None) -> list[str]:
|
||
"""本镜开口说话的顺序去重人名(逐句台词与单条 dialogue 都走同一套解析)。"""
|
||
speakers: list[str] = []
|
||
for line in (lines if lines is not None else joint_dialogue_lines(shot)):
|
||
name = str(line.get("speaker") or "").strip()
|
||
if name and name not in speakers:
|
||
speakers.append(name)
|
||
return speakers
|
||
|
||
|
||
def speaking_subject_note(shot: Shot, lines: list[dict] | None = None) -> str:
|
||
"""台词之外那句「谁在镜头前出声」的构图描述——**只给图像通道用**。
|
||
|
||
项目 11《告诉你个小秘密第1期》shot 36 连摇四轮 A/B(逐段词级 ASR):
|
||
首帧里两个人都闭着嘴微笑时,H3 找不到出声的人,就在开头即兴补一段无源人声,
|
||
中段还把机位切到另一张更像在说话的脸上(观众听到的「每段视频前面那几句莫名其妙的话」);
|
||
首帧换成「说话人正面朝向镜头、嘴已经张开」后,说话人与镜头主体一致。
|
||
但这句**写进 H3 的文字里就会被念出来**(take2/3/4 全部命中),
|
||
所以联合 caption 不再引用它,见 :func:`compose_joint_caption` 的 4b 注释。
|
||
|
||
``params_json.speaking_lock=false`` 可以关掉(画外音、背影镜头)。
|
||
"""
|
||
if not bool((shot.params_json or {}).get("speaking_lock", True)):
|
||
return ""
|
||
speakers = dialogue_speakers(shot, lines)
|
||
if not speakers:
|
||
return ""
|
||
on_cam = "、".join(speakers[:2])
|
||
others = [n for n in (str(c.name or "").strip() for c in (shot.characters or []))
|
||
if n and n not in speakers][:2]
|
||
if len(speakers) == 1:
|
||
text = f"{on_cam}位于前景正中,正面朝向镜头,人物最大最清晰"
|
||
else:
|
||
# 一镜多人轮流开口:每个人轮到自己时都要正对镜头,否则模型照样找人替说
|
||
text = f"{on_cam}依次正面朝向镜头,轮到时位于前景正中、人物最大最清晰"
|
||
if others:
|
||
# 非说话人不给任何「脸部/发声」描述,免得模型安排一问一答
|
||
text += f";{'、'.join(others)}位于侧后方,面朝桌面"
|
||
return text
|
||
|
||
|
||
def keyframe_speech_note(shot: Shot) -> str:
|
||
"""有台词镜头的首帧:把「正在讲话的那个人」画出来,i2v 才知道该让谁出声。
|
||
|
||
联合音视频模型是照着首帧决定出声者的(详见 :func:`speaking_subject_note`),
|
||
所以首帧构图不是「好不好看」的问题,而是音画同步的前置条件。
|
||
图像模型没有「文字会被念出来」的顾虑,这里可以用完整措辞。
|
||
"""
|
||
if not bool((shot.params_json or {}).get("speaking_lock", True)):
|
||
return ""
|
||
speakers = dialogue_speakers(shot)
|
||
if not speakers:
|
||
return ""
|
||
# 首帧定格在镜头开头,所以画的是**第一个开口的人**;后面才轮到的角色不必张嘴
|
||
on_cam = speakers[0]
|
||
others = [n for n in (str(c.name or "").strip() for c in (shot.characters or []))
|
||
if n and n != on_cam][:2]
|
||
text = (f"{on_cam}是本帧画面的主体,正面或四分之三侧面朝向镜头,"
|
||
f"嘴部微张、停在正在讲话的那一瞬间")
|
||
if others:
|
||
text += f";{'、'.join(others)}位于背景或只露出背影侧后方,嘴部闭合"
|
||
return text
|
||
|
||
|
||
CONVERSATIONAL_MARKERS = ("听着", "在听", "倾听", "聆听", "解释", "介绍", "说明", "讨论",
|
||
"交谈", "聊天", "商量", "回应", "回答", "答复", "询问", "提问",
|
||
"叮嘱", "提醒", "寒暄", "打招呼", "告别", "道谢")
|
||
|
||
|
||
def drop_conversational(text: str) -> str:
|
||
"""剔除「正在进行一场交谈」式动作短语,只留下确实看得见的姿态。
|
||
|
||
联合音视频模型把提示词同时当声音脚本(见 :data:`app.constants.AUDIO_TOPIC_MARKERS`):
|
||
shot 36 的「紫小慧在背景里**听着**」「一只手做**解释**的手势」让它先安排了一问
|
||
一答(0.0~1.2s 俊杰、1.4~2.2s 紫小慧各一句即兴话语),2.6s 之后才念真正的台词。
|
||
丢一个手势细节换开头干净,是划算的。
|
||
"""
|
||
kept = [piece for piece in split_phrases(text)
|
||
if not any(marker in piece for marker in CONVERSATIONAL_MARKERS)]
|
||
return ",".join(kept)
|
||
|
||
|
||
def joint_voice_names(db: Session, project: Project, shot: Shot, *,
|
||
voices: list | None = None, limit: int = 3) -> list[str]:
|
||
"""参考音色的**下发顺序** -> 对应的说话人名,用于写 ``<Audio n>`` 标签。
|
||
|
||
``<Audio 2>`` 指的是第 2 条 ``ref_audio_1``:序号由 ComfyUI 按节点输入顺序分配,
|
||
所以这里必须复用 ``reference_voice_audios`` 那一份列表,顺序一错标签就把台词
|
||
安到别人的嗓子上。``voices`` 留空(``sync_prompt`` 那条路径)时按同口径自算。
|
||
"""
|
||
if voices is None:
|
||
_paths, voices = reference_voice_audios(db, project, shot, limit=limit)
|
||
chars = list(project.characters or [])
|
||
out: list[str] = []
|
||
for voice in voices or []:
|
||
name = ""
|
||
for char in chars:
|
||
if getattr(char, "default_voice_id", None) == getattr(voice, "id", None):
|
||
name = str(char.name or "").strip()
|
||
break
|
||
out.append(name)
|
||
return out
|
||
|
||
|
||
def joint_speech_duration_seconds(db: Session, project: Project, shot: Shot, caps, *,
|
||
voices: list, base: float) -> float:
|
||
"""联合音视频模型的时长对齐:**音轨长度 = 请求帧数**,画面比台词长就得由模型填空档。
|
||
|
||
与 :func:`speech_duration_seconds`(TTS 口径)的三点区别:
|
||
|
||
* 用 H3 实测语速 :data:`JOINT_CPS_CJK`,不用 TTS 的保守估值 4.3;
|
||
* **不**叠加时间线的入点/尾帧留白——那是给 TTS 补定格帧用的,喂给 H3 只会变成空档;
|
||
* **允许短于 shot.duration**:台词 7 秒念完就不要生成 9 秒的画面。
|
||
时间线按产物真实时长排布,短一点只是少两秒废画面,不需要同步改分镜。
|
||
|
||
时长贴在台词上、且贴到**合法帧数网格**上,是这一条路径存在的真正原因。
|
||
曾经的写法是 ``max(need, caps.min_duration)``:H3 的 ``min_duration`` 来自节点
|
||
tooltip 的训练建议区间(124~362 帧),于是所有短台词镜头一律被抬到 124 帧。
|
||
「告诉你个小秘密第 2 期」四条镜头逐条 ASR 复现了后果——
|
||
|
||
S01 台词 4.45s / 下发 5.17s(空档 0.72s)→ 干净
|
||
S02 台词 5.45s / 下发 5.88s(空档 0.42s)→ 开头「不用担心」换成「都市清新风格」
|
||
S03 台词 4.05s / 下发 5.17s(空档 1.12s)→ 念出「都市清新风格,中景,膝盖」
|
||
S04 台词 3.25s / 下发 5.17s(空档 1.92s)→ 独立一段「都市清新風格」,台词 2.19s 才开口
|
||
|
||
空档越大越严重,且**音轨和画面等长、空档不会静音**(模型把语音铺满整段,
|
||
语速自适应:同一句 15 字在 5.17s 档是 3.7 字/秒、压到 3.75s 档是 5.3 字/秒且字字清晰)。
|
||
2×2 对照实验还证伪了「精简提示词」这条路:删掉「都市清新风格」,模型改念
|
||
「医院诊室内」——它填的是空档,不是某个特定短语。
|
||
|
||
所以现在取**离 need 最近的合法档位**(``DurationGrid.snap``),把偏差从最多
|
||
+1.92s 压到 ±0.354s;下限另设 :attr:`Capabilities.joint_min_duration`,
|
||
宁可低于训练建议区间,也不留可被念出来的时间。
|
||
"""
|
||
lines = joint_dialogue_lines(shot)
|
||
text = "".join(str(line["text"]) for line in lines) or str(shot.dialogue or "").strip()
|
||
if not text:
|
||
return base
|
||
speed = 1.0
|
||
if voices:
|
||
try:
|
||
speed = float((voices[0].tuning or {}).get("speed", 1.0) or 1.0)
|
||
except (TypeError, ValueError):
|
||
speed = 1.0
|
||
cjk = sum(1 for ch in text if "\u4e00" <= ch <= "\u9fff")
|
||
latin = len(re.findall(r"[A-Za-z0-9']+", text))
|
||
need = cjk / JOINT_CPS_CJK + latin / JOINT_WPS_LATIN + JOINT_SPEECH_PAD_SECONDS
|
||
need = need / max(0.5, min(speed, 2.0))
|
||
# 带台词下限只允许比通用下限**更宽松**:模型没声明时照旧走 min_duration。
|
||
low = float(caps.min_duration or 0)
|
||
joint_low = float(getattr(caps, "joint_min_duration", 0.0) or 0.0)
|
||
if 0 < joint_low < low:
|
||
low = joint_low
|
||
grid = getattr(caps, "duration_grid", None)
|
||
value = grid.snap(need, floor=low) if grid is not None else max(need, low)
|
||
if caps.max_duration and value > float(caps.max_duration):
|
||
value = float(caps.max_duration)
|
||
return round(value, 2)
|
||
|
||
|
||
def joint_target_seconds(db: Session, project: Project, shot: Shot) -> float:
|
||
"""派发时**真正会下发的**时长(秒)。非联合音视频、或台词走 TTS 时就是 shot.duration。
|
||
|
||
质检必须和派发共用这一个口径:台词驱动的缩短是刻意为之(见
|
||
:func:`joint_speech_duration_seconds` 里的实测表),拿分镜里写的 8 秒去比 3 秒的产物,
|
||
「时长偏差」会永远不合格,于是真正的穿帮被淹在误报里看不见。
|
||
"""
|
||
base = float(shot.duration or 0)
|
||
try:
|
||
from app.providers import registry as model_registry
|
||
from app.services import timeline as timeline_service
|
||
|
||
spec, _adapter = model_registry.resolve_video(db, shot.provider or project.default_provider,
|
||
shot.model or None)
|
||
caps = model_registry.capabilities_of(spec)
|
||
if not caps.joint_av:
|
||
return base
|
||
tl_conf = timeline_service.settings_of(db, project)
|
||
if timeline_service.voice_source_mode(tl_conf) == "dub":
|
||
return base
|
||
_paths, voices = reference_voice_audios(db, project, shot,
|
||
limit=int(caps.max_reference_audios or 0))
|
||
return joint_speech_duration_seconds(db, project, shot, caps, voices=voices, base=base)
|
||
except Exception: # noqa: BLE001 - 算不出就按分镜时长
|
||
return base
|
||
|
||
|
||
def joint_unvoiced_speakers(db: Session, project: Project, shot: Shot, *,
|
||
voices: list | None = None) -> list[str]:
|
||
"""有台词、但拿不到「自己那条参考音色」的说话人(按开口顺序去重)。
|
||
|
||
``<Audio n>`` 只能指向真正下发的那几条 ``ref_audio``。落空的三种情况都算:
|
||
角色没绑定默认声线、声线没有可用的克隆样本、出镜人数超过参考音频条数上限。
|
||
后果是这一句没有标签,H3 只能从现有参考里自己挑嗓子——跨镜头「同一个人换声」
|
||
就是这么来的,而且是静默发生的。派发前在素材检查里点名,比出片后再返工便宜。
|
||
"""
|
||
lines = joint_dialogue_lines(shot)
|
||
if not lines:
|
||
return []
|
||
bound = {str(x or "").strip() for x in joint_voice_names(db, project, shot, voices=voices)}
|
||
out: list[str] = []
|
||
for line in lines:
|
||
name = str(line.get("speaker") or "").strip()
|
||
if not name or name == "角色" or name in bound or name in out:
|
||
continue
|
||
out.append(name)
|
||
return out
|
||
|
||
|
||
def compose_joint_caption(project: Project, shot: Shot, *, db: Session | None = None,
|
||
roles: list[dict] | None = None,
|
||
duration_seconds: float | None = None,
|
||
voice_names: list[str] | None = None) -> str:
|
||
"""联合音视频模型(MiniMax H3)专用 caption:**只写看得见的东西 + 官方语音标记**。
|
||
|
||
H3 的文字入口**只有一个** ``prompt``(ComfyUI ``MiniMaxH3ReferenceToVideo`` 的入参是
|
||
``clip/prompt/width/height/length/ref_image_size`` + ``ref_images/ref_videos/
|
||
ref_audios``,既没有 negative 也没有独立的 dialogue 字段),文本编码器把参考素材
|
||
标签拼在前面、然后**原样拼接这段文字**(无 chat 模板、无 system prompt)。
|
||
⇒ 这段文字里的每一个「主语 + 谓语」句子都是候选台词。所以这里只放三类内容:
|
||
|
||
* ``<Picture n>`` 定语式身份/场景锚定 + 名词短语的环境、动作、镜头语言;
|
||
* ``<Audio n><d>…</d>``:官方说话段落标记 + 参考音色引用;
|
||
* 听得见的环境声名词(``shot.ambience`` + 镜头音效名)。
|
||
|
||
**加了又删掉、以后不要再加**的东西(每一条都曾在成片开头以「念提示词」的形式还回来):
|
||
「画面里只有…共 N 位人物」、「时长约 N 秒,画幅 9:16」(时长/画幅本来就是
|
||
``length``/``width``/``height`` 结构化入参)、「画面中不要出现:…」(H3 没有
|
||
negative 通道,那是一句可被念出来的话)、以及任何「谁在出声」的说明句
|
||
(谁说话由首帧的镜头调度决定,见 :func:`keyframe_speech_note`)。
|
||
"""
|
||
characters = list(shot.characters or [])
|
||
if db is not None:
|
||
for char in mentioned_characters(db, shot):
|
||
if char.id not in {c.id for c in characters}:
|
||
characters.append(char)
|
||
scenes = list(shot.scenes or [])
|
||
lines = joint_dialogue_lines(shot)
|
||
|
||
people_roles = [r for r in (roles or []) if r.get("owner_type") == "human"]
|
||
scene_roles = [r for r in (roles or []) if r.get("owner_type") == "scene"]
|
||
frames = [r for r in (roles or []) if r.get("owner_type") == "frame"]
|
||
|
||
def picture(index: object) -> str:
|
||
return f"{JOINT_PICTURE_MARK}{int(index)}>"
|
||
|
||
inline = JOINT_REF_STYLE == "inline"
|
||
# 角色名 -> 「<Picture n>中的名字,看得见的人物特征」,用于替换正文里第一次出现的名字
|
||
person_refs: dict[str, str] = {}
|
||
for role in people_roles:
|
||
char = next((c for c in characters if c.id == role.get("owner_id")), None)
|
||
name = str((char.name if char is not None else role.get("name")) or "").strip()
|
||
if not name:
|
||
continue
|
||
bound = bool(portrait_bound_ids(db, shot) & {char.id}) \
|
||
if (db is not None and char is not None) else True
|
||
brief = joint_cast_brief(char, portrait_bound=bound) if char is not None else ""
|
||
person_refs.setdefault(name, picture(role["index"]) + "中的" + name
|
||
+ (f",{brief}" if brief else ""))
|
||
|
||
parts: list[str] = []
|
||
if not inline:
|
||
# 旧写法(留作 A/B 回退开关):若干条「<Picture n>是X」陈述整句。picture()
|
||
# 的返回值自带结尾的「>」,这里不能再补一个,否则输出「<Picture 1>>是…」。
|
||
if frames:
|
||
parts.append(f"{picture(frames[0]['index'])}是这一镜的画面")
|
||
for role in people_roles:
|
||
char = next((c for c in characters if c.id == role.get("owner_id")), None)
|
||
name = str((char.name if char is not None else role.get("name")) or "").strip()
|
||
clause = picture(role["index"]) + f"是{name}"
|
||
if char is not None:
|
||
bound = bool(portrait_bound_ids(db, shot) & {char.id})
|
||
brief = joint_cast_brief(char, portrait_bound=bound)
|
||
if brief:
|
||
clause += f",{brief}"
|
||
parts.append(clause)
|
||
for role in scene_roles:
|
||
parts.append(f"{picture(role['index'])}是这一镜的场景")
|
||
|
||
# 1) 场景:只留看得见的环境名词
|
||
if scenes:
|
||
scene = scenes[0]
|
||
scene_bits = [scene.prompt or scene.description, scene.time_of_day, scene.lighting, scene.palette]
|
||
text = sanitize_visual(",".join(str(b).strip() for b in scene_bits if b))
|
||
if text:
|
||
lead = ""
|
||
if inline:
|
||
if frames:
|
||
lead += picture(frames[0]["index"]) + "中的画面,"
|
||
if scene_roles:
|
||
lead += picture(scene_roles[0]["index"]) + "中的"
|
||
parts.append(lead + text)
|
||
style = drop_phrases(sanitize_visual(project.style_guide or ""), _JOINT_STYLE_DROP_MARKERS)
|
||
if style:
|
||
parts.append(style)
|
||
|
||
# 2) 画面动作 + 镜头语言。inline 模式下把出镜角色的标签嵌进动作句里:
|
||
# 「<Picture 3>中的紫小慧,一名年轻东亚女生,…,急匆匆地跑进办公室」——
|
||
# 身份锚定一句不少,但整段没有「X 是 Y」这种会被念出来的陈述句。
|
||
scene_name = str(scenes[0].name or "").strip() if scenes else ""
|
||
desc = sanitize_visual(shot.description or "")
|
||
if desc and scene_name:
|
||
# 「医院诊室内,」这种纯地点复述:场景块已经用 <Picture 3> 说过一遍,
|
||
# 再念一遍既浪费预算又给了模型一段可填进空档的现成词。
|
||
echo = re.compile(rf"^{re.escape(scene_name)}(内|里|中|外|门口|前|走廊)?$")
|
||
desc = ",".join(p for p in split_phrases(desc) if not echo.match(p.strip()))
|
||
if desc and lines:
|
||
# 没有台词的镜头不必动:那里的环境声/动作短语本身就是有效内容
|
||
desc = drop_conversational(desc)
|
||
if inline and desc:
|
||
orphans: list[str] = []
|
||
for name, clause in person_refs.items():
|
||
if name in desc:
|
||
desc = desc.replace(name, clause + ",", 1)
|
||
else:
|
||
orphans.append(clause)
|
||
if orphans:
|
||
desc = ",".join(orphans) + "," + desc
|
||
# 人物锚点各占一句:「<Picture 3>中的俊杰,高大,<Picture 2>中的紫小慧…」
|
||
# 挤在一句里,模型会把前一个人的特征演到后一个人身上。
|
||
desc = re.sub(r",+\s*(?=<Picture\s*\d+>)", "。", re.sub(r",+", ",", desc)).strip(",")
|
||
if desc:
|
||
parts.append(desc)
|
||
photo = [v for v in (sanitize_visual(str(t)) for t in camera_terms(shot, terse=True)) if v]
|
||
if photo:
|
||
parts.append(",".join(photo))
|
||
|
||
# 3) 环境声:听得见的名词短语,绝不写成句子(放在台词之前,让 <d> 段落收尾)
|
||
ambience = sanitize_visual(shot.ambience or "")
|
||
sfx_names = ",".join(dict.fromkeys(str(row.get("name") or "").strip()
|
||
for row in shot.all_sound_effects()
|
||
if str(row.get("name") or "").strip()))
|
||
ambience = ",".join([x for x in (ambience, sanitize_visual(sfx_names)) if x])
|
||
if ambience:
|
||
parts.append(ambience)
|
||
|
||
# 4) 台词:最后一句,官方 <d> 段落;说话人只通过 <Audio n> 绑定参考音色。
|
||
labels = [str(x or "").strip() for x in (voice_names or [])]
|
||
speakers = [n for n in dialogue_speakers(shot, lines) if n]
|
||
|
||
def audio_label(speaker: str) -> str:
|
||
"""把这一句绑到它自己的参考音色上;绑不上就干脆不加标签。
|
||
|
||
只有一个说话人的镜头,下发的那条参考音频必然就是他本人的嗓子,
|
||
名字没匹配上(声线记录没回指到角色)也可以放心标 ``<Audio 1>``。
|
||
多人对白里只收到一条音色时必须**留空**:标了就把第二个人与第一个人的
|
||
音色硬绑在一起,模型照着标签演,第二个角色会直接换上别人的嗓子说话。
|
||
"""
|
||
if not labels:
|
||
return ""
|
||
index = next((i for i, n in enumerate(labels) if n and n == speaker), None)
|
||
if index is None and len(labels) == 1 and len(speakers) <= 1:
|
||
index = 0 # 单音色 + 单说话人:这条嗓子就是本镜说话人的
|
||
return "" if index is None else f"{JOINT_AUDIO_MARK}{index + 1}>"
|
||
|
||
# 先收口正文,再追加台词:``<d>`` 里是编剧原文,任何清理都不许碰。
|
||
parts = [tidy_caption(x) for x in parts]
|
||
for line in lines:
|
||
parts.append(audio_label(line["speaker"]) + JOINT_SPEECH_OPEN
|
||
+ str(line["text"]).strip() + JOINT_SPEECH_CLOSE)
|
||
|
||
text = "。".join(x for x in parts if x)
|
||
# 连续两段台词之间那个句号是拼接产物:「</d>。<Audio 2><d>」读起来像被标点
|
||
# 掐断的同一句话,容易被模型当成两句各配一段气口。段与段的边界交给标签本身;
|
||
# 环境声与第一段台词之间照旧留句号,那是两个话题的分界。
|
||
for mark in (JOINT_SPEECH_OPEN, JOINT_AUDIO_MARK):
|
||
text = text.replace(JOINT_SPEECH_CLOSE + "。" + mark, JOINT_SPEECH_CLOSE + mark)
|
||
return text.replace("。。", "。").strip("。")
|
||
|
||
|
||
def compose_prompt(project: Project, shot: Shot, *, characters: list[Character] | None = None,
|
||
scenes: list[Scene] | None = None, db: Session | None = None,
|
||
native_voice: bool | None = None, duration_seconds: float | None = None,
|
||
joint_av: bool | None = None, roles: list[dict] | None = None,
|
||
voice_names: list[str] | None = None) -> str:
|
||
"""组装镜头提示词。
|
||
|
||
``native_voice=True`` 表示本镜头已经带上了「参考音色」音频、台词将由视频模型
|
||
直出(MiniMax H3 原生音画同步)。此时不能再写「说话音色:中年男声」这类
|
||
**文字**音色描述——模型会拿文字去覆盖随附的参考音频,角色一开口就换了嗓子。
|
||
``duration_seconds`` 是本次生成真正下发的时长(台词长时会被拉长),
|
||
提示词里的「时长约 N 秒」必须跟它一致,否则模型按短时长压缩语速。
|
||
``native_voice`` 留空时按「时间线设置 + 本镜视频模型能力」现算,
|
||
这样 ``sync_prompt`` 写回的缓存提示词与真正下发的那份口径一致。
|
||
``joint_av`` 留空时按模型能力位现算;命中联合音视频模型时直接转走
|
||
:func:`compose_joint_caption`(``native_voice`` 在那条分支里没有意义)。
|
||
"""
|
||
if native_voice is None:
|
||
native_voice = native_voice_mode(db, project, shot) if db is not None else False
|
||
# 联合音视频模型(H3)走另一条通道:整段提示词都可能被念出声,
|
||
# 所以「怎么写」比「写什么」更关键,见 compose_joint_caption 的规则说明。
|
||
if joint_av is None:
|
||
joint_av = joint_av_mode(db, project, shot)
|
||
if joint_av:
|
||
roles = roles if roles is not None else (picture_plan(db, project, shot) if db is not None else [])
|
||
if voice_names is None:
|
||
# 参考音色的顺序只有 build_video_request 那一份是权威的;缓存路径按同口径自算。
|
||
voice_names = joint_voice_names(db, project, shot) if (db is not None and native_voice) else []
|
||
return compose_joint_caption(project, shot, db=db, roles=roles,
|
||
duration_seconds=duration_seconds, voice_names=voice_names)
|
||
characters = characters if characters is not None else list(shot.characters or [])
|
||
scenes = scenes if scenes is not None else list(shot.scenes or [])
|
||
# 人工覆写优先:审核驳回时「调整提示词」写入 params_json.prompt_override
|
||
override = str((shot.params_json or {}).get("prompt_override") or "").strip()
|
||
if override:
|
||
return override
|
||
parts: list[str] = []
|
||
if project.style_guide:
|
||
parts.append(project.style_guide.strip())
|
||
if scenes:
|
||
scene = scenes[0]
|
||
scene_bits = [scene.prompt or scene.description, scene.time_of_day, scene.lighting, scene.palette]
|
||
parts.append(",".join(str(b).strip() for b in scene_bits if b))
|
||
bound = portrait_bound_ids(db, shot) if db is not None else set()
|
||
cast = list(characters)
|
||
if db is not None: # 文案点名的人也要出现在出镜角色里,
|
||
for char in mentioned_characters(db, shot): # 否则定妆照喂了却没名字可对应
|
||
if char.id not in {c.id for c in cast}:
|
||
cast.append(char)
|
||
if cast:
|
||
parts.append("出镜角色(保持造型一致):"
|
||
+ ";".join(character_brief(c, portrait_bound=c.id in bound)
|
||
for c in cast[:3]))
|
||
if bound:
|
||
parts.append("出镜人物的五官、发型与服装严格以上传的定妆图/三视图为准,"
|
||
"不得按文字另行改写衣着")
|
||
cloned = multi_view_characters(db, shot)
|
||
if cloned:
|
||
# 只有「没有定妆照、只能拿三视图当参照」的人物才会走到这里
|
||
parts.append("、".join(cloned) + "的参考图是同一人物的多角度三视图,"
|
||
"画面中他只允许出现一位,严禁把三视图里的另一个角度画成第二个旁人")
|
||
if shot.description:
|
||
parts.append(shot.description.strip())
|
||
photo = camera_terms(shot)
|
||
if photo:
|
||
parts.append("镜头语言:" + ",".join(photo))
|
||
hands = hand_ownership_note(shot)
|
||
if hands:
|
||
parts.append(hands)
|
||
dialogue = (shot.dialogue or "").strip()
|
||
if dialogue:
|
||
speaker = shot.speaker.name if shot.speaker else (characters[0].name if characters else "角色")
|
||
timbre = "" if native_voice else (voice_timbre_hint(db, project, shot) if db is not None else "")
|
||
if native_voice:
|
||
# 口型同步 + 音色以参考音频为准:这是「H3 直出声音」能取代 TTS 的前提。
|
||
parts.append(f"{speaker}台词:「{dialogue}」;{NATIVE_SPEECH_NOTE}")
|
||
else:
|
||
parts.append(f"{speaker}台词:「{dialogue}」,口型与情绪自然"
|
||
+ (f",说话音色:{timbre}" if timbre else ""))
|
||
if shot.style_note:
|
||
parts.append(shot.style_note.strip())
|
||
parts.append(f"时长约 {(float(duration_seconds) if duration_seconds else float(shot.duration)):.0f} 秒,"
|
||
f"画幅 {project.aspect_ratio}")
|
||
text = "。".join(p for p in parts if p)
|
||
return text.replace("。。", "。").strip("。")
|
||
|
||
|
||
def negative_for(project: Project, shot: Shot) -> str:
|
||
override = str((shot.params_json or {}).get("negative_override") or "").strip()
|
||
if override:
|
||
return override
|
||
# shot.negative_prompt 保存的是上一次组装后的完整结果,不是镜头级原始配置。
|
||
# 若再次并回项目负面词,修改项目设定或后续重算时会把旧词永久粘住。
|
||
# 镜头级人工负面词统一走 negative_override。
|
||
bits = [project.global_negative_prompt or ""]
|
||
default = "文字水印,画面抖动,肢体畸变,多余手指,五官漂移,风格突变,低分辨率"
|
||
# shot.negative_prompt 本身可能是上一次自动组装的结果。若每次都直接拼接,
|
||
# 绑定/修改镜头会触发提示词重算,反向词会呈指数级重复并挤占模型上下文。
|
||
phrases: list[str] = []
|
||
seen: set[str] = set()
|
||
for value in (default, *bits):
|
||
for phrase in re.split(r"[,,;;\n]+", value or ""):
|
||
phrase = phrase.strip(" ,")
|
||
if not phrase or phrase in seen:
|
||
continue
|
||
# 「水印」已被「文字水印」覆盖、「抖动」已被「画面抖动」覆盖。
|
||
# 保留更具体的既有表述,避免同义短语反复增加上下文长度。
|
||
if any(phrase in existing for existing in phrases):
|
||
continue
|
||
phrases = [existing for existing in phrases if existing not in phrase]
|
||
seen = set(phrases)
|
||
seen.add(phrase)
|
||
phrases.append(phrase)
|
||
return ",".join(phrases)
|
||
|
||
|
||
def tidy_caption(text: str) -> str:
|
||
"""删掉冗余描述词之后收口,别让提示词带着半截话下发。
|
||
|
||
* ``「…,高大,<Picture 2>中的紫小慧…」`` → 在 ``<Picture n>`` 前断句。
|
||
两个人物挤在同一句里,模型会把前一个人的特征演到后一个人身上;
|
||
* 合并重复的 ``,、。``,去掉句尾悬空的连接符。
|
||
只对正文调用(见 :func:`compose_joint_caption`),台词一个字不动。
|
||
"""
|
||
out = re.sub(r"[,、]{2,}", ",", str(text or ""))
|
||
out = re.sub(r"[,、;]\s*(?=[。!?])", "", out)
|
||
out = re.sub(r"。{2,}", "。", out)
|
||
out = re.sub(r"^[,、;。\s]+", "", out)
|
||
return re.sub(r"[,、;\s]+$", "", out).strip()
|
||
|
||
|
||
def sync_prompt(db: Session, project: Project, shot: Shot, *, reason: str = "", actor: str = "studio",
|
||
record: bool = True) -> str:
|
||
prompt = compose_prompt(project, shot, db=db)
|
||
negative = negative_for(project, shot)
|
||
if joint_av_mode(db, project, shot):
|
||
# 「音画不同步」这类负面词对音画一次成片的模型既没意义又会被念出来,
|
||
# 适配器投递时也会洗一遍;这里同步写回,界面上看到的和下发的一致。
|
||
negative = ",".join(x for x in negative.replace(",", ",").split(",")
|
||
if x.strip() and not is_audio_topic(x))
|
||
changed = prompt != (shot.prompt or "") or negative != (shot.negative_prompt or "")
|
||
if record and (changed or not shot.prompt or reason):
|
||
db.add(PromptRevision(shot_id=shot.id, prompt=prompt, negative_prompt=negative,
|
||
params_json={"mode": shot.mode, "model": shot.model, "seed": shot.seed,
|
||
"duration": shot.duration},
|
||
reason=reason or ("自动组装" if changed else ""), actor=actor, applied=True))
|
||
shot.prompt = prompt
|
||
shot.negative_prompt = negative
|
||
db.flush()
|
||
return prompt
|
||
|
||
|
||
def mentioned_characters(db: Session, shot: Shot) -> list[Character]:
|
||
"""画面描述/梗概/标题/台词里点名提到、却没挂进本镜出镜名单的项目人物。
|
||
|
||
编导在分镜里写「来到俊杰面前」「俊杰坐在服务台后」,俊杰是项目里的另一个角色。
|
||
以前只有出镜名单里的人物才会被收集定妆照,于是这种**剧本要求出镜的人**
|
||
一张参照图都没进模型,每一镜都凭文字臆造一套长相与服装,两人同框时
|
||
还会互相串装(质检看到的就是「西装代替 T 恤黑丝」)。
|
||
判定口径与画面质检的 `expected_cast` 保持一致:只认文案里真正点名的人。
|
||
"""
|
||
project = shot.project
|
||
if project is None:
|
||
return []
|
||
known = {(c.name or "").strip() for c in (shot.characters or [])}
|
||
script = " ".join(filter(None, [shot.description, shot.synopsis, shot.title, shot.dialogue]))
|
||
found: list[Character] = []
|
||
for char in list(project.characters or []):
|
||
name = (char.name or "").strip()
|
||
if not name or name in known or name not in script:
|
||
continue
|
||
known.add(name)
|
||
found.append(char)
|
||
return found
|
||
|
||
|
||
def collect_reference_details(db: Session, shot: Shot, *, scene_first: bool = False) -> list[dict]:
|
||
"""按优先级列出本镜头可用的参考素材(含来源),供预检与「实际入模素材」展示。
|
||
|
||
每个人物的每种素材都单独收集:旧实现用 ``first_asset_path(..., 多种 kind)``
|
||
只会命中一张(定妆图有了就再也不看三视图),母版里精心准备的
|
||
正面像 + 三视图最后只有一张进了模型。
|
||
"""
|
||
items: list[dict] = []
|
||
# 用户在分镜里显式上传的参考图优先级最高;历史上这里只收集人物和场景素材,
|
||
# 导致“参考图”虽然上传成功,却从未进入视频模型请求。
|
||
for asset in storage.assets_of(db, "shot", shot.id, AssetKind.REFERENCE_IMAGE):
|
||
if storage.exists(asset.path):
|
||
items.append({"path": str(storage.to_absolute(asset.path)), "owner_type": "shot",
|
||
"owner_id": shot.id, "owner_name": "镜头参考图", "kind": asset.kind})
|
||
characters: list[dict] = []
|
||
cast = list(shot.characters or [])
|
||
# 文案里点名、但没挂进出镜名单的人物同样要参照物,否则模型只能臆造他的形象
|
||
cast += [c for c in mentioned_characters(db, shot) if c.id not in {x.id for x in cast}]
|
||
for char in cast:
|
||
# 一人一张:定妆图在就不再附三视图,否则模型会把三视图里的另外两个角度
|
||
# 当成两个额外的路人画进画面(见 IDENTITY_KINDS 注释)。
|
||
for kind in IDENTITY_KINDS:
|
||
row = storage.first_asset_row(db, "human", char.id, kind)
|
||
if row is None:
|
||
continue
|
||
characters.append({"path": str(storage.to_absolute(row.path)), "owner_type": "human",
|
||
"owner_id": char.id, "owner_name": char.name, "kind": kind,
|
||
"asset_id": row.id, "multi_view": kind == "turnaround"})
|
||
break
|
||
scenes: list[dict] = []
|
||
for scene in (shot.scenes or []):
|
||
row = storage.first_asset_row(db, "scene", scene.id, "scene_image")
|
||
if row is not None:
|
||
scenes.append({"path": str(storage.to_absolute(row.path)), "owner_type": "scene",
|
||
"owner_id": scene.id, "owner_name": scene.name, "kind": "scene_image",
|
||
"asset_id": row.id})
|
||
# 关键帧阶段把场景母图放第 1 张:Qwen 用第 1 张参考图决定画布与空间结构,
|
||
# 先场景再人物,出图才是「这个角色站在那间屋子里」;视频阶段相反,
|
||
# 关键帧已经锚定构图,人物定妆图必须排在前面保身份。
|
||
items.extend(scenes if scene_first else characters)
|
||
items.extend(characters if scene_first else scenes)
|
||
deduped: list[dict] = []
|
||
seen: set[str] = set()
|
||
for item in items:
|
||
if item["path"] in seen:
|
||
continue
|
||
seen.add(item["path"])
|
||
deduped.append(item)
|
||
return deduped
|
||
|
||
|
||
def collect_references(db: Session, shot: Shot, *, limit: int = 0) -> tuple[list[str], list[str], int]:
|
||
"""按优先级收集镜头参考素材,返回(全部素材, 显式参考图, 素材总数)。
|
||
|
||
优先级:镜头显式参考图 > 人物定妆图/三视图/服装 > 场景图。
|
||
``limit > 0`` 时按优先级截断——供应商侧的参考图上限是「取前 N 张」,
|
||
不是「超限就报错」,所以截断(而不是阻塞生成)才是正确语义;
|
||
预检与请求构造共用本函数,保证「预检看到的」== 「模型实际收到的」。
|
||
"""
|
||
details = collect_reference_details(db, shot)
|
||
explicit_refs = [row["path"] for row in details if row["owner_type"] == "shot"]
|
||
ranked = [row["path"] for row in details]
|
||
total = len(ranked)
|
||
refs = ranked[:limit] if limit and limit > 0 else ranked
|
||
return refs, [path for path in explicit_refs if path in refs], total
|
||
|
||
|
||
def speech_duration_seconds(db: Session, project: Project, shot: Shot, caps, *,
|
||
voices: list, base: float) -> float:
|
||
"""台词长、画面短时按语音长度拉长本镜头的生成时长(不改 shot.duration)。
|
||
|
||
H3 会在整段画面里说这句话:画面只有 5 秒、台词要念 9 秒时,模型只能加速念或
|
||
半句被截。所以先按语速估时长,再加时间线的入点/尾帧留白,最后夹到模型能力区间。
|
||
时间线用的是产物真实时长,因此这里只影响「本次下发给模型的时长」。
|
||
"""
|
||
from app.services import audio, timeline as timeline_service
|
||
|
||
text = str(shot.dialogue or "").strip()
|
||
if not text:
|
||
return base
|
||
speed = 1.0
|
||
if voices:
|
||
try:
|
||
speed = float((voices[0].tuning or {}).get("speed", 1.0) or 1.0)
|
||
except (TypeError, ValueError):
|
||
speed = 1.0
|
||
conf = timeline_service.settings_of(db, project)
|
||
pad_ms = int(conf.get("lead_padding_ms") or 0) + int(conf.get("tail_padding_ms") or 0)
|
||
need = (audio.estimate_duration_ms(text, speed=speed) + max(0, pad_ms)) / 1000.0
|
||
value = max(base, need)
|
||
low, high = float(caps.min_duration or 0), float(caps.max_duration or value)
|
||
if low and value < low:
|
||
value = low
|
||
if high and value > high:
|
||
value = high
|
||
return round(value, 2)
|
||
|
||
|
||
def picture_plan(db: Session, project: Project, shot: Shot) -> list[dict]:
|
||
"""本镜实际下发的参考图顺序 + 身份标签。``sync_prompt`` 与 ``build_video_request``
|
||
必须共用它,否则缓存里写的「<Picture 2>是俊杰」和真正下发的那张图可能不是同一张。"""
|
||
limit = _ref_limit(db, project, shot)
|
||
first_frame = storage.first_asset_path(db, "shot", shot.id, "keyframe")
|
||
last_frame = storage.first_asset_path(db, "shot", shot.id, "last_frame")
|
||
return picture_roles(db, shot, first_frame=str(storage.to_absolute(first_frame)) if first_frame else "",
|
||
last_frame=str(storage.to_absolute(last_frame)) if last_frame else "", limit=limit)
|
||
|
||
|
||
def _ref_limit(db: Session, project: Project, shot: Shot) -> int:
|
||
"""本镜视频模型的参考图上限(0 = 不限制)。提示词与请求必须用同一个值截断。"""
|
||
from app.providers import registry as model_registry
|
||
|
||
try:
|
||
spec, _adapter = model_registry.resolve_video(db, shot.provider or project.default_provider,
|
||
shot.model or None)
|
||
return int(model_registry.capabilities_of(spec).max_reference_images or 0)
|
||
except Exception: # noqa: BLE001
|
||
return 0
|
||
|
||
|
||
def shot_idempotency_key(shot: Shot) -> str:
|
||
"""视频请求的幂等键:镜头号 + 人工重摇轮次。"""
|
||
take = int((shot.params_json or {}).get("take") or 1)
|
||
return f"shot-{shot.id}" if take <= 1 else f"shot-{shot.id}-take{take}"
|
||
|
||
|
||
def build_video_request(db: Session, project: Project, shot: Shot) -> tuple[object, list[str]]:
|
||
"""构造供应商请求(含关键帧、镜头参考图、定妆图、场景图、三视图等素材)。"""
|
||
from app.constants import canvas_for
|
||
from app.providers.base import VideoGenRequest
|
||
from app.providers import registry as model_registry
|
||
|
||
spec, _adapter = model_registry.resolve_video(db, shot.provider or project.default_provider,
|
||
shot.model or None)
|
||
caps = model_registry.capabilities_of(spec)
|
||
limit = int(caps.max_reference_images or 0)
|
||
refs, explicit_refs, _total = collect_references(db, shot, limit=limit)
|
||
first_frame = storage.first_asset_path(db, "shot", shot.id, "keyframe")
|
||
last_frame = storage.first_asset_path(db, "shot", shot.id, "last_frame")
|
||
# 景别/机位/运镜是模型的**结构化入参**,不只是提示词里的中文描述:
|
||
# mock 的 _motion_filter、支持 camera control 的供应商都直接读 request.params,
|
||
# 不下发就会一律退化成固定机位——镜头上改了运镜,出片却毫无变化。
|
||
camera = {"shot_size": shot.shot_size, "camera_angle": shot.camera_angle,
|
||
"camera_movement": shot.camera_movement}
|
||
# 台词走「模型直出」还是「平台 TTS」:只有前一种才需要参考音色。
|
||
# 时间线选了 dub(强制配音)时不喂音色、也不为台词拉长画面,省钱且不误导模型。
|
||
from app.services import timeline as timeline_service
|
||
|
||
tl_conf = timeline_service.settings_of(db, project)
|
||
voice_paths, voices = reference_voice_audios(
|
||
db, project, shot, limit=int(caps.max_reference_audios or 0),
|
||
allow=timeline_service.voice_source_mode(tl_conf) != "dub")
|
||
joint = joint_av_mode(db, project, shot)
|
||
roles = picture_plan(db, project, shot) if joint else []
|
||
voice_names = joint_voice_names(db, project, shot, voices=voices) if joint else []
|
||
duration = float(shot.duration)
|
||
if voice_paths:
|
||
# H3 的音轨和画面等长:按 TTS 的保守语速排它会留下 1.5~2.4s 空档,
|
||
# 模型拿空档去念提示词。联合音视频模型一律按实测语速算,且允许短于分镜时长。
|
||
calc = joint_speech_duration_seconds if joint else speech_duration_seconds
|
||
duration = calc(db, project, shot, caps, voices=voices, base=duration)
|
||
prompt_text = (shot.prompt or "").strip()
|
||
stale_voice_plan = voice_plan_stale(prompt_text, native=bool(voice_paths)) \
|
||
or joint_plan_stale(prompt_text, joint=joint, has_dialogue=bool(voice_paths))
|
||
if prompt_text and not stale_voice_plan and not joint and duration != float(shot.duration):
|
||
# 缓存里的「时长约 5 秒」是台词没拉长画面时算的,模型会照旧按 5 秒念完
|
||
stale_voice_plan = bool(re.search(rf"时长约 {float(shot.duration):.0f} 秒", prompt_text)) \
|
||
and not re.search(rf"时长约 {duration:.0f} 秒", prompt_text)
|
||
if not prompt_text or stale_voice_plan:
|
||
prompt_text = compose_prompt(project, shot, db=db,
|
||
native_voice=bool(voice_paths), duration_seconds=duration,
|
||
joint_av=joint, roles=roles, voice_names=voice_names)
|
||
request = VideoGenRequest(
|
||
prompt=prompt_text,
|
||
duration_seconds=duration,
|
||
aspect_ratio=project.aspect_ratio, resolution=project.resolution, fps=project.fps,
|
||
mode=shot.mode, first_frame=str(storage.to_absolute(first_frame)) if first_frame else None,
|
||
last_frame=str(storage.to_absolute(last_frame)) if last_frame else None,
|
||
reference_images=refs, explicit_reference_images=explicit_refs,
|
||
reference_audios=voice_paths,
|
||
negative_prompt=shot.negative_prompt or negative_for(project, shot),
|
||
seed=shot.seed, params={**camera, **(shot.params_json or {})},
|
||
label=f"SHOT-{shot.order_index:02d} {shot.title}".strip(),
|
||
# take:人工「重新生成」时提示词常常一字未改,种子是从「幂等键 + 提示词摘要」
|
||
# 派生的,两者都不变就会让 ComfyUI 命中缓存原样返回同一份文件(重摇变空转)。
|
||
# 轮次进键之后:不改建 take 会真正重新采样,不重摇时同一提示词依旧可复现。
|
||
idempotency_key=shot_idempotency_key(shot),
|
||
)
|
||
return request, [first_frame or "", last_frame or "", *refs]
|
||
|
||
|
||
def canvas(project: Project) -> tuple[int, int]:
|
||
from app.constants import canvas_for
|
||
|
||
return canvas_for(project.resolution, project.aspect_ratio)
|