Publish Seedance 2.5 draft mode and video updates
- Add the 样片模式 flow: 480p draft generation, a linkable draft task ID, and pre-flight verification before the 1080p final request. - Allow reference images and audio in video edit/extend requests, matching the provider's 2.5 contract. - Move 主模型 and 样片模式 ahead of 生成模式, default 主模型 to seedance 2.5, and migrate saved widget values. - Refresh the video panel, asset API response logs, and LLM node handling; cover the new behavior with offline tests.
This commit is contained in:
@@ -9,8 +9,8 @@
|
|||||||
- 📐 10 种宽高比
|
- 📐 10 种宽高比
|
||||||
- 🎯 智能分辨率,或手动选择 1K / 2K / 4K
|
- 🎯 智能分辨率,或手动选择 1K / 2K / 4K
|
||||||
- 🌱 可控随机种子
|
- 🌱 可控随机种子
|
||||||
- 💬 左侧「聊天」面板支持多模型对话,初始默认使用 `gpt-6-sol`
|
- 💬 左侧「聊天」面板支持多模型对话,可选 `gemini-4-argon` 和 `claude-opus-5-5`;初始默认使用 `claude-opus-5-5`
|
||||||
- 🧠「提示词专家」节点支持多模型文本与多模态输入,新建节点默认使用 `gpt-6-sol`
|
- 🧠「提示词专家」节点支持多模型文本与多模态输入,可选 `gemini-4-argon` 和 `claude-opus-5-5`;新建节点默认使用 `claude-opus-5-5`
|
||||||
|
|
||||||
## 项目文档
|
## 项目文档
|
||||||
|
|
||||||
@@ -259,15 +259,17 @@ Google Gemini 模型节点,支持更多模型选择。
|
|||||||
|
|
||||||
「Seedance 多模态参考生视频」的参考图片、参考视频和参考音频端口会在连接后按需增加,不再一次铺开全部端口。图片、视频和音频素材 ID 也采用渐进填写:每组始终保留一个空输入框,填入当前项后才显示下一项。旧工作流中的编号端口、已填写素材 ID 和“真人素材ID”名称会自动迁移。
|
「Seedance 多模态参考生视频」的参考图片、参考视频和参考音频端口会在连接后按需增加,不再一次铺开全部端口。图片、视频和音频素材 ID 也采用渐进填写:每组始终保留一个空输入框,填入当前项后才显示下一项。旧工作流中的编号端口、已填写素材 ID 和“真人素材ID”名称会自动迁移。
|
||||||
|
|
||||||
「Seedance 全能生成视频」保留“素材创建模式”参数,默认“关闭”:隐藏全部素材 ID,并按线路自动创建连接的素材;改为“打开”后,才显示下方的素材 ID 单行输入并使用已有 ID。输入行与「Seedance 多模态参考生视频」一样按编号渐进展开:每类先显示一行,填写后展开下一空行。切回关闭不会清除已填 ID;旧工作流的“自动创建 / 手动”和三类聚合 ID 会自动迁移。输入端随生成模式动态增删:多模态仅显示参考图片、视频、音频,并随连接渐进增加端口;首尾帧仅显示首帧图片、尾帧图片。切换模式会断开被移除端口的连线,切回后需重新连接。
|
「Seedance 全能生成视频」保留“素材创建模式”参数,默认“关闭”:不创建素材,连接的素材直接上传并以公网 URL 提交;改为“自动创建”才按线路创建 HC/Doubao 素材;改为“手动”后显示下方的素材 ID 单行输入并使用已有 ID。输入行与「Seedance 多模态参考生视频」一样按编号渐进展开:每类先显示一行,填写后展开下一空行。切回关闭不会清除已填 ID;旧工作流的“自动创建 / 手动”和三类聚合 ID 会自动迁移。输入端随生成模式动态增删:多模态仅显示参考图片、视频、音频,并随连接渐进增加端口;首尾帧仅显示首帧图片、尾帧图片。切换模式会断开被移除端口的连线,切回后需重新连接。
|
||||||
|
|
||||||
「Seedance 多模态参考生视频」和「Seedance 全能生成视频」的模型线路均支持“海外”和“国内”;“海外”沿用原“海外HC”线路,旧工作流会自动迁移。国内线路会按所选主模型调用对应的 Seedance 2.0、fast、mini 或 2.5 国内模型,新建节点默认使用“国内”。
|
「Seedance 多模态参考生视频」和「Seedance 全能生成视频」的模型线路均支持“海外”和“国内”;“海外”沿用原“海外HC”线路,旧工作流会自动迁移。国内线路会按所选主模型调用对应的 Seedance 2.0、fast、mini 或 2.5 国内模型,新建节点默认使用“国内”。
|
||||||
|
|
||||||
两个单节点及「Seedance 全能生成视频(批量)」共用模型能力限制:Seedance 2.0 系列支持 4~15 秒,Seedance 2.5 支持 4~30 秒;2.5 支持 `480p / 720p / 1080p / 4k`,并允许最多 30 个图片类、10 个视频类和 10 个音频类参考内容。多模态节点中的直接媒体与对应素材 ID 共用这组数量额度。fast 和 mini 模型仍只支持 `480p / 720p`。宽高比统一为智能、`16:9 / 9:16 / 4:3 / 3:4 / 1:1 / 21:9`。
|
两个单节点及「Seedance 全能生成视频(批量)」共用模型能力限制:Seedance 2.0 系列支持 4~15 秒,Seedance 2.5 支持 4~30 秒;2.5 支持 `480p / 720p / 1080p`,并允许最多 30 个图片类、10 个视频类和 10 个音频类参考内容。批量节点固定使用直接上传,不创建素材。多模态节点中的直接媒体与对应素材 ID 共用这组数量额度。fast 和 mini 模型仍只支持 `480p / 720p`。宽高比统一为智能、`16:9 / 9:16 / 4:3 / 3:4 / 1:1 / 21:9`,其中“智能”按上游 `adaptive` 提交,首帧和首尾帧模式跟随图片比例;时长的“自动”按上游 `-1` 提交。
|
||||||
|
|
||||||
「Seedance 全能生成视频」现与「o1key 视频生成」共用参数标准、素材限制、`content` 请求体构造和 Seedance 提交/轮询/下载客户端。生成模式简化为“多模态”和“首尾帧”:新节点默认多模态,无参考素材而仅填写提示词时自动按文生视频提交;首尾帧需要一个首帧素材,尾帧可选,没有尾帧时自动按仅首帧提交。“素材创建模式”默认关闭,此时上传连接素材并按线路创建 HC/Doubao Asset;打开后显示编号式素材 ID 输入并跳过上传,使用已有图片、视频和音频素材 ID,其中首尾帧模式填写一个或两个图片素材 ID。连接的图片会按 PNG 上传且单项不超过 30MB,宽高各为 `300~6000px`、比例为 `0.4~2.5`;视频仅支持 MP4/MOV,单项不超过 512MB,并额外要求总像素为 `407,696~8,295,044`;音频支持 WAV/MP3/M4A/AAC/FLAC/OGG,单项不超过 100MB。所有素材在上传和创建素材前完成校验,准备阶段最多并发处理三个素材并保持输入顺序。seed 保留在普通参数区最下方;“联网搜索”和“返回末帧图片”暂时隐藏,不提供用户设置,但保留旧工作流中的值及参数顺序。联网搜索仅为旧工作流保留,当前统一的 `content` 请求不会发送该参数。旧的四种生成模式、参数顺序和“海外HC”线路会在加载时自动迁移。
|
「Seedance 全能生成视频」现与「o1key 视频生成」共用参数标准、素材限制、`content` 请求体构造和 Seedance 提交/轮询/下载客户端。生成模式简化为“多模态”和“首尾帧”:新节点默认多模态,无参考素材而仅填写提示词时自动按文生视频提交;首尾帧需要一个首帧素材,尾帧可选,没有尾帧时自动按仅首帧提交。“素材创建模式”默认关闭,此时上传连接素材并按线路创建 HC/Doubao Asset;打开后显示编号式素材 ID 输入并跳过上传,使用已有图片、视频和音频素材 ID,其中首尾帧模式填写一个或两个图片素材 ID。连接的图片会按 PNG 上传且单项不超过 30MB,宽高各为 `300~6000px`、比例为 `0.4~2.5`;视频仅支持 MP4/MOV,单项不超过 200MB,并额外要求总像素为 `407,696~8,295,044`;音频支持 WAV/MP3,单项不超过 15MB。参考视频和参考音频的单项及总时长上限为 15 秒(2.0 系列)或 30 秒(2.5)。所有素材在上传和创建素材前完成校验,准备阶段最多并发处理三个素材并保持输入顺序。seed 仍位于普通参数区,但仅作为 ComfyUI 的重新执行判断依据,不会随请求提交,实际种子由 Seedance 自行生成。"联网搜索"为旧工作流保留并保持隐藏,"返回末帧图片"可正常使用。联网搜索仅为旧工作流保留,当前统一的 `content` 请求不会发送该参数。旧的四种生成模式、参数顺序和“海外HC”线路会在加载时自动迁移。
|
||||||
|
|
||||||
「o1key 视频生成」是面板式统一入口,新建节点默认使用“多模态参考”,并支持 Seedance 2.0、2.0 Fast、2.0 Mini 和 2.5,以及文生视频、首帧、首尾帧和多模态参考四种模式。切换到其他工作流再返回时,节点会恢复离开前的生成模式、提示词、参数、素材 ID 和已上传图片/视频/音频。直接上传的首帧、尾帧和多模态参考图片遵循火山方舟官方输入限制:宽、高各为 `300~6000px`,宽高比为 `0.4~2.5`;官方没有为参考图片另设总像素下限。参考视频除相同的宽高及比例限制外,总像素必须在 `407,696~8,295,044` 之间。校验在上传前提示,并在后端素材快照阶段再次强制执行;浏览器无法读取受支持的 MOV/H.265 元数据时会交由后端 PyAV 校验,不会仅因浏览器解码能力不足而误拒绝。使用需要参考素材的 Seedance 模式时,还可选择“素材创建”:默认“自动创建”并显示对应的上传区;多模态区右上角使用一个统一的“上传”按钮,可一次选择图片、视频和音频并自动分类。自动模式会复用「Seedance 创建素材」的统一服务,海外线路创建 HC 素材,国内线路创建 Doubao 素材,素材进入可用状态后才提交视频。相同内容会复用已验证可用的素材 ID,视频提交失败后的重新生成也会直接复用本次已创建的 ID。选择“手动”后上传区会切换为素材 ID 输入,首帧模式需要一个图片素材 ID,首尾帧模式需要两个图片素材 ID,多模态模式可填写图片、视频和音频素材 ID。手动 ID 可通过「Seedance 创建素材」节点提前获取。面板沿用「o1key 图片生成」的视觉语言:提示词卡片、自定义下拉、素材缩略图、状态条和主操作按钮保持一致;视频参数仍采用单列布局,切换生成模式或素材创建方式时,只展示当前模式需要的素材区并同步调整节点高度。提示词右下角的「✨ AI帮写」使用独立视频默认预设,根据当前模式、时长、宽高比和音频开关组织连续的动作与镜头;首帧、尾帧及参考图按当前角色和顺序参与视觉分析,参考视频和音频只提供数量与顺序语义,不会把媒体内容上传给帮写模型。参考视频缩略图直接使用浏览器原生视频解码显示首个可用画面,不生成额外封面文件;若当前浏览器无法解码该格式,才回退为播放图标和文件名。上传图片后可通过缩略图左上角按钮打开与图片生成节点相同的编辑器;多张参考图片、视频和音频都可拖拽调整提交顺序,编号角标会同步更新。它不使用 ComfyUI 原生任务队列:每点一次「开始生成」都会创建并连线原生「保存视频」节点,开启「返回尾帧」时再同时创建原生「保存图像」节点,然后提交一个可并行运行的后台任务。插件不限制独立视频任务的并行数量;每个任务的素材准备阶段最多同时处理三个素材,避免瞬间冲击上传和素材接口。生成按钮只在本次上传或提交期间短暂禁用。上游服务仍可能依据账户配额或服务状态限流。
|
“生成模式”除“多模态”和“首尾帧”外,还提供 Seedance 2.5 专用的“视频编辑”和“视频延长”:两者都要求连接且仅连接一段参考视频并填写提示词,宽高比固定按 `adaptive` 提交,编辑任务按上游要求显式传 `duration: -1`,延长任务可选 4~30 秒或自动。选择“输出格式”为 `mov` 时,2.5 任务会附带 `output_format`,便于需要保留音画连续的延长结果。
|
||||||
|
|
||||||
|
「o1key 视频生成」是面板式统一入口,新建节点默认使用“多模态参考”,并支持 Seedance 2.0、2.0 Fast、2.0 Mini 和 2.5,以及文生视频、首帧、首尾帧和多模态参考四种通用模式,另有 Seedance 2.5 专属的视频编辑和视频延长:两者只显示参考视频上传区,要求上传且仅上传一段参考视频并填写提示词,宽高比固定为智能,编辑的时长固定为自动。切换到其他工作流再返回时,节点会恢复离开前的生成模式、提示词、参数、素材 ID 和已上传图片/视频/音频。直接上传的首帧、尾帧和多模态参考图片遵循火山方舟官方输入限制:宽、高各为 `300~6000px`,宽高比为 `0.4~2.5`;官方没有为参考图片另设总像素下限。参考视频除相同的宽高及比例限制外,总像素必须在 `407,696~8,295,044` 之间。校验在上传前提示,并在后端素材快照阶段再次强制执行;浏览器无法读取受支持的 MOV/H.265 元数据时会交由后端 PyAV 校验,不会仅因浏览器解码能力不足而误拒绝。使用需要参考素材的 Seedance 模式时,还可选择“素材创建”:默认“直接上传”,连接的素材只上传到存储并以公网 URL 提交;多模态区右上角使用一个统一的“上传”按钮,可一次选择图片、视频和音频并自动分类。切换为“自动创建”后才会复用「Seedance 创建素材」的统一服务,海外线路创建 HC 素材,国内线路创建 Doubao 素材,素材进入可用状态后才提交视频;相同内容会复用已验证可用的素材 ID,视频提交失败后的重新生成也会直接复用本次已创建的 ID。选择“手动”后上传区会切换为素材 ID 输入,首帧模式需要一个图片素材 ID,首尾帧模式需要两个图片素材 ID,多模态模式可填写图片、视频和音频素材 ID。手动 ID 可通过「Seedance 创建素材」节点提前获取。面板沿用「o1key 图片生成」的视觉语言:提示词卡片、自定义下拉、素材缩略图、状态条和主操作按钮保持一致;视频参数仍采用单列布局,切换生成模式或素材创建方式时,只展示当前模式需要的素材区并同步调整节点高度。提示词右下角的「✨ AI帮写」使用独立视频默认预设,根据当前模式、时长、宽高比和音频开关组织连续的动作与镜头;首帧、尾帧及参考图按当前角色和顺序参与视觉分析,参考视频和音频只提供数量与顺序语义,不会把媒体内容上传给帮写模型。参考视频缩略图直接使用浏览器原生视频解码显示首个可用画面,不生成额外封面文件;若当前浏览器无法解码该格式,才回退为播放图标和文件名。上传图片后可通过缩略图左上角按钮打开与图片生成节点相同的编辑器;多张参考图片、视频和音频都可拖拽调整提交顺序,编号角标会同步更新。它不使用 ComfyUI 原生任务队列:每点一次「开始生成」都会创建并连线原生「保存视频」节点,开启「返回尾帧」时再同时创建原生「保存图像」节点,然后提交一个可并行运行的后台任务。插件不限制独立视频任务的并行数量;每个任务的素材准备阶段最多同时处理三个素材,避免瞬间冲击上传和素材接口。生成按钮只在本次上传或提交期间短暂禁用。上游服务仍可能依据账户配额或服务状态限流。
|
||||||
|
|
||||||
该统一视频节点会为当前及后续新增的视频模型共用友好审查提示。错误中出现 `copyright` 时优先按版权限制处理,并结合 `audio / video / content / real` 字段或关键词分别提示输出音频、输出视频、提示词或真人内容触发限制;例如 `The request failed because the output audio may be related to copyright restrictions` 会显示“请求失败,输出视频中音频触发版权限制!”。其他安全、内容审查或策略拒绝错误也会按同样对象给出中文提示;普通网络和参数错误仍保留原诊断信息。
|
该统一视频节点会为当前及后续新增的视频模型共用友好审查提示。错误中出现 `copyright` 时优先按版权限制处理,并结合 `audio / video / content / real` 字段或关键词分别提示输出音频、输出视频、提示词或真人内容触发限制;例如 `The request failed because the output audio may be related to copyright restrictions` 会显示“请求失败,输出视频中音频触发版权限制!”。其他安全、内容审查或策略拒绝错误也会按同样对象给出中文提示;普通网络和参数错误仍保留原诊断信息。
|
||||||
|
|
||||||
|
|||||||
+3
-3
@@ -1227,7 +1227,7 @@ try:
|
|||||||
return web.json_response({"error": "未配置 API Key"}, status=401)
|
return web.json_response({"error": "未配置 API Key"}, status=401)
|
||||||
|
|
||||||
base_url = NETWORK_ROUTES[get_network_route()]
|
base_url = NETWORK_ROUTES[get_network_route()]
|
||||||
model = data.get("model", "gpt-6-sol")
|
model = data.get("model", "claude-opus-5-5")
|
||||||
messages = data.get("messages", [])
|
messages = data.get("messages", [])
|
||||||
if not isinstance(messages, list) or not messages:
|
if not isinstance(messages, list) or not messages:
|
||||||
return web.json_response({"error": "缺少对话内容"}, status=400)
|
return web.json_response({"error": "缺少对话内容"}, status=400)
|
||||||
@@ -1246,12 +1246,12 @@ try:
|
|||||||
if reasoning not in ("low", "medium", "high"):
|
if reasoning not in ("low", "medium", "high"):
|
||||||
reasoning = "high"
|
reasoning = "high"
|
||||||
body = {"model": model, "messages": messages, "stream": True}
|
body = {"model": model, "messages": messages, "stream": True}
|
||||||
if model == "claude-fable-5":
|
if model in ("claude-fable-5", "claude-opus-5-5"):
|
||||||
budgets = {"low": 2048, "medium": 8192, "high": 16384}
|
budgets = {"low": 2048, "medium": 8192, "high": 16384}
|
||||||
budget = budgets[reasoning]
|
budget = budgets[reasoning]
|
||||||
body["thinking"] = {"type": "enabled", "budget_tokens": budget}
|
body["thinking"] = {"type": "enabled", "budget_tokens": budget}
|
||||||
body["max_tokens"] = budget + 8192
|
body["max_tokens"] = budget + 8192
|
||||||
elif model in ("gpt-5.5", "gpt-5.6-sol", "gpt-6-astra", "gpt-6-sol", "gemini-3.1-pro-preview"):
|
elif model in ("gpt-5.5", "gpt-5.6-sol", "gpt-6-astra", "gpt-6-sol", "gpt-6.1-sol", "gemini-3.1-pro-preview", "gemini-4-argon"):
|
||||||
body["reasoning_effort"] = reasoning
|
body["reasoning_effort"] = reasoning
|
||||||
|
|
||||||
search_trace = None
|
search_trace = None
|
||||||
|
|||||||
+46
-15
@@ -87,6 +87,32 @@ class SeedanceClient:
|
|||||||
|
|
||||||
# ── 2. 轮询状态 ────────────────────────────────────────────────────
|
# ── 2. 轮询状态 ────────────────────────────────────────────────────
|
||||||
|
|
||||||
|
async def get_task_async(
|
||||||
|
self,
|
||||||
|
task_id: str,
|
||||||
|
session: aiohttp.ClientSession = None,
|
||||||
|
) -> Dict[str, Any]:
|
||||||
|
"""查询一次任务详情(不轮询),用于样片任务出片前校验。"""
|
||||||
|
url = f"{self.base_url}{self.STATUS_ENDPOINT.format(task_id=task_id)}"
|
||||||
|
should_close = session is None
|
||||||
|
if session is None:
|
||||||
|
connector = aiohttp.TCPConnector(ssl=False, force_close=True)
|
||||||
|
session = aiohttp.ClientSession(connector=connector)
|
||||||
|
try:
|
||||||
|
check_interrupt()
|
||||||
|
resp = await run_with_interrupt(async_request_with_retry(
|
||||||
|
session, "GET", url, headers=self._headers(), prefix="Seedance 任务查询: "
|
||||||
|
))
|
||||||
|
text = await resp.text()
|
||||||
|
resp.release()
|
||||||
|
payload = json.loads(text)
|
||||||
|
if not isinstance(payload, dict):
|
||||||
|
raise RuntimeError("Seedance 任务查询返回格式错误")
|
||||||
|
return payload
|
||||||
|
finally:
|
||||||
|
if should_close:
|
||||||
|
await session.close()
|
||||||
|
|
||||||
async def poll_async(
|
async def poll_async(
|
||||||
self,
|
self,
|
||||||
task_id: str,
|
task_id: str,
|
||||||
@@ -102,18 +128,13 @@ class SeedanceClient:
|
|||||||
while True:
|
while True:
|
||||||
deadline.check()
|
deadline.check()
|
||||||
check_interrupt()
|
check_interrupt()
|
||||||
async with session.get(url, headers=self._headers()) as resp:
|
# 轮询同样走重试:长任务中途的 429/503 不应让已付费的任务作废
|
||||||
text = await resp.text()
|
resp = await run_with_interrupt(async_request_with_retry(
|
||||||
if resp.status != 200:
|
session, "GET", url, headers=self._headers(), prefix="Seedance 状态查询: "
|
||||||
try:
|
))
|
||||||
err = json.loads(text)
|
text = await resp.text()
|
||||||
msg = (err.get("error", {}).get("message")
|
resp.release()
|
||||||
or err.get("message")
|
result = json.loads(text)
|
||||||
or text)
|
|
||||||
except Exception:
|
|
||||||
msg = text
|
|
||||||
raise RuntimeError(f"状态查询失败 ({resp.status}): {msg}")
|
|
||||||
result = json.loads(text)
|
|
||||||
|
|
||||||
# new-api 包装格式:真实数据在 result["data"] 里
|
# new-api 包装格式:真实数据在 result["data"] 里
|
||||||
inner = result.get("data") or result
|
inner = result.get("data") or result
|
||||||
@@ -129,20 +150,27 @@ class SeedanceClient:
|
|||||||
|
|
||||||
if is_success_status(status):
|
if is_success_status(status):
|
||||||
# 响应结构:result["data"] = inner,inner["data"] = platform_data
|
# 响应结构:result["data"] = inner,inner["data"] = platform_data
|
||||||
# 视频 URL 在 inner["result_url"] 或 inner["data"]["content"]["video_url"]
|
# 视频 URL 在 inner["result_url"] 或 metadata.url
|
||||||
|
# 末帧图片 URL 在 metadata.last_frame_url
|
||||||
platform_data = inner.get("data") or {}
|
platform_data = inner.get("data") or {}
|
||||||
content = platform_data.get("content") or {}
|
content = platform_data.get("content") or {}
|
||||||
|
metadata = inner.get("metadata")
|
||||||
|
if not isinstance(metadata, dict):
|
||||||
|
metadata = platform_data.get("metadata")
|
||||||
|
if not isinstance(metadata, dict):
|
||||||
|
metadata = {}
|
||||||
video_url = (
|
video_url = (
|
||||||
inner.get("result_url")
|
inner.get("result_url")
|
||||||
|
or metadata.get("url")
|
||||||
or content.get("video_url")
|
or content.get("video_url")
|
||||||
or platform_data.get("video_url")
|
or platform_data.get("video_url")
|
||||||
or inner.get("url")
|
or inner.get("url")
|
||||||
)
|
)
|
||||||
if not video_url:
|
if not video_url:
|
||||||
raise RuntimeError("任务成功但未找到视频 URL")
|
raise RuntimeError("任务成功但未找到视频 URL")
|
||||||
# 末帧图片 URL 在 inner["data"]["content"]["last_frame_url"]
|
|
||||||
last_frame_url = (
|
last_frame_url = (
|
||||||
content.get("last_frame_url")
|
metadata.get("last_frame_url")
|
||||||
|
or content.get("last_frame_url")
|
||||||
or platform_data.get("last_frame_url")
|
or platform_data.get("last_frame_url")
|
||||||
or inner.get("last_frame_url")
|
or inner.get("last_frame_url")
|
||||||
)
|
)
|
||||||
@@ -178,6 +206,7 @@ class SeedanceClient:
|
|||||||
on_stage: Optional[Callable[[str], None]] = None,
|
on_stage: Optional[Callable[[str], None]] = None,
|
||||||
on_progress: Optional[Callable[[int], None]] = None,
|
on_progress: Optional[Callable[[int], None]] = None,
|
||||||
use_new_format: bool = False,
|
use_new_format: bool = False,
|
||||||
|
on_submitted: Optional[Callable[[str], None]] = None,
|
||||||
) -> tuple:
|
) -> tuple:
|
||||||
"""提交 → 轮询 → 下载,返回 (本地视频路径, 末帧图片URL或None)"""
|
"""提交 → 轮询 → 下载,返回 (本地视频路径, 末帧图片URL或None)"""
|
||||||
connector = aiohttp.TCPConnector(ssl=False, force_close=True)
|
connector = aiohttp.TCPConnector(ssl=False, force_close=True)
|
||||||
@@ -189,6 +218,8 @@ class SeedanceClient:
|
|||||||
on_stage("submitting")
|
on_stage("submitting")
|
||||||
task_id = await self.submit_async(body, session, use_new_format=use_new_format)
|
task_id = await self.submit_async(body, session, use_new_format=use_new_format)
|
||||||
print(f"[Seedance] 任务已提交 → {task_id}")
|
print(f"[Seedance] 任务已提交 → {task_id}")
|
||||||
|
if on_submitted:
|
||||||
|
on_submitted(task_id)
|
||||||
if on_stage:
|
if on_stage:
|
||||||
on_stage(f"submitted:{task_id}")
|
on_stage(f"submitted:{task_id}")
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ Seedance 2.0 真人素材(Element)API 客户端
|
|||||||
"""
|
"""
|
||||||
|
|
||||||
import json
|
import json
|
||||||
|
import re
|
||||||
import aiohttp
|
import aiohttp
|
||||||
from typing import Optional
|
from typing import Optional
|
||||||
from urllib.parse import quote
|
from urllib.parse import quote
|
||||||
@@ -12,6 +13,53 @@ from ..utils.config import get_api_key_or_raise, get_base_url_by_route
|
|||||||
from ..utils.video_task import PollDeadline, check_interrupt, interruptible_sleep
|
from ..utils.video_task import PollDeadline, check_interrupt, interruptible_sleep
|
||||||
|
|
||||||
|
|
||||||
|
_MAX_LOG_RESPONSE_CHARS = 4000
|
||||||
|
_LOG_URL_PATTERN = re.compile(r"https?://[^\s\"'<>]+")
|
||||||
|
_LOG_BASE64_PATTERN = re.compile(r"data:[^,\s]+;base64,[A-Za-z0-9+/=]+")
|
||||||
|
_LOG_TOKEN_PATTERN = re.compile(r"(?i)bearer\s+[^\s\"']+")
|
||||||
|
|
||||||
|
|
||||||
|
def _redact_log_text(text: str) -> str:
|
||||||
|
"""Fold credentials, signed URLs and Base64 media before logging."""
|
||||||
|
|
||||||
|
text = _LOG_URL_PATTERN.sub("<URL 已隐藏>", text)
|
||||||
|
text = _LOG_BASE64_PATTERN.sub("<Base64 已隐藏>", text)
|
||||||
|
return _LOG_TOKEN_PATTERN.sub("Bearer <已隐藏>", text)
|
||||||
|
|
||||||
|
|
||||||
|
def _log_value(value, key: str = "", depth: int = 0):
|
||||||
|
if depth >= 12:
|
||||||
|
return "<嵌套内容已省略>"
|
||||||
|
if isinstance(value, dict):
|
||||||
|
return {
|
||||||
|
_redact_log_text(str(name)[:200]): _log_value(item, str(name), depth + 1)
|
||||||
|
for name, item in value.items()
|
||||||
|
}
|
||||||
|
if isinstance(value, list):
|
||||||
|
items = [_log_value(item, key, depth + 1) for item in value[:50]]
|
||||||
|
if len(value) > 50:
|
||||||
|
items.append(f"<其余 {len(value) - 50} 项已省略>")
|
||||||
|
return items
|
||||||
|
if isinstance(value, str):
|
||||||
|
if len(value) > 1200:
|
||||||
|
return f"<长文本 {len(value)} 字符已省略>"
|
||||||
|
return _redact_log_text(value)
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
def _format_log_response(payload) -> str:
|
||||||
|
"""Render an asset API response for the terminal with only secrets folded."""
|
||||||
|
|
||||||
|
try:
|
||||||
|
rendered = json.dumps(_log_value(payload), ensure_ascii=False, indent=2)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
rendered = _redact_log_text(str(payload))
|
||||||
|
if len(rendered) > _MAX_LOG_RESPONSE_CHARS:
|
||||||
|
rendered = f"{rendered[:_MAX_LOG_RESPONSE_CHARS]}...<后续内容已省略>"
|
||||||
|
return rendered
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
class SeedanceElementClient:
|
class SeedanceElementClient:
|
||||||
"""Seedance 2.0 真人素材客户端"""
|
"""Seedance 2.0 真人素材客户端"""
|
||||||
|
|
||||||
@@ -172,11 +220,9 @@ class SeedanceElementClient:
|
|||||||
async with session.post(url, json=body, headers=self._hc_headers()) as resp:
|
async with session.post(url, json=body, headers=self._hc_headers()) as resp:
|
||||||
result = await self._read_json_response(resp)
|
result = await self._read_json_response(resp)
|
||||||
print(
|
print(
|
||||||
f"[Seedance素材][{request_label}] 创建响应体:\n"
|
f"[Seedance素材][{request_label}] 创建响应体 HTTP {resp.status}:\n"
|
||||||
+ json.dumps(
|
+ _format_log_response(result),
|
||||||
{"http_status": resp.status, "success": bool(result.get("success"))},
|
flush=True,
|
||||||
ensure_ascii=False,
|
|
||||||
)
|
|
||||||
)
|
)
|
||||||
if resp.status < 200 or resp.status >= 300:
|
if resp.status < 200 or resp.status >= 300:
|
||||||
message = self._hc_error_message(result, "创建素材失败")
|
message = self._hc_error_message(result, "创建素材失败")
|
||||||
@@ -218,13 +264,30 @@ class SeedanceElementClient:
|
|||||||
headers=self._hc_headers(),
|
headers=self._hc_headers(),
|
||||||
) as resp:
|
) as resp:
|
||||||
result = await self._read_json_response(resp)
|
result = await self._read_json_response(resp)
|
||||||
|
data = result.get("data")
|
||||||
|
status = str(data.get("Status", "")).strip() if isinstance(data, dict) else ""
|
||||||
|
failed = (
|
||||||
|
resp.status < 200
|
||||||
|
or resp.status >= 300
|
||||||
|
or not result.get("success", False)
|
||||||
|
)
|
||||||
|
logged_status = getattr(self, "_logged_asset_status", None)
|
||||||
|
if logged_status is None:
|
||||||
|
logged_status = self._logged_asset_status = {}
|
||||||
|
if failed or logged_status.get(asset_id) != status:
|
||||||
|
logged_status[asset_id] = status
|
||||||
|
print(
|
||||||
|
f"[Seedance素材][{request_label}] 查询响应体 HTTP {resp.status}:\n"
|
||||||
|
+ _format_log_response(result),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
if resp.status < 200 or resp.status >= 300:
|
if resp.status < 200 or resp.status >= 300:
|
||||||
message = self._hc_error_message(result, "查询素材状态失败")
|
message = self._hc_error_message(result, "查询素材状态失败")
|
||||||
raise RuntimeError(f"查询 {request_label} 素材失败 ({resp.status}): {message}")
|
raise RuntimeError(f"查询 {request_label} 素材失败 ({resp.status}): {message}")
|
||||||
if not result.get("success", False):
|
if not result.get("success", False):
|
||||||
raise RuntimeError(self._hc_error_message(result, f"查询 {request_label} 素材失败"))
|
raise RuntimeError(self._hc_error_message(result, f"查询 {request_label} 素材失败"))
|
||||||
|
|
||||||
data = result.get("data")
|
|
||||||
if not isinstance(data, dict):
|
if not isinstance(data, dict):
|
||||||
raise RuntimeError(f"查询 {request_label} 素材未返回 data")
|
raise RuntimeError(f"查询 {request_label} 素材未返回 data")
|
||||||
return data
|
return data
|
||||||
@@ -237,7 +300,7 @@ class SeedanceElementClient:
|
|||||||
name: str,
|
name: str,
|
||||||
asset_url: str,
|
asset_url: str,
|
||||||
asset_type: str,
|
asset_type: str,
|
||||||
poll_interval: float = 3.0,
|
poll_interval: float = 1.5,
|
||||||
request_type: str = "hc",
|
request_type: str = "hc",
|
||||||
) -> dict:
|
) -> dict:
|
||||||
"""创建 HC 或 Doubao 素材并等待其进入 Active 状态。"""
|
"""创建 HC 或 Doubao 素材并等待其进入 Active 状态。"""
|
||||||
|
|||||||
@@ -210,9 +210,9 @@ The released `O1keyGPTImage` and `O1keyGPTImageBatch` nodes reuse the same text-
|
|||||||
|
|
||||||
`SeedanceMultiModal` uses V3 `Autogrow.TemplateNames` for its released numbered image, video, and audio inputs. The saved node ID and Autogrow leaf names remain stable; `migrateWorkflow.js` rewrites legacy flat input names such as `参考图片1` to `参考图片.参考图片1` and renames `真人素材IDn` inputs to `图片素材IDn` before graph configuration. Both migrations are safe to repeat, and the backend retains the former material-ID kwargs as aliases for API-workflow compatibility. Autogrow cannot retain editable string widgets because widget templates become connection-only, so the material-ID inputs remain ordinary append-order string widgets. `seedanceMultiModalDynamic.js` hides only the unused trailing widgets in each ID family, reveals one new empty row after the highest filled value, and recomputes the node height from the currently visible rows while preserving its width. This frontend visibility rule never reorders values, allowing legacy positional `widgets_values` to load unchanged. Before submission, the node prints its finalized request body to the ComfyUI log; the logged copy preserves ordinary parameters and `asset://` IDs but folds credentials, Base64 media, binary data, and HTTP(S) temporary media URLs without changing the submitted body.
|
`SeedanceMultiModal` uses V3 `Autogrow.TemplateNames` for its released numbered image, video, and audio inputs. The saved node ID and Autogrow leaf names remain stable; `migrateWorkflow.js` rewrites legacy flat input names such as `参考图片1` to `参考图片.参考图片1` and renames `真人素材IDn` inputs to `图片素材IDn` before graph configuration. Both migrations are safe to repeat, and the backend retains the former material-ID kwargs as aliases for API-workflow compatibility. Autogrow cannot retain editable string widgets because widget templates become connection-only, so the material-ID inputs remain ordinary append-order string widgets. `seedanceMultiModalDynamic.js` hides only the unused trailing widgets in each ID family, reveals one new empty row after the highest filled value, and recomputes the node height from the currently visible rows while preserving its width. This frontend visibility rule never reorders values, allowing legacy positional `widgets_values` to load unchanged. Before submission, the node prints its finalized request body to the ComfyUI log; the logged copy preserves ordinary parameters and `asset://` IDs but folds credentials, Base64 media, binary data, and HTTP(S) temporary media URLs without changing the submitted body.
|
||||||
|
|
||||||
Seedance model capabilities are shared across the single, multimodal, and batch boundaries. Seedance 2.5 accepts 4–30 seconds, all four exposed resolutions (`480p / 720p / 1080p / 4k`), and 30 image, 10 video, and 10 audio content items; direct media and matching `asset://` IDs count toward the same per-type limit. Seedance 2.0 variants remain capped at 4–15 seconds and 9/3/3 content items, while fast and mini retain the `480p / 720p` resolution restriction. `SeedanceMultiModal` expands its Autogrow leaf-name lists to the 2.5 maxima. Its original 9 image, 3 video, and 3 audio ID widgets retain their exact positional order, and additional ID widgets are appended after that legacy block so saved positional `widgets_values` remain compatible; only the former image-widget name is migrated from `真人素材IDn` to `图片素材IDn`.
|
Seedance model capabilities are shared across the single, multimodal, and batch boundaries. Seedance 2.5 accepts 4–30 seconds, the three exposed resolutions (`480p / 720p / 1080p`), and 30 image, 10 video, and 10 audio content items; direct media and matching `asset://` IDs count toward the same per-type limit. Seedance 2.0 variants remain capped at 4–15 seconds and 9/3/3 content items, while fast and mini retain the `480p / 720p` resolution restriction. Reference video and audio are limited to 2–15 s per item with a 15 s total for the 2.0 variants, and to a 30 s total for 2.5; uploaded video clips are capped at 200 MB and audio at 15 MB in WAV or MP3. The 2.5 `edit` and `extend` generation modes require exactly one reference video but may also carry reference images and audio, because the provider contract only mandates the video; they send `omni_reference_task_type`, force `adaptive` ratio, and set `duration: -1` for edits; 2.5 first-frame and first/last-frame requests are also normalized to `adaptive`. The `seed` widget is a ComfyUI cache key only: it is never included in the request body, so the provider always generates its own seed. Editing it re-runs the node without changing the generated video parameters. `SeedanceMultiModal` expands its Autogrow leaf-name lists to the 2.5 maxima. Its original 9 image, 3 video, and 3 audio ID widgets retain their exact positional order, and additional ID widgets are appended after that legacy block so saved positional `widgets_values` remain compatible; only the former image-widget name is migrated from `真人素材IDn` to `图片素材IDn`.
|
||||||
|
|
||||||
`SeedanceMultiModal`, `SeedanceAutoPass`, and `SeedanceAutoPassBatch` expose both `国内` and `海外` model routes and default newly created nodes to `国内`; `海外` is the display-name replacement for the former `海外HC` value. The domestic route maps the four existing base-model choices to `doubao-seedance-2-0-260128-max`, `doubao-seedance-2-0-fast-260128-max`, `doubao-seedance-2-0-mini-260615-max`, and `doubao-seedance-2-5-260628-max`; it reuses the same capability envelope and new-format request body as the corresponding overseas choices. `SeedanceAutoPass` exposes only `多模态` and `首尾帧`: the backend resolves prompt-only multimodal calls to `text`, and resolves one or two frame images to `first_frame` or `first_last_frame`. Its `素材创建` branch mirrors the unified generator's `auto/manual` contract; automatic media is validated and converted into HC/Doubao assets, while manual IDs bypass upload and enter `build_seedance_video_body` through the `assets` fields. The node translates its Chinese widget values into `o1key_video_catalog.py` and submits through `SeedanceClient`, so the unified panel and graph node cannot drift in scalar parameters or request shape. `migrateWorkflow.js` performs an idempotent compatibility migration for the former four mode values, moved web-search widget, former route label, last-frame default, and newly added asset-creation selector.
|
`SeedanceMultiModal`, `SeedanceAutoPass`, and `SeedanceAutoPassBatch` expose both `国内` and `海外` model routes and default newly created nodes to `国内`; `海外` is the display-name replacement for the former `海外HC` value. The domestic route maps the four existing base-model choices to `doubao-seedance-2-0-260128-max`, `doubao-seedance-2-0-fast-260128-max`, `doubao-seedance-2-0-mini-260615-max`, and `doubao-seedance-2-5-260628-max`; it reuses the same capability envelope and new-format request body as the corresponding overseas choices. `SeedanceAutoPass` exposes `多模态`, `首尾帧`, `视频编辑`, and `视频延长`: the backend resolves prompt-only multimodal calls to `text`, resolves one or two frame images to `first_frame` or `first_last_frame`, and passes an explicitly selected edit/extend mode through with its single reference video plus any optional reference images and audio. Its `素材创建` branch mirrors the unified generator's `auto/manual` contract; automatic media is validated and converted into HC/Doubao assets, while manual IDs bypass upload and enter `build_seedance_video_body` through the `assets` fields. The node translates its Chinese widget values into `o1key_video_catalog.py` and submits through `SeedanceClient`, so the unified panel and graph node cannot drift in scalar parameters or request shape. `migrateWorkflow.js` performs an idempotent compatibility migration for the former four mode values, moved web-search widget, former route label, last-frame default, and newly added asset-creation selector. Seedance 2.5's draft flow is exposed through the append-only `样片模式` / `样片任务ID` widgets and the new `样片任务ID` output: `生成样片` submits the normal request body with `draft: true` and a forced `480p` resolution and returns the preview plus the provider task ID, while `按样片生成` submits only `content: [{"type": "draft_task", "draft_task": {"id": ...}}]` so the provider reuses the draft's prompt, media, duration, ratio, and audio and renders the 1080p final; both requests go through `SeedanceClient`, and the task ID is captured from the submission callback. The draft task ID can be typed into the widget or received through the optional `样片任务ID输入` STRING socket (a connected link wins over the widget); before submitting the final request the node queries the task once through `SeedanceClient.get_task_async`, requires a succeeded status, logs the reported model/resolution/duration, and reuses the reported model for the final body.
|
||||||
|
|
||||||
#### Panel-driven unified video generation
|
#### Panel-driven unified video generation
|
||||||
|
|
||||||
@@ -265,4 +265,4 @@ Completed videos are atomically promoted into the configured output location wit
|
|||||||
- The GPT Image batch node pairs every populated folder through its selected pairing mode and runs the resulting tasks concurrently. It has no random-folder selector or concurrency widget; workflow migration removes both values from older saved nodes.
|
- The GPT Image batch node pairs every populated folder through its selected pairing mode and runs the resulting tasks concurrently. It has no random-folder selector or concurrency widget; workflow migration removes both values from older saved nodes.
|
||||||
- The Nano Banana batch node's optional colour correction never resizes the generated image, uses only reference image 1, and runs exactly once after generation and before save; its standalone counterpart and `O1keyImageGenerator` have no correction stage.
|
- The Nano Banana batch node's optional colour correction never resizes the generated image, uses only reference image 1, and runs exactly once after generation and before save; its standalone counterpart and `O1keyImageGenerator` have no correction stage.
|
||||||
- Route-label changes never alter the serialized values `畅速`, `直连`, and `专线`.
|
- Route-label changes never alter the serialized values `畅速`, `直连`, and `专线`.
|
||||||
- `SeedanceAutoPass` retains a visible `素材创建模式` combo with default `关闭` (automatic assets and hidden IDs) and `打开` (manual IDs shown below). Material IDs use ordinary numbered single-line widgets in image/video/audio order (30/10/10), revealing one empty successor after the highest filled row as in `SeedanceMultiModal`. Visibility never removes serialized widgets or clears IDs. The former `素材创建` input and `自动创建 / 手动` values migrate to this toggle without shifting its position; aggregate fields migrate into numbered rows, and legacy API kwargs remain accepted. Web-search, seed, and last-frame parameters remain at the bottom. The ordinary generation-mode combo drives actual media-socket removal/restoration in the frontend: only progressive reference-image/video/audio sockets in multimodal, only first/last-frame sockets in frame mode. Inactive Autogrow groups are suspended to prevent ghost sockets; switching disconnects removed media links but preserves unrelated widget sockets, and saved workflows are reconciled after configuration.
|
- `SeedanceAutoPass` retains a visible `素材创建模式` combo with default `关闭` (direct public URLs, no asset creation), `自动创建` (HC/Doubao assets created before submission), and `手动` (numbered asset IDs shown below). Material IDs use ordinary numbered single-line widgets in image/video/audio order (30/10/10), revealing one empty successor after the highest filled row as in `SeedanceMultiModal`. Visibility never removes serialized widgets or clears IDs. The former `素材创建` input and `自动创建 / 手动` values migrate to this toggle without shifting its position; aggregate fields migrate into numbered rows, and legacy API kwargs remain accepted. Web-search, seed, last-frame, and output-format parameters remain at the bottom; only web search stays hidden because the shared `content` request never sends it. The ordinary generation-mode combo drives actual media-socket removal/restoration in the frontend: progressive reference-image/video/audio sockets in multimodal and in the 2.5 edit and extend modes, and only first/last-frame sockets in frame mode. Inactive Autogrow groups are suspended to prevent ghost sockets; switching disconnects removed media links but preserves unrelated widget sockets, and saved workflows are reconciled after configuration.
|
||||||
|
|||||||
+1
-1
@@ -60,7 +60,7 @@ Panel-triggered image batches must be represented in ComfyUI's native task queue
|
|||||||
|
|
||||||
`O1keyVideoGenerator` is intentionally different from the image generator: its panel jobs must not enter or imitate ComfyUI's native queue. Keep paid work exclusively behind `/o1key/video/jobs`; native generator execution may resolve completed local descriptors but must never submit or retry generation. One click must create one connected native `SaveVideo`, plus one connected native `SaveImage` only when `return_last_frame` is enabled, and one independent server job record. Dispatch completed safe descriptors to those exact native nodes and persist enough safe association state to restore previews or resume polling after workflow reload. Keep the released `O1keyVideoResult` registered as deprecated compatibility support, but never create it for new panel submissions. Re-enable the action as soon as submission returns so later clicks remain independent. Provider adapters belong behind `o1key_video_catalog.py` and `o1key_video_jobs.py`: add the capability entry, scalar/media validation, request-body builder, executor dispatch, frontend controls, and offline tests together. Seedance automatic material creation must go through `seedance_assets.py`, map the video route to the matching HC or Doubao asset namespace, wait for `Active`, and submit `asset://` references only. Keep material concurrency bounded independently of video-job concurrency, preserve input order after concurrent preparation, and let terminal results retain only safe resolved IDs so retries do not recreate assets. Content reuse may persist fingerprints and IDs, but never upload URLs, local paths, credentials, or complete provider envelopes. Validate all limits before uploads or paid requests, snapshot only sanitized Comfy input descriptors, and persist neither credentials, Base64, signed URLs, nor absolute input paths.
|
`O1keyVideoGenerator` is intentionally different from the image generator: its panel jobs must not enter or imitate ComfyUI's native queue. Keep paid work exclusively behind `/o1key/video/jobs`; native generator execution may resolve completed local descriptors but must never submit or retry generation. One click must create one connected native `SaveVideo`, plus one connected native `SaveImage` only when `return_last_frame` is enabled, and one independent server job record. Dispatch completed safe descriptors to those exact native nodes and persist enough safe association state to restore previews or resume polling after workflow reload. Keep the released `O1keyVideoResult` registered as deprecated compatibility support, but never create it for new panel submissions. Re-enable the action as soon as submission returns so later clicks remain independent. Provider adapters belong behind `o1key_video_catalog.py` and `o1key_video_jobs.py`: add the capability entry, scalar/media validation, request-body builder, executor dispatch, frontend controls, and offline tests together. Seedance automatic material creation must go through `seedance_assets.py`, map the video route to the matching HC or Doubao asset namespace, wait for `Active`, and submit `asset://` references only. Keep material concurrency bounded independently of video-job concurrency, preserve input order after concurrent preparation, and let terminal results retain only safe resolved IDs so retries do not recreate assets. Content reuse may persist fingerprints and IDs, but never upload URLs, local paths, credentials, or complete provider envelopes. Validate all limits before uploads or paid requests, snapshot only sanitized Comfy input descriptors, and persist neither credentials, Base64, signed URLs, nor absolute input paths.
|
||||||
|
|
||||||
`SeedanceAutoPass` is the graph-connected counterpart to the panel generator. Preserve its released Chinese input IDs or provide an explicit idempotent `migrateWorkflow.js` rewrite when a user-requested layout change moves positional widgets. Translate displayed values into `normalize_seedance_parameters`, use the shared reference-dimension/count constants, delegate request-body construction to `build_seedance_video_body`, and submit through `SeedanceClient`. Its two displayed modes must resolve to the canonical `text / multimodal / first_frame / first_last_frame` values from the connected media count. Automatic assets validate every connected tensor or media source before the bounded three-item HC/Doubao preparation stage; manual assets skip upload and pass normalized IDs through the shared body's `assets` fields.
|
`SeedanceAutoPass` is the graph-connected counterpart to the panel generator. Preserve its released Chinese input IDs or provide an explicit idempotent `migrateWorkflow.js` rewrite when a user-requested layout change moves positional widgets. Translate displayed values into `normalize_seedance_parameters`, use the shared reference-dimension/count constants, delegate request-body construction to `build_seedance_video_body`, and submit through `SeedanceClient`. Its four displayed modes (`多模态 / 首尾帧 / 视频编辑 / 视频延长`) must resolve to the canonical `text / multimodal / first_frame / first_last_frame / edit / extend` values from the connected media count; edit and extend require exactly one reference video and may additionally carry reference images and audio, matching the provider's 2.5 edit contract. The 2.5 draft flow must keep its two stages separate: `生成样片` forces `draft: true` with `480p` and returns the provider task ID, and `按样片生成` sends only the `draft_task` content item, never the original media or generation parameters; keep both request bodies covered by offline tests. The draft task ID arrives either through the optional `样片任务ID输入` STRING socket or the manual widget (socket wins), and the final stage must verify the task once with `SeedanceClient.get_task_async` and reuse the model reported by the task before submitting. Automatic assets validate every connected tensor or media source before the bounded three-item HC/Doubao preparation stage; manual assets skip upload and pass normalized IDs through the shared body's `assets` fields.
|
||||||
|
|
||||||
In automatic multimodal mode, render reference images, videos, and audio cards in one shared horizontal material track. Keep one mixed-media upload control in the track header, and do not render trailing type-specific image, video, or audio add cards. Detect each selected file's media type before upload, retain type-specific validation and type-local ordering, and preserve the existing `reference_images` / `reference_videos` / `reference_audios` workflow fields; the compact layout is presentation-only and must not merge or reorder those serialized manifests.
|
In automatic multimodal mode, render reference images, videos, and audio cards in one shared horizontal material track. Keep one mixed-media upload control in the track header, and do not render trailing type-specific image, video, or audio add cards. Detect each selected file's media type before upload, retain type-specific validation and type-local ordering, and preserve the existing `reference_images` / `reference_videos` / `reference_audios` workflow fields; the compact layout is presentation-only and must not merge or reorder those serialized manifests.
|
||||||
|
|
||||||
|
|||||||
@@ -111,7 +111,7 @@ class O1keyVideoGenerator(io.ComfyNode):
|
|||||||
io.Combo.Input(
|
io.Combo.Input(
|
||||||
"asset_creation_mode",
|
"asset_creation_mode",
|
||||||
options=SEEDANCE_ASSET_CREATION_MODE_OPTIONS,
|
options=SEEDANCE_ASSET_CREATION_MODE_OPTIONS,
|
||||||
default="auto",
|
default="direct",
|
||||||
socketless=True,
|
socketless=True,
|
||||||
),
|
),
|
||||||
io.String.Input("video_manifest", default="{}", multiline=True, socketless=True),
|
io.String.Input("video_manifest", default="{}", multiline=True, socketless=True),
|
||||||
|
|||||||
+322
-60
@@ -24,10 +24,11 @@ from ..clients.seedance_element_client import SeedanceElementClient
|
|||||||
from ..utils.config import get_base_url_by_route
|
from ..utils.config import get_base_url_by_route
|
||||||
from ..utils.r2_uploader import upload_image, upload_video, upload_audio
|
from ..utils.r2_uploader import upload_image, upload_video, upload_audio
|
||||||
from ..utils.image_utils import pil_to_tensor, tensor_to_pil
|
from ..utils.image_utils import pil_to_tensor, tensor_to_pil
|
||||||
from ..utils.video_task import format_seedance_generation_error
|
from ..utils.video_task import extract_error_message, format_seedance_generation_error
|
||||||
from ..utils.o1key_video_catalog import (
|
from ..utils.o1key_video_catalog import (
|
||||||
SEEDANCE_CAPABILITIES,
|
SEEDANCE_CAPABILITIES,
|
||||||
SEEDANCE_MODEL_MATRIX,
|
SEEDANCE_MODEL_MATRIX,
|
||||||
|
SEEDANCE_REFERENCE_AUDIO_EXTENSIONS,
|
||||||
SEEDANCE_REFERENCE_AUDIO_MAX_BYTES,
|
SEEDANCE_REFERENCE_AUDIO_MAX_BYTES,
|
||||||
SEEDANCE_REFERENCE_IMAGE_MAX_BYTES,
|
SEEDANCE_REFERENCE_IMAGE_MAX_BYTES,
|
||||||
SEEDANCE_REFERENCE_VIDEO_MAX_BYTES,
|
SEEDANCE_REFERENCE_VIDEO_MAX_BYTES,
|
||||||
@@ -35,6 +36,7 @@ from ..utils.o1key_video_catalog import (
|
|||||||
resolve_seedance_model,
|
resolve_seedance_model,
|
||||||
validate_seedance_media_counts,
|
validate_seedance_media_counts,
|
||||||
validate_seedance_reference_dimensions,
|
validate_seedance_reference_dimensions,
|
||||||
|
validate_seedance_reference_durations,
|
||||||
)
|
)
|
||||||
from ..utils.o1key_video_jobs import build_seedance_video_body
|
from ..utils.o1key_video_jobs import build_seedance_video_body
|
||||||
|
|
||||||
@@ -42,6 +44,8 @@ from comfy_api.latest import InputImpl, io
|
|||||||
|
|
||||||
|
|
||||||
_BASE_MODELS = ["seedance 2.0", "seedance 2.0 fast", "seedance 2.0 mini", "seedance 2.5"]
|
_BASE_MODELS = ["seedance 2.0", "seedance 2.0 fast", "seedance 2.0 mini", "seedance 2.5"]
|
||||||
|
# 全能生成视频节点把最新的 2.5 放在模型选择最上方。
|
||||||
|
_AUTOPASS_BASE_MODELS = ["seedance 2.5", "seedance 2.0", "seedance 2.0 fast", "seedance 2.0 mini"]
|
||||||
_MODEL_ROUTES = ["海外", "国内"]
|
_MODEL_ROUTES = ["海外", "国内"]
|
||||||
_LEGACY_MODEL_ROUTES = {
|
_LEGACY_MODEL_ROUTES = {
|
||||||
"海外HC": "海外",
|
"海外HC": "海外",
|
||||||
@@ -126,7 +130,14 @@ _GENERATION_MODES = [
|
|||||||
]
|
]
|
||||||
_UI_MODE_MULTIMODAL = "多模态"
|
_UI_MODE_MULTIMODAL = "多模态"
|
||||||
_UI_MODE_FIRST_LAST = "首尾帧"
|
_UI_MODE_FIRST_LAST = "首尾帧"
|
||||||
_UI_GENERATION_MODES = [_UI_MODE_MULTIMODAL, _UI_MODE_FIRST_LAST]
|
_UI_MODE_EDIT = "视频编辑"
|
||||||
|
_UI_MODE_EXTEND = "视频延长"
|
||||||
|
_UI_GENERATION_MODES = [
|
||||||
|
_UI_MODE_MULTIMODAL,
|
||||||
|
_UI_MODE_FIRST_LAST,
|
||||||
|
_UI_MODE_EDIT,
|
||||||
|
_UI_MODE_EXTEND,
|
||||||
|
]
|
||||||
_CANONICAL_GENERATION_MODES = {
|
_CANONICAL_GENERATION_MODES = {
|
||||||
_MODE_MULTIMODAL: "multimodal",
|
_MODE_MULTIMODAL: "multimodal",
|
||||||
_MODE_FIRST_FRAME: "first_frame",
|
_MODE_FIRST_FRAME: "first_frame",
|
||||||
@@ -134,11 +145,20 @@ _CANONICAL_GENERATION_MODES = {
|
|||||||
_MODE_TEXT: "text",
|
_MODE_TEXT: "text",
|
||||||
_UI_MODE_MULTIMODAL: "multimodal",
|
_UI_MODE_MULTIMODAL: "multimodal",
|
||||||
_UI_MODE_FIRST_LAST: "first_last_frame",
|
_UI_MODE_FIRST_LAST: "first_last_frame",
|
||||||
|
_UI_MODE_EDIT: "edit",
|
||||||
|
_UI_MODE_EXTEND: "extend",
|
||||||
}
|
}
|
||||||
|
|
||||||
_ASSET_MODE_AUTO = "关闭"
|
_ASSET_MODE_DIRECT = "关闭"
|
||||||
_ASSET_MODE_MANUAL = "打开"
|
_ASSET_MODE_AUTO = "自动创建"
|
||||||
_ASSET_MODES = [_ASSET_MODE_AUTO, _ASSET_MODE_MANUAL]
|
_ASSET_MODE_MANUAL = "手动"
|
||||||
|
_ASSET_MODES = [_ASSET_MODE_DIRECT, _ASSET_MODE_AUTO, _ASSET_MODE_MANUAL]
|
||||||
|
|
||||||
|
_DRAFT_OFF = "关闭"
|
||||||
|
_DRAFT_GENERATE = "生成样片"
|
||||||
|
_DRAFT_FROM = "按样片生成"
|
||||||
|
_DRAFT_MODES = [_DRAFT_OFF, _DRAFT_GENERATE, _DRAFT_FROM]
|
||||||
|
|
||||||
|
|
||||||
_SUCCESS_STATUSES = {"succeeded", "success", "completed", "done", "finished"}
|
_SUCCESS_STATUSES = {"succeeded", "success", "completed", "done", "finished"}
|
||||||
_FAILURE_STATUSES = {"failed", "fail", "failure", "error", "expired", "cancelled", "canceled"}
|
_FAILURE_STATUSES = {"failed", "fail", "failure", "error", "expired", "cancelled", "canceled"}
|
||||||
@@ -152,17 +172,23 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
return io.Schema(
|
return io.Schema(
|
||||||
node_id="SeedanceAutoPass",
|
node_id="SeedanceAutoPass",
|
||||||
display_name="Seedance 全能生成视频",
|
display_name="Seedance 全能生成视频",
|
||||||
description="支持多模态(含文生视频)和首尾帧(尾帧可选)两种生成模式。",
|
description="支持多模态(含文生视频)、首尾帧、视频编辑与视频延长;视频编辑/延长以一段参考视频为底片,可附带参考图和参考音频;2.5 支持样片模式(480p 预览 → 1080p 成片)。",
|
||||||
category="comfyui_o1key/Seedance",
|
category="comfyui_o1key/Seedance",
|
||||||
inputs=[
|
inputs=[
|
||||||
io.String.Input("提示词", multiline=True, default=""),
|
io.String.Input("提示词", multiline=True, default=""),
|
||||||
|
io.Combo.Input("主模型", options=_AUTOPASS_BASE_MODELS, default="seedance 2.5"),
|
||||||
|
io.Combo.Input(
|
||||||
|
"样片模式",
|
||||||
|
options=_DRAFT_MODES,
|
||||||
|
default=_DRAFT_OFF,
|
||||||
|
tooltip="Seedance 2.5 专用。生成样片:固定 480p 预览并输出样片任务 ID;按样片生成:只提交该 ID,复用样片的提示词/素材/时长/比例/音频,输出 1080p。",
|
||||||
|
),
|
||||||
io.Combo.Input(
|
io.Combo.Input(
|
||||||
"生成模式",
|
"生成模式",
|
||||||
options=_UI_GENERATION_MODES,
|
options=_UI_GENERATION_MODES,
|
||||||
default=_UI_MODE_MULTIMODAL,
|
default=_UI_MODE_MULTIMODAL,
|
||||||
tooltip="多模态无素材时支持文生视频;首尾帧的尾帧图片可以不连接。",
|
tooltip="多模态无素材时支持文生视频;首尾帧的尾帧图片可以不连接;视频编辑/延长必须接一段参考视频,参考图和参考音频可选。",
|
||||||
),
|
),
|
||||||
io.Combo.Input("主模型", options=_BASE_MODELS, default="seedance 2.0"),
|
|
||||||
io.Combo.Input("模型线路", options=_MODEL_ROUTES, default="国内"),
|
io.Combo.Input("模型线路", options=_MODEL_ROUTES, default="国内"),
|
||||||
io.Combo.Input("分辨率", options=_RESOLUTIONS, default="720p"),
|
io.Combo.Input("分辨率", options=_RESOLUTIONS, default="720p"),
|
||||||
io.Combo.Input("宽高比", options=_RATIOS, default="智能"),
|
io.Combo.Input("宽高比", options=_RATIOS, default="智能"),
|
||||||
@@ -200,11 +226,18 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
),
|
),
|
||||||
io.Image.Input("首帧图片", optional=True),
|
io.Image.Input("首帧图片", optional=True),
|
||||||
io.Image.Input("尾帧图片", optional=True),
|
io.Image.Input("尾帧图片", optional=True),
|
||||||
|
io.String.Input(
|
||||||
|
"样片任务ID输入",
|
||||||
|
display_name="样片任务ID(连线)",
|
||||||
|
optional=True,
|
||||||
|
force_input=True,
|
||||||
|
tooltip="接入上一步输出的「样片任务ID」;连线优先于下方手填值。",
|
||||||
|
),
|
||||||
io.Combo.Input(
|
io.Combo.Input(
|
||||||
"素材创建模式",
|
"素材创建模式",
|
||||||
options=_ASSET_MODES,
|
options=_ASSET_MODES,
|
||||||
default=_ASSET_MODE_AUTO,
|
default=_ASSET_MODE_DIRECT,
|
||||||
tooltip="关闭:隐藏素材 ID 并自动创建连接的素材;打开:显示并使用已有素材 ID。",
|
tooltip="关闭:直接上传并以公网 URL 提交;自动创建:按线路创建素材后提交;手动:使用下方素材 ID。",
|
||||||
),
|
),
|
||||||
*[
|
*[
|
||||||
io.String.Input(f"{prefix}{index}", default="", tooltip="手动模式使用;填写一个 Asset ID。")
|
io.String.Input(f"{prefix}{index}", default="", tooltip="手动模式使用;填写一个 Asset ID。")
|
||||||
@@ -223,16 +256,29 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
default=0,
|
default=0,
|
||||||
min=0,
|
min=0,
|
||||||
max=0xffffffffffffffff,
|
max=0xffffffffffffffff,
|
||||||
|
tooltip="仅用于触发重新执行,不会发送给接口;种子由 Seedance 自行生成。",
|
||||||
),
|
),
|
||||||
io.Combo.Input(
|
io.Combo.Input(
|
||||||
"返回末帧图片",
|
"返回末帧图片",
|
||||||
options=["关闭", "打开"],
|
options=["关闭", "打开"],
|
||||||
default="关闭",
|
default="关闭",
|
||||||
),
|
),
|
||||||
|
io.Combo.Input(
|
||||||
|
"输出格式",
|
||||||
|
options=["mp4", "mov"],
|
||||||
|
default="mp4",
|
||||||
|
tooltip="Seedance 2.5 专用;mov 更适合需要保留音画连续的延长任务。",
|
||||||
|
),
|
||||||
|
io.String.Input(
|
||||||
|
"样片任务ID",
|
||||||
|
default="",
|
||||||
|
tooltip="按样片生成时填写 7 天内的样片任务 ID;可直接粘贴上一个节点输出的「样片任务ID」。",
|
||||||
|
),
|
||||||
],
|
],
|
||||||
outputs=[
|
outputs=[
|
||||||
io.Video.Output(display_name="视频"),
|
io.Video.Output(display_name="视频"),
|
||||||
io.Image.Output(display_name="末帧图片"),
|
io.Image.Output(display_name="末帧图片"),
|
||||||
|
io.String.Output(display_name="样片任务ID"),
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -263,16 +309,18 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
def _asset_creation_inputs(kwargs):
|
def _asset_creation_inputs(kwargs):
|
||||||
"""读取素材创建分支;旧工作流没有该控件时默认自动创建。"""
|
"""读取素材创建分支;旧工作流没有该控件时默认自动创建。"""
|
||||||
|
|
||||||
asset_inputs = kwargs.get("素材创建模式", kwargs.get("素材创建", _ASSET_MODE_AUTO))
|
asset_inputs = kwargs.get("素材创建模式", kwargs.get("素材创建", _ASSET_MODE_DIRECT))
|
||||||
if isinstance(asset_inputs, dict):
|
if isinstance(asset_inputs, dict):
|
||||||
mode = asset_inputs.get("素材创建模式", asset_inputs.get("素材创建", _ASSET_MODE_AUTO))
|
mode = asset_inputs.get("素材创建模式", asset_inputs.get("素材创建", _ASSET_MODE_DIRECT))
|
||||||
inputs = asset_inputs
|
inputs = asset_inputs
|
||||||
else:
|
else:
|
||||||
mode = asset_inputs
|
mode = asset_inputs
|
||||||
inputs = kwargs
|
inputs = kwargs
|
||||||
if mode in {"manual", "手动", _ASSET_MODE_MANUAL}:
|
if mode in {"manual", "打开", _ASSET_MODE_MANUAL}:
|
||||||
return _ASSET_MODE_MANUAL, inputs
|
return _ASSET_MODE_MANUAL, inputs
|
||||||
return _ASSET_MODE_AUTO, inputs
|
if mode in {"auto", _ASSET_MODE_AUTO}:
|
||||||
|
return _ASSET_MODE_AUTO, inputs
|
||||||
|
return _ASSET_MODE_DIRECT, inputs
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _parse_asset_ids(value):
|
def _parse_asset_ids(value):
|
||||||
@@ -311,9 +359,15 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
return "first_last_frame"
|
return "first_last_frame"
|
||||||
if generation_mode in {_UI_MODE_FIRST_LAST}:
|
if generation_mode in {_UI_MODE_FIRST_LAST}:
|
||||||
return "first_frame" if image_count == 1 else "first_last_frame"
|
return "first_frame" if image_count == 1 else "first_last_frame"
|
||||||
|
if generation_mode == _UI_MODE_EDIT:
|
||||||
|
return "edit"
|
||||||
|
if generation_mode == _UI_MODE_EXTEND:
|
||||||
|
return "extend"
|
||||||
if generation_mode in {_UI_MODE_MULTIMODAL, _MODE_MULTIMODAL}:
|
if generation_mode in {_UI_MODE_MULTIMODAL, _MODE_MULTIMODAL}:
|
||||||
return "multimodal" if image_count or video_count or audio_count else "text"
|
return "multimodal" if image_count or video_count or audio_count else "text"
|
||||||
if generation_mode in {"text", "first_frame", "first_last_frame", "multimodal"}:
|
if generation_mode in {
|
||||||
|
"text", "first_frame", "first_last_frame", "multimodal", "edit", "extend",
|
||||||
|
}:
|
||||||
return generation_mode
|
return generation_mode
|
||||||
raise ValueError(f"不支持的生成模式:{generation_mode}")
|
raise ValueError(f"不支持的生成模式:{generation_mode}")
|
||||||
|
|
||||||
@@ -339,6 +393,15 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
raise ValueError("文生视频模式下提示词不能为空")
|
raise ValueError("文生视频模式下提示词不能为空")
|
||||||
return canonical_mode
|
return canonical_mode
|
||||||
|
|
||||||
|
if canonical_mode in {"edit", "extend"}:
|
||||||
|
if len(ref_videos) != 1:
|
||||||
|
raise ValueError("视频编辑和视频延长必须且只能提供一段参考视频")
|
||||||
|
if base_model != "seedance 2.5":
|
||||||
|
raise ValueError("视频编辑和视频延长仅支持 seedance 2.5")
|
||||||
|
if not prompt:
|
||||||
|
raise ValueError("视频编辑和视频延长必须填写提示词")
|
||||||
|
return canonical_mode
|
||||||
|
|
||||||
if canonical_mode in {"first_frame", "first_last_frame"}:
|
if canonical_mode in {"first_frame", "first_last_frame"}:
|
||||||
if generation_mode == _MODE_FIRST_FRAME and len(ref_images) != 1:
|
if generation_mode == _MODE_FIRST_FRAME and len(ref_images) != 1:
|
||||||
raise ValueError("图生视频-首帧模式必须提供首帧图片")
|
raise ValueError("图生视频-首帧模式必须提供首帧图片")
|
||||||
@@ -354,6 +417,8 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
raise ValueError("多模态模式下,提示词和参考素材不能同时为空")
|
raise ValueError("多模态模式下,提示词和参考素材不能同时为空")
|
||||||
if base_model != "seedance 2.5" and ref_audios and not (ref_images or ref_videos):
|
if base_model != "seedance 2.5" and ref_audios and not (ref_images or ref_videos):
|
||||||
raise ValueError("Seedance 2.0 系列不可单独输入参考音频,须同时提供参考图片或参考视频")
|
raise ValueError("Seedance 2.0 系列不可单独输入参考音频,须同时提供参考图片或参考视频")
|
||||||
|
if base_model == "seedance 2.5" and ref_audios and not (ref_images or ref_videos) and not prompt:
|
||||||
|
raise ValueError("Seedance 2.5 仅有参考音频时必须填写提示词")
|
||||||
return canonical_mode
|
return canonical_mode
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
@@ -404,7 +469,6 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
duration_s,
|
duration_s,
|
||||||
gen_audio,
|
gen_audio,
|
||||||
return_last,
|
return_last,
|
||||||
seed,
|
|
||||||
asset_creation_mode="auto",
|
asset_creation_mode="auto",
|
||||||
):
|
):
|
||||||
"""Translate the released Chinese widgets into the shared video catalog."""
|
"""Translate the released Chinese widgets into the shared video catalog."""
|
||||||
@@ -414,7 +478,9 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
canonical_model = _CANONICAL_MODELS[base_model]
|
canonical_model = _CANONICAL_MODELS[base_model]
|
||||||
canonical_route = _CANONICAL_ROUTES[route]
|
canonical_route = _CANONICAL_ROUTES[route]
|
||||||
canonical_mode = generation_mode
|
canonical_mode = generation_mode
|
||||||
if canonical_mode not in {"text", "first_frame", "first_last_frame", "multimodal"}:
|
if canonical_mode not in {
|
||||||
|
"text", "first_frame", "first_last_frame", "multimodal", "edit", "extend",
|
||||||
|
}:
|
||||||
canonical_mode = _CANONICAL_GENERATION_MODES[generation_mode]
|
canonical_mode = _CANONICAL_GENERATION_MODES[generation_mode]
|
||||||
except KeyError as exc:
|
except KeyError as exc:
|
||||||
raise ValueError(f"Seedance 参数无效:{exc.args[0]}") from None
|
raise ValueError(f"Seedance 参数无效:{exc.args[0]}") from None
|
||||||
@@ -430,45 +496,87 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
"duration": "auto" if duration_s == "自动" else str(duration_s).removesuffix("秒"),
|
"duration": "auto" if duration_s == "自动" else str(duration_s).removesuffix("秒"),
|
||||||
"generate_audio": gen_audio,
|
"generate_audio": gen_audio,
|
||||||
"return_last_frame": return_last,
|
"return_last_frame": return_last,
|
||||||
"seed": seed,
|
|
||||||
})
|
})
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def execute(cls, **kwargs):
|
async def execute(cls, **kwargs):
|
||||||
generation_mode, mode_inputs = cls._mode_inputs(kwargs)
|
generation_mode, mode_inputs = cls._mode_inputs(kwargs)
|
||||||
asset_mode, asset_inputs = cls._asset_creation_inputs(kwargs)
|
asset_mode, asset_inputs = cls._asset_creation_inputs(kwargs)
|
||||||
|
draft_mode = str(kwargs.get("样片模式", _DRAFT_OFF) or _DRAFT_OFF).strip()
|
||||||
|
if draft_mode not in _DRAFT_MODES:
|
||||||
|
raise ValueError(f"不支持的样片模式:{draft_mode}")
|
||||||
|
draft_task_id = str(
|
||||||
|
kwargs.get("样片任务ID输入") or kwargs.get("样片任务ID", "") or ""
|
||||||
|
).strip()
|
||||||
manual_assets = asset_mode == _ASSET_MODE_MANUAL
|
manual_assets = asset_mode == _ASSET_MODE_MANUAL
|
||||||
|
auto_assets = asset_mode == _ASSET_MODE_AUTO
|
||||||
prompt = (kwargs.get("提示词", mode_inputs.get("提示词", "")) or "").strip()
|
prompt = (kwargs.get("提示词", mode_inputs.get("提示词", "")) or "").strip()
|
||||||
base_model = kwargs["主模型"]
|
base_model = kwargs["主模型"]
|
||||||
model_route = _normalize_model_route(kwargs["模型线路"])
|
model_route = _normalize_model_route(kwargs["模型线路"])
|
||||||
model = _resolve_model_matrix(base_model, model_route)
|
model = _resolve_model_matrix(base_model, model_route)
|
||||||
resolution = kwargs["分辨率"]
|
resolution = kwargs["分辨率"]
|
||||||
|
if draft_mode == _DRAFT_GENERATE:
|
||||||
|
# 官方样片只允许 480p 预览,其他分辨率会直接报错。
|
||||||
|
resolution = "480p"
|
||||||
ratio = kwargs["宽高比"]
|
ratio = kwargs["宽高比"]
|
||||||
duration_s = kwargs["时长"]
|
duration_s = kwargs["时长"]
|
||||||
gen_audio = kwargs["生成音频"] == "打开"
|
gen_audio = kwargs["生成音频"] == "打开"
|
||||||
web_search = kwargs.get("联网搜索", mode_inputs.get("联网搜索", "关闭")) == "打开"
|
web_search = kwargs.get("联网搜索", mode_inputs.get("联网搜索", "关闭")) == "打开"
|
||||||
return_last = kwargs.get("返回末帧图片", "关闭") == "打开"
|
return_last = kwargs.get("返回末帧图片", "关闭") == "打开"
|
||||||
create_mode = _resolve_asset_creation_mode(model_route)
|
create_mode = _resolve_asset_creation_mode(model_route)
|
||||||
seed = int(kwargs.get("seed", 0))
|
output_format = kwargs.get("输出格式", "mp4")
|
||||||
|
base_url = get_base_url_by_route()
|
||||||
|
|
||||||
|
if draft_mode != _DRAFT_OFF and base_model != "seedance 2.5":
|
||||||
|
raise ValueError("样片模式仅支持 seedance 2.5")
|
||||||
|
if draft_mode == _DRAFT_FROM:
|
||||||
|
# 先校验 ID 格式,再去查任务,避免拿空 ID 去请求接口。
|
||||||
|
body = cls._build_draft_final_body(model, draft_task_id)
|
||||||
|
summary = await cls._verify_draft_task(base_url, draft_task_id)
|
||||||
|
if summary.get("model"):
|
||||||
|
body["model"] = summary["model"]
|
||||||
|
print(
|
||||||
|
f"[Seedance自动过审] 按样片生成:{draft_task_id}"
|
||||||
|
"(复用样片的提示词/素材/参数,输出 1080p)",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
cls._print_request(base_url, body)
|
||||||
|
result_path, _last_frame_url = await cls._submit_poll_download(body, base_url)
|
||||||
|
return io.NodeOutput(InputImpl.VideoFromFile(result_path), None, draft_task_id)
|
||||||
|
|
||||||
if generation_mode in {_UI_MODE_MULTIMODAL, _MODE_MULTIMODAL}:
|
if generation_mode in {_UI_MODE_MULTIMODAL, _MODE_MULTIMODAL}:
|
||||||
ref_images = cls._autogrow_values(mode_inputs, "参考图片", "参考图片", 30)
|
ref_images = cls._autogrow_values(mode_inputs, "参考图片", "参考图片", 30)
|
||||||
ref_videos = cls._autogrow_values(mode_inputs, "参考视频", "参考视频", 10)
|
ref_videos = cls._autogrow_values(mode_inputs, "参考视频", "参考视频", 10)
|
||||||
ref_audios = cls._autogrow_values(mode_inputs, "参考音频", "参考音频", 10)
|
ref_audios = cls._autogrow_values(mode_inputs, "参考音频", "参考音频", 10)
|
||||||
elif generation_mode in {_UI_MODE_FIRST_LAST, _MODE_FIRST_FRAME, _MODE_FIRST_LAST}:
|
elif generation_mode in {_UI_MODE_EDIT, _UI_MODE_EXTEND, _MODE_FIRST_FRAME, _MODE_FIRST_LAST, _UI_MODE_FIRST_LAST}:
|
||||||
first_frame = mode_inputs.get("首帧图片")
|
ref_images = []
|
||||||
last_frame = mode_inputs.get("尾帧图片")
|
|
||||||
if not manual_assets and first_frame is None:
|
|
||||||
raise ValueError("首尾帧模式必须提供首帧图片,尾帧图片可以不提供")
|
|
||||||
ref_images = [first_frame, last_frame]
|
|
||||||
ref_videos = []
|
ref_videos = []
|
||||||
ref_audios = []
|
ref_audios = []
|
||||||
|
if generation_mode in {_UI_MODE_EDIT, _UI_MODE_EXTEND}:
|
||||||
|
ref_videos = cls._autogrow_values(mode_inputs, "参考视频", "参考视频", 10)
|
||||||
|
# 官方 2.5 的编辑/延长允许在参考视频之外附带参考图和参考音频。
|
||||||
|
ref_images = cls._autogrow_values(mode_inputs, "参考图片", "参考图片", 30)
|
||||||
|
ref_audios = cls._autogrow_values(mode_inputs, "参考音频", "参考音频", 10)
|
||||||
|
else:
|
||||||
|
first_frame = mode_inputs.get("首帧图片")
|
||||||
|
last_frame = mode_inputs.get("尾帧图片")
|
||||||
|
if not manual_assets and first_frame is None:
|
||||||
|
raise ValueError("首尾帧模式必须提供首帧图片,尾帧图片可以不提供")
|
||||||
|
ref_images = [first_frame, last_frame]
|
||||||
else:
|
else:
|
||||||
ref_images = []
|
ref_images = []
|
||||||
ref_videos = []
|
ref_videos = []
|
||||||
ref_audios = []
|
ref_audios = []
|
||||||
|
|
||||||
ref_images = [value for value in ref_images if value is not None]
|
ref_images = [value for value in ref_images if value is not None]
|
||||||
|
print(
|
||||||
|
"[Seedance自动过审] 执行参数: "
|
||||||
|
f"生成模式={generation_mode} 主模型={base_model} 模型线路={model_route} "
|
||||||
|
f"分辨率={resolution} 宽高比={ratio} 时长={duration_s} "
|
||||||
|
f"生成音频={'打开' if gen_audio else '关闭'} 素材创建模式={asset_mode} "
|
||||||
|
f"参考=图片{len(ref_images)}/视频{len(ref_videos)}/音频{len(ref_audios)}",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
if manual_assets:
|
if manual_assets:
|
||||||
image_urls = cls._manual_asset_ids(asset_inputs, "图片素材ID", 30)
|
image_urls = cls._manual_asset_ids(asset_inputs, "图片素材ID", 30)
|
||||||
video_urls = cls._manual_asset_ids(asset_inputs, "视频素材ID", 10)
|
video_urls = cls._manual_asset_ids(asset_inputs, "视频素材ID", 10)
|
||||||
@@ -508,36 +616,46 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
duration_s,
|
duration_s,
|
||||||
gen_audio,
|
gen_audio,
|
||||||
return_last,
|
return_last,
|
||||||
seed,
|
"manual" if manual_assets else ("auto" if auto_assets else "direct"),
|
||||||
"manual" if manual_assets else "auto",
|
|
||||||
)
|
)
|
||||||
if not manual_assets:
|
if not manual_assets:
|
||||||
cls._validate_reference_media(ref_images, ref_videos, ref_audios)
|
cls._validate_reference_media(base_model, ref_images, ref_videos, ref_audios)
|
||||||
|
|
||||||
base_url = get_base_url_by_route()
|
|
||||||
|
|
||||||
if not manual_assets:
|
if not manual_assets:
|
||||||
image_urls, video_urls, audio_urls = await cls._create_assets(
|
if auto_assets:
|
||||||
ref_images, ref_videos, ref_audios, base_url, create_mode
|
image_urls, video_urls, audio_urls = await cls._create_assets(
|
||||||
)
|
ref_images, ref_videos, ref_audios, base_url, create_mode
|
||||||
|
)
|
||||||
|
else:
|
||||||
|
image_urls, video_urls, audio_urls = await cls._upload_assets(
|
||||||
|
ref_images, ref_videos, ref_audios, base_url
|
||||||
|
)
|
||||||
|
|
||||||
body = cls._build_body(
|
body = cls._build_body(
|
||||||
model, prompt, resolution, ratio, duration_s,
|
model, prompt, resolution, normalized["aspect_ratio"], normalized["duration"],
|
||||||
gen_audio, web_search, seed,
|
gen_audio, web_search,
|
||||||
image_urls, video_urls, audio_urls,
|
image_urls, video_urls, audio_urls,
|
||||||
use_asset_protocol=True,
|
use_asset_protocol=True,
|
||||||
generation_mode=canonical_mode,
|
generation_mode=canonical_mode,
|
||||||
return_last_frame=normalized["return_last_frame"],
|
return_last_frame=normalized["return_last_frame"],
|
||||||
asset_creation_mode=normalized["asset_creation_mode"],
|
asset_creation_mode=normalized["asset_creation_mode"],
|
||||||
|
output_format=(
|
||||||
|
output_format
|
||||||
|
if base_model == "seedance 2.5" and output_format == "mov"
|
||||||
|
else None
|
||||||
|
),
|
||||||
)
|
)
|
||||||
|
|
||||||
pretty = json.dumps(body, ensure_ascii=False, indent=2)
|
if draft_mode == _DRAFT_GENERATE:
|
||||||
print("[Seedance自动过审] ── 提交请求体 ─────────────────")
|
body["draft"] = True
|
||||||
print(f"[Seedance自动过审] POST {base_url}/v1/video/generations")
|
|
||||||
print(pretty)
|
|
||||||
|
|
||||||
|
cls._print_request(base_url, body)
|
||||||
|
|
||||||
|
captured = {}
|
||||||
try:
|
try:
|
||||||
result_path, last_frame_url = await cls._submit_poll_download(body, base_url)
|
result_path, last_frame_url = await cls._submit_poll_download(
|
||||||
|
body, base_url, captured
|
||||||
|
)
|
||||||
except Exception as exc:
|
except Exception as exc:
|
||||||
message = format_seedance_generation_error(exc)
|
message = format_seedance_generation_error(exc)
|
||||||
if message == str(exc):
|
if message == str(exc):
|
||||||
@@ -546,16 +664,89 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
last_frame = None
|
last_frame = None
|
||||||
if return_last and last_frame_url:
|
if return_last and last_frame_url:
|
||||||
last_frame = await cls._url_to_tensor(last_frame_url)
|
last_frame = await cls._url_to_tensor(last_frame_url)
|
||||||
return io.NodeOutput(InputImpl.VideoFromFile(result_path), last_frame)
|
draft_result = captured.get("task_id", "") if draft_mode == _DRAFT_GENERATE else ""
|
||||||
|
return io.NodeOutput(InputImpl.VideoFromFile(result_path), last_frame, draft_result)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _build_draft_final_body(model, draft_task_id):
|
||||||
|
"""按样片生成:content 只带 draft_task,正式参数由样片任务复用。"""
|
||||||
|
|
||||||
|
task_id = str(draft_task_id or "").strip()
|
||||||
|
if not task_id:
|
||||||
|
raise ValueError("按样片生成必须填写样片任务ID")
|
||||||
|
if not re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", task_id):
|
||||||
|
raise ValueError("样片任务ID格式无效")
|
||||||
|
return {
|
||||||
|
"model": model,
|
||||||
|
"content": [
|
||||||
|
{"type": "draft_task", "draft_task": {"id": task_id}},
|
||||||
|
],
|
||||||
|
}
|
||||||
|
|
||||||
|
@classmethod
|
||||||
|
async def _verify_draft_task(cls, base_url, draft_task_id):
|
||||||
|
"""出正片前确认样片任务已成功,并取回它的模型与规格。"""
|
||||||
|
|
||||||
|
client = SeedanceClient()
|
||||||
|
client.base_url = base_url
|
||||||
|
try:
|
||||||
|
payload = await client.get_task_async(draft_task_id)
|
||||||
|
except Exception as exc:
|
||||||
|
raise RuntimeError(f"查询样片任务失败:{exc}") from None
|
||||||
|
inner = payload.get("data")
|
||||||
|
if not isinstance(inner, dict):
|
||||||
|
inner = payload
|
||||||
|
status = str(inner.get("status") or payload.get("status") or "").strip()
|
||||||
|
normalized = status.lower()
|
||||||
|
if normalized in {"failed", "expired", "canceled", "cancelled", "rejected"}:
|
||||||
|
reason = extract_error_message(payload) or status or "未知原因"
|
||||||
|
raise ValueError(f"样片任务已失败({draft_task_id}):{reason}")
|
||||||
|
if normalized not in {"succeeded", "success", "completed", "done", "finished"}:
|
||||||
|
raise ValueError(
|
||||||
|
f"样片任务尚未完成(当前状态:{status or '未知'}),"
|
||||||
|
"请等样片跑完再出正片。"
|
||||||
|
)
|
||||||
|
summary = {
|
||||||
|
"status": status,
|
||||||
|
"model": str(inner.get("model") or payload.get("model") or "").strip(),
|
||||||
|
"resolution": str(inner.get("resolution") or payload.get("resolution") or "").strip(),
|
||||||
|
"duration": inner.get("duration") if inner.get("duration") is not None else payload.get("duration"),
|
||||||
|
}
|
||||||
|
print(
|
||||||
|
f"[Seedance自动过审] 样片任务 {draft_task_id}: {status}"
|
||||||
|
f" 模型={summary['model'] or '未返回'}"
|
||||||
|
f" 分辨率={summary['resolution'] or '未返回'}"
|
||||||
|
f" 时长={summary['duration'] if summary['duration'] is not None else '未返回'}",
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
return summary
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _print_request(base_url, body):
|
||||||
|
"""Print the finalized generation request so the terminal shows what is sent."""
|
||||||
|
|
||||||
|
print(
|
||||||
|
"\n".join((
|
||||||
|
"[Seedance自动过审] ────────── 提交生成请求 ──────────",
|
||||||
|
f"[Seedance自动过审] POST {base_url}/v1/video/generations",
|
||||||
|
"[Seedance自动过审] Authorization: Bearer ***",
|
||||||
|
"[Seedance自动过审] Content-Type: application/json",
|
||||||
|
"[Seedance自动过审] Body:",
|
||||||
|
json.dumps(body, ensure_ascii=False, indent=2),
|
||||||
|
"[Seedance自动过审] ───────────────────────────────────",
|
||||||
|
)),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def _build_body(model, prompt, resolution, ratio, duration_s,
|
def _build_body(model, prompt, resolution, ratio, duration_s,
|
||||||
gen_audio, web_search, seed,
|
gen_audio, web_search,
|
||||||
image_urls, video_urls, audio_urls,
|
image_urls, video_urls, audio_urls,
|
||||||
use_asset_protocol=False,
|
use_asset_protocol=False,
|
||||||
generation_mode=_MODE_MULTIMODAL,
|
generation_mode=_MODE_MULTIMODAL,
|
||||||
return_last_frame=False,
|
return_last_frame=False,
|
||||||
asset_creation_mode="auto"):
|
asset_creation_mode="auto",
|
||||||
|
output_format=None):
|
||||||
"""
|
"""
|
||||||
按主站验证过的格式拼装请求体。
|
按主站验证过的格式拼装请求体。
|
||||||
|
|
||||||
@@ -570,13 +761,29 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
len(video_urls),
|
len(video_urls),
|
||||||
len(audio_urls),
|
len(audio_urls),
|
||||||
)
|
)
|
||||||
duration = 5 if duration_s == "自动" else int(str(duration_s).removesuffix("秒"))
|
duration = (
|
||||||
|
duration_s
|
||||||
|
if isinstance(duration_s, int)
|
||||||
|
else (-1 if duration_s == "自动" else int(str(duration_s).removesuffix("秒")))
|
||||||
|
)
|
||||||
manual_assets = asset_creation_mode == "manual"
|
manual_assets = asset_creation_mode == "manual"
|
||||||
|
frame_mode = canonical_mode in {"first_frame", "first_last_frame"}
|
||||||
prepared = {
|
prepared = {
|
||||||
"first_frame": None if manual_assets else (image_urls[0] if image_urls else None),
|
"first_frame": (
|
||||||
"last_frame": None if manual_assets else (image_urls[1] if len(image_urls) > 1 else None),
|
None
|
||||||
|
if manual_assets or not frame_mode
|
||||||
|
else (image_urls[0] if image_urls else None)
|
||||||
|
),
|
||||||
|
"last_frame": (
|
||||||
|
None
|
||||||
|
if manual_assets or canonical_mode != "first_last_frame"
|
||||||
|
else (image_urls[1] if len(image_urls) > 1 else None)
|
||||||
|
),
|
||||||
|
# 编辑/延长与多模态一样携带参考图;首尾帧模式走上面的 first/last 角色。
|
||||||
"reference_images": (
|
"reference_images": (
|
||||||
[] if manual_assets or canonical_mode != "multimodal" else list(image_urls)
|
[]
|
||||||
|
if manual_assets or canonical_mode not in {"multimodal", "edit", "extend"}
|
||||||
|
else list(image_urls)
|
||||||
),
|
),
|
||||||
"reference_videos": [] if manual_assets else list(video_urls),
|
"reference_videos": [] if manual_assets else list(video_urls),
|
||||||
"reference_audios": [] if manual_assets else list(audio_urls),
|
"reference_audios": [] if manual_assets else list(audio_urls),
|
||||||
@@ -596,11 +803,11 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
"aspect_ratio": "auto" if ratio == "智能" else ratio,
|
"aspect_ratio": "auto" if ratio == "智能" else ratio,
|
||||||
"generate_audio": bool(gen_audio),
|
"generate_audio": bool(gen_audio),
|
||||||
"return_last_frame": bool(return_last_frame),
|
"return_last_frame": bool(return_last_frame),
|
||||||
"seed": int(seed),
|
"output_format": output_format,
|
||||||
}, prepared)
|
}, prepared)
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
async def _submit_poll_download(cls, body, base_url):
|
async def _submit_poll_download(cls, body, base_url, captured=None):
|
||||||
"""Use the same submit/poll/download client as o1key 视频生成."""
|
"""Use the same submit/poll/download client as o1key 视频生成."""
|
||||||
|
|
||||||
file_handle, save_path = tempfile.mkstemp(
|
file_handle, save_path = tempfile.mkstemp(
|
||||||
@@ -610,12 +817,17 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
os.close(file_handle)
|
os.close(file_handle)
|
||||||
client = SeedanceClient()
|
client = SeedanceClient()
|
||||||
client.base_url = base_url
|
client.base_url = base_url
|
||||||
try:
|
call_kwargs = {
|
||||||
return await client.generate_async(
|
"body": body,
|
||||||
body=body,
|
"save_path": save_path,
|
||||||
save_path=save_path,
|
"use_new_format": True,
|
||||||
use_new_format=True,
|
}
|
||||||
|
if isinstance(captured, dict):
|
||||||
|
call_kwargs["on_submitted"] = lambda task_id: captured.__setitem__(
|
||||||
|
"task_id", str(task_id)
|
||||||
)
|
)
|
||||||
|
try:
|
||||||
|
return await client.generate_async(**call_kwargs)
|
||||||
except BaseException:
|
except BaseException:
|
||||||
try:
|
try:
|
||||||
if os.path.isfile(save_path):
|
if os.path.isfile(save_path):
|
||||||
@@ -702,7 +914,7 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
raise ValueError(f"无法读取{label}文件")
|
raise ValueError(f"无法读取{label}文件")
|
||||||
|
|
||||||
@classmethod
|
@classmethod
|
||||||
def _validate_reference_media(cls, ref_images, ref_videos, ref_audios):
|
def _validate_reference_media(cls, base_model, ref_images, ref_videos, ref_audios):
|
||||||
"""Validate every reference before the first upload or asset request."""
|
"""Validate every reference before the first upload or asset request."""
|
||||||
|
|
||||||
for index, image in enumerate(ref_images, start=1):
|
for index, image in enumerate(ref_images, start=1):
|
||||||
@@ -716,19 +928,23 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
if not 0 < buffer.getbuffer().nbytes <= SEEDANCE_REFERENCE_IMAGE_MAX_BYTES:
|
if not 0 < buffer.getbuffer().nbytes <= SEEDANCE_REFERENCE_IMAGE_MAX_BYTES:
|
||||||
raise ValueError(f"{label}文件大小必须在 1 字节到 30MB 之间")
|
raise ValueError(f"{label}文件大小必须在 1 字节到 30MB 之间")
|
||||||
|
|
||||||
|
video_seconds = []
|
||||||
for index, video in enumerate(ref_videos, start=1):
|
for index, video in enumerate(ref_videos, start=1):
|
||||||
label = f"参考视频{index}"
|
label = f"参考视频{index}"
|
||||||
source = cls._video_source(video)
|
source = cls._video_source(video)
|
||||||
size = cls._stream_size(source, label)
|
size = cls._stream_size(source, label)
|
||||||
if not 0 < size <= SEEDANCE_REFERENCE_VIDEO_MAX_BYTES:
|
if not 0 < size <= SEEDANCE_REFERENCE_VIDEO_MAX_BYTES:
|
||||||
raise ValueError(f"{label}文件大小必须在 1 字节到 512MB 之间")
|
raise ValueError(f"{label}文件大小必须在 1 字节到 200MB 之间")
|
||||||
if isinstance(source, (str, os.PathLike)):
|
if isinstance(source, (str, os.PathLike)):
|
||||||
extension = os.path.splitext(os.fspath(source))[1].lower()
|
extension = os.path.splitext(os.fspath(source))[1].lower()
|
||||||
if extension not in {".mp4", ".mov"}:
|
if extension not in {".mp4", ".mov"}:
|
||||||
raise ValueError(f"{label}格式须为 mp4 或 mov")
|
raise ValueError(f"{label}格式须为 mp4 或 mov")
|
||||||
|
seconds = None
|
||||||
try:
|
try:
|
||||||
if hasattr(video, "get_dimensions"):
|
if hasattr(video, "get_dimensions"):
|
||||||
width, height = video.get_dimensions()
|
width, height = video.get_dimensions()
|
||||||
|
if hasattr(video, "get_duration"):
|
||||||
|
seconds = float(video.get_duration())
|
||||||
else:
|
else:
|
||||||
import av
|
import av
|
||||||
|
|
||||||
@@ -742,6 +958,8 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
if stream is None:
|
if stream is None:
|
||||||
raise ValueError
|
raise ValueError
|
||||||
width, height = stream.width, stream.height
|
width, height = stream.width, stream.height
|
||||||
|
if container.duration is not None:
|
||||||
|
seconds = float(container.duration) / 1_000_000
|
||||||
except Exception:
|
except Exception:
|
||||||
raise ValueError(f"{label}不是可读取的视频") from None
|
raise ValueError(f"{label}不是可读取的视频") from None
|
||||||
finally:
|
finally:
|
||||||
@@ -753,15 +971,18 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
label,
|
label,
|
||||||
require_video_pixel_range=True,
|
require_video_pixel_range=True,
|
||||||
)
|
)
|
||||||
|
if seconds is not None:
|
||||||
|
video_seconds.append(seconds)
|
||||||
|
|
||||||
supported_audio = {".wav", ".mp3", ".m4a", ".aac", ".flac", ".ogg"}
|
audio_seconds = []
|
||||||
for index, audio in enumerate(ref_audios, start=1):
|
for index, audio in enumerate(ref_audios, start=1):
|
||||||
label = f"参考音频{index}"
|
label = f"参考音频{index}"
|
||||||
if isinstance(audio, (str, os.PathLike)):
|
if isinstance(audio, (str, os.PathLike)):
|
||||||
extension = os.path.splitext(os.fspath(audio))[1].lower()
|
extension = os.path.splitext(os.fspath(audio))[1].lower()
|
||||||
if extension not in supported_audio:
|
if extension not in SEEDANCE_REFERENCE_AUDIO_EXTENSIONS:
|
||||||
raise ValueError(f"{label}格式须为 wav/mp3/m4a/aac/flac/ogg")
|
raise ValueError(f"{label}格式须为 wav 或 mp3")
|
||||||
size = cls._stream_size(audio, label)
|
size = cls._stream_size(audio, label)
|
||||||
|
seconds = cls._media_seconds(audio)
|
||||||
elif isinstance(audio, dict) and audio.get("waveform") is not None:
|
elif isinstance(audio, dict) and audio.get("waveform") is not None:
|
||||||
waveform = audio["waveform"]
|
waveform = audio["waveform"]
|
||||||
try:
|
try:
|
||||||
@@ -769,10 +990,35 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
except Exception:
|
except Exception:
|
||||||
raise ValueError(f"{label}无法读取") from None
|
raise ValueError(f"{label}无法读取") from None
|
||||||
size = 44 + sample_count * 2
|
size = 44 + sample_count * 2
|
||||||
|
sample_rate = int(audio.get("sample_rate") or 0)
|
||||||
|
seconds = sample_count / sample_rate if sample_rate > 0 else None
|
||||||
else:
|
else:
|
||||||
raise ValueError(f"{label}无法读取")
|
raise ValueError(f"{label}无法读取")
|
||||||
if not 0 < size <= SEEDANCE_REFERENCE_AUDIO_MAX_BYTES:
|
if not 0 < size <= SEEDANCE_REFERENCE_AUDIO_MAX_BYTES:
|
||||||
raise ValueError(f"{label}文件大小必须在 1 字节到 100MB 之间")
|
raise ValueError(f"{label}文件大小必须在 1 字节到 15MB 之间")
|
||||||
|
if seconds is not None:
|
||||||
|
audio_seconds.append(seconds)
|
||||||
|
|
||||||
|
validate_seedance_reference_durations(
|
||||||
|
_CANONICAL_MODELS[base_model],
|
||||||
|
video_seconds,
|
||||||
|
audio_seconds,
|
||||||
|
model_label=base_model,
|
||||||
|
)
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def _media_seconds(path):
|
||||||
|
"""Read container duration in seconds; return None when unavailable."""
|
||||||
|
|
||||||
|
try:
|
||||||
|
import av
|
||||||
|
|
||||||
|
with av.open(os.fspath(path), mode="r") as container:
|
||||||
|
if container.duration is None:
|
||||||
|
return None
|
||||||
|
return float(container.duration) / 1_000_000
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
async def _url_to_tensor(url):
|
async def _url_to_tensor(url):
|
||||||
@@ -854,6 +1100,22 @@ class SeedanceAutoPass(io.ComfyNode):
|
|||||||
if not str(uploaded_url).startswith("https://"):
|
if not str(uploaded_url).startswith("https://"):
|
||||||
raise ValueError(f"参考{label}上传后未获得 HTTPS 公网地址")
|
raise ValueError(f"参考{label}上传后未获得 HTTPS 公网地址")
|
||||||
name = f"参考{label}{index}"
|
name = f"参考{label}{index}"
|
||||||
|
print(
|
||||||
|
"\n".join((
|
||||||
|
f"[Seedance自动过审][自动创建] POST {base_url}/v1/seedance/assets",
|
||||||
|
"[Seedance自动过审][自动创建] "
|
||||||
|
+ json.dumps(
|
||||||
|
{
|
||||||
|
"type": request_type,
|
||||||
|
"url": "<刚上传的临时地址>",
|
||||||
|
"asset_type": asset_types[kind].lower(),
|
||||||
|
"name": name,
|
||||||
|
},
|
||||||
|
ensure_ascii=False,
|
||||||
|
),
|
||||||
|
)),
|
||||||
|
flush=True,
|
||||||
|
)
|
||||||
result = await element_client.create_hc_asset_and_wait(
|
result = await element_client.create_hc_asset_and_wait(
|
||||||
name=name,
|
name=name,
|
||||||
asset_url=uploaded_url,
|
asset_url=uploaded_url,
|
||||||
|
|||||||
@@ -28,9 +28,10 @@ from ..utils.video_task import (
|
|||||||
InterruptProcessingException,
|
InterruptProcessingException,
|
||||||
)
|
)
|
||||||
from ..utils.http_error import async_request_with_retry
|
from ..utils.http_error import async_request_with_retry
|
||||||
|
from ..utils.o1key_video_catalog import SEEDANCE_REFERENCE_AUDIO_EXTENSIONS
|
||||||
from .seedance_autopass import (
|
from .seedance_autopass import (
|
||||||
SeedanceAutoPass,
|
SeedanceAutoPass,
|
||||||
_BASE_MODELS,
|
_AUTOPASS_BASE_MODELS,
|
||||||
_SUCCESS_STATUSES,
|
_SUCCESS_STATUSES,
|
||||||
_FAILURE_STATUSES,
|
_FAILURE_STATUSES,
|
||||||
_RATIOS,
|
_RATIOS,
|
||||||
@@ -46,7 +47,6 @@ from .seedance_autopass import (
|
|||||||
_LIMITED_RESOLUTION_MODELS,
|
_LIMITED_RESOLUTION_MODELS,
|
||||||
_normalize_model_route,
|
_normalize_model_route,
|
||||||
_resolve_model_matrix,
|
_resolve_model_matrix,
|
||||||
_resolve_asset_creation_mode,
|
|
||||||
)
|
)
|
||||||
from .seedance_video import (
|
from .seedance_video import (
|
||||||
_MM_MODELS,
|
_MM_MODELS,
|
||||||
@@ -67,7 +67,7 @@ except ImportError:
|
|||||||
_LABEL = "Seedance全能生成视频(批量)"
|
_LABEL = "Seedance全能生成视频(批量)"
|
||||||
_MAX_BATCH = 10 # 每批最多并发提交数(用户要求硬上限 10)
|
_MAX_BATCH = 10 # 每批最多并发提交数(用户要求硬上限 10)
|
||||||
_VIDEO_EXTENSIONS = {".mp4", ".mov"}
|
_VIDEO_EXTENSIONS = {".mp4", ".mov"}
|
||||||
_AUDIO_EXTENSIONS = {".wav", ".mp3", ".m4a", ".aac", ".flac", ".ogg"}
|
_AUDIO_EXTENSIONS = set(SEEDANCE_REFERENCE_AUDIO_EXTENSIONS)
|
||||||
_MM_DEFAULT_MODEL = _MM_MODELS[0]
|
_MM_DEFAULT_MODEL = _MM_MODELS[0]
|
||||||
|
|
||||||
|
|
||||||
@@ -234,7 +234,7 @@ class _LegacySeedanceAutoPassBatch:
|
|||||||
web_search = kwargs["联网搜索"] == "打开"
|
web_search = kwargs["联网搜索"] == "打开"
|
||||||
batch_size = max(1, min(int(kwargs.get("每批并发数", _MAX_BATCH)), _MAX_BATCH))
|
batch_size = max(1, min(int(kwargs.get("每批并发数", _MAX_BATCH)), _MAX_BATCH))
|
||||||
sub_dir = (kwargs.get("输出子目录") or "").strip()
|
sub_dir = (kwargs.get("输出子目录") or "").strip()
|
||||||
seed = int(kwargs.get("seed", 0))
|
seed = int(kwargs.get("seed", -1))
|
||||||
|
|
||||||
# 解析真实模型 ID 并做分辨率校验
|
# 解析真实模型 ID 并做分辨率校验
|
||||||
model_id = _resolve_model(model_label)
|
model_id = _resolve_model(model_label)
|
||||||
@@ -472,7 +472,7 @@ class SeedanceAutoPassBatch(io.ComfyNode):
|
|||||||
io.String.Input(
|
io.String.Input(
|
||||||
"音频文件夹",
|
"音频文件夹",
|
||||||
default="",
|
default="",
|
||||||
tooltip="支持 wav/mp3/m4a/aac/flac/ogg,按序号配对。",
|
tooltip="支持 wav/mp3,按序号配对。",
|
||||||
),
|
),
|
||||||
],
|
],
|
||||||
),
|
),
|
||||||
@@ -522,7 +522,7 @@ class SeedanceAutoPassBatch(io.ComfyNode):
|
|||||||
],
|
],
|
||||||
tooltip="切换后仅显示当前模式需要的文件夹输入。",
|
tooltip="切换后仅显示当前模式需要的文件夹输入。",
|
||||||
),
|
),
|
||||||
io.Combo.Input("主模型", options=_BASE_MODELS, default="seedance 2.0"),
|
io.Combo.Input("主模型", options=_AUTOPASS_BASE_MODELS, default="seedance 2.5"),
|
||||||
io.Combo.Input("模型线路", options=_MODEL_ROUTES, default="国内"),
|
io.Combo.Input("模型线路", options=_MODEL_ROUTES, default="国内"),
|
||||||
io.Combo.Input("分辨率", options=_RESOLUTIONS, default="720p"),
|
io.Combo.Input("分辨率", options=_RESOLUTIONS, default="720p"),
|
||||||
io.Combo.Input("宽高比", options=_RATIOS, default="智能"),
|
io.Combo.Input("宽高比", options=_RATIOS, default="智能"),
|
||||||
@@ -680,8 +680,6 @@ class SeedanceAutoPassBatch(io.ComfyNode):
|
|||||||
duration_s = kwargs["时长"]
|
duration_s = kwargs["时长"]
|
||||||
gen_audio = kwargs["生成音频"] == "打开"
|
gen_audio = kwargs["生成音频"] == "打开"
|
||||||
web_search = mode_inputs.get("联网搜索", "关闭") == "打开"
|
web_search = mode_inputs.get("联网搜索", "关闭") == "打开"
|
||||||
create_mode = _resolve_asset_creation_mode(model_route)
|
|
||||||
seed = int(kwargs.get("seed", 0))
|
|
||||||
batch_size = max(1, min(int(kwargs.get("每批并发数", _MAX_BATCH)), _MAX_BATCH))
|
batch_size = max(1, min(int(kwargs.get("每批并发数", _MAX_BATCH)), _MAX_BATCH))
|
||||||
sub_dir = (kwargs.get("输出子目录") or "").strip()
|
sub_dir = (kwargs.get("输出子目录") or "").strip()
|
||||||
|
|
||||||
@@ -699,7 +697,7 @@ class SeedanceAutoPassBatch(io.ComfyNode):
|
|||||||
task["images"], task["videos"], task["audios"],
|
task["images"], task["videos"], task["audios"],
|
||||||
)
|
)
|
||||||
SeedanceAutoPass._validate_reference_media(
|
SeedanceAutoPass._validate_reference_media(
|
||||||
task["images"], task["videos"], task["audios"],
|
base_model, task["images"], task["videos"], task["audios"],
|
||||||
)
|
)
|
||||||
|
|
||||||
if not FOLDER_PATHS_AVAILABLE:
|
if not FOLDER_PATHS_AVAILABLE:
|
||||||
@@ -735,7 +733,7 @@ class SeedanceAutoPassBatch(io.ComfyNode):
|
|||||||
cls._run_one(
|
cls._run_one(
|
||||||
session, base_url, headers, out_dir,
|
session, base_url, headers, out_dir,
|
||||||
model, resolution, ratio, duration_s,
|
model, resolution, ratio, duration_s,
|
||||||
gen_audio, web_search, seed, create_mode,
|
gen_audio, web_search,
|
||||||
generation_mode, task, start + offset + 1, total,
|
generation_mode, task, start + offset + 1, total,
|
||||||
)
|
)
|
||||||
for offset, task in enumerate(batch)
|
for offset, task in enumerate(batch)
|
||||||
@@ -774,17 +772,17 @@ class SeedanceAutoPassBatch(io.ComfyNode):
|
|||||||
async def _run_one(
|
async def _run_one(
|
||||||
cls, session, base_url, headers, out_dir,
|
cls, session, base_url, headers, out_dir,
|
||||||
model, resolution, ratio, duration_s,
|
model, resolution, ratio, duration_s,
|
||||||
gen_audio, web_search, seed, create_mode,
|
gen_audio, web_search,
|
||||||
generation_mode, task, task_no, total,
|
generation_mode, task, task_no, total,
|
||||||
):
|
):
|
||||||
prompt = task["prompt"]
|
prompt = task["prompt"]
|
||||||
try:
|
try:
|
||||||
image_urls, video_urls, audio_urls = await SeedanceAutoPass._create_assets(
|
image_urls, video_urls, audio_urls = await SeedanceAutoPass._upload_assets(
|
||||||
task["images"], task["videos"], task["audios"], base_url, create_mode
|
task["images"], task["videos"], task["audios"], base_url
|
||||||
)
|
)
|
||||||
body = SeedanceAutoPass._build_body(
|
body = SeedanceAutoPass._build_body(
|
||||||
model, prompt, resolution, ratio, duration_s,
|
model, prompt, resolution, ratio, duration_s,
|
||||||
gen_audio, web_search, seed,
|
gen_audio, web_search,
|
||||||
image_urls, video_urls, audio_urls,
|
image_urls, video_urls, audio_urls,
|
||||||
use_asset_protocol=True,
|
use_asset_protocol=True,
|
||||||
generation_mode=generation_mode,
|
generation_mode=generation_mode,
|
||||||
|
|||||||
+37
-40
@@ -14,6 +14,7 @@ from ..clients.gemini_client import GeminiAPIClient
|
|||||||
from ..utils.image_utils import tensor_to_pil, pil_to_tensor
|
from ..utils.image_utils import tensor_to_pil, pil_to_tensor
|
||||||
from ..utils.r2_uploader import upload_image, upload_video, upload_audio
|
from ..utils.r2_uploader import upload_image, upload_video, upload_audio
|
||||||
from ..utils.config import get_base_url_by_route
|
from ..utils.config import get_base_url_by_route
|
||||||
|
from ..utils.o1key_video_catalog import SEEDANCE_CAPABILITIES, SEEDANCE_MODEL_MATRIX
|
||||||
from .seedance_autopass import (
|
from .seedance_autopass import (
|
||||||
SeedanceAutoPass,
|
SeedanceAutoPass,
|
||||||
_BASE_MODELS as _LATEST_BASE_MODELS,
|
_BASE_MODELS as _LATEST_BASE_MODELS,
|
||||||
@@ -71,19 +72,23 @@ def _resolve_model(model: str) -> str:
|
|||||||
return _MM_MODEL_LABEL_TO_ID.get(model, model)
|
return _MM_MODEL_LABEL_TO_ID.get(model, model)
|
||||||
|
|
||||||
|
|
||||||
# 多模态参考生视频支持 4k
|
# 多模态参考生视频支持的分辨率下拉;2.5 与 fast/mini 的实际可用项由能力表过滤
|
||||||
_MM_RESOLUTIONS = ["720p", "1080p", "4k", "480p"]
|
_MM_RESOLUTIONS = ["720p", "1080p", "4k", "480p"]
|
||||||
# 受限模型仅支持 480p / 720p(前端做选择时报错提示)
|
# 实际模型 ID → 支持的分辨率(共享能力表为唯一来源)
|
||||||
_LIMITED_RESOLUTION_MODELS = {
|
_MODEL_RESOLUTIONS = {
|
||||||
"doubao-seedance-2-0-fast-260128",
|
actual_model: tuple(SEEDANCE_CAPABILITIES[model]["resolutions"])
|
||||||
"doubao-seedance-2-0-fast-260128-max",
|
for (model, _route), actual_model in SEEDANCE_MODEL_MATRIX.items()
|
||||||
"doubao-seedance-2-0-mini-260615-max",
|
}
|
||||||
"dreamina-seedance-2-0-fast-hc",
|
# 批量节点仍在用的旧模型 ID,能力沿用同一系列
|
||||||
"seedance-2-0-fast-260128-d",
|
_MODEL_RESOLUTIONS |= {
|
||||||
"seedance-2-0-fast-d-ep",
|
actual_model: tuple(SEEDANCE_CAPABILITIES[model]["resolutions"])
|
||||||
"dreamina-seedance-2-0-mini-hc",
|
for actual_model, model in {
|
||||||
|
"seedance-2-0-fast-260128-d": "seedance-2.0-fast",
|
||||||
|
"seedance-2-0-fast-d-ep": "seedance-2.0-fast",
|
||||||
|
"seedance-2-0-mini-260615-d": "seedance-2.0-mini",
|
||||||
|
"seedance-2-0-mini-260615-d-ep": "seedance-2.0-mini",
|
||||||
|
}.items()
|
||||||
}
|
}
|
||||||
_FAST_UNSUPPORTED_RESOLUTIONS = ["1080p", "4k"]
|
|
||||||
|
|
||||||
_MAX_IMAGE_BYTES = 30 * 1024 * 1024
|
_MAX_IMAGE_BYTES = 30 * 1024 * 1024
|
||||||
_MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024
|
_MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024
|
||||||
@@ -92,16 +97,17 @@ _MAX_REQUEST_BODY_BYTES = 64 * 1024 * 1024
|
|||||||
# ── 模型能力判断 ──────────────────────────────────────────────────────────────
|
# ── 模型能力判断 ──────────────────────────────────────────────────────────────
|
||||||
|
|
||||||
def _check_fast_resolution(model: str, resolution: str):
|
def _check_fast_resolution(model: str, resolution: str):
|
||||||
"""受限模型不支持 1080p / 4k,提交前拦截(保留旧函数名兼容调用方)。"""
|
"""按模型能力表在提交前拦截不支持的分辨率。"""
|
||||||
if model in _LIMITED_RESOLUTION_MODELS and resolution in _FAST_UNSUPPORTED_RESOLUTIONS:
|
supported = _MODEL_RESOLUTIONS.get(model)
|
||||||
|
if supported and resolution not in supported:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"{model} 不支持 {resolution} 分辨率,"
|
f"{model} 不支持 {resolution} 分辨率,"
|
||||||
f"请改用 {_FAST_UNSUPPORTED_RESOLUTIONS} 以外的分辨率(如 720p)。"
|
f"请改用 {' / '.join(supported)} 之一。"
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
def _is_new_format_model(model: str) -> bool:
|
def _is_new_format_model(model: str) -> bool:
|
||||||
"""判断是否使用新请求体格式的模型(顶层 content,role 用 subject)
|
"""判断是否使用新请求体格式的模型(顶层 content)
|
||||||
|
|
||||||
端点与老格式模型相同(均为 /v1/video/generations),
|
端点与老格式模型相同(均为 /v1/video/generations),
|
||||||
仅请求体结构不同,由此函数控制节点侧如何拼装 body。
|
仅请求体结构不同,由此函数控制节点侧如何拼装 body。
|
||||||
@@ -312,7 +318,13 @@ class SeedanceMultiModal(io.ComfyNode):
|
|||||||
io.Combo.Input("生成音频", options=["关闭", "打开"], default="关闭"),
|
io.Combo.Input("生成音频", options=["关闭", "打开"], default="关闭"),
|
||||||
io.Combo.Input("联网搜索", options=["关闭", "打开"], default="关闭"),
|
io.Combo.Input("联网搜索", options=["关闭", "打开"], default="关闭"),
|
||||||
io.Combo.Input("返回末帧图片", options=["关闭", "打开"], default="关闭"),
|
io.Combo.Input("返回末帧图片", options=["关闭", "打开"], default="关闭"),
|
||||||
io.Int.Input("seed", default=0, min=0, max=0xffffffffffffffff),
|
io.Int.Input(
|
||||||
|
"seed",
|
||||||
|
default=0,
|
||||||
|
min=0,
|
||||||
|
max=0xffffffffffffffff,
|
||||||
|
tooltip="仅用于触发重新执行,不会发送给接口;种子由 Seedance 自行生成。",
|
||||||
|
),
|
||||||
io.Autogrow.Input(
|
io.Autogrow.Input(
|
||||||
"参考图片",
|
"参考图片",
|
||||||
optional=True,
|
optional=True,
|
||||||
@@ -400,7 +412,6 @@ class SeedanceMultiModal(io.ComfyNode):
|
|||||||
gen_audio = _first(kwargs.get("生成音频"), "关闭") == "打开"
|
gen_audio = _first(kwargs.get("生成音频"), "关闭") == "打开"
|
||||||
web_search = _first(kwargs.get("联网搜索"), "关闭") == "打开"
|
web_search = _first(kwargs.get("联网搜索"), "关闭") == "打开"
|
||||||
return_last = _first(kwargs.get("返回末帧图片"), "关闭") == "打开"
|
return_last = _first(kwargs.get("返回末帧图片"), "关闭") == "打开"
|
||||||
seed = _first(kwargs.get("seed"), 0)
|
|
||||||
|
|
||||||
ref_images = cls._autogrow_values(kwargs, "参考图片", "参考图片", _MM_IMAGE_LIMIT)
|
ref_images = cls._autogrow_values(kwargs, "参考图片", "参考图片", _MM_IMAGE_LIMIT)
|
||||||
ref_videos = cls._autogrow_values(kwargs, "参考视频", "参考视频", _MM_VIDEO_LIMIT)
|
ref_videos = cls._autogrow_values(kwargs, "参考视频", "参考视频", _MM_VIDEO_LIMIT)
|
||||||
@@ -448,23 +459,17 @@ class SeedanceMultiModal(io.ComfyNode):
|
|||||||
content = []
|
content = []
|
||||||
base_url = get_base_url_by_route()
|
base_url = get_base_url_by_route()
|
||||||
|
|
||||||
# 真人素材 ID(与参考图片共用当前模型的图片额度,优先级最高)
|
# 真人素材 ID(与参考图片共用当前模型的图片额度)
|
||||||
if has_element:
|
if has_element:
|
||||||
for idx, eid in enumerate(element_ids, start=1):
|
for idx, eid in enumerate(element_ids, start=1):
|
||||||
# 确保 element_id 格式正确
|
# 确保 element_id 格式正确
|
||||||
asset_url = eid if eid.startswith("asset://") else f"asset://{eid}"
|
asset_url = eid if eid.startswith("asset://") else f"asset://{eid}"
|
||||||
# 第一个素材ID作为主体(subject),其余作为参考图片(reference_image)
|
|
||||||
if idx == 1:
|
|
||||||
role = "subject" if use_new_format else "reference_image"
|
|
||||||
else:
|
|
||||||
role = "reference_image"
|
|
||||||
content.append({
|
content.append({
|
||||||
"type": "image_url",
|
"type": "image_url",
|
||||||
"image_url": {"url": asset_url},
|
"image_url": {"url": asset_url},
|
||||||
"role": role,
|
"role": "reference_image",
|
||||||
})
|
})
|
||||||
role_label = "主体" if role == "subject" else "参考"
|
print(f"[SeedanceMultiModal] 使用图片素材ID{idx} → {asset_url}")
|
||||||
print(f"[SeedanceMultiModal] 使用图片素材ID{idx}({role_label}) → {asset_url}")
|
|
||||||
|
|
||||||
# 参考图片(2.5 最多 30 个独立槽位,用户自行选择连接哪几个)
|
# 参考图片(2.5 最多 30 个独立槽位,用户自行选择连接哪几个)
|
||||||
if has_image:
|
if has_image:
|
||||||
@@ -517,12 +522,8 @@ class SeedanceMultiModal(io.ComfyNode):
|
|||||||
})
|
})
|
||||||
print(f"[SeedanceMultiModal] 使用音频素材ID{idx} → {asset_url}")
|
print(f"[SeedanceMultiModal] 使用音频素材ID{idx} → {asset_url}")
|
||||||
|
|
||||||
# 文本提示词(放最后)
|
# 文本提示词:content 必须包含非空文本项,纯素材请求也要带上占位
|
||||||
if prompt:
|
content.append({"type": "text", "text": prompt or " "})
|
||||||
content.append({"type": "text", "text": prompt})
|
|
||||||
|
|
||||||
if not content:
|
|
||||||
raise ValueError("content 为空,请至少提供参考图片、参考视频或提示词。")
|
|
||||||
|
|
||||||
# ── 构建请求体 ──────────────────────────────────────────────────────
|
# ── 构建请求体 ──────────────────────────────────────────────────────
|
||||||
if use_new_format:
|
if use_new_format:
|
||||||
@@ -541,15 +542,14 @@ class SeedanceMultiModal(io.ComfyNode):
|
|||||||
body = {
|
body = {
|
||||||
"model": model,
|
"model": model,
|
||||||
"content": ordered_content,
|
"content": ordered_content,
|
||||||
"duration": duration if duration != -1 else 5,
|
"duration": duration,
|
||||||
"resolution": resolution,
|
"resolution": resolution,
|
||||||
"ratio": ratio if ratio not in ("智能", "adaptive") else "16:9", # adaptive 为旧工作流兼容
|
# adaptive 让模型跟随首帧或参考素材比例;旧工作流的「智能」同样映射到它
|
||||||
|
"ratio": ratio if ratio and ratio not in ("智能", "adaptive") else "adaptive",
|
||||||
"generate_audio": gen_audio,
|
"generate_audio": gen_audio,
|
||||||
"watermark": False,
|
"watermark": False,
|
||||||
"return_last_frame": return_last,
|
"return_last_frame": return_last,
|
||||||
}
|
}
|
||||||
if seed != 0:
|
|
||||||
body["seed"] = seed
|
|
||||||
|
|
||||||
print(f"[SeedanceMultiModal] 新格式请求体: model={model}, content_len={len(ordered_content)}, duration={body['duration']}, resolution={body['resolution']}")
|
print(f"[SeedanceMultiModal] 新格式请求体: model={model}, content_len={len(ordered_content)}, duration={body['duration']}, resolution={body['resolution']}")
|
||||||
else:
|
else:
|
||||||
@@ -562,14 +562,11 @@ class SeedanceMultiModal(io.ComfyNode):
|
|||||||
|
|
||||||
if ratio not in ("智能", "adaptive"): # adaptive 为旧工作流兼容
|
if ratio not in ("智能", "adaptive"): # adaptive 为旧工作流兼容
|
||||||
metadata["ratio"] = ratio
|
metadata["ratio"] = ratio
|
||||||
if duration != -1:
|
metadata["duration"] = duration
|
||||||
metadata["duration"] = duration
|
|
||||||
if gen_audio:
|
if gen_audio:
|
||||||
metadata["generate_audio"] = True
|
metadata["generate_audio"] = True
|
||||||
if return_last:
|
if return_last:
|
||||||
metadata["return_last_frame"] = True
|
metadata["return_last_frame"] = True
|
||||||
if seed != 0:
|
|
||||||
metadata["seed"] = seed
|
|
||||||
if web_search:
|
if web_search:
|
||||||
metadata["tools"] = [{"type": "web_search"}]
|
metadata["tools"] = [{"type": "web_search"}]
|
||||||
|
|
||||||
|
|||||||
@@ -25,13 +25,15 @@ from ..utils.file_types import FileList
|
|||||||
# 模型配置
|
# 模型配置
|
||||||
# ============================================================================
|
# ============================================================================
|
||||||
|
|
||||||
DEFAULT_MODEL = "gpt-6-sol"
|
DEFAULT_MODEL = "claude-opus-5-5"
|
||||||
|
|
||||||
SUPPORTED_MODELS = [
|
SUPPORTED_MODELS = [
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
|
"gpt-6-sol",
|
||||||
"gpt-6-astra",
|
"gpt-6-astra",
|
||||||
"gpt-5.6-sol",
|
"gpt-5.6-sol",
|
||||||
"gpt-5.5",
|
"gpt-5.5",
|
||||||
|
"gemini-4-argon",
|
||||||
"gemini-3.1-pro-preview",
|
"gemini-3.1-pro-preview",
|
||||||
"deepseek-v4-pro",
|
"deepseek-v4-pro",
|
||||||
"claude-opus-5",
|
"claude-opus-5",
|
||||||
|
|||||||
@@ -7,20 +7,26 @@ ROOT = Path(__file__).resolve().parents[1]
|
|||||||
|
|
||||||
|
|
||||||
class ChatPanelModelTests(unittest.TestCase):
|
class ChatPanelModelTests(unittest.TestCase):
|
||||||
def test_gpt_6_astra_is_the_frontend_and_proxy_default(self):
|
def test_chat_model_list_uses_current_gpt_model_names(self):
|
||||||
frontend = (ROOT / "web" / "js" / "chatPanel.js").read_text(encoding="utf-8")
|
frontend = (ROOT / "web" / "js" / "chatPanel.js").read_text(encoding="utf-8")
|
||||||
backend = (ROOT / "__init__.py").read_text(encoding="utf-8")
|
backend = (ROOT / "__init__.py").read_text(encoding="utf-8")
|
||||||
|
|
||||||
self.assertIn('const DEFAULT_MODEL = "gpt-6-sol";', frontend)
|
self.assertIn('const DEFAULT_MODEL = "claude-opus-5-5";', frontend)
|
||||||
self.assertIn("let currentModel = DEFAULT_MODEL;", frontend)
|
self.assertIn("let currentModel = DEFAULT_MODEL;", frontend)
|
||||||
models = re.search(r"const MODELS = \[(.*?)\];", frontend, re.DOTALL)
|
models = re.search(r"const MODELS = \[(.*?)\];", frontend, re.DOTALL)
|
||||||
self.assertIsNotNone(models)
|
self.assertIsNotNone(models)
|
||||||
self.assertEqual(models.group(1).strip().splitlines()[0].strip(), "DEFAULT_MODEL,")
|
model_list = models.group(1).strip()
|
||||||
|
self.assertEqual(model_list.splitlines()[0].strip(), "DEFAULT_MODEL,")
|
||||||
|
self.assertIn('"gemini-4-argon"', model_list)
|
||||||
|
self.assertIn('"gpt-6.1-sol"', model_list)
|
||||||
|
self.assertNotIn('"gpt-6-sol"', model_list)
|
||||||
|
self.assertNotIn('"gpt-5.5"', model_list)
|
||||||
|
|
||||||
self.assertIn('data.get("model", "gpt-6-sol")', backend)
|
self.assertIn('data.get("model", "claude-opus-5-5")', backend)
|
||||||
|
self.assertIn('if model in ("claude-fable-5", "claude-opus-5-5"):', backend)
|
||||||
self.assertRegex(
|
self.assertRegex(
|
||||||
backend,
|
backend,
|
||||||
r'elif model in \([^\n]*"gpt-6-sol"[^\n]*\):\n\s+body\["reasoning_effort"\] = reasoning',
|
r'elif model in \([^\n]*"gpt-6\.1-sol"[^\n]*\):\n\s+body\["reasoning_effort"\] = reasoning',
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -3877,9 +3877,9 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
};
|
};
|
||||||
dynamicExtension.nodeCreated(node);
|
dynamicExtension.nodeCreated(node);
|
||||||
|
|
||||||
assert.deepEqual(Array.from(resolutionWidget.options.values), ["480p", "720p", "1080p", "4k"]);
|
assert.deepEqual(Array.from(resolutionWidget.options.values), ["480p", "720p", "1080p"]);
|
||||||
assert.equal(routeWidget.value, "海外");
|
assert.equal(routeWidget.value, "海外");
|
||||||
assert.equal(resolutionWidget.value, "4k");
|
assert.equal(resolutionWidget.value, "720p");
|
||||||
assert.equal(durationWidget.options.values.at(-1), "30秒");
|
assert.equal(durationWidget.options.values.at(-1), "30秒");
|
||||||
|
|
||||||
routeWidget.value = "国内";
|
routeWidget.value = "国内";
|
||||||
@@ -3917,8 +3917,8 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
};
|
};
|
||||||
guardExtension.nodeCreated(node);
|
guardExtension.nodeCreated(node);
|
||||||
|
|
||||||
assert.deepEqual(Array.from(resolutionWidget.options.values), ["720p", "1080p", "4k", "480p"]);
|
assert.deepEqual(Array.from(resolutionWidget.options.values), ["720p", "1080p", "480p"]);
|
||||||
assert.equal(resolutionWidget.value, "4k");
|
assert.equal(resolutionWidget.value, "720p");
|
||||||
assert.equal(durationWidget.options.values.at(-1), "30秒");
|
assert.equal(durationWidget.options.values.at(-1), "30秒");
|
||||||
|
|
||||||
modelWidget.value = "seedance 2.0 fast";
|
modelWidget.value = "seedance 2.0 fast";
|
||||||
@@ -4062,12 +4062,13 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
Array.from(autoPassNode.widgets_values),
|
Array.from(autoPassNode.widgets_values),
|
||||||
[
|
[
|
||||||
"提示词", "多模态", "seedance 2.5", "国内",
|
"提示词", "seedance 2.5", "关闭", "多模态", "国内",
|
||||||
"720p", "智能", "5秒", "关闭", "关闭", ...Array(50).fill(""), "关闭", 0, "关闭",
|
"720p", "智能", "5秒", "关闭", "关闭", ...Array(50).fill(""), "关闭", 0, "关闭",
|
||||||
|
"mp4", "",
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
migrationExtension.beforeConfigureGraph({ nodes: [autoPassNode] });
|
migrationExtension.beforeConfigureGraph({ nodes: [autoPassNode] });
|
||||||
assert.equal(autoPassNode.widgets_values.length, 62);
|
assert.equal(autoPassNode.widgets_values.length, 65);
|
||||||
|
|
||||||
const legacyFrameNode = {
|
const legacyFrameNode = {
|
||||||
type: "SeedanceAutoPass",
|
type: "SeedanceAutoPass",
|
||||||
@@ -4084,8 +4085,9 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
Array.from(legacyFrameNode.widgets_values),
|
Array.from(legacyFrameNode.widgets_values),
|
||||||
[
|
[
|
||||||
"提示词", "首尾帧", "seedance 2.0", "海外",
|
"提示词", "seedance 2.0", "关闭", "首尾帧", "海外",
|
||||||
"720p", "16:9", "5秒", "关闭", "关闭", ...Array(50).fill(""), "打开", 9, "打开",
|
"720p", "16:9", "5秒", "关闭", "关闭", ...Array(50).fill(""), "打开", 9, "打开",
|
||||||
|
"mp4", "",
|
||||||
],
|
],
|
||||||
);
|
);
|
||||||
assert.deepEqual(
|
assert.deepEqual(
|
||||||
@@ -4093,7 +4095,7 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
["联网搜索", "首帧图片"],
|
["联网搜索", "首帧图片"],
|
||||||
);
|
);
|
||||||
migrationExtension.beforeConfigureGraph({ nodes: [legacyFrameNode] });
|
migrationExtension.beforeConfigureGraph({ nodes: [legacyFrameNode] });
|
||||||
assert.equal(legacyFrameNode.widgets_values.length, 62);
|
assert.equal(legacyFrameNode.widgets_values.length, 65);
|
||||||
|
|
||||||
const legacyIdNode = {
|
const legacyIdNode = {
|
||||||
type: "SeedanceAutoPass",
|
type: "SeedanceAutoPass",
|
||||||
@@ -4104,13 +4106,33 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
],
|
],
|
||||||
};
|
};
|
||||||
migrationExtension.beforeConfigureGraph({nodes: [legacyIdNode]});
|
migrationExtension.beforeConfigureGraph({nodes: [legacyIdNode]});
|
||||||
assert.equal(legacyIdNode.widgets_values.length, 62);
|
assert.equal(legacyIdNode.widgets_values.length, 65);
|
||||||
assert.equal(legacyIdNode.widgets_values[8], "打开");
|
assert.equal(legacyIdNode.widgets_values[9], "打开");
|
||||||
assert.deepEqual(legacyIdNode.widgets_values.slice(9, 12), ["image-1", "image-2", "asset://image-3"]);
|
assert.deepEqual(legacyIdNode.widgets_values.slice(10, 13), ["image-1", "image-2", "asset://image-3"]);
|
||||||
assert.deepEqual(legacyIdNode.widgets_values.slice(39, 41), ["video-1", "video-2"]);
|
assert.deepEqual(legacyIdNode.widgets_values.slice(40, 42), ["video-1", "video-2"]);
|
||||||
assert.equal(legacyIdNode.widgets_values[49], "audio-1");
|
assert.equal(legacyIdNode.widgets_values[50], "audio-1");
|
||||||
assert.deepEqual(legacyIdNode.widgets_values.slice(59), ["打开", 42, "打开"]);
|
assert.deepEqual(legacyIdNode.widgets_values.slice(60), ["打开", 42, "打开", "mp4", ""]);
|
||||||
assert.deepEqual(legacyIdNode.inputs.map(input => input.name), ["图片素材ID1", "视频素材ID1", "素材创建模式"]);
|
assert.deepEqual(legacyIdNode.inputs.map(input => input.name), ["图片素材ID1", "视频素材ID1", "素材创建模式"]);
|
||||||
|
|
||||||
|
const currentLayoutNode = {
|
||||||
|
type: "SeedanceAutoPass",
|
||||||
|
inputs: [],
|
||||||
|
widgets_values: [
|
||||||
|
"提示词", "视频编辑", "seedance 2.5", "国内", "480p", "智能", "自动", "关闭",
|
||||||
|
"自动创建", ...Array(50).fill(""), "关闭", 0, "关闭", "mp4", "生成样片", "cgt-20260101120000",
|
||||||
|
],
|
||||||
|
};
|
||||||
|
migrationExtension.beforeConfigureGraph({nodes: [currentLayoutNode]});
|
||||||
|
assert.deepEqual(
|
||||||
|
Array.from(currentLayoutNode.widgets_values),
|
||||||
|
[
|
||||||
|
"提示词", "seedance 2.5", "生成样片", "视频编辑", "国内", "480p", "智能", "自动", "关闭",
|
||||||
|
"自动创建", ...Array(50).fill(""), "关闭", 0, "关闭", "mp4", "cgt-20260101120000",
|
||||||
|
],
|
||||||
|
);
|
||||||
|
const migratedCurrent = [...currentLayoutNode.widgets_values];
|
||||||
|
migrationExtension.beforeConfigureGraph({nodes: [currentLayoutNode]});
|
||||||
|
assert.deepEqual(currentLayoutNode.widgets_values, migratedCurrent);
|
||||||
const migratedIds = [...legacyIdNode.widgets_values];
|
const migratedIds = [...legacyIdNode.widgets_values];
|
||||||
migrationExtension.beforeConfigureGraph({nodes: [legacyIdNode]});
|
migrationExtension.beforeConfigureGraph({nodes: [legacyIdNode]});
|
||||||
assert.deepEqual(legacyIdNode.widgets_values, migratedIds);
|
assert.deepEqual(legacyIdNode.widgets_values, migratedIds);
|
||||||
@@ -4254,13 +4276,14 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
setSize(value) {this.size = value;}, setDirtyCanvas() {},
|
setSize(value) {this.size = value;}, setDirtyCanvas() {},
|
||||||
};
|
};
|
||||||
extension.nodeCreated(node);
|
extension.nodeCreated(node);
|
||||||
for (const widget of [search, lastFrame]) {
|
for (const widget of [search]) {
|
||||||
assert.equal(widget.hidden, true);
|
assert.equal(widget.hidden, true);
|
||||||
assert.equal(widget.options.hidden, true);
|
assert.equal(widget.options.hidden, true);
|
||||||
assert.deepEqual(Array.from(widget.computeSize()), [0, -4]);
|
assert.deepEqual(Array.from(widget.computeSize()), [0, -4]);
|
||||||
assert.equal(widget.value, "打开", "hiding must preserve saved workflow values");
|
assert.equal(widget.value, "打开", "hiding must preserve saved workflow values");
|
||||||
}
|
}
|
||||||
assert.deepEqual(Array.from(node.size), [360, 148]);
|
assert.notEqual(lastFrame.hidden, true, "the last-frame output stays configurable");
|
||||||
|
assert.deepEqual(Array.from(node.size), [360, 172]);
|
||||||
assert.equal(assetMode.hidden, false);
|
assert.equal(assetMode.hidden, false);
|
||||||
assert.notEqual(seed.hidden, true);
|
assert.notEqual(seed.hidden, true);
|
||||||
assert.equal(seed.value, 42);
|
assert.equal(seed.value, 42);
|
||||||
@@ -4272,7 +4295,8 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
extension.loadedGraphNode(node);
|
extension.loadedGraphNode(node);
|
||||||
assetMode.value = "打开";
|
assetMode.value = "打开";
|
||||||
assetMode.callback(assetMode.value);
|
assetMode.callback(assetMode.value);
|
||||||
assert.ok(search.hidden && lastFrame.hidden);
|
assert.ok(search.hidden);
|
||||||
|
assert.notEqual(lastFrame.hidden, true);
|
||||||
assert.deepEqual(node.widgets, widgets);
|
assert.deepEqual(node.widgets, widgets);
|
||||||
assert.deepEqual(node.widgets.map(widget => widget.value), ["打开", "打开", 42, "打开"]);
|
assert.deepEqual(node.widgets.map(widget => widget.value), ["打开", "打开", 42, "打开"]);
|
||||||
const otherWidgets = [{name: "联网搜索", value: "关闭", options: {}}, {name: "返回末帧图片", value: "关闭", options: {}}];
|
const otherWidgets = [{name: "联网搜索", value: "关闭", options: {}}, {name: "返回末帧图片", value: "关闭", options: {}}];
|
||||||
@@ -4280,10 +4304,64 @@ assert.match(migrationSource, /原生 seed 参数/);
|
|||||||
assert.ok(otherWidgets.every(widget => !widget.hidden), "hide only the single all-in-one node");
|
assert.ok(otherWidgets.every(widget => !widget.hidden), "hide only the single all-in-one node");
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log("o1key image generator frontend tests passed");
|
{
|
||||||
|
let extension;
|
||||||
|
vm.runInNewContext(seedanceAutoPassDynamicSource.replace(/^import .*;\s*$/gm, ""), {
|
||||||
|
app: {registerExtension(value) {extension = value;}}, console,
|
||||||
|
});
|
||||||
|
const makeWidget = (name, value, values = []) => ({name, value, options: {values}, callback() {}});
|
||||||
|
const model = makeWidget("主模型", "seedance 2.5", ["seedance 2.0", "seedance 2.5"]);
|
||||||
|
const route = makeWidget("模型线路", "国内", ["海外", "国内"]);
|
||||||
|
const resolution = makeWidget("分辨率", "1080p", ["480p", "720p", "1080p"]);
|
||||||
|
const duration = makeWidget("时长", "5秒", ["自动", "5秒"]);
|
||||||
|
const draft = makeWidget("样片模式", "关闭", ["关闭", "生成样片", "按样片生成"]);
|
||||||
|
const taskId = {name: "样片任务ID", value: "", options: {}};
|
||||||
|
const node = {
|
||||||
|
comfyClass: "SeedanceAutoPass",
|
||||||
|
widgets: [model, route, resolution, duration, draft, taskId],
|
||||||
|
size: [360, 600],
|
||||||
|
computeSize() { return [360, 600]; },
|
||||||
|
setSize(size) { this.size = size; },
|
||||||
|
setDirtyCanvas() {},
|
||||||
|
inputs: [],
|
||||||
|
comfyDynamic: {autogrow: {}},
|
||||||
|
addInput() {},
|
||||||
|
removeInput() {},
|
||||||
|
};
|
||||||
|
extension.nodeCreated(node);
|
||||||
|
assert.equal(taskId.hidden, true, "sample task id stays hidden until needed");
|
||||||
|
assert.equal(draft.hidden, false);
|
||||||
|
|
||||||
|
draft.value = "生成样片";
|
||||||
|
draft.callback("生成样片");
|
||||||
|
assert.equal(resolution.value, "480p");
|
||||||
|
assert.deepEqual(Array.from(resolution.options.values), ["480p"]);
|
||||||
|
|
||||||
|
model.value = "seedance 2.0";
|
||||||
|
model.callback("seedance 2.0");
|
||||||
|
assert.equal(draft.value, "关闭");
|
||||||
|
assert.equal(draft.hidden, true);
|
||||||
|
assert.ok(resolution.options.values.includes("1080p"));
|
||||||
|
|
||||||
|
model.value = "seedance 2.5";
|
||||||
|
model.callback("seedance 2.5");
|
||||||
|
assert.equal(draft.hidden, false);
|
||||||
|
draft.value = "按样片生成";
|
||||||
|
draft.callback("按样片生成");
|
||||||
|
assert.equal(taskId.hidden, false);
|
||||||
|
|
||||||
|
node.inputs = [{name: "样片任务ID输入", link: 7}];
|
||||||
|
node.onConnectionsChange?.();
|
||||||
|
assert.equal(taskId.hidden, true, "linked draft task id hides the manual field");
|
||||||
|
node.inputs = [{name: "样片任务ID输入", link: null}];
|
||||||
|
node.onConnectionsChange?.();
|
||||||
|
assert.equal(taskId.hidden, false);
|
||||||
|
}
|
||||||
|
|
||||||
|
console.log("o1key image generator frontend tests passed");
|
||||||
const nanoThinkingSource = fs.readFileSync(new URL("../web/js/nanoBananaThinkingLevel.js", import.meta.url), "utf8");
|
const nanoThinkingSource = fs.readFileSync(new URL("../web/js/nanoBananaThinkingLevel.js", import.meta.url), "utf8");
|
||||||
|
|
||||||
|
|
||||||
{
|
{
|
||||||
let thinkingExtension;
|
let thinkingExtension;
|
||||||
vm.runInNewContext(nanoThinkingSource.replace(/^import .*;\s*$/gm, ""), {
|
vm.runInNewContext(nanoThinkingSource.replace(/^import .*;\s*$/gm, ""), {
|
||||||
|
|||||||
@@ -43,6 +43,7 @@ from comfyui_o1key.utils.o1key_video_catalog import ( # noqa: E402
|
|||||||
normalize_seedance_parameters,
|
normalize_seedance_parameters,
|
||||||
public_video_capabilities,
|
public_video_capabilities,
|
||||||
resolve_seedance_model,
|
resolve_seedance_model,
|
||||||
|
validate_seedance_reference_durations,
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -86,17 +87,24 @@ class CatalogTests(unittest.TestCase):
|
|||||||
normalize_seedance_parameters(payload(model="seedance-2.0-fast", resolution="1080p"))
|
normalize_seedance_parameters(payload(model="seedance-2.0-fast", resolution="1080p"))
|
||||||
with self.assertRaises(ValueError):
|
with self.assertRaises(ValueError):
|
||||||
normalize_seedance_parameters(payload(model="seedance-2.0", duration="16"))
|
normalize_seedance_parameters(payload(model="seedance-2.0", duration="16"))
|
||||||
result = normalize_seedance_parameters(payload(model="seedance-2.5", duration="30", resolution="4k"))
|
result = normalize_seedance_parameters(payload(model="seedance-2.5", duration="30", resolution="1080p"))
|
||||||
self.assertEqual(result["duration"], 30)
|
self.assertEqual(result["duration"], 30)
|
||||||
|
with self.assertRaisesRegex(ValueError, "分辨率仅支持"):
|
||||||
|
normalize_seedance_parameters(payload(model="seedance-2.5", resolution="4k"))
|
||||||
|
self.assertEqual(
|
||||||
|
normalize_seedance_parameters(payload(duration="auto"))["duration"],
|
||||||
|
-1,
|
||||||
|
)
|
||||||
|
|
||||||
def test_asset_creation_mode_defaults_and_options(self):
|
def test_asset_creation_mode_defaults_and_options(self):
|
||||||
normalized = normalize_seedance_parameters({
|
normalized = normalize_seedance_parameters({
|
||||||
key: value for key, value in payload().items()
|
key: value for key, value in payload().items()
|
||||||
if key != "asset_creation_mode"
|
if key != "asset_creation_mode"
|
||||||
})
|
})
|
||||||
self.assertEqual(normalized["asset_creation_mode"], "auto")
|
self.assertEqual(normalized["asset_creation_mode"], "direct")
|
||||||
modes = public_video_capabilities()["providers"][0]["asset_creation_modes"]
|
modes = public_video_capabilities()["providers"][0]["asset_creation_modes"]
|
||||||
self.assertEqual(modes, [
|
self.assertEqual(modes, [
|
||||||
|
{"value": "direct", "label": "直接上传"},
|
||||||
{"value": "auto", "label": "自动创建"},
|
{"value": "auto", "label": "自动创建"},
|
||||||
{"value": "manual", "label": "手动"},
|
{"value": "manual", "label": "手动"},
|
||||||
])
|
])
|
||||||
@@ -178,6 +186,126 @@ class PayloadAndBodyTests(unittest.TestCase):
|
|||||||
self.assertNotIn("web_search", body)
|
self.assertNotIn("web_search", body)
|
||||||
self.assertNotIn("online_search", body)
|
self.assertNotIn("online_search", body)
|
||||||
|
|
||||||
|
def test_reference_durations_apply_per_item_and_total_limits(self):
|
||||||
|
self.assertEqual(validate_seedance_reference_durations("seedance-2.0", [10, 5], [15]), None)
|
||||||
|
with self.assertRaisesRegex(ValueError, "总时长"):
|
||||||
|
validate_seedance_reference_durations("seedance-2.0", [10, 10], [])
|
||||||
|
with self.assertRaisesRegex(ValueError, "时长必须在"):
|
||||||
|
validate_seedance_reference_durations("seedance-2.0", [16], [])
|
||||||
|
validate_seedance_reference_durations("seedance-2.5", [20, 10], [30])
|
||||||
|
|
||||||
|
def test_seed_is_never_part_of_the_request(self):
|
||||||
|
job = JOBS.normalize_video_job_payload(payload(seed=2**63))
|
||||||
|
self.assertNotIn("seed", job)
|
||||||
|
body = JOBS.build_seedance_video_body(job, {
|
||||||
|
"first_frame": None,
|
||||||
|
"last_frame": None,
|
||||||
|
"reference_images": [],
|
||||||
|
"reference_videos": [],
|
||||||
|
"reference_audios": [],
|
||||||
|
})
|
||||||
|
self.assertNotIn("seed", body)
|
||||||
|
|
||||||
|
def test_reference_only_body_keeps_text_item_and_adaptive_ratio(self):
|
||||||
|
job = JOBS.normalize_video_job_payload(payload(
|
||||||
|
generation_mode="multimodal",
|
||||||
|
asset_creation_mode="manual",
|
||||||
|
prompt="",
|
||||||
|
aspect_ratio="auto",
|
||||||
|
assets={"images": ["image-1"]},
|
||||||
|
))
|
||||||
|
body = JOBS.build_seedance_video_body(job, {
|
||||||
|
"first_frame": None,
|
||||||
|
"last_frame": None,
|
||||||
|
"reference_images": [],
|
||||||
|
"reference_videos": [],
|
||||||
|
"reference_audios": [],
|
||||||
|
})
|
||||||
|
self.assertEqual(body["content"][0]["type"], "text")
|
||||||
|
self.assertTrue(body["content"][0]["text"])
|
||||||
|
self.assertEqual(body["ratio"], "adaptive")
|
||||||
|
self.assertEqual(
|
||||||
|
[item.get("role") for item in body["content"] if item["type"] == "image_url"],
|
||||||
|
["reference_image"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_edit_and_extend_modes_use_reference_video(self):
|
||||||
|
clip = {"name": "clip.mp4", "type": "input"}
|
||||||
|
edit = JOBS.normalize_video_job_payload(payload(
|
||||||
|
model="seedance-2.5",
|
||||||
|
generation_mode="edit",
|
||||||
|
media={"reference_videos": [clip]},
|
||||||
|
duration="10",
|
||||||
|
aspect_ratio="16:9",
|
||||||
|
))
|
||||||
|
self.assertEqual(edit["duration"], -1)
|
||||||
|
self.assertEqual(edit["aspect_ratio"], "auto")
|
||||||
|
edit_body = JOBS.build_seedance_video_body(edit, {
|
||||||
|
"first_frame": None,
|
||||||
|
"last_frame": None,
|
||||||
|
"reference_images": [],
|
||||||
|
"reference_videos": ["https://example.invalid/clip.mp4"],
|
||||||
|
"reference_audios": [],
|
||||||
|
})
|
||||||
|
self.assertEqual(edit_body["omni_reference_task_type"], "edit")
|
||||||
|
self.assertEqual(edit_body["ratio"], "adaptive")
|
||||||
|
self.assertEqual(
|
||||||
|
[item["video_url"]["url"] for item in edit_body["content"] if item["type"] == "video_url"],
|
||||||
|
["https://example.invalid/clip.mp4"],
|
||||||
|
)
|
||||||
|
|
||||||
|
extend = JOBS.normalize_video_job_payload(payload(
|
||||||
|
model="seedance-2.5",
|
||||||
|
generation_mode="extend",
|
||||||
|
media={"reference_videos": [clip]},
|
||||||
|
duration="20",
|
||||||
|
))
|
||||||
|
self.assertEqual(extend["duration"], 20)
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(ValueError, "2.5"):
|
||||||
|
JOBS.normalize_video_job_payload(payload(
|
||||||
|
model="seedance-2.0",
|
||||||
|
generation_mode="edit",
|
||||||
|
media={"reference_videos": [clip]},
|
||||||
|
))
|
||||||
|
|
||||||
|
def test_edit_and_extend_accept_reference_images(self):
|
||||||
|
clip = {"name": "clip.mp4", "type": "input"}
|
||||||
|
image = {"name": "person.png", "type": "input"}
|
||||||
|
for mode in ("edit", "extend"):
|
||||||
|
with self.subTest(mode=mode):
|
||||||
|
job = JOBS.normalize_video_job_payload(payload(
|
||||||
|
model="seedance-2.5",
|
||||||
|
generation_mode=mode,
|
||||||
|
prompt="把 @video1 里的男子替换为 @image1 的女子",
|
||||||
|
media={
|
||||||
|
"reference_images": [image],
|
||||||
|
"reference_videos": [clip],
|
||||||
|
},
|
||||||
|
))
|
||||||
|
body = JOBS.build_seedance_video_body(job, {
|
||||||
|
"first_frame": None,
|
||||||
|
"last_frame": None,
|
||||||
|
"reference_images": ["https://example.invalid/person.png"],
|
||||||
|
"reference_videos": ["https://example.invalid/clip.mp4"],
|
||||||
|
"reference_audios": [],
|
||||||
|
})
|
||||||
|
self.assertEqual(body["omni_reference_task_type"], mode)
|
||||||
|
self.assertEqual(body["ratio"], "adaptive")
|
||||||
|
self.assertEqual(
|
||||||
|
[item.get("role") for item in body["content"] if item["type"] != "text"],
|
||||||
|
["reference_image", "reference_video"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_edit_mode_still_requires_one_reference_video(self):
|
||||||
|
image = {"name": "person.png", "type": "input"}
|
||||||
|
with self.assertRaisesRegex(ValueError, "必须且只能提供一段参考视频"):
|
||||||
|
JOBS.normalize_video_job_payload(payload(
|
||||||
|
model="seedance-2.5",
|
||||||
|
generation_mode="edit",
|
||||||
|
media={"reference_images": [image]},
|
||||||
|
))
|
||||||
|
|
||||||
def test_multimodal_manual_asset_ids_respect_model_limits(self):
|
def test_multimodal_manual_asset_ids_respect_model_limits(self):
|
||||||
with self.assertRaisesRegex(ValueError, "最多支持 9"):
|
with self.assertRaisesRegex(ValueError, "最多支持 9"):
|
||||||
JOBS.normalize_video_job_payload(payload(
|
JOBS.normalize_video_job_payload(payload(
|
||||||
@@ -492,5 +620,29 @@ class ParallelManagerTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.assertTrue(all(manager.status(item["batch_id"])["state"] == "completed" for item in submitted))
|
self.assertTrue(all(manager.status(item["batch_id"])["state"] == "completed" for item in submitted))
|
||||||
|
|
||||||
|
|
||||||
|
class AssetPreparationTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def test_direct_mode_uploads_without_creating_assets(self):
|
||||||
|
with tempfile.TemporaryDirectory() as root:
|
||||||
|
path = os.path.join(root, "first.png")
|
||||||
|
Image.new("RGB", (300, 300)).save(path)
|
||||||
|
job = {
|
||||||
|
"route": "domestic",
|
||||||
|
"asset_creation_mode": "direct",
|
||||||
|
"assets": {},
|
||||||
|
"snapshot_media": {"first_frame": path},
|
||||||
|
}
|
||||||
|
with (
|
||||||
|
patch.object(JOBS, "upload_image", AsyncMock(return_value="https://cdn.example/first.png")) as upload,
|
||||||
|
patch.object(JOBS, "SeedanceAssetService") as service,
|
||||||
|
patch.object(JOBS, "get_base_url_by_route", return_value="https://api.example.com"),
|
||||||
|
):
|
||||||
|
prepared = await JOBS._prepare_seedance_media(job, lambda **kwargs: None)
|
||||||
|
|
||||||
|
upload.assert_awaited_once()
|
||||||
|
service.assert_not_called()
|
||||||
|
self.assertEqual(prepared["first_frame"], "https://cdn.example/first.png")
|
||||||
|
self.assertEqual(job["resolved_assets"], {"images": [], "videos": [], "audios": []})
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -40,9 +40,12 @@ assert.match(source, /value: "manual", label: "手动"/);
|
|||||||
assert.match(source, /makeField\("素材创建", assetCreation\)/);
|
assert.match(source, /makeField\("素材创建", assetCreation\)/);
|
||||||
assert.match(source, /assetCreationField\.style\.display = isSeedance \? "grid" : "none"/);
|
assert.match(source, /assetCreationField\.style\.display = isSeedance \? "grid" : "none"/);
|
||||||
assert.match(source, /assetCreation\._trigger\.disabled = !assetModeAvailable/);
|
assert.match(source, /assetCreation\._trigger\.disabled = !assetModeAvailable/);
|
||||||
assert.match(source, /imageIdField\.style\.display = manualAssets \? "grid" : "none"/);
|
assert.match(source, /imageIdField\.style\.display = manualAssets && activeModeResolved === "multimodal" \? "grid" : "none"/);
|
||||||
assert.match(source, /videoIdField\.style\.display = manualAssets && activeMode === "multimodal"/);
|
assert.match(source, /videoIdField\.style\.display = manualAssets && showsVideo \? "grid" : "none"/);
|
||||||
assert.match(source, /asset_creation_mode: manualAssets \? "manual" : "auto"/);
|
assert.match(source, /asset_creation_mode: manualAssets \? "manual" : \(assetCreation\.value === "auto" \? "auto" : "direct"\)/);
|
||||||
|
assert.match(source, /\{ value: "edit", label: "视频编辑"/);
|
||||||
|
assert.match(source, /\{ value: "extend", label: "视频延长"/);
|
||||||
|
assert.match(source, /\{ value: "direct", label: "直接上传"/);
|
||||||
assert.match(source, /assets: manualAssets \? manualRequestAssets : \{\}/);
|
assert.match(source, /assets: manualAssets \? manualRequestAssets : \{\}/);
|
||||||
assert.match(source, /function requestForRetry\(node\)/);
|
assert.match(source, /function requestForRetry\(node\)/);
|
||||||
assert.match(source, /request\.asset_creation_mode !== "auto"/);
|
assert.match(source, /request\.asset_creation_mode !== "auto"/);
|
||||||
@@ -116,8 +119,8 @@ assert.doesNotMatch(multimodalSource, /添加\$\{source\.shortTitle\}/);
|
|||||||
assert.doesNotMatch(multimodalSource, /sourceInput|source\.input/);
|
assert.doesNotMatch(multimodalSource, /sourceInput|source\.input/);
|
||||||
assert.match(source, /\.o1vg-multimodal-assets \.o1vg-add\{min-width:58px;height:29px;gap:4px;padding:0 10px;[^}]*font-size:11px;font-weight:600/);
|
assert.match(source, /\.o1vg-multimodal-assets \.o1vg-add\{min-width:58px;height:29px;gap:4px;padding:0 10px;[^}]*font-size:11px;font-weight:600/);
|
||||||
assert.match(source, /mediaHost\.append\(firstSection, lastSection, multimodalSection\)/);
|
assert.match(source, /mediaHost\.append\(firstSection, lastSection, multimodalSection\)/);
|
||||||
assert.match(source, /multimodalSection\.style\.display = !manualAssets && activeMode === "multimodal" \? "flex" : "none"/);
|
assert.match(source, /multimodalSection\.style\.display = !manualAssets && showsVideo \? "flex" : "none"/);
|
||||||
assert.match(source, /automaticHeights = \{ text: 679, first_frame: 824, first_last_frame: 964, multimodal: 824 \}/);
|
assert.match(source, /automaticHeights = \{ text: 679, first_frame: 824, first_last_frame: 964, multimodal: 824, edit: 824, extend: 824 \}/);
|
||||||
assert.match(source, /widget\(node, "generation_mode"\)\?\.value \|\| "multimodal"/);
|
assert.match(source, /widget\(node, "generation_mode"\)\?\.value \|\| "multimodal"/);
|
||||||
assert.match(source, /const restore = \(\) =>/);
|
assert.match(source, /const restore = \(\) =>/);
|
||||||
assert.match(source, /mode\.value = value\("generation_mode", "multimodal"\)/);
|
assert.match(source, /mode\.value = value\("generation_mode", "multimodal"\)/);
|
||||||
|
|||||||
@@ -50,12 +50,15 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
self.assertIn("生成模式", inputs)
|
self.assertIn("生成模式", inputs)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
[input_def.id for input_def in schema.inputs[:3]],
|
[input_def.id for input_def in schema.inputs[:3]],
|
||||||
["提示词", "生成模式", "主模型"],
|
["提示词", "主模型", "样片模式"],
|
||||||
)
|
)
|
||||||
|
|
||||||
mode_input = inputs["生成模式"]
|
mode_input = inputs["生成模式"]
|
||||||
self.assertEqual(mode_input.io_type, "COMBO")
|
self.assertEqual(mode_input.io_type, "COMBO")
|
||||||
self.assertEqual(mode_input.options, ["多模态", "首尾帧"])
|
self.assertEqual(
|
||||||
|
mode_input.options,
|
||||||
|
["多模态", "首尾帧", "视频编辑", "视频延长"],
|
||||||
|
)
|
||||||
self.assertEqual(mode_input.default, "多模态")
|
self.assertEqual(mode_input.default, "多模态")
|
||||||
|
|
||||||
expected = {
|
expected = {
|
||||||
@@ -78,11 +81,21 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertTrue(inputs["首帧图片"].optional)
|
self.assertTrue(inputs["首帧图片"].optional)
|
||||||
self.assertTrue(inputs["尾帧图片"].optional)
|
self.assertTrue(inputs["尾帧图片"].optional)
|
||||||
|
self.assertTrue(inputs["样片任务ID输入"].optional)
|
||||||
|
self.assertTrue(inputs["样片任务ID输入"].force_input)
|
||||||
|
self.assertEqual(
|
||||||
|
inputs["样片任务ID输入"].display_name,
|
||||||
|
"样片任务ID(连线)",
|
||||||
|
)
|
||||||
self.assertNotIn("自动创建素材", inputs)
|
self.assertNotIn("自动创建素材", inputs)
|
||||||
self.assertNotIn("素材创建", inputs)
|
self.assertNotIn("素材创建", inputs)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
[input_def.id for input_def in schema.inputs[-3:]],
|
[input_def.id for input_def in schema.inputs[-3:]],
|
||||||
["联网搜索", "seed", "返回末帧图片"],
|
["返回末帧图片", "输出格式", "样片任务ID"],
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
[input_def.id for input_def in schema.inputs[-5:-1]],
|
||||||
|
["联网搜索", "seed", "返回末帧图片", "输出格式"],
|
||||||
)
|
)
|
||||||
for prefix, maximum in (("图片素材ID", 30), ("视频素材ID", 10), ("音频素材ID", 10)):
|
for prefix, maximum in (("图片素材ID", 30), ("视频素材ID", 10), ("音频素材ID", 10)):
|
||||||
self.assertNotIn(prefix, inputs)
|
self.assertNotIn(prefix, inputs)
|
||||||
@@ -92,12 +105,12 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
for former_advanced_name in ("联网搜索", "seed", "返回末帧图片"):
|
for former_advanced_name in ("联网搜索", "seed", "返回末帧图片"):
|
||||||
self.assertFalse(inputs[former_advanced_name].advanced)
|
self.assertFalse(inputs[former_advanced_name].advanced)
|
||||||
self.assertEqual(inputs["素材创建模式"].io_type, "COMBO")
|
self.assertEqual(inputs["素材创建模式"].io_type, "COMBO")
|
||||||
self.assertEqual(inputs["素材创建模式"].options, ["关闭", "打开"])
|
self.assertEqual(inputs["素材创建模式"].options, ["关闭", "自动创建", "手动"])
|
||||||
self.assertEqual(inputs["素材创建模式"].default, "关闭")
|
self.assertEqual(inputs["素材创建模式"].default, "关闭")
|
||||||
self.assertEqual(inputs["返回末帧图片"].default, "关闭")
|
self.assertEqual(inputs["返回末帧图片"].default, "关闭")
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
[output.display_name for output in schema.outputs],
|
[output.display_name for output in schema.outputs],
|
||||||
["视频", "末帧图片"],
|
["视频", "末帧图片", "样片任务ID"],
|
||||||
)
|
)
|
||||||
|
|
||||||
self.assertEqual(schema.display_name, "Seedance 全能生成视频")
|
self.assertEqual(schema.display_name, "Seedance 全能生成视频")
|
||||||
@@ -127,10 +140,12 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
for inputs, expected in [
|
for inputs, expected in [
|
||||||
({}, "关闭"),
|
({}, "关闭"),
|
||||||
({"素材创建模式": "关闭"}, "关闭"),
|
({"素材创建模式": "关闭"}, "关闭"),
|
||||||
({"素材创建模式": "打开"}, "打开"),
|
({"素材创建模式": "自动创建"}, "自动创建"),
|
||||||
({"素材创建": "自动创建"}, "关闭"),
|
({"素材创建模式": "手动"}, "手动"),
|
||||||
({"素材创建": "手动"}, "打开"),
|
({"素材创建模式": "打开"}, "手动"),
|
||||||
({"素材创建": {"素材创建": "手动"}}, "打开"),
|
({"素材创建": "自动创建"}, "自动创建"),
|
||||||
|
({"素材创建": "手动"}, "手动"),
|
||||||
|
({"素材创建": {"素材创建": "手动"}}, "手动"),
|
||||||
]:
|
]:
|
||||||
self.assertEqual(SeedanceAutoPass._asset_creation_inputs(inputs)[0], expected)
|
self.assertEqual(SeedanceAutoPass._asset_creation_inputs(inputs)[0], expected)
|
||||||
|
|
||||||
@@ -165,15 +180,23 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_v3_async_execution_adapter_is_active(self):
|
def test_v3_async_execution_adapter_is_active(self):
|
||||||
self.assertEqual(SeedanceAutoPass.FUNCTION, "EXECUTE_NORMALIZED_ASYNC")
|
self.assertEqual(SeedanceAutoPass.FUNCTION, "EXECUTE_NORMALIZED_ASYNC")
|
||||||
self.assertEqual(SeedanceAutoPass.RETURN_TYPES, ["VIDEO", "IMAGE"])
|
self.assertEqual(SeedanceAutoPass.RETURN_TYPES, ["VIDEO", "IMAGE", "STRING"])
|
||||||
self.assertEqual(SeedanceAutoPass.RETURN_NAMES, ["视频", "末帧图片"])
|
self.assertEqual(
|
||||||
|
SeedanceAutoPass.RETURN_NAMES,
|
||||||
|
["视频", "末帧图片", "样片任务ID"],
|
||||||
|
)
|
||||||
|
|
||||||
def test_model_defaults_and_seedance_25_capabilities_are_exposed(self):
|
def test_model_defaults_and_seedance_25_capabilities_are_exposed(self):
|
||||||
schema = SeedanceAutoPass.GET_SCHEMA()
|
schema = SeedanceAutoPass.GET_SCHEMA()
|
||||||
inputs = {input_def.id: input_def for input_def in schema.inputs}
|
inputs = {input_def.id: input_def for input_def in schema.inputs}
|
||||||
|
|
||||||
self.assertIn("seedance 2.5", inputs["主模型"].options)
|
self.assertEqual(inputs["主模型"].options, [
|
||||||
self.assertEqual(inputs["主模型"].default, "seedance 2.0")
|
"seedance 2.5",
|
||||||
|
"seedance 2.0",
|
||||||
|
"seedance 2.0 fast",
|
||||||
|
"seedance 2.0 mini",
|
||||||
|
])
|
||||||
|
self.assertEqual(inputs["主模型"].default, "seedance 2.5")
|
||||||
self.assertEqual(inputs["模型线路"].default, "国内")
|
self.assertEqual(inputs["模型线路"].default, "国内")
|
||||||
self.assertEqual(inputs["模型线路"].options, ["海外", "国内"])
|
self.assertEqual(inputs["模型线路"].options, ["海外", "国内"])
|
||||||
self.assertEqual(inputs["分辨率"].default, "720p")
|
self.assertEqual(inputs["分辨率"].default, "720p")
|
||||||
@@ -253,8 +276,15 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
|
|
||||||
def test_mode_validation_matches_seedance_20_and_25_rules(self):
|
def test_mode_validation_matches_seedance_20_and_25_rules(self):
|
||||||
audio = object()
|
audio = object()
|
||||||
SeedanceAutoPass._validate_mode_inputs(
|
with self.assertRaisesRegex(ValueError, "仅有参考音频时必须填写提示词"):
|
||||||
"多模态参考生视频", "seedance 2.5", "", [], [], [audio]
|
SeedanceAutoPass._validate_mode_inputs(
|
||||||
|
"多模态参考生视频", "seedance 2.5", "", [], [], [audio]
|
||||||
|
)
|
||||||
|
self.assertEqual(
|
||||||
|
SeedanceAutoPass._validate_mode_inputs(
|
||||||
|
"多模态参考生视频", "seedance 2.5", "prompt", [], [], [audio]
|
||||||
|
),
|
||||||
|
"multimodal",
|
||||||
)
|
)
|
||||||
|
|
||||||
with self.assertRaisesRegex(ValueError, "不可单独输入参考音频"):
|
with self.assertRaisesRegex(ValueError, "不可单独输入参考音频"):
|
||||||
@@ -275,6 +305,38 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
"图生视频-首尾帧", "seedance 2.5", "", [object()], [], []
|
"图生视频-首尾帧", "seedance 2.5", "", [object()], [], []
|
||||||
)
|
)
|
||||||
|
|
||||||
|
def test_edit_mode_accepts_reference_images(self):
|
||||||
|
self.assertEqual(
|
||||||
|
SeedanceAutoPass._validate_mode_inputs(
|
||||||
|
"视频编辑",
|
||||||
|
"seedance 2.5",
|
||||||
|
"把 @video1 中的男子替换为 @image1 中的女子",
|
||||||
|
[object()],
|
||||||
|
[object()],
|
||||||
|
[],
|
||||||
|
),
|
||||||
|
"edit",
|
||||||
|
)
|
||||||
|
with self.assertRaisesRegex(ValueError, "必须且只能提供一段参考视频"):
|
||||||
|
SeedanceAutoPass._validate_mode_inputs(
|
||||||
|
"视频编辑", "seedance 2.5", "替换", [object()], [], []
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_draft_final_body_reuses_only_the_task_id(self):
|
||||||
|
body = SeedanceAutoPass._build_draft_final_body(
|
||||||
|
"doubao-seedance-2-5-260628-max", " cgt-20260101120000-abc "
|
||||||
|
)
|
||||||
|
self.assertEqual(body, {
|
||||||
|
"model": "doubao-seedance-2-5-260628-max",
|
||||||
|
"content": [
|
||||||
|
{"type": "draft_task", "draft_task": {"id": "cgt-20260101120000-abc"}},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
with self.assertRaisesRegex(ValueError, "必须填写样片任务ID"):
|
||||||
|
SeedanceAutoPass._build_draft_final_body("model", "")
|
||||||
|
with self.assertRaisesRegex(ValueError, "格式无效"):
|
||||||
|
SeedanceAutoPass._build_draft_final_body("model", "bad id!")
|
||||||
|
|
||||||
def test_simplified_modes_resolve_to_provider_modes_from_connected_media(self):
|
def test_simplified_modes_resolve_to_provider_modes_from_connected_media(self):
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
SeedanceAutoPass._validate_mode_inputs(
|
SeedanceAutoPass._validate_mode_inputs(
|
||||||
@@ -310,7 +372,6 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
"5秒",
|
"5秒",
|
||||||
True,
|
True,
|
||||||
False,
|
False,
|
||||||
0,
|
|
||||||
["https://example.com/first.png", "https://example.com/last.png"],
|
["https://example.com/first.png", "https://example.com/last.png"],
|
||||||
[],
|
[],
|
||||||
[],
|
[],
|
||||||
@@ -321,11 +382,11 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
self.assertNotIn("prompt", body)
|
self.assertNotIn("prompt", body)
|
||||||
self.assertNotIn("images", body)
|
self.assertNotIn("images", body)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
[item["role"] for item in body["content"]],
|
[item["role"] for item in body["content"] if item["type"] != "text"],
|
||||||
["first_frame", "last_frame"],
|
["first_frame", "last_frame"],
|
||||||
)
|
)
|
||||||
|
|
||||||
def test_first_frame_mode_omits_image_role(self):
|
def test_first_frame_mode_sets_first_frame_role(self):
|
||||||
body = SeedanceAutoPass._build_body(
|
body = SeedanceAutoPass._build_body(
|
||||||
"dreamina-seedance-2-5-hc",
|
"dreamina-seedance-2-5-hc",
|
||||||
"",
|
"",
|
||||||
@@ -334,7 +395,6 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
"5秒",
|
"5秒",
|
||||||
True,
|
True,
|
||||||
False,
|
False,
|
||||||
0,
|
|
||||||
["https://ark-project.tos-cn-beijing.volces.com/doc_image/i2v_foxrgirl.png"],
|
["https://ark-project.tos-cn-beijing.volces.com/doc_image/i2v_foxrgirl.png"],
|
||||||
[],
|
[],
|
||||||
[],
|
[],
|
||||||
@@ -342,12 +402,14 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
generation_mode="首尾帧",
|
generation_mode="首尾帧",
|
||||||
)
|
)
|
||||||
|
|
||||||
self.assertEqual(body["content"][0], {
|
image_items = [item for item in body["content"] if item["type"] == "image_url"]
|
||||||
|
self.assertEqual(image_items, [{
|
||||||
"type": "image_url",
|
"type": "image_url",
|
||||||
"image_url": {
|
"image_url": {
|
||||||
"url": "https://ark-project.tos-cn-beijing.volces.com/doc_image/i2v_foxrgirl.png"
|
"url": "https://ark-project.tos-cn-beijing.volces.com/doc_image/i2v_foxrgirl.png"
|
||||||
},
|
},
|
||||||
})
|
"role": "first_frame",
|
||||||
|
}])
|
||||||
|
|
||||||
def test_request_body_matches_o1key_video_builder(self):
|
def test_request_body_matches_o1key_video_builder(self):
|
||||||
actual = SeedanceAutoPass._build_body(
|
actual = SeedanceAutoPass._build_body(
|
||||||
@@ -358,7 +420,6 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
"30秒",
|
"30秒",
|
||||||
True,
|
True,
|
||||||
True,
|
True,
|
||||||
42,
|
|
||||||
["asset://image-1"],
|
["asset://image-1"],
|
||||||
["asset://video-1"],
|
["asset://video-1"],
|
||||||
["asset://audio-1"],
|
["asset://audio-1"],
|
||||||
@@ -377,7 +438,6 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
"aspect_ratio": "auto",
|
"aspect_ratio": "auto",
|
||||||
"generate_audio": True,
|
"generate_audio": True,
|
||||||
"return_last_frame": True,
|
"return_last_frame": True,
|
||||||
"seed": 42,
|
|
||||||
}, {
|
}, {
|
||||||
"first_frame": None,
|
"first_frame": None,
|
||||||
"last_frame": None,
|
"last_frame": None,
|
||||||
@@ -388,6 +448,24 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
self.assertEqual(actual, expected)
|
self.assertEqual(actual, expected)
|
||||||
self.assertNotIn("web_search", actual)
|
self.assertNotIn("web_search", actual)
|
||||||
|
|
||||||
|
def test_request_body_is_printed_without_credentials(self):
|
||||||
|
body = {
|
||||||
|
"model": "dreamina-seedance-2-0-hc",
|
||||||
|
"content": [{"type": "text", "text": "prompt"}],
|
||||||
|
"duration": -1,
|
||||||
|
}
|
||||||
|
|
||||||
|
with patch("builtins.print") as print_mock:
|
||||||
|
SeedanceAutoPass._print_request("https://api.example.com", body)
|
||||||
|
|
||||||
|
printed = "\n".join(
|
||||||
|
str(call.args[0]) for call in print_mock.call_args_list if call.args
|
||||||
|
)
|
||||||
|
self.assertIn("POST https://api.example.com/v1/video/generations", printed)
|
||||||
|
self.assertIn('"model": "dreamina-seedance-2-0-hc"', printed)
|
||||||
|
self.assertIn("Authorization: Bearer ***", printed)
|
||||||
|
self.assertTrue(print_mock.call_args.kwargs.get("flush"))
|
||||||
|
|
||||||
def test_manual_asset_creation_uses_existing_asset_ids(self):
|
def test_manual_asset_creation_uses_existing_asset_ids(self):
|
||||||
body = SeedanceAutoPass._build_body(
|
body = SeedanceAutoPass._build_body(
|
||||||
"dreamina-seedance-2-5-hc",
|
"dreamina-seedance-2-5-hc",
|
||||||
@@ -397,7 +475,6 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
"5秒",
|
"5秒",
|
||||||
False,
|
False,
|
||||||
False,
|
False,
|
||||||
0,
|
|
||||||
["image-1"],
|
["image-1"],
|
||||||
["asset://video-1"],
|
["asset://video-1"],
|
||||||
["audio-1"],
|
["audio-1"],
|
||||||
@@ -435,12 +512,12 @@ class SeedanceAutoPassV3Tests(unittest.TestCase):
|
|||||||
audio_path = Path(root) / "reference.mp3"
|
audio_path = Path(root) / "reference.mp3"
|
||||||
audio_path.write_bytes(b"audio")
|
audio_path.write_bytes(b"audio")
|
||||||
SeedanceAutoPass._validate_reference_media(
|
SeedanceAutoPass._validate_reference_media(
|
||||||
[valid_image], [Video()], [str(audio_path)],
|
"seedance 2.0", [valid_image], [Video()], [str(audio_path)],
|
||||||
)
|
)
|
||||||
|
|
||||||
with self.assertRaisesRegex(ValueError, "宽高必须分别在 300~6000px"):
|
with self.assertRaisesRegex(ValueError, "宽高必须分别在 300~6000px"):
|
||||||
SeedanceAutoPass._validate_reference_media(
|
SeedanceAutoPass._validate_reference_media(
|
||||||
[Image.new("RGB", (299, 300))], [], [],
|
"seedance 2.0", [Image.new("RGB", (299, 300))], [], [],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
||||||
@@ -718,36 +795,50 @@ class SeedanceAutoPassExecuteTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
"seed": [0],
|
"seed": [0],
|
||||||
})
|
})
|
||||||
|
|
||||||
async def test_seedance_25_supports_1080p_and_4k(self):
|
async def test_seedance_25_accepts_1080p_and_rejects_4k(self):
|
||||||
for resolution in ("1080p", "4k"):
|
create = AsyncMock(return_value=([], [], []))
|
||||||
with self.subTest(resolution=resolution):
|
submit = AsyncMock(return_value=("result.mp4", "done"))
|
||||||
create = AsyncMock(return_value=([], [], []))
|
with (
|
||||||
submit = AsyncMock(return_value=("result.mp4", "done"))
|
patch.object(SeedanceAutoPass, "_create_assets", create),
|
||||||
with (
|
patch.object(SeedanceAutoPass, "_submit_poll_download", submit),
|
||||||
patch.object(SeedanceAutoPass, "_create_assets", create),
|
patch.object(InputImpl, "VideoFromFile", return_value=object()),
|
||||||
patch.object(SeedanceAutoPass, "_submit_poll_download", submit),
|
patch(
|
||||||
patch.object(InputImpl, "VideoFromFile", return_value=object()),
|
"comfyui_o1key.nodes.seedance_autopass.get_base_url_by_route",
|
||||||
patch(
|
return_value="https://api.example.com",
|
||||||
"comfyui_o1key.nodes.seedance_autopass.get_base_url_by_route",
|
),
|
||||||
return_value="https://api.example.com",
|
):
|
||||||
),
|
await SeedanceAutoPass.execute(**{
|
||||||
):
|
"提示词": "test prompt",
|
||||||
await SeedanceAutoPass.execute(**{
|
"生成模式": {
|
||||||
"提示词": "test prompt",
|
"生成模式": "文生视频",
|
||||||
"生成模式": {
|
"联网搜索": "关闭",
|
||||||
"生成模式": "文生视频",
|
},
|
||||||
"联网搜索": "关闭",
|
"主模型": "seedance 2.5",
|
||||||
},
|
"模型线路": "海外HC",
|
||||||
"主模型": "seedance 2.5",
|
"分辨率": "1080p",
|
||||||
"模型线路": "海外HC",
|
"宽高比": "智能",
|
||||||
"分辨率": resolution,
|
"时长": "30秒",
|
||||||
"宽高比": "智能",
|
"生成音频": "关闭",
|
||||||
"时长": "30秒",
|
"seed": 0,
|
||||||
"生成音频": "关闭",
|
})
|
||||||
"seed": 0,
|
|
||||||
})
|
|
||||||
|
|
||||||
self.assertEqual(submit.await_args.args[0]["resolution"], resolution)
|
self.assertEqual(submit.await_args.args[0]["resolution"], "1080p")
|
||||||
|
|
||||||
|
with self.assertRaisesRegex(ValueError, "分辨率仅支持"):
|
||||||
|
await SeedanceAutoPass.execute(**{
|
||||||
|
"提示词": "test prompt",
|
||||||
|
"生成模式": {
|
||||||
|
"生成模式": "文生视频",
|
||||||
|
"联网搜索": "关闭",
|
||||||
|
},
|
||||||
|
"主模型": "seedance 2.5",
|
||||||
|
"模型线路": "海外HC",
|
||||||
|
"分辨率": "4k",
|
||||||
|
"宽高比": "智能",
|
||||||
|
"时长": "30秒",
|
||||||
|
"生成音频": "关闭",
|
||||||
|
"seed": 0,
|
||||||
|
})
|
||||||
|
|
||||||
async def test_seedance_fast_still_rejects_1080p_before_upload(self):
|
async def test_seedance_fast_still_rejects_1080p_before_upload(self):
|
||||||
with self.assertRaisesRegex(ValueError, "仅支持 480p / 720p"):
|
with self.assertRaisesRegex(ValueError, "仅支持 480p / 720p"):
|
||||||
@@ -805,7 +896,7 @@ class SeedanceAutoPassExecuteTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
"联网搜索": "关闭",
|
"联网搜索": "关闭",
|
||||||
# 旧工作流参数即使仍存在,也必须被新的自动匹配规则忽略。
|
# 旧工作流参数即使仍存在,也必须被新的自动匹配规则忽略。
|
||||||
"自动创建素材": "关闭",
|
"自动创建素材": "关闭",
|
||||||
"素材创建模式": "标准",
|
"素材创建模式": "自动创建",
|
||||||
"seed": 0,
|
"seed": 0,
|
||||||
})
|
})
|
||||||
|
|
||||||
@@ -821,7 +912,238 @@ class SeedanceAutoPassExecuteTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
self.assertNotIn("camera_fixed", body)
|
self.assertNotIn("camera_fixed", body)
|
||||||
self.assertIs(output.result[0], video_output)
|
self.assertIs(output.result[0], video_output)
|
||||||
self.assertIsNone(output.result[1])
|
self.assertIsNone(output.result[1])
|
||||||
self.assertEqual(len(output.result), 2)
|
self.assertEqual(output.result[2], "")
|
||||||
|
self.assertEqual(len(output.result), 3)
|
||||||
|
|
||||||
|
async def test_execute_keeps_reference_images_in_video_edit_mode(self):
|
||||||
|
image_1 = object()
|
||||||
|
video_1 = object()
|
||||||
|
|
||||||
|
create = AsyncMock(return_value=(["asset://image-1"], ["asset://video-1"], []))
|
||||||
|
submit = AsyncMock(return_value=("result.mp4", None))
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch.object(SeedanceAutoPass, "_create_assets", create),
|
||||||
|
patch.object(SeedanceAutoPass, "_validate_reference_media"),
|
||||||
|
patch.object(SeedanceAutoPass, "_submit_poll_download", submit),
|
||||||
|
patch.object(InputImpl, "VideoFromFile", return_value=object()),
|
||||||
|
patch(
|
||||||
|
"comfyui_o1key.nodes.seedance_autopass.get_base_url_by_route",
|
||||||
|
return_value="https://api.example.com",
|
||||||
|
),
|
||||||
|
):
|
||||||
|
await SeedanceAutoPass.execute(**{
|
||||||
|
"提示词": "把 @video1 的男子替换为 @image1 的女子",
|
||||||
|
"生成模式": "视频编辑",
|
||||||
|
"主模型": "seedance 2.5",
|
||||||
|
"模型线路": "国内",
|
||||||
|
"分辨率": "480p",
|
||||||
|
"宽高比": "智能",
|
||||||
|
"时长": "自动",
|
||||||
|
"生成音频": "关闭",
|
||||||
|
"素材创建模式": "自动创建",
|
||||||
|
"参考图片": {"参考图片1": image_1},
|
||||||
|
"参考视频": {"参考视频1": video_1},
|
||||||
|
"seed": 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
create.assert_awaited_once_with(
|
||||||
|
[image_1], [video_1], [], "https://api.example.com", "Doubao"
|
||||||
|
)
|
||||||
|
body = submit.await_args.args[0]
|
||||||
|
self.assertEqual(body["omni_reference_task_type"], "edit")
|
||||||
|
self.assertEqual(
|
||||||
|
[item.get("role") for item in body["content"] if item["type"] != "text"],
|
||||||
|
["reference_image", "reference_video"],
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_draft_generation_forces_480p_and_returns_task_id(self):
|
||||||
|
video_output = object()
|
||||||
|
draft_task = "cgt-20260101120000-draft"
|
||||||
|
|
||||||
|
async def fake_submit(body, base_url, captured=None):
|
||||||
|
if isinstance(captured, dict):
|
||||||
|
captured["task_id"] = draft_task
|
||||||
|
return "result.mp4", None
|
||||||
|
|
||||||
|
submit = AsyncMock(side_effect=fake_submit)
|
||||||
|
with (
|
||||||
|
patch.object(
|
||||||
|
SeedanceAutoPass, "_create_assets", AsyncMock(return_value=([], [], []))
|
||||||
|
),
|
||||||
|
patch.object(SeedanceAutoPass, "_validate_reference_media"),
|
||||||
|
patch.object(SeedanceAutoPass, "_submit_poll_download", submit),
|
||||||
|
patch.object(InputImpl, "VideoFromFile", return_value=video_output),
|
||||||
|
patch(
|
||||||
|
"comfyui_o1key.nodes.seedance_autopass.get_base_url_by_route",
|
||||||
|
return_value="https://api.example.com",
|
||||||
|
),
|
||||||
|
):
|
||||||
|
output = await SeedanceAutoPass.execute(**{
|
||||||
|
"提示词": "一只猫在院子里追蝴蝶",
|
||||||
|
"生成模式": "多模态",
|
||||||
|
"主模型": "seedance 2.5",
|
||||||
|
"模型线路": "国内",
|
||||||
|
"分辨率": "1080p",
|
||||||
|
"宽高比": "智能",
|
||||||
|
"时长": "自动",
|
||||||
|
"生成音频": "关闭",
|
||||||
|
"素材创建模式": "自动创建",
|
||||||
|
"样片模式": "生成样片",
|
||||||
|
"seed": 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
body = submit.await_args.args[0]
|
||||||
|
self.assertTrue(body["draft"])
|
||||||
|
self.assertEqual(body["resolution"], "480p")
|
||||||
|
self.assertIs(output.result[0], video_output)
|
||||||
|
self.assertEqual(output.result[2], draft_task)
|
||||||
|
|
||||||
|
async def test_draft_final_request_carries_only_the_draft_task(self):
|
||||||
|
video_output = object()
|
||||||
|
submit = AsyncMock(return_value=("result.mp4", None))
|
||||||
|
create = AsyncMock()
|
||||||
|
verify = AsyncMock(return_value={"model": ""})
|
||||||
|
with (
|
||||||
|
patch.object(SeedanceAutoPass, "_create_assets", create),
|
||||||
|
patch.object(SeedanceAutoPass, "_validate_reference_media"),
|
||||||
|
patch.object(SeedanceAutoPass, "_verify_draft_task", verify),
|
||||||
|
patch.object(SeedanceAutoPass, "_submit_poll_download", submit),
|
||||||
|
patch.object(InputImpl, "VideoFromFile", return_value=video_output),
|
||||||
|
patch(
|
||||||
|
"comfyui_o1key.nodes.seedance_autopass.get_base_url_by_route",
|
||||||
|
return_value="https://api.example.com",
|
||||||
|
),
|
||||||
|
):
|
||||||
|
output = await SeedanceAutoPass.execute(**{
|
||||||
|
"提示词": "这段提示词会被样片复用,不应再次发送",
|
||||||
|
"生成模式": "多模态",
|
||||||
|
"主模型": "seedance 2.5",
|
||||||
|
"模型线路": "国内",
|
||||||
|
"分辨率": "1080p",
|
||||||
|
"宽高比": "智能",
|
||||||
|
"时长": "自动",
|
||||||
|
"生成音频": "关闭",
|
||||||
|
"素材创建模式": "自动创建",
|
||||||
|
"样片模式": "按样片生成",
|
||||||
|
"样片任务ID": "cgt-20260101120000-draft",
|
||||||
|
"seed": 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
create.assert_not_awaited()
|
||||||
|
verify.assert_awaited_once_with("https://api.example.com", "cgt-20260101120000-draft")
|
||||||
|
self.assertEqual(submit.await_args.args[0], {
|
||||||
|
"model": "doubao-seedance-2-5-260628-max",
|
||||||
|
"content": [
|
||||||
|
{
|
||||||
|
"type": "draft_task",
|
||||||
|
"draft_task": {"id": "cgt-20260101120000-draft"},
|
||||||
|
},
|
||||||
|
],
|
||||||
|
})
|
||||||
|
self.assertEqual(output.result[2], "cgt-20260101120000-draft")
|
||||||
|
|
||||||
|
async def test_draft_final_prefers_linked_task_id_and_uses_draft_model(self):
|
||||||
|
submit = AsyncMock(return_value=("result.mp4", None))
|
||||||
|
verify = AsyncMock(return_value={"model": "dreamina-seedance-2-5-hc"})
|
||||||
|
with (
|
||||||
|
patch.object(SeedanceAutoPass, "_validate_reference_media"),
|
||||||
|
patch.object(SeedanceAutoPass, "_verify_draft_task", verify),
|
||||||
|
patch.object(SeedanceAutoPass, "_submit_poll_download", submit),
|
||||||
|
patch.object(InputImpl, "VideoFromFile", return_value=object()),
|
||||||
|
patch(
|
||||||
|
"comfyui_o1key.nodes.seedance_autopass.get_base_url_by_route",
|
||||||
|
return_value="https://api.example.com",
|
||||||
|
),
|
||||||
|
):
|
||||||
|
await SeedanceAutoPass.execute(**{
|
||||||
|
"提示词": "ignored",
|
||||||
|
"生成模式": "多模态",
|
||||||
|
"主模型": "seedance 2.5",
|
||||||
|
"模型线路": "海外",
|
||||||
|
"分辨率": "1080p",
|
||||||
|
"宽高比": "智能",
|
||||||
|
"时长": "自动",
|
||||||
|
"生成音频": "关闭",
|
||||||
|
"素材创建模式": "自动创建",
|
||||||
|
"样片模式": "按样片生成",
|
||||||
|
"样片任务ID": "cgt-widget",
|
||||||
|
"样片任务ID输入": "cgt-linked",
|
||||||
|
"seed": 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
verify.assert_awaited_once_with("https://api.example.com", "cgt-linked")
|
||||||
|
body = submit.await_args.args[0]
|
||||||
|
self.assertEqual(body["content"][0]["draft_task"]["id"], "cgt-linked")
|
||||||
|
self.assertEqual(body["model"], "dreamina-seedance-2-5-hc")
|
||||||
|
|
||||||
|
async def test_draft_task_verification_rejects_unfinished_task(self):
|
||||||
|
fake_client = type("FakeSeedanceClient", (), {})()
|
||||||
|
fake_client.base_url = ""
|
||||||
|
fake_client.get_task_async = AsyncMock(return_value={
|
||||||
|
"data": {"status": "running"},
|
||||||
|
})
|
||||||
|
with patch(
|
||||||
|
"comfyui_o1key.nodes.seedance_autopass.SeedanceClient",
|
||||||
|
return_value=fake_client,
|
||||||
|
):
|
||||||
|
with self.assertRaisesRegex(ValueError, "尚未完成"):
|
||||||
|
await SeedanceAutoPass._verify_draft_task(
|
||||||
|
"https://api.example.com", "cgt-1"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_draft_task_verification_reports_failed_task(self):
|
||||||
|
fake_client = type("FakeSeedanceClient", (), {})()
|
||||||
|
fake_client.base_url = ""
|
||||||
|
fake_client.get_task_async = AsyncMock(return_value={
|
||||||
|
"data": {"status": "failed", "error": {"message": "policy violation"}},
|
||||||
|
})
|
||||||
|
with patch(
|
||||||
|
"comfyui_o1key.nodes.seedance_autopass.SeedanceClient",
|
||||||
|
return_value=fake_client,
|
||||||
|
):
|
||||||
|
with self.assertRaisesRegex(ValueError, "已失败.*policy violation"):
|
||||||
|
await SeedanceAutoPass._verify_draft_task(
|
||||||
|
"https://api.example.com", "cgt-1"
|
||||||
|
)
|
||||||
|
|
||||||
|
async def test_draft_task_verification_returns_draft_specs(self):
|
||||||
|
fake_client = type("FakeSeedanceClient", (), {})()
|
||||||
|
fake_client.base_url = ""
|
||||||
|
fake_client.get_task_async = AsyncMock(return_value={
|
||||||
|
"data": {
|
||||||
|
"status": "succeeded",
|
||||||
|
"model": "doubao-seedance-2-5-260628-max",
|
||||||
|
"resolution": "480p",
|
||||||
|
"duration": 6,
|
||||||
|
},
|
||||||
|
})
|
||||||
|
with patch(
|
||||||
|
"comfyui_o1key.nodes.seedance_autopass.SeedanceClient",
|
||||||
|
return_value=fake_client,
|
||||||
|
):
|
||||||
|
summary = await SeedanceAutoPass._verify_draft_task(
|
||||||
|
"https://api.example.com", "cgt-1"
|
||||||
|
)
|
||||||
|
self.assertEqual(summary["model"], "doubao-seedance-2-5-260628-max")
|
||||||
|
self.assertEqual(summary["resolution"], "480p")
|
||||||
|
self.assertEqual(summary["duration"], 6)
|
||||||
|
|
||||||
|
async def test_draft_mode_requires_seedance_25(self):
|
||||||
|
with self.assertRaisesRegex(ValueError, "样片模式仅支持 seedance 2.5"):
|
||||||
|
await SeedanceAutoPass.execute(**{
|
||||||
|
"提示词": "prompt",
|
||||||
|
"生成模式": "多模态",
|
||||||
|
"主模型": "seedance 2.0",
|
||||||
|
"模型线路": "国内",
|
||||||
|
"分辨率": "720p",
|
||||||
|
"宽高比": "智能",
|
||||||
|
"时长": "5秒",
|
||||||
|
"生成音频": "关闭",
|
||||||
|
"素材创建模式": "自动创建",
|
||||||
|
"样片模式": "生成样片",
|
||||||
|
"seed": 0,
|
||||||
|
})
|
||||||
|
|
||||||
|
|
||||||
class SeedanceAutoPassBatchV3Tests(unittest.TestCase):
|
class SeedanceAutoPassBatchV3Tests(unittest.TestCase):
|
||||||
|
|||||||
@@ -0,0 +1,112 @@
|
|||||||
|
"""Offline tests for Seedance task polling and result parsing."""
|
||||||
|
|
||||||
|
import json
|
||||||
|
import sys
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
from unittest.mock import AsyncMock, call, patch
|
||||||
|
|
||||||
|
|
||||||
|
PACKAGE_DIR = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(PACKAGE_DIR.parent))
|
||||||
|
|
||||||
|
# Load only the client module. Importing the plugin-wide registry would make
|
||||||
|
# this offline test depend on the portable build's CUDA availability.
|
||||||
|
package = types.ModuleType("comfyui_o1key")
|
||||||
|
package.__path__ = [str(PACKAGE_DIR)]
|
||||||
|
sys.modules["comfyui_o1key"] = package
|
||||||
|
for child in ("clients", "utils"):
|
||||||
|
module = types.ModuleType(f"comfyui_o1key.{child}")
|
||||||
|
module.__path__ = [str(PACKAGE_DIR / child)]
|
||||||
|
sys.modules[f"comfyui_o1key.{child}"] = module
|
||||||
|
|
||||||
|
from comfyui_o1key.clients.seedance_client import SeedanceClient # noqa: E402
|
||||||
|
|
||||||
|
|
||||||
|
def make_client():
|
||||||
|
client = SeedanceClient.__new__(SeedanceClient)
|
||||||
|
client.api_key = "test-token"
|
||||||
|
client.base_url = "https://new-api.example.com"
|
||||||
|
return client
|
||||||
|
|
||||||
|
|
||||||
|
def response(payload):
|
||||||
|
value = AsyncMock()
|
||||||
|
value.text = AsyncMock(return_value=json.dumps(payload))
|
||||||
|
value.release = lambda: None
|
||||||
|
return value
|
||||||
|
|
||||||
|
|
||||||
|
class SeedancePollingTests(unittest.IsolatedAsyncioTestCase):
|
||||||
|
async def test_completed_task_reads_metadata_urls(self):
|
||||||
|
request = AsyncMock(side_effect=[
|
||||||
|
response({
|
||||||
|
"task_id": "task-1",
|
||||||
|
"status": "queued",
|
||||||
|
"progress": 0,
|
||||||
|
}),
|
||||||
|
response({
|
||||||
|
"task_id": "task-1",
|
||||||
|
"status": "completed",
|
||||||
|
"progress": 100,
|
||||||
|
"metadata": {
|
||||||
|
"url": "https://cdn.example.com/video.mp4",
|
||||||
|
"last_frame_url": "https://cdn.example.com/frame.png",
|
||||||
|
},
|
||||||
|
}),
|
||||||
|
])
|
||||||
|
|
||||||
|
with (
|
||||||
|
patch("comfyui_o1key.clients.seedance_client.async_request_with_retry", request),
|
||||||
|
patch("comfyui_o1key.clients.seedance_client.interruptible_sleep", AsyncMock()),
|
||||||
|
):
|
||||||
|
video_url, last_frame_url = await make_client().poll_async("task-1", object())
|
||||||
|
|
||||||
|
self.assertEqual(video_url, "https://cdn.example.com/video.mp4")
|
||||||
|
self.assertEqual(last_frame_url, "https://cdn.example.com/frame.png")
|
||||||
|
|
||||||
|
async def test_polling_uses_the_retrying_request_helper(self):
|
||||||
|
request = AsyncMock(return_value=response({
|
||||||
|
"status": "completed",
|
||||||
|
"result_url": "https://cdn.example.com/video.mp4",
|
||||||
|
}))
|
||||||
|
|
||||||
|
with patch("comfyui_o1key.clients.seedance_client.async_request_with_retry", request):
|
||||||
|
await make_client().poll_async("task-1", object())
|
||||||
|
|
||||||
|
self.assertEqual(request.await_args_list, [
|
||||||
|
call(
|
||||||
|
unittest.mock.ANY,
|
||||||
|
"GET",
|
||||||
|
"https://new-api.example.com/v1/video/generations/task-1",
|
||||||
|
headers={
|
||||||
|
"Authorization": "Bearer test-token",
|
||||||
|
"Content-Type": "application/json",
|
||||||
|
},
|
||||||
|
prefix="Seedance 状态查询: ",
|
||||||
|
),
|
||||||
|
])
|
||||||
|
|
||||||
|
|
||||||
|
async def test_get_task_async_reads_one_status_response(self):
|
||||||
|
request = AsyncMock(return_value=response({
|
||||||
|
"data": {
|
||||||
|
"status": "succeeded",
|
||||||
|
"model": "doubao-seedance-2-5-260628-max",
|
||||||
|
"resolution": "480p",
|
||||||
|
},
|
||||||
|
}))
|
||||||
|
|
||||||
|
with patch("comfyui_o1key.clients.seedance_client.async_request_with_retry", request):
|
||||||
|
payload = await make_client().get_task_async(
|
||||||
|
"cgt-1", session=object()
|
||||||
|
)
|
||||||
|
|
||||||
|
self.assertEqual(payload["data"]["status"], "succeeded")
|
||||||
|
self.assertEqual(request.await_args.args[2], "https://new-api.example.com/v1/video/generations/cgt-1")
|
||||||
|
self.assertEqual(request.await_args.kwargs["prefix"], "Seedance 任务查询: ")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
unittest.main()
|
||||||
@@ -5,6 +5,7 @@ import sys
|
|||||||
import types
|
import types
|
||||||
import unittest
|
import unittest
|
||||||
from pathlib import Path
|
from pathlib import Path
|
||||||
|
from unittest.mock import patch
|
||||||
|
|
||||||
|
|
||||||
PACKAGE_DIR = Path(__file__).resolve().parents[1]
|
PACKAGE_DIR = Path(__file__).resolve().parents[1]
|
||||||
@@ -146,6 +147,50 @@ class SeedanceHCAssetClientTests(unittest.IsolatedAsyncioTestCase):
|
|||||||
_, query_kwargs = session.get_call
|
_, query_kwargs = session.get_call
|
||||||
self.assertEqual(query_kwargs["params"], {"type": "doubao"})
|
self.assertEqual(query_kwargs["params"], {"type": "doubao"})
|
||||||
|
|
||||||
|
async def test_create_logs_full_response_but_folds_signed_urls(self):
|
||||||
|
session = _FakeSession(post_payload={
|
||||||
|
"success": True,
|
||||||
|
"data": {
|
||||||
|
"Id": "asset-test",
|
||||||
|
"Status": "Active",
|
||||||
|
"SourceUrl": "https://upload.example.com/a.png?signature=secret",
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
with patch("builtins.print") as print_mock:
|
||||||
|
await self.client.create_hc_asset(
|
||||||
|
name="参考图片1",
|
||||||
|
asset_url="https://upload.o1key.com/uploads/reference.png",
|
||||||
|
asset_type="image",
|
||||||
|
session=session,
|
||||||
|
)
|
||||||
|
|
||||||
|
printed = "\n".join(
|
||||||
|
str(call.args[0]) for call in print_mock.call_args_list if call.args
|
||||||
|
)
|
||||||
|
self.assertIn("创建响应体 HTTP 200", printed)
|
||||||
|
self.assertIn('"Id": "asset-test"', printed)
|
||||||
|
self.assertIn('"Status": "Active"', printed)
|
||||||
|
self.assertNotIn("signature=secret", printed)
|
||||||
|
|
||||||
|
async def test_query_logs_response_only_when_status_changes(self):
|
||||||
|
session = _FakeSession(get_payload={
|
||||||
|
"success": True,
|
||||||
|
"data": {"Id": "asset-q", "Status": "Processing"},
|
||||||
|
})
|
||||||
|
|
||||||
|
with patch("builtins.print") as print_mock:
|
||||||
|
await self.client.get_hc_asset("asset-q", session=session)
|
||||||
|
await self.client.get_hc_asset("asset-q", session=session)
|
||||||
|
|
||||||
|
printed = [
|
||||||
|
str(call.args[0])
|
||||||
|
for call in print_mock.call_args_list
|
||||||
|
if call.args
|
||||||
|
]
|
||||||
|
self.assertEqual(sum("查询响应体" in line for line in printed), 1)
|
||||||
|
self.assertIn('"Status": "Processing"', "\n".join(printed))
|
||||||
|
|
||||||
|
|
||||||
if __name__ == "__main__":
|
if __name__ == "__main__":
|
||||||
unittest.main()
|
unittest.main()
|
||||||
|
|||||||
@@ -24,6 +24,7 @@ for child in ("nodes", "utils", "clients"):
|
|||||||
|
|
||||||
from comfyui_o1key.nodes import seedance_element
|
from comfyui_o1key.nodes import seedance_element
|
||||||
from comfyui_o1key.nodes.seedance_element import SeedanceElementCreate
|
from comfyui_o1key.nodes.seedance_element import SeedanceElementCreate
|
||||||
|
from comfyui_o1key.nodes.seedance_autopass import SeedanceAutoPass
|
||||||
from comfyui_o1key.nodes import seedance_video
|
from comfyui_o1key.nodes import seedance_video
|
||||||
from comfyui_o1key.nodes.seedance_video import (
|
from comfyui_o1key.nodes.seedance_video import (
|
||||||
SeedanceMultiModal,
|
SeedanceMultiModal,
|
||||||
@@ -69,6 +70,7 @@ class SeedanceParameterSyncTests(unittest.TestCase):
|
|||||||
)
|
)
|
||||||
self.assertIn("30秒", inputs["时长"].options)
|
self.assertIn("30秒", inputs["时长"].options)
|
||||||
self.assertEqual(inputs["seed"].max, 0xffffffffffffffff)
|
self.assertEqual(inputs["seed"].max, 0xffffffffffffffff)
|
||||||
|
self.assertEqual(inputs["seed"].default, 0)
|
||||||
self.assertEqual(
|
self.assertEqual(
|
||||||
_resolve_model_matrix("seedance 2.5", "海外HC"),
|
_resolve_model_matrix("seedance 2.5", "海外HC"),
|
||||||
"dreamina-seedance-2-5-hc",
|
"dreamina-seedance-2-5-hc",
|
||||||
@@ -87,17 +89,112 @@ class SeedanceParameterSyncTests(unittest.TestCase):
|
|||||||
self.assertTrue(_is_new_format_model("dreamina-seedance-2-0-hc"))
|
self.assertTrue(_is_new_format_model("dreamina-seedance-2-0-hc"))
|
||||||
self.assertTrue(_is_new_format_model("dreamina-seedance-2-5-hc"))
|
self.assertTrue(_is_new_format_model("dreamina-seedance-2-5-hc"))
|
||||||
_check_fast_resolution("dreamina-seedance-2-5-hc", "1080p")
|
_check_fast_resolution("dreamina-seedance-2-5-hc", "1080p")
|
||||||
_check_fast_resolution("dreamina-seedance-2-5-hc", "4k")
|
with self.assertRaisesRegex(ValueError, "不支持 4k"):
|
||||||
|
_check_fast_resolution("dreamina-seedance-2-5-hc", "4k")
|
||||||
with self.assertRaisesRegex(ValueError, "不支持 4k"):
|
with self.assertRaisesRegex(ValueError, "不支持 4k"):
|
||||||
_check_fast_resolution("dreamina-seedance-2-0-fast-hc", "4k")
|
_check_fast_resolution("dreamina-seedance-2-0-fast-hc", "4k")
|
||||||
for limited_model in (
|
for limited_model in (
|
||||||
"doubao-seedance-2-0-fast-260128-max",
|
"doubao-seedance-2-0-fast-260128-max",
|
||||||
"doubao-seedance-2-0-mini-260615-max",
|
"doubao-seedance-2-0-mini-260615-max",
|
||||||
|
"seedance-2-0-fast-260128-d",
|
||||||
|
"seedance-2-0-mini-260615-d",
|
||||||
):
|
):
|
||||||
with self.subTest(limited_model=limited_model):
|
with self.subTest(limited_model=limited_model):
|
||||||
with self.assertRaisesRegex(ValueError, "不支持 4k"):
|
with self.assertRaisesRegex(ValueError, "不支持 4k"):
|
||||||
_check_fast_resolution(limited_model, "4k")
|
_check_fast_resolution(limited_model, "4k")
|
||||||
_check_fast_resolution("doubao-seedance-2-5-260628-max", "4k")
|
with self.assertRaisesRegex(ValueError, "不支持 4k"):
|
||||||
|
_check_fast_resolution("doubao-seedance-2-5-260628-max", "4k")
|
||||||
|
|
||||||
|
def test_seed_is_never_sent_to_the_provider(self):
|
||||||
|
body = SeedanceAutoPass._build_body(
|
||||||
|
"doubao-seedance-2-5-260628-max",
|
||||||
|
"prompt",
|
||||||
|
"1080p",
|
||||||
|
"智能",
|
||||||
|
"5秒",
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
["asset://image-1"],
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
generation_mode="多模态参考生视频",
|
||||||
|
)
|
||||||
|
self.assertNotIn("seed", body)
|
||||||
|
|
||||||
|
def test_generation_modes_cover_document_scenarios(self):
|
||||||
|
schema = SeedanceAutoPass.GET_SCHEMA()
|
||||||
|
inputs = {item.id: item for item in schema.inputs}
|
||||||
|
self.assertEqual(
|
||||||
|
inputs["生成模式"].options,
|
||||||
|
["多模态", "首尾帧", "视频编辑", "视频延长"],
|
||||||
|
)
|
||||||
|
self.assertEqual(inputs["输出格式"].options, ["mp4", "mov"])
|
||||||
|
self.assertEqual(inputs["seed"].default, 0)
|
||||||
|
|
||||||
|
def test_edit_body_carries_task_type_and_output_format(self):
|
||||||
|
body = SeedanceAutoPass._build_body(
|
||||||
|
"doubao-seedance-2-5-260628-max",
|
||||||
|
"去掉背景里的行人",
|
||||||
|
"1080p",
|
||||||
|
"auto",
|
||||||
|
-1,
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
[],
|
||||||
|
["https://example.invalid/clip.mp4"],
|
||||||
|
[],
|
||||||
|
generation_mode="edit",
|
||||||
|
output_format="mov",
|
||||||
|
)
|
||||||
|
self.assertEqual(body["omni_reference_task_type"], "edit")
|
||||||
|
self.assertEqual(body["output_format"], "mov")
|
||||||
|
self.assertEqual(body["duration"], -1)
|
||||||
|
self.assertEqual(body["ratio"], "adaptive")
|
||||||
|
self.assertEqual(
|
||||||
|
[item["video_url"]["url"] for item in body["content"] if item["type"] == "video_url"],
|
||||||
|
["https://example.invalid/clip.mp4"],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_edit_body_carries_reference_images_before_the_video(self):
|
||||||
|
body = SeedanceAutoPass._build_body(
|
||||||
|
"doubao-seedance-2-5-260628-max",
|
||||||
|
"把 @video1 中的男子替换为 @image1 中的女子",
|
||||||
|
"480p",
|
||||||
|
"auto",
|
||||||
|
-1,
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
["asset://image-1"],
|
||||||
|
["asset://video-1"],
|
||||||
|
[],
|
||||||
|
generation_mode="edit",
|
||||||
|
)
|
||||||
|
self.assertEqual(body["omni_reference_task_type"], "edit")
|
||||||
|
self.assertEqual(
|
||||||
|
[item.get("role") for item in body["content"] if item["type"] != "text"],
|
||||||
|
["reference_image", "reference_video"],
|
||||||
|
)
|
||||||
|
self.assertNotIn(
|
||||||
|
"first_frame",
|
||||||
|
[item.get("role") for item in body["content"]],
|
||||||
|
)
|
||||||
|
|
||||||
|
def test_auto_duration_and_adaptive_ratio_reach_the_request_body(self):
|
||||||
|
body = SeedanceAutoPass._build_body(
|
||||||
|
"doubao-seedance-2-5-260628-max",
|
||||||
|
"prompt",
|
||||||
|
"1080p",
|
||||||
|
"智能",
|
||||||
|
"自动",
|
||||||
|
False,
|
||||||
|
False,
|
||||||
|
["asset://image-1"],
|
||||||
|
[],
|
||||||
|
[],
|
||||||
|
generation_mode="多模态参考生视频",
|
||||||
|
)
|
||||||
|
self.assertEqual(body["duration"], -1)
|
||||||
|
self.assertEqual(body["ratio"], "adaptive")
|
||||||
|
|
||||||
def test_multimodal_uses_v3_autogrow_media_inputs(self):
|
def test_multimodal_uses_v3_autogrow_media_inputs(self):
|
||||||
self.assertTrue(issubclass(SeedanceMultiModal, io.ComfyNode))
|
self.assertTrue(issubclass(SeedanceMultiModal, io.ComfyNode))
|
||||||
|
|||||||
@@ -24,13 +24,16 @@ from comfyui_o1key.nodes.universal_llm import ( # noqa: E402
|
|||||||
|
|
||||||
|
|
||||||
class UniversalLLMModelTests(unittest.TestCase):
|
class UniversalLLMModelTests(unittest.TestCase):
|
||||||
def test_gpt_6_sol_is_supported_and_default(self):
|
def test_new_models_are_supported_and_claude_opus_5_5_is_default(self):
|
||||||
schema = UniversalLLMChat.GET_SCHEMA()
|
schema = UniversalLLMChat.GET_SCHEMA()
|
||||||
schema.validate()
|
schema.validate()
|
||||||
model_input = next(item for item in schema.inputs if item.id == "模型")
|
model_input = next(item for item in schema.inputs if item.id == "模型")
|
||||||
|
|
||||||
self.assertEqual(DEFAULT_MODEL, "gpt-6-sol")
|
self.assertEqual(DEFAULT_MODEL, "claude-opus-5-5")
|
||||||
self.assertEqual(SUPPORTED_MODELS[0], DEFAULT_MODEL)
|
self.assertEqual(SUPPORTED_MODELS[0], DEFAULT_MODEL)
|
||||||
|
self.assertIn("gemini-4-argon", SUPPORTED_MODELS)
|
||||||
|
self.assertIn("gpt-6-sol", SUPPORTED_MODELS)
|
||||||
|
self.assertIn("claude-opus-5", SUPPORTED_MODELS)
|
||||||
self.assertIn("gpt-6-astra", SUPPORTED_MODELS)
|
self.assertIn("gpt-6-astra", SUPPORTED_MODELS)
|
||||||
self.assertEqual(model_input.options, SUPPORTED_MODELS)
|
self.assertEqual(model_input.options, SUPPORTED_MODELS)
|
||||||
self.assertEqual(model_input.default, DEFAULT_MODEL)
|
self.assertEqual(model_input.default, DEFAULT_MODEL)
|
||||||
|
|||||||
@@ -13,12 +13,14 @@ SEEDANCE_MODEL_OPTIONS = [
|
|||||||
"seedance-2.5",
|
"seedance-2.5",
|
||||||
]
|
]
|
||||||
SEEDANCE_ROUTE_OPTIONS = ["domestic", "overseas_hc"]
|
SEEDANCE_ROUTE_OPTIONS = ["domestic", "overseas_hc"]
|
||||||
SEEDANCE_ASSET_CREATION_MODE_OPTIONS = ["auto", "manual"]
|
SEEDANCE_ASSET_CREATION_MODE_OPTIONS = ["direct", "auto", "manual"]
|
||||||
VIDEO_GENERATION_MODE_OPTIONS = [
|
VIDEO_GENERATION_MODE_OPTIONS = [
|
||||||
"text",
|
"text",
|
||||||
"first_frame",
|
"first_frame",
|
||||||
"first_last_frame",
|
"first_last_frame",
|
||||||
"multimodal",
|
"multimodal",
|
||||||
|
"edit",
|
||||||
|
"extend",
|
||||||
]
|
]
|
||||||
VIDEO_RESOLUTION_OPTIONS = ["480p", "720p", "1080p", "4k"]
|
VIDEO_RESOLUTION_OPTIONS = ["480p", "720p", "1080p", "4k"]
|
||||||
VIDEO_ASPECT_RATIO_OPTIONS = ["auto", "16:9", "9:16", "4:3", "3:4", "1:1", "21:9"]
|
VIDEO_ASPECT_RATIO_OPTIONS = ["auto", "16:9", "9:16", "4:3", "3:4", "1:1", "21:9"]
|
||||||
@@ -26,8 +28,10 @@ VIDEO_DURATION_OPTIONS = ["auto", *[str(value) for value in range(4, 31)]]
|
|||||||
|
|
||||||
MAX_VIDEO_PROMPT_CHARS = 20_000
|
MAX_VIDEO_PROMPT_CHARS = 20_000
|
||||||
SEEDANCE_REFERENCE_IMAGE_MAX_BYTES = 30 * 1024 * 1024
|
SEEDANCE_REFERENCE_IMAGE_MAX_BYTES = 30 * 1024 * 1024
|
||||||
SEEDANCE_REFERENCE_VIDEO_MAX_BYTES = 512 * 1024 * 1024
|
SEEDANCE_REFERENCE_VIDEO_MAX_BYTES = 200 * 1024 * 1024
|
||||||
SEEDANCE_REFERENCE_AUDIO_MAX_BYTES = 100 * 1024 * 1024
|
SEEDANCE_REFERENCE_AUDIO_MAX_BYTES = 15 * 1024 * 1024
|
||||||
|
SEEDANCE_REFERENCE_AUDIO_EXTENSIONS = (".wav", ".mp3")
|
||||||
|
SEEDANCE_REFERENCE_MIN_SECONDS = 2
|
||||||
SEEDANCE_REFERENCE_MIN_DIMENSION = 300
|
SEEDANCE_REFERENCE_MIN_DIMENSION = 300
|
||||||
SEEDANCE_REFERENCE_MAX_DIMENSION = 6000
|
SEEDANCE_REFERENCE_MAX_DIMENSION = 6000
|
||||||
SEEDANCE_REFERENCE_MIN_ASPECT_RATIO = 0.4
|
SEEDANCE_REFERENCE_MIN_ASPECT_RATIO = 0.4
|
||||||
@@ -54,6 +58,7 @@ SEEDANCE_CAPABILITIES = {
|
|||||||
"videos": 3,
|
"videos": 3,
|
||||||
"audios": 3,
|
"audios": 3,
|
||||||
"resolutions": ["480p", "720p", "1080p", "4k"],
|
"resolutions": ["480p", "720p", "1080p", "4k"],
|
||||||
|
"reference_seconds": 15,
|
||||||
},
|
},
|
||||||
"seedance-2.0-fast": {
|
"seedance-2.0-fast": {
|
||||||
"duration_min": 4,
|
"duration_min": 4,
|
||||||
@@ -62,6 +67,7 @@ SEEDANCE_CAPABILITIES = {
|
|||||||
"videos": 3,
|
"videos": 3,
|
||||||
"audios": 3,
|
"audios": 3,
|
||||||
"resolutions": ["480p", "720p"],
|
"resolutions": ["480p", "720p"],
|
||||||
|
"reference_seconds": 15,
|
||||||
},
|
},
|
||||||
"seedance-2.0-mini": {
|
"seedance-2.0-mini": {
|
||||||
"duration_min": 4,
|
"duration_min": 4,
|
||||||
@@ -70,6 +76,7 @@ SEEDANCE_CAPABILITIES = {
|
|||||||
"videos": 3,
|
"videos": 3,
|
||||||
"audios": 3,
|
"audios": 3,
|
||||||
"resolutions": ["480p", "720p"],
|
"resolutions": ["480p", "720p"],
|
||||||
|
"reference_seconds": 15,
|
||||||
},
|
},
|
||||||
"seedance-2.5": {
|
"seedance-2.5": {
|
||||||
"duration_min": 4,
|
"duration_min": 4,
|
||||||
@@ -77,7 +84,8 @@ SEEDANCE_CAPABILITIES = {
|
|||||||
"images": 30,
|
"images": 30,
|
||||||
"videos": 10,
|
"videos": 10,
|
||||||
"audios": 10,
|
"audios": 10,
|
||||||
"resolutions": ["480p", "720p", "1080p", "4k"],
|
"resolutions": ["480p", "720p", "1080p"],
|
||||||
|
"reference_seconds": 30,
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -111,7 +119,7 @@ def normalize_seedance_parameters(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
mode = str(payload.get("generation_mode") or "text").strip()
|
mode = str(payload.get("generation_mode") or "text").strip()
|
||||||
if mode not in VIDEO_GENERATION_MODE_OPTIONS:
|
if mode not in VIDEO_GENERATION_MODE_OPTIONS:
|
||||||
raise ValueError(f"不支持的视频生成模式:{mode}")
|
raise ValueError(f"不支持的视频生成模式:{mode}")
|
||||||
asset_creation_mode = str(payload.get("asset_creation_mode") or "auto").strip()
|
asset_creation_mode = str(payload.get("asset_creation_mode") or "direct").strip()
|
||||||
if asset_creation_mode not in SEEDANCE_ASSET_CREATION_MODE_OPTIONS:
|
if asset_creation_mode not in SEEDANCE_ASSET_CREATION_MODE_OPTIONS:
|
||||||
raise ValueError(f"不支持的素材创建模式:{asset_creation_mode}")
|
raise ValueError(f"不支持的素材创建模式:{asset_creation_mode}")
|
||||||
|
|
||||||
@@ -133,23 +141,27 @@ def normalize_seedance_parameters(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
|
|
||||||
raw_duration = str(payload.get("duration") or "5").strip().lower()
|
raw_duration = str(payload.get("duration") or "5").strip().lower()
|
||||||
if raw_duration == "auto":
|
if raw_duration == "auto":
|
||||||
duration = 5
|
# -1 是上游约定的自动时长,必须原样透传。
|
||||||
|
duration = -1
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
duration = int(raw_duration.removesuffix("秒"))
|
duration = int(raw_duration.removesuffix("秒"))
|
||||||
except ValueError:
|
except ValueError:
|
||||||
raise ValueError(f"无效的视频时长:{raw_duration}") from None
|
raise ValueError(f"无效的视频时长:{raw_duration}") from None
|
||||||
if not capabilities["duration_min"] <= duration <= capabilities["duration_max"]:
|
if duration != -1 and not capabilities["duration_min"] <= duration <= capabilities["duration_max"]:
|
||||||
raise ValueError(
|
raise ValueError(
|
||||||
f"{model} 的时长仅支持 {capabilities['duration_min']}-{capabilities['duration_max']} 秒"
|
f"{model} 的时长仅支持 {capabilities['duration_min']}-{capabilities['duration_max']} 秒"
|
||||||
)
|
)
|
||||||
|
|
||||||
try:
|
# 文档约束:2.5 的编辑/延长只用 adaptive,编辑必须显式 -1,首帧类也跟随图片比例
|
||||||
seed = int(payload.get("seed") or 0)
|
if mode in {"edit", "extend"}:
|
||||||
except (TypeError, ValueError):
|
if model != "seedance-2.5":
|
||||||
raise ValueError("seed 必须是非负整数") from None
|
raise ValueError("视频编辑和视频延长仅支持 Seedance 2.5")
|
||||||
if not 0 <= seed <= 0xFFFFFFFFFFFFFFFF:
|
aspect_ratio = "auto"
|
||||||
raise ValueError("seed 必须是 0 到 18446744073709551615 之间的整数")
|
if mode == "edit":
|
||||||
|
duration = -1
|
||||||
|
if model == "seedance-2.5" and mode in {"first_frame", "first_last_frame"}:
|
||||||
|
aspect_ratio = "auto"
|
||||||
|
|
||||||
filename_prefix = str(payload.get("filename_prefix") or "o1key_video").strip()
|
filename_prefix = str(payload.get("filename_prefix") or "o1key_video").strip()
|
||||||
if not filename_prefix:
|
if not filename_prefix:
|
||||||
@@ -170,7 +182,6 @@ def normalize_seedance_parameters(payload: dict[str, Any]) -> dict[str, Any]:
|
|||||||
"duration": duration,
|
"duration": duration,
|
||||||
"generate_audio": _as_bool(payload.get("generate_audio")),
|
"generate_audio": _as_bool(payload.get("generate_audio")),
|
||||||
"return_last_frame": _as_bool(payload.get("return_last_frame")),
|
"return_last_frame": _as_bool(payload.get("return_last_frame")),
|
||||||
"seed": seed,
|
|
||||||
"filename_prefix": filename_prefix,
|
"filename_prefix": filename_prefix,
|
||||||
"save_location": str(payload.get("save_location") or "").strip(),
|
"save_location": str(payload.get("save_location") or "").strip(),
|
||||||
"capabilities": capabilities,
|
"capabilities": capabilities,
|
||||||
@@ -200,6 +211,31 @@ def validate_seedance_media_counts(
|
|||||||
raise ValueError(f"{label} 最多支持 {limit} 个{media_label},当前输入 {count} 个")
|
raise ValueError(f"{label} 最多支持 {limit} 个{media_label},当前输入 {count} 个")
|
||||||
|
|
||||||
|
|
||||||
|
def validate_seedance_reference_durations(
|
||||||
|
model: str,
|
||||||
|
video_seconds: list[float],
|
||||||
|
audio_seconds: list[float],
|
||||||
|
*,
|
||||||
|
model_label: str | None = None,
|
||||||
|
) -> None:
|
||||||
|
"""Apply the shared per-item and total reference-time limits."""
|
||||||
|
|
||||||
|
if model not in SEEDANCE_CAPABILITIES:
|
||||||
|
raise ValueError(f"不支持的 Seedance 模型:{model}")
|
||||||
|
limit = SEEDANCE_CAPABILITIES[model]["reference_seconds"]
|
||||||
|
label = model_label or model
|
||||||
|
for media_label, durations in (("参考视频", video_seconds), ("参考音频", audio_seconds)):
|
||||||
|
for index, seconds in enumerate(durations, start=1):
|
||||||
|
if not SEEDANCE_REFERENCE_MIN_SECONDS <= seconds <= limit:
|
||||||
|
raise ValueError(
|
||||||
|
f"{label} 的{media_label}{index}时长必须在 "
|
||||||
|
f"{SEEDANCE_REFERENCE_MIN_SECONDS}~{limit} 秒,当前为 {seconds:.1f} 秒"
|
||||||
|
)
|
||||||
|
total = sum(durations)
|
||||||
|
if total > limit:
|
||||||
|
raise ValueError(f"{label} 的{media_label}总时长不能超过 {limit} 秒,当前为 {total:.1f} 秒")
|
||||||
|
|
||||||
|
|
||||||
def validate_seedance_reference_dimensions(
|
def validate_seedance_reference_dimensions(
|
||||||
width: int,
|
width: int,
|
||||||
height: int,
|
height: int,
|
||||||
@@ -268,8 +304,11 @@ def public_video_capabilities() -> dict[str, Any]:
|
|||||||
{"value": "first_frame", "label": "首帧图生视频"},
|
{"value": "first_frame", "label": "首帧图生视频"},
|
||||||
{"value": "first_last_frame", "label": "首尾帧生视频"},
|
{"value": "first_last_frame", "label": "首尾帧生视频"},
|
||||||
{"value": "multimodal", "label": "多模态参考生视频"},
|
{"value": "multimodal", "label": "多模态参考生视频"},
|
||||||
|
{"value": "edit", "label": "视频编辑"},
|
||||||
|
{"value": "extend", "label": "视频延长"},
|
||||||
],
|
],
|
||||||
"asset_creation_modes": [
|
"asset_creation_modes": [
|
||||||
|
{"value": "direct", "label": "直接上传"},
|
||||||
{"value": "auto", "label": "自动创建"},
|
{"value": "auto", "label": "自动创建"},
|
||||||
{"value": "manual", "label": "手动"},
|
{"value": "manual", "label": "手动"},
|
||||||
],
|
],
|
||||||
@@ -286,7 +325,9 @@ __all__ = [
|
|||||||
"SEEDANCE_MODEL_MATRIX",
|
"SEEDANCE_MODEL_MATRIX",
|
||||||
"SEEDANCE_MODEL_OPTIONS",
|
"SEEDANCE_MODEL_OPTIONS",
|
||||||
"SEEDANCE_REFERENCE_AUDIO_MAX_BYTES",
|
"SEEDANCE_REFERENCE_AUDIO_MAX_BYTES",
|
||||||
|
"SEEDANCE_REFERENCE_AUDIO_EXTENSIONS",
|
||||||
"SEEDANCE_REFERENCE_IMAGE_MAX_BYTES",
|
"SEEDANCE_REFERENCE_IMAGE_MAX_BYTES",
|
||||||
|
"SEEDANCE_REFERENCE_MIN_SECONDS",
|
||||||
"SEEDANCE_REFERENCE_MAX_ASPECT_RATIO",
|
"SEEDANCE_REFERENCE_MAX_ASPECT_RATIO",
|
||||||
"SEEDANCE_REFERENCE_MAX_DIMENSION",
|
"SEEDANCE_REFERENCE_MAX_DIMENSION",
|
||||||
"SEEDANCE_REFERENCE_MIN_ASPECT_RATIO",
|
"SEEDANCE_REFERENCE_MIN_ASPECT_RATIO",
|
||||||
@@ -305,4 +346,5 @@ __all__ = [
|
|||||||
"resolve_seedance_model",
|
"resolve_seedance_model",
|
||||||
"validate_seedance_media_counts",
|
"validate_seedance_media_counts",
|
||||||
"validate_seedance_reference_dimensions",
|
"validate_seedance_reference_dimensions",
|
||||||
|
"validate_seedance_reference_durations",
|
||||||
]
|
]
|
||||||
|
|||||||
+133
-33
@@ -23,6 +23,7 @@ from .config import get_base_url_by_route
|
|||||||
from .http_error import format_o1key_video_error
|
from .http_error import format_o1key_video_error
|
||||||
from .o1key_image_save import normalize_save_location
|
from .o1key_image_save import normalize_save_location
|
||||||
from .o1key_video_catalog import (
|
from .o1key_video_catalog import (
|
||||||
|
SEEDANCE_REFERENCE_AUDIO_EXTENSIONS,
|
||||||
SEEDANCE_REFERENCE_AUDIO_MAX_BYTES,
|
SEEDANCE_REFERENCE_AUDIO_MAX_BYTES,
|
||||||
SEEDANCE_REFERENCE_IMAGE_MAX_BYTES,
|
SEEDANCE_REFERENCE_IMAGE_MAX_BYTES,
|
||||||
SEEDANCE_REFERENCE_VIDEO_MAX_BYTES,
|
SEEDANCE_REFERENCE_VIDEO_MAX_BYTES,
|
||||||
@@ -30,6 +31,7 @@ from .o1key_video_catalog import (
|
|||||||
public_video_capabilities,
|
public_video_capabilities,
|
||||||
validate_seedance_media_counts,
|
validate_seedance_media_counts,
|
||||||
validate_seedance_reference_dimensions,
|
validate_seedance_reference_dimensions,
|
||||||
|
validate_seedance_reference_durations,
|
||||||
)
|
)
|
||||||
from .r2_uploader import upload_audio, upload_image, upload_video
|
from .r2_uploader import upload_audio, upload_image, upload_video
|
||||||
from .seedance_assets import (
|
from .seedance_assets import (
|
||||||
@@ -47,7 +49,7 @@ _MEDIA_RULES = {
|
|||||||
"last_frame": ({".png", ".jpg", ".jpeg", ".webp", ".bmp"}, SEEDANCE_REFERENCE_IMAGE_MAX_BYTES),
|
"last_frame": ({".png", ".jpg", ".jpeg", ".webp", ".bmp"}, SEEDANCE_REFERENCE_IMAGE_MAX_BYTES),
|
||||||
"reference_images": ({".png", ".jpg", ".jpeg", ".webp", ".bmp"}, SEEDANCE_REFERENCE_IMAGE_MAX_BYTES),
|
"reference_images": ({".png", ".jpg", ".jpeg", ".webp", ".bmp"}, SEEDANCE_REFERENCE_IMAGE_MAX_BYTES),
|
||||||
"reference_videos": ({".mp4", ".mov"}, SEEDANCE_REFERENCE_VIDEO_MAX_BYTES),
|
"reference_videos": ({".mp4", ".mov"}, SEEDANCE_REFERENCE_VIDEO_MAX_BYTES),
|
||||||
"reference_audios": ({".wav", ".mp3", ".m4a", ".aac", ".flac", ".ogg"}, SEEDANCE_REFERENCE_AUDIO_MAX_BYTES),
|
"reference_audios": (set(SEEDANCE_REFERENCE_AUDIO_EXTENSIONS), SEEDANCE_REFERENCE_AUDIO_MAX_BYTES),
|
||||||
}
|
}
|
||||||
_LIST_MEDIA_ROLES = {"reference_images", "reference_videos", "reference_audios"}
|
_LIST_MEDIA_ROLES = {"reference_images", "reference_videos", "reference_audios"}
|
||||||
_IMAGE_MEDIA_ROLES = {"first_frame", "last_frame", "reference_images"}
|
_IMAGE_MEDIA_ROLES = {"first_frame", "last_frame", "reference_images"}
|
||||||
@@ -195,6 +197,9 @@ def normalize_video_job_payload(payload: Any) -> dict[str, Any]:
|
|||||||
elif mode == "first_last_frame":
|
elif mode == "first_last_frame":
|
||||||
if len(assets["images"]) != 2 or assets["videos"] or assets["audios"]:
|
if len(assets["images"]) != 2 or assets["videos"] or assets["audios"]:
|
||||||
raise ValueError("首尾帧生视频的手动模式必须且只能填写两个图片素材 ID")
|
raise ValueError("首尾帧生视频的手动模式必须且只能填写两个图片素材 ID")
|
||||||
|
elif mode in {"edit", "extend"}:
|
||||||
|
if len(assets["videos"]) != 1:
|
||||||
|
raise ValueError("视频编辑和视频延长必须且只能填写一个视频素材 ID")
|
||||||
elif not asset_count:
|
elif not asset_count:
|
||||||
raise ValueError("多模态手动模式至少需要填写一个素材 ID")
|
raise ValueError("多模态手动模式至少需要填写一个素材 ID")
|
||||||
else:
|
else:
|
||||||
@@ -206,6 +211,11 @@ def normalize_video_job_payload(payload: Any) -> dict[str, Any]:
|
|||||||
elif mode == "first_last_frame":
|
elif mode == "first_last_frame":
|
||||||
if not first_frame or not last_frame or reference_count or video_count or audio_count:
|
if not first_frame or not last_frame or reference_count or video_count or audio_count:
|
||||||
raise ValueError("首尾帧生视频必须且只能提供首帧和尾帧图片")
|
raise ValueError("首尾帧生视频必须且只能提供首帧和尾帧图片")
|
||||||
|
elif mode in {"edit", "extend"}:
|
||||||
|
if video_count != 1 or first_frame or last_frame:
|
||||||
|
raise ValueError("视频编辑和视频延长必须且只能提供一段参考视频")
|
||||||
|
if not normalized["prompt"]:
|
||||||
|
raise ValueError("视频编辑和视频延长必须填写提示词")
|
||||||
elif not (
|
elif not (
|
||||||
normalized["prompt"]
|
normalized["prompt"]
|
||||||
or reference_count
|
or reference_count
|
||||||
@@ -236,6 +246,15 @@ def normalize_video_job_payload(payload: Any) -> dict[str, Any]:
|
|||||||
and not video_total
|
and not video_total
|
||||||
):
|
):
|
||||||
raise ValueError("Seedance 2.0 系列不可单独使用参考音频")
|
raise ValueError("Seedance 2.0 系列不可单独使用参考音频")
|
||||||
|
if (
|
||||||
|
mode == "multimodal"
|
||||||
|
and normalized["model"] == "seedance-2.5"
|
||||||
|
and audio_total
|
||||||
|
and not image_total
|
||||||
|
and not video_total
|
||||||
|
and not normalized["prompt"]
|
||||||
|
):
|
||||||
|
raise ValueError("Seedance 2.5 仅有参考音频时必须填写提示词")
|
||||||
|
|
||||||
normalized.update({
|
normalized.update({
|
||||||
"batch_id": _canonical_batch_id(payload.get("batch_id")),
|
"batch_id": _canonical_batch_id(payload.get("batch_id")),
|
||||||
@@ -322,22 +341,50 @@ def _probe_video_dimensions(path: str) -> tuple[int, int]:
|
|||||||
return width, height
|
return width, height
|
||||||
|
|
||||||
|
|
||||||
|
def _probe_media_seconds(path: str) -> float | None:
|
||||||
|
"""Read the container duration used by the Seedance reference-time limits."""
|
||||||
|
|
||||||
|
try:
|
||||||
|
import av
|
||||||
|
except ImportError:
|
||||||
|
raise ValueError("当前 ComfyUI 环境缺少 PyAV,无法校验参考素材时长") from None
|
||||||
|
|
||||||
|
try:
|
||||||
|
with av.open(path) as container:
|
||||||
|
if container.duration is None:
|
||||||
|
return None
|
||||||
|
return float(container.duration) / 1_000_000
|
||||||
|
except Exception:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
def snapshot_video_job_media(job: dict[str, Any], input_directory: str, temp_directory: str) -> None:
|
def snapshot_video_job_media(job: dict[str, Any], input_directory: str, temp_directory: str) -> None:
|
||||||
batch_root = os.path.join(temp_directory, "o1key_video_jobs", job["batch_id"])
|
batch_root = os.path.join(temp_directory, "o1key_video_jobs", job["batch_id"])
|
||||||
input_root = os.path.join(batch_root, "inputs")
|
input_root = os.path.join(batch_root, "inputs")
|
||||||
os.makedirs(input_root, exist_ok=False)
|
os.makedirs(input_root, exist_ok=False)
|
||||||
snapshots: dict[str, Any] = {}
|
snapshots: dict[str, Any] = {}
|
||||||
|
video_seconds: list[float] = []
|
||||||
|
audio_seconds: list[float] = []
|
||||||
for role, raw_value in job["media"].items():
|
for role, raw_value in job["media"].items():
|
||||||
values = raw_value if isinstance(raw_value, list) else ([raw_value] if raw_value else [])
|
values = raw_value if isinstance(raw_value, list) else ([raw_value] if raw_value else [])
|
||||||
copied = []
|
copied = []
|
||||||
for index, descriptor in enumerate(values, start=1):
|
for index, descriptor in enumerate(values, start=1):
|
||||||
source = _resolve_input_path(input_directory, descriptor, role)
|
source = _resolve_input_path(input_directory, descriptor, role)
|
||||||
_validate_media_file(source, role)
|
_validate_media_file(source, role)
|
||||||
|
if role == "reference_videos":
|
||||||
|
seconds = _probe_media_seconds(source)
|
||||||
|
if seconds is not None:
|
||||||
|
video_seconds.append(seconds)
|
||||||
|
elif role == "reference_audios":
|
||||||
|
seconds = _probe_media_seconds(source)
|
||||||
|
if seconds is not None:
|
||||||
|
audio_seconds.append(seconds)
|
||||||
extension = os.path.splitext(source)[1].lower()
|
extension = os.path.splitext(source)[1].lower()
|
||||||
target = os.path.join(input_root, f"{role}_{index:02d}{extension}")
|
target = os.path.join(input_root, f"{role}_{index:02d}{extension}")
|
||||||
shutil.copy2(source, target)
|
shutil.copy2(source, target)
|
||||||
copied.append(target)
|
copied.append(target)
|
||||||
snapshots[role] = copied if role in _LIST_MEDIA_ROLES else (copied[0] if copied else None)
|
snapshots[role] = copied if role in _LIST_MEDIA_ROLES else (copied[0] if copied else None)
|
||||||
|
validate_seedance_reference_durations(job["model"], video_seconds, audio_seconds)
|
||||||
job["snapshot_root"] = batch_root
|
job["snapshot_root"] = batch_root
|
||||||
job["snapshot_media"] = snapshots
|
job["snapshot_media"] = snapshots
|
||||||
|
|
||||||
@@ -375,7 +422,6 @@ async def _prepare_seedance_media(job: dict[str, Any], update) -> dict[str, Any]
|
|||||||
for kind in ("images", "videos", "audios")
|
for kind in ("images", "videos", "audios")
|
||||||
}
|
}
|
||||||
return prepared
|
return prepared
|
||||||
|
|
||||||
items = []
|
items = []
|
||||||
if snapshots.get("first_frame"):
|
if snapshots.get("first_frame"):
|
||||||
items.append(("first_frame", "image", snapshots["first_frame"]))
|
items.append(("first_frame", "image", snapshots["first_frame"]))
|
||||||
@@ -397,9 +443,10 @@ async def _prepare_seedance_media(job: dict[str, Any], update) -> dict[str, Any]
|
|||||||
job["resolved_assets"] = {"images": [], "videos": [], "audios": []}
|
job["resolved_assets"] = {"images": [], "videos": [], "audios": []}
|
||||||
return prepared
|
return prepared
|
||||||
|
|
||||||
request_type = seedance_asset_request_type(job["route"])
|
direct_assets = job.get("asset_creation_mode") == "direct"
|
||||||
|
request_type = "" if direct_assets else seedance_asset_request_type(job["route"])
|
||||||
request_label = "HC" if request_type == "hc" else "Doubao"
|
request_label = "HC" if request_type == "hc" else "Doubao"
|
||||||
service = SeedanceAssetService(
|
service = None if direct_assets else SeedanceAssetService(
|
||||||
client=SeedanceElementClient(base_url=base_url),
|
client=SeedanceElementClient(base_url=base_url),
|
||||||
cache_path=job.get("asset_cache_path"),
|
cache_path=job.get("asset_cache_path"),
|
||||||
)
|
)
|
||||||
@@ -409,9 +456,31 @@ async def _prepare_seedance_media(job: dict[str, Any], update) -> dict[str, Any]
|
|||||||
active_count = 0
|
active_count = 0
|
||||||
total = len(items)
|
total = len(items)
|
||||||
|
|
||||||
|
async def upload_media(item_number: int, path: str, kind: str) -> str:
|
||||||
|
nonlocal uploaded_count
|
||||||
|
update(stage=f"上传素材 {item_number}/{total}")
|
||||||
|
if kind == "image":
|
||||||
|
with Image.open(path) as opened:
|
||||||
|
opened.load()
|
||||||
|
value = await upload_image(opened.convert("RGB"), base_url=base_url)
|
||||||
|
elif kind == "video":
|
||||||
|
value = await upload_video(path, base_url=base_url)
|
||||||
|
else:
|
||||||
|
value = await upload_audio(path, base_url=base_url)
|
||||||
|
async with progress_lock:
|
||||||
|
uploaded_count += 1
|
||||||
|
update(
|
||||||
|
stage=f"已上传素材 {uploaded_count}/{total}",
|
||||||
|
progress=0.02 + (uploaded_count / total) * 0.08,
|
||||||
|
)
|
||||||
|
return value
|
||||||
|
|
||||||
async def prepare(item_number: int, path: str, kind: str) -> tuple[str, str]:
|
async def prepare(item_number: int, path: str, kind: str) -> tuple[str, str]:
|
||||||
nonlocal uploaded_count, active_count
|
nonlocal active_count
|
||||||
async with semaphore:
|
async with semaphore:
|
||||||
|
if direct_assets:
|
||||||
|
return await upload_media(item_number, path, kind), ""
|
||||||
|
|
||||||
fingerprint = await asyncio.to_thread(
|
fingerprint = await asyncio.to_thread(
|
||||||
seedance_asset_fingerprint,
|
seedance_asset_fingerprint,
|
||||||
path,
|
path,
|
||||||
@@ -420,22 +489,7 @@ async def _prepare_seedance_media(job: dict[str, Any], update) -> dict[str, Any]
|
|||||||
)
|
)
|
||||||
|
|
||||||
async def upload() -> str:
|
async def upload() -> str:
|
||||||
nonlocal uploaded_count
|
value = await upload_media(item_number, path, kind)
|
||||||
update(stage=f"上传素材 {item_number}/{total}")
|
|
||||||
if kind == "image":
|
|
||||||
with Image.open(path) as opened:
|
|
||||||
opened.load()
|
|
||||||
value = await upload_image(opened.convert("RGB"), base_url=base_url)
|
|
||||||
elif kind == "video":
|
|
||||||
value = await upload_video(path, base_url=base_url)
|
|
||||||
else:
|
|
||||||
value = await upload_audio(path, base_url=base_url)
|
|
||||||
async with progress_lock:
|
|
||||||
uploaded_count += 1
|
|
||||||
update(
|
|
||||||
stage=f"已上传素材 {uploaded_count}/{total}",
|
|
||||||
progress=0.02 + (uploaded_count / total) * 0.06,
|
|
||||||
)
|
|
||||||
update(stage=f"创建 {request_label} 素材 {item_number}/{total}")
|
update(stage=f"创建 {request_label} 素材 {item_number}/{total}")
|
||||||
return value
|
return value
|
||||||
|
|
||||||
@@ -464,20 +518,20 @@ async def _prepare_seedance_media(job: dict[str, Any], update) -> dict[str, Any]
|
|||||||
for item_number, (_role, kind, path) in enumerate(items, start=1)
|
for item_number, (_role, kind, path) in enumerate(items, start=1)
|
||||||
))
|
))
|
||||||
resolved = {"images": [], "videos": [], "audios": []}
|
resolved = {"images": [], "videos": [], "audios": []}
|
||||||
for (role, kind, _path), (asset_url, asset_id) in zip(items, results):
|
for (role, kind, _path), (url, asset_id) in zip(items, results):
|
||||||
if role in {"first_frame", "last_frame"}:
|
if role in {"first_frame", "last_frame"}:
|
||||||
prepared[role] = asset_url
|
prepared[role] = url
|
||||||
else:
|
else:
|
||||||
prepared[role].append(asset_url)
|
prepared[role].append(url)
|
||||||
resolved[f"{kind}s"].append(asset_id)
|
if asset_id:
|
||||||
|
resolved[f"{kind}s"].append(asset_id)
|
||||||
job["resolved_assets"] = resolved
|
job["resolved_assets"] = resolved
|
||||||
return prepared
|
return prepared
|
||||||
|
|
||||||
|
|
||||||
def build_seedance_video_body(job: dict[str, Any], prepared: dict[str, Any]) -> dict[str, Any]:
|
def build_seedance_video_body(job: dict[str, Any], prepared: dict[str, Any]) -> dict[str, Any]:
|
||||||
content = []
|
# content 必须包含至少一个非空文本项,纯参考素材请求也要带上提示词占位。
|
||||||
if job["prompt"]:
|
content = [{"type": "text", "text": job["prompt"] or " "}]
|
||||||
content.append({"type": "text", "text": job["prompt"]})
|
|
||||||
mode = job["generation_mode"]
|
mode = job["generation_mode"]
|
||||||
image_asset_ids = job["assets"].get("images", job["assets"].get("persons", []))
|
image_asset_ids = job["assets"].get("images", job["assets"].get("persons", []))
|
||||||
manual_assets = job.get("asset_creation_mode") == "manual"
|
manual_assets = job.get("asset_creation_mode") == "manual"
|
||||||
@@ -486,6 +540,7 @@ def build_seedance_video_body(job: dict[str, Any], prepared: dict[str, Any]) ->
|
|||||||
content.append({
|
content.append({
|
||||||
"type": "image_url",
|
"type": "image_url",
|
||||||
"image_url": {"url": image_url},
|
"image_url": {"url": image_url},
|
||||||
|
"role": "first_frame",
|
||||||
})
|
})
|
||||||
elif mode == "first_last_frame":
|
elif mode == "first_last_frame":
|
||||||
image_urls = (
|
image_urls = (
|
||||||
@@ -506,11 +561,11 @@ def build_seedance_video_body(job: dict[str, Any], prepared: dict[str, Any]) ->
|
|||||||
},
|
},
|
||||||
])
|
])
|
||||||
elif mode == "multimodal":
|
elif mode == "multimodal":
|
||||||
for index, asset_id in enumerate(image_asset_ids):
|
for asset_id in image_asset_ids:
|
||||||
content.append({
|
content.append({
|
||||||
"type": "image_url",
|
"type": "image_url",
|
||||||
"image_url": {"url": _asset_url(asset_id)},
|
"image_url": {"url": _asset_url(asset_id)},
|
||||||
"role": "subject" if index == 0 else "reference_image",
|
"role": "reference_image",
|
||||||
})
|
})
|
||||||
content.extend(
|
content.extend(
|
||||||
{
|
{
|
||||||
@@ -552,19 +607,64 @@ def build_seedance_video_body(job: dict[str, Any], prepared: dict[str, Any]) ->
|
|||||||
}
|
}
|
||||||
for url in prepared["reference_audios"]
|
for url in prepared["reference_audios"]
|
||||||
)
|
)
|
||||||
|
elif mode in {"edit", "extend"}:
|
||||||
|
# 官方 2.5 的编辑/延长以参考视频为底片,同时允许附带参考图与参考音频。
|
||||||
|
# 图片排在视频前面,保证提示词里 @image1 / @video1 的编号稳定。
|
||||||
|
edit_image_urls = (
|
||||||
|
[_asset_url(value) for value in job["assets"]["images"]]
|
||||||
|
if manual_assets
|
||||||
|
else prepared["reference_images"]
|
||||||
|
)
|
||||||
|
content.extend(
|
||||||
|
{
|
||||||
|
"type": "image_url",
|
||||||
|
"image_url": {"url": url},
|
||||||
|
"role": "reference_image",
|
||||||
|
}
|
||||||
|
for url in edit_image_urls
|
||||||
|
)
|
||||||
|
video_urls = (
|
||||||
|
[_asset_url(value) for value in job["assets"]["videos"]]
|
||||||
|
if manual_assets
|
||||||
|
else prepared["reference_videos"]
|
||||||
|
)
|
||||||
|
content.extend(
|
||||||
|
{
|
||||||
|
"type": "video_url",
|
||||||
|
"video_url": {"url": url},
|
||||||
|
"role": "reference_video",
|
||||||
|
}
|
||||||
|
for url in video_urls
|
||||||
|
)
|
||||||
|
edit_audio_urls = (
|
||||||
|
[_asset_url(value) for value in job["assets"]["audios"]]
|
||||||
|
if manual_assets
|
||||||
|
else prepared["reference_audios"]
|
||||||
|
)
|
||||||
|
content.extend(
|
||||||
|
{
|
||||||
|
"type": "audio_url",
|
||||||
|
"audio_url": {"url": url},
|
||||||
|
"role": "reference_audio",
|
||||||
|
}
|
||||||
|
for url in edit_audio_urls
|
||||||
|
)
|
||||||
|
|
||||||
body = {
|
body = {
|
||||||
"model": job["actual_model"],
|
"model": job["actual_model"],
|
||||||
"content": content,
|
"content": content,
|
||||||
"duration": job["duration"],
|
"duration": job["duration"],
|
||||||
"resolution": job["resolution"],
|
"resolution": job["resolution"],
|
||||||
"ratio": "16:9" if job["aspect_ratio"] == "auto" else job["aspect_ratio"],
|
"ratio": "adaptive" if job["aspect_ratio"] == "auto" else job["aspect_ratio"],
|
||||||
"generate_audio": job["generate_audio"],
|
"generate_audio": job["generate_audio"],
|
||||||
"watermark": False,
|
"watermark": False,
|
||||||
"return_last_frame": job["return_last_frame"],
|
"return_last_frame": job["return_last_frame"],
|
||||||
}
|
}
|
||||||
if job["seed"]:
|
if mode in {"edit", "extend"}:
|
||||||
body["seed"] = job["seed"]
|
body["omni_reference_task_type"] = mode
|
||||||
|
if job.get("output_format"):
|
||||||
|
body["output_format"] = job["output_format"]
|
||||||
|
# seed 只作为 ComfyUI 的缓存键,由上游自行生成,绝不随请求发送。
|
||||||
return body
|
return body
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
+3
-2
@@ -2,7 +2,7 @@ import { app } from "../../../scripts/app.js";
|
|||||||
|
|
||||||
// ─── State ───────────────────────────────────────────────────────────────────
|
// ─── State ───────────────────────────────────────────────────────────────────
|
||||||
const STORAGE_KEY = "o1key-chat-conversations";
|
const STORAGE_KEY = "o1key-chat-conversations";
|
||||||
const DEFAULT_MODEL = "gpt-6-sol";
|
const DEFAULT_MODEL = "claude-opus-5-5";
|
||||||
let conversations = [];
|
let conversations = [];
|
||||||
let activeConvId = null;
|
let activeConvId = null;
|
||||||
let currentModel = DEFAULT_MODEL;
|
let currentModel = DEFAULT_MODEL;
|
||||||
@@ -55,10 +55,11 @@ function truncateFilename(name, maxLen = 20) {
|
|||||||
|
|
||||||
const MODELS = [
|
const MODELS = [
|
||||||
DEFAULT_MODEL,
|
DEFAULT_MODEL,
|
||||||
|
"gpt-6.1-sol",
|
||||||
"gpt-6-astra",
|
"gpt-6-astra",
|
||||||
"gpt-5.6-sol",
|
"gpt-5.6-sol",
|
||||||
"gpt-5.5",
|
|
||||||
"claude-fable-5",
|
"claude-fable-5",
|
||||||
|
"gemini-4-argon",
|
||||||
"gemini-3.1-pro-preview",
|
"gemini-3.1-pro-preview",
|
||||||
"deepseek-v4-pro",
|
"deepseek-v4-pro",
|
||||||
"doubao-seed-2.0-pro",
|
"doubao-seed-2.0-pro",
|
||||||
|
|||||||
@@ -55,6 +55,7 @@ const SEEDANCE_AUTO_PASS_ROUTES = new Set(["国内", "海外", "海外HC", "海
|
|||||||
const SEEDANCE_AUTO_PASS_NODE_TYPES = new Set(["SeedanceAutoPass", "SeedanceAutoPassBatch"]);
|
const SEEDANCE_AUTO_PASS_NODE_TYPES = new Set(["SeedanceAutoPass", "SeedanceAutoPassBatch"]);
|
||||||
const SEEDANCE_ASSET_CREATE_TOGGLES = new Set(["关闭", "打开"]);
|
const SEEDANCE_ASSET_CREATE_TOGGLES = new Set(["关闭", "打开"]);
|
||||||
const SEEDANCE_ASSET_CREATE_MODES = new Set(["标准", "高并发", "HC"]);
|
const SEEDANCE_ASSET_CREATE_MODES = new Set(["标准", "高并发", "HC"]);
|
||||||
|
const SEEDANCE_DRAFT_MODES = new Set(["关闭", "生成样片", "按样片生成"]);
|
||||||
const SEEDANCE_AUTO_PASS_DEFAULT_MODE = "多模态";
|
const SEEDANCE_AUTO_PASS_DEFAULT_MODE = "多模态";
|
||||||
const SEEDANCE_AUTO_PASS_MODE_ALIASES = new Map([
|
const SEEDANCE_AUTO_PASS_MODE_ALIASES = new Map([
|
||||||
["多模态参考生视频", "多模态"],
|
["多模态参考生视频", "多模态"],
|
||||||
@@ -1027,11 +1028,43 @@ const MIGRATIONS = [
|
|||||||
&& REMOVED_NANO_BANANA_RESOLUTIONS.has(wv[4]),
|
&& REMOVED_NANO_BANANA_RESOLUTIONS.has(wv[4]),
|
||||||
apply: (wv) => { wv[4] = "1K"; },
|
apply: (wv) => { wv[4] = "1K"; },
|
||||||
},
|
},
|
||||||
|
{
|
||||||
|
type: "SeedanceAutoPass",
|
||||||
|
note: "将主模型与样片模式移到生成模式之前",
|
||||||
|
when: (wv) => wv.length >= 62
|
||||||
|
&& typeof wv[0] === "string"
|
||||||
|
&& _isSeedanceAutoPassMode(wv[1])
|
||||||
|
&& SEEDANCE_AUTO_PASS_MODELS.has(wv[2]),
|
||||||
|
apply: (wv) => {
|
||||||
|
const hasDraft = wv.length >= 65
|
||||||
|
&& SEEDANCE_DRAFT_MODES.has(wv[wv.length - 2])
|
||||||
|
&& typeof wv[wv.length - 1] === "string";
|
||||||
|
const hasOutputFormat = hasDraft || wv.length >= 63;
|
||||||
|
const draftMode = hasDraft ? wv[wv.length - 2] : "关闭";
|
||||||
|
const draftTaskId = hasDraft ? wv[wv.length - 1] : "";
|
||||||
|
const bodyEnd = hasDraft ? wv.length - 2 : wv.length;
|
||||||
|
const body = wv.slice(3, bodyEnd);
|
||||||
|
const [prompt, mode, model] = wv;
|
||||||
|
wv.splice(
|
||||||
|
0,
|
||||||
|
wv.length,
|
||||||
|
prompt,
|
||||||
|
model,
|
||||||
|
draftMode,
|
||||||
|
mode,
|
||||||
|
...body,
|
||||||
|
...(hasOutputFormat ? [] : ["mp4"]),
|
||||||
|
draftTaskId,
|
||||||
|
);
|
||||||
|
},
|
||||||
|
},
|
||||||
];
|
];
|
||||||
|
|
||||||
function _isSeedanceAutoPassMode(value) {
|
function _isSeedanceAutoPassMode(value) {
|
||||||
return value === "多模态"
|
return value === "多模态"
|
||||||
|| value === "首尾帧"
|
|| value === "首尾帧"
|
||||||
|
|| value === "视频编辑"
|
||||||
|
|| value === "视频延长"
|
||||||
|| value === "多模态参考生视频"
|
|| value === "多模态参考生视频"
|
||||||
|| value === "图生视频-首帧"
|
|| value === "图生视频-首帧"
|
||||||
|| value === "图生视频-首尾帧"
|
|| value === "图生视频-首尾帧"
|
||||||
|
|||||||
@@ -35,9 +35,12 @@ const MODE_OPTIONS = [
|
|||||||
{ value: "first_frame", label: "首帧图生视频", description: "1 张图" },
|
{ value: "first_frame", label: "首帧图生视频", description: "1 张图" },
|
||||||
{ value: "first_last_frame", label: "首尾帧生视频", description: "2 张图" },
|
{ value: "first_last_frame", label: "首尾帧生视频", description: "2 张图" },
|
||||||
{ value: "multimodal", label: "多模态参考", description: "图/视频/音频" },
|
{ value: "multimodal", label: "多模态参考", description: "图/视频/音频" },
|
||||||
|
{ value: "edit", label: "视频编辑", description: "Seedance 2.5" },
|
||||||
|
{ value: "extend", label: "视频延长", description: "Seedance 2.5" },
|
||||||
];
|
];
|
||||||
const ASSET_CREATION_OPTIONS = [
|
const ASSET_CREATION_OPTIONS = [
|
||||||
{ value: "auto", label: "自动创建", description: "直接上传" },
|
{ value: "direct", label: "直接上传", description: "公网 URL" },
|
||||||
|
{ value: "auto", label: "自动创建", description: "创建素材" },
|
||||||
{ value: "manual", label: "手动", description: "填写素材 ID" },
|
{ value: "manual", label: "手动", description: "填写素材 ID" },
|
||||||
];
|
];
|
||||||
const RATIO_OPTIONS = [
|
const RATIO_OPTIONS = [
|
||||||
@@ -51,8 +54,9 @@ const MODEL_CAPS = {
|
|||||||
"seedance-2.0": { maxDuration: 15, resolutions: ["480p", "720p", "1080p", "4k"] },
|
"seedance-2.0": { maxDuration: 15, resolutions: ["480p", "720p", "1080p", "4k"] },
|
||||||
"seedance-2.0-fast": { maxDuration: 15, resolutions: ["480p", "720p"] },
|
"seedance-2.0-fast": { maxDuration: 15, resolutions: ["480p", "720p"] },
|
||||||
"seedance-2.0-mini": { maxDuration: 15, resolutions: ["480p", "720p"] },
|
"seedance-2.0-mini": { maxDuration: 15, resolutions: ["480p", "720p"] },
|
||||||
"seedance-2.5": { maxDuration: 30, resolutions: ["480p", "720p", "1080p", "4k"] },
|
"seedance-2.5": { maxDuration: 30, resolutions: ["480p", "720p", "1080p"] },
|
||||||
};
|
};
|
||||||
|
const VIDEO_ONLY_MODES = new Set(["edit", "extend"]);
|
||||||
|
|
||||||
const CSS = `
|
const CSS = `
|
||||||
.o1vg-panel{
|
.o1vg-panel{
|
||||||
@@ -495,6 +499,8 @@ function makeMultimodalMediaSection(node) {
|
|||||||
{ key: "reference_audios", title: "参考音频", shortTitle: "音频", hint: "节奏与声音参考", accept: "audio/*,.wav,.mp3,.m4a,.aac,.flac,.ogg", kind: "audio", icon: "♫" },
|
{ key: "reference_audios", title: "参考音频", shortTitle: "音频", hint: "节奏与声音参考", accept: "audio/*,.wav,.mp3,.m4a,.aac,.flac,.ogg", kind: "audio", icon: "♫" },
|
||||||
];
|
];
|
||||||
const section = el("section", "o1vg-assets o1vg-multimodal-assets");
|
const section = el("section", "o1vg-assets o1vg-multimodal-assets");
|
||||||
|
// 官方 2.5 的视频编辑/延长接受参考图、参考视频与参考音频,素材区不再按模式裁剪。
|
||||||
|
const visibleSources = () => sources;
|
||||||
const header = el("div", "o1vg-asset-header");
|
const header = el("div", "o1vg-asset-header");
|
||||||
const meta = el("div", "o1vg-asset-meta");
|
const meta = el("div", "o1vg-asset-meta");
|
||||||
const hintElement = el("span", "o1vg-asset-hint");
|
const hintElement = el("span", "o1vg-asset-hint");
|
||||||
@@ -555,8 +561,8 @@ function makeMultimodalMediaSection(node) {
|
|||||||
releaseVideoPreviews(track);
|
releaseVideoPreviews(track);
|
||||||
track.replaceChildren();
|
track.replaceChildren();
|
||||||
const media = ensureMediaState(node);
|
const media = ensureMediaState(node);
|
||||||
hintElement.textContent = sources.map((source) => `${source.shortTitle} ${(media[source.key] || []).length}`).join(" · ");
|
hintElement.textContent = visibleSources().map((source) => `${source.shortTitle} ${(media[source.key] || []).length}`).join(" · ");
|
||||||
for (const source of sources) {
|
for (const source of visibleSources()) {
|
||||||
const values = media[source.key] || [];
|
const values = media[source.key] || [];
|
||||||
values.forEach((item, index) => {
|
values.forEach((item, index) => {
|
||||||
const sortable = values.length > 1;
|
const sortable = values.length > 1;
|
||||||
@@ -762,8 +768,8 @@ async function submitNativeJob(source, targets, request, batchId) {
|
|||||||
function setPanelStatus(node, text = "", kind = "") { if (!node._o1vgStatus) return; node._o1vgStatus.textContent = text; node._o1vgStatus.className = `o1vg-status${text ? " visible" : ""}${kind === "error" ? " error" : ""}`; }
|
function setPanelStatus(node, text = "", kind = "") { if (!node._o1vgStatus) return; node._o1vgStatus.textContent = text; node._o1vgStatus.className = `o1vg-status${text ? " visible" : ""}${kind === "error" ? " error" : ""}`; }
|
||||||
function setPromptWriteStatus(node, text = "", kind = "") { if (!node._o1vgPromptWriteStatus) return; node._o1vgPromptWriteStatus.textContent = text; node._o1vgPromptWriteStatus.className = `o1vg-prompt-write-status${text ? " visible" : ""}${kind ? ` ${kind}` : ""}`; }
|
function setPromptWriteStatus(node, text = "", kind = "") { if (!node._o1vgPromptWriteStatus) return; node._o1vgPromptWriteStatus.textContent = text; node._o1vgPromptWriteStatus.className = `o1vg-prompt-write-status${text ? " visible" : ""}${kind ? ` ${kind}` : ""}`; }
|
||||||
function fitGenerator(node, mode, manualAssets = false) {
|
function fitGenerator(node, mode, manualAssets = false) {
|
||||||
const automaticHeights = { text: 679, first_frame: 824, first_last_frame: 964, multimodal: 824 };
|
const automaticHeights = { text: 679, first_frame: 824, first_last_frame: 964, multimodal: 824, edit: 824, extend: 824 };
|
||||||
const manualHeights = { text: 679, first_frame: 739, first_last_frame: 739, multimodal: 824 };
|
const manualHeights = { text: 679, first_frame: 739, first_last_frame: 739, multimodal: 824, edit: 739, extend: 739 };
|
||||||
const heights = manualAssets ? manualHeights : automaticHeights;
|
const heights = manualAssets ? manualHeights : automaticHeights;
|
||||||
node.setSize([Math.max(560, Number(node.size?.[0]) || 560), heights[mode] || heights.text]);
|
node.setSize([Math.max(560, Number(node.size?.[0]) || 560), heights[mode] || heights.text]);
|
||||||
}
|
}
|
||||||
@@ -805,7 +811,7 @@ function setupGenerator(node) {
|
|||||||
const model = makeSelect(MODEL_OPTIONS, widget(node, "model")?.value || "seedance-2.0", "模型");
|
const model = makeSelect(MODEL_OPTIONS, widget(node, "model")?.value || "seedance-2.0", "模型");
|
||||||
const route = makeSelect(ROUTE_OPTIONS, widget(node, "route")?.value || "domestic", "模型线路");
|
const route = makeSelect(ROUTE_OPTIONS, widget(node, "route")?.value || "domestic", "模型线路");
|
||||||
const mode = makeSelect(MODE_OPTIONS, widget(node, "generation_mode")?.value || "multimodal", "生成模式");
|
const mode = makeSelect(MODE_OPTIONS, widget(node, "generation_mode")?.value || "multimodal", "生成模式");
|
||||||
const assetCreation = makeSelect(ASSET_CREATION_OPTIONS, widget(node, "asset_creation_mode")?.value || "auto", "素材创建");
|
const assetCreation = makeSelect(ASSET_CREATION_OPTIONS, widget(node, "asset_creation_mode")?.value || "direct", "素材创建");
|
||||||
const resolution = makeSelect(["480p", "720p", "1080p", "4k"], widget(node, "resolution")?.value || "720p", "分辨率");
|
const resolution = makeSelect(["480p", "720p", "1080p", "4k"], widget(node, "resolution")?.value || "720p", "分辨率");
|
||||||
const ratio = makeSelect(RATIO_OPTIONS, widget(node, "aspect_ratio")?.value || "auto", "宽高比");
|
const ratio = makeSelect(RATIO_OPTIONS, widget(node, "aspect_ratio")?.value || "auto", "宽高比");
|
||||||
const duration = makeSelect(["auto", ...Array.from({ length: 27 }, (_, index) => ({ value: String(index + 4), label: `${index + 4}秒` }))], widget(node, "duration")?.value || "5", "时长");
|
const duration = makeSelect(["auto", ...Array.from({ length: 27 }, (_, index) => ({ value: String(index + 4), label: `${index + 4}秒` }))], widget(node, "duration")?.value || "5", "时长");
|
||||||
@@ -834,21 +840,33 @@ function setupGenerator(node) {
|
|||||||
const selectedDuration = duration.value === "auto" || Number(duration.value) <= caps.maxDuration ? duration.value : "15";
|
const selectedDuration = duration.value === "auto" || Number(duration.value) <= caps.maxDuration ? duration.value : "15";
|
||||||
if (duration._options.length !== durationOptions.length) setDropdownOptions(duration, durationOptions, selectedDuration);
|
if (duration._options.length !== durationOptions.length) setDropdownOptions(duration, durationOptions, selectedDuration);
|
||||||
const activeMode = mode.value;
|
const activeMode = mode.value;
|
||||||
|
const videoOnly = VIDEO_ONLY_MODES.has(activeMode);
|
||||||
|
if (videoOnly && model.value !== "seedance-2.5") setDropdownValue(mode, "multimodal");
|
||||||
|
const activeModeResolved = mode.value;
|
||||||
|
if (VIDEO_ONLY_MODES.has(activeModeResolved)) {
|
||||||
|
// 2.5 的编辑/延长只支持 adaptive 比例,编辑还要求 -1 时长
|
||||||
|
setDropdownValue(ratio, "auto");
|
||||||
|
if (activeModeResolved === "edit") setDropdownValue(duration, "auto");
|
||||||
|
}
|
||||||
const isSeedance = model.value.startsWith("seedance-");
|
const isSeedance = model.value.startsWith("seedance-");
|
||||||
const assetModeAvailable = isSeedance && activeMode !== "text";
|
const assetModeAvailable = isSeedance && activeModeResolved !== "text";
|
||||||
if (!assetModeAvailable && assetCreation.value !== "auto") setDropdownValue(assetCreation, "auto");
|
if (!assetModeAvailable && assetCreation.value !== "direct") setDropdownValue(assetCreation, "direct");
|
||||||
const manualAssets = assetModeAvailable && assetCreation.value === "manual";
|
const assetMode = assetCreation.value;
|
||||||
|
const manualAssets = assetModeAvailable && assetMode === "manual";
|
||||||
assetCreationField.style.display = isSeedance ? "grid" : "none";
|
assetCreationField.style.display = isSeedance ? "grid" : "none";
|
||||||
assetCreation._trigger.disabled = !assetModeAvailable;
|
assetCreation._trigger.disabled = !assetModeAvailable;
|
||||||
firstSection.style.display = !manualAssets && ["first_frame", "first_last_frame"].includes(activeMode) ? "flex" : "none";
|
ratio._trigger.disabled = VIDEO_ONLY_MODES.has(activeModeResolved);
|
||||||
lastSection.style.display = !manualAssets && activeMode === "first_last_frame" ? "flex" : "none";
|
duration._trigger.disabled = activeModeResolved === "edit";
|
||||||
multimodalSection.style.display = !manualAssets && activeMode === "multimodal" ? "flex" : "none";
|
const showsVideo = activeModeResolved === "multimodal" || VIDEO_ONLY_MODES.has(activeModeResolved);
|
||||||
imageIdField.style.display = manualAssets ? "grid" : "none";
|
firstSection.style.display = !manualAssets && ["first_frame", "first_last_frame"].includes(activeModeResolved) ? "flex" : "none";
|
||||||
videoIdField.style.display = manualAssets && activeMode === "multimodal" ? "grid" : "none";
|
lastSection.style.display = !manualAssets && activeModeResolved === "first_last_frame" ? "flex" : "none";
|
||||||
audioIdField.style.display = manualAssets && activeMode === "multimodal" ? "grid" : "none";
|
multimodalSection.style.display = !manualAssets && showsVideo ? "flex" : "none";
|
||||||
setWidget(node, "prompt", prompt.value); setWidget(node, "model", model.value); setWidget(node, "route", route.value); setWidget(node, "generation_mode", activeMode); setWidget(node, "asset_creation_mode", manualAssets ? "manual" : "auto"); setWidget(node, "resolution", resolution.value); setWidget(node, "aspect_ratio", ratio.value); setWidget(node, "duration", duration.value); setWidget(node, "generate_audio", generateAudio.value === "on"); setWidget(node, "return_last_frame", returnLast.value === "on"); setWidget(node, "seed", Math.max(0, Math.floor(Number(seed.value) || 0))); setWidget(node, "filename_prefix", prefix.value); setWidget(node, "save_location", location.value);
|
imageIdField.style.display = manualAssets && activeModeResolved === "multimodal" ? "grid" : "none";
|
||||||
|
videoIdField.style.display = manualAssets && showsVideo ? "grid" : "none";
|
||||||
|
audioIdField.style.display = manualAssets && activeModeResolved === "multimodal" ? "grid" : "none";
|
||||||
|
setWidget(node, "prompt", prompt.value); setWidget(node, "model", model.value); setWidget(node, "route", route.value); setWidget(node, "generation_mode", activeModeResolved); setWidget(node, "asset_creation_mode", manualAssets ? "manual" : (assetMode === "auto" ? "auto" : "direct")); setWidget(node, "resolution", resolution.value); setWidget(node, "aspect_ratio", ratio.value); setWidget(node, "duration", duration.value); setWidget(node, "generate_audio", generateAudio.value === "on"); setWidget(node, "return_last_frame", returnLast.value === "on"); setWidget(node, "seed", Math.max(0, Math.floor(Number(seed.value) || 0))); setWidget(node, "filename_prefix", prefix.value); setWidget(node, "save_location", location.value);
|
||||||
node.properties.o1keyVideoAssets = { images: imageIds.value, videos: videoIds.value, audios: audioIds.value };
|
node.properties.o1keyVideoAssets = { images: imageIds.value, videos: videoIds.value, audios: audioIds.value };
|
||||||
fitGenerator(node, activeMode, manualAssets); updateNode(node);
|
fitGenerator(node, activeModeResolved, manualAssets); updateNode(node);
|
||||||
};
|
};
|
||||||
const restore = () => {
|
const restore = () => {
|
||||||
const value = (name, fallback) => widget(node, name)?.value ?? fallback;
|
const value = (name, fallback) => widget(node, name)?.value ?? fallback;
|
||||||
@@ -856,7 +874,7 @@ function setupGenerator(node) {
|
|||||||
model.value = value("model", "seedance-2.0");
|
model.value = value("model", "seedance-2.0");
|
||||||
route.value = value("route", "domestic");
|
route.value = value("route", "domestic");
|
||||||
mode.value = value("generation_mode", "multimodal");
|
mode.value = value("generation_mode", "multimodal");
|
||||||
assetCreation.value = value("asset_creation_mode", "auto");
|
assetCreation.value = value("asset_creation_mode", "direct");
|
||||||
resolution.value = value("resolution", "720p");
|
resolution.value = value("resolution", "720p");
|
||||||
ratio.value = value("aspect_ratio", "auto");
|
ratio.value = value("aspect_ratio", "auto");
|
||||||
duration.value = value("duration", "5");
|
duration.value = value("duration", "5");
|
||||||
@@ -941,33 +959,41 @@ function setupGenerator(node) {
|
|||||||
if (node._o1vgWriting) { setPromptWriteStatus(node, "请等待 AI帮写完成", "error"); return; }
|
if (node._o1vgWriting) { setPromptWriteStatus(node, "请等待 AI帮写完成", "error"); return; }
|
||||||
if (node._o1vgUploading) { setPanelStatus(node, "请等待参考素材上传完成", "error"); return; }
|
if (node._o1vgUploading) { setPanelStatus(node, "请等待参考素材上传完成", "error"); return; }
|
||||||
sync(); const media = ensureMediaState(node);
|
sync(); const media = ensureMediaState(node);
|
||||||
|
const videoOnly = VIDEO_ONLY_MODES.has(mode.value);
|
||||||
const manualAssets = mode.value !== "text" && assetCreation.value === "manual";
|
const manualAssets = mode.value !== "text" && assetCreation.value === "manual";
|
||||||
const selectedAssets = {
|
const selectedAssets = {
|
||||||
images: parseIds(imageIds.value),
|
images: parseIds(imageIds.value),
|
||||||
videos: parseIds(videoIds.value),
|
videos: parseIds(videoIds.value),
|
||||||
audios: parseIds(audioIds.value),
|
audios: parseIds(audioIds.value),
|
||||||
};
|
};
|
||||||
|
if (videoOnly && !String(prompt.value || "").trim()) return toast("error", "缺少提示词", "视频编辑和视频延长必须填写提示词");
|
||||||
if (manualAssets && mode.value === "first_frame" && selectedAssets.images.length !== 1) return toast("error", "素材 ID 数量不正确", "首帧图生视频需要填写一个图片素材 ID");
|
if (manualAssets && mode.value === "first_frame" && selectedAssets.images.length !== 1) return toast("error", "素材 ID 数量不正确", "首帧图生视频需要填写一个图片素材 ID");
|
||||||
if (manualAssets && mode.value === "first_last_frame" && selectedAssets.images.length !== 2) return toast("error", "素材 ID 数量不正确", "首尾帧生视频需要填写两个图片素材 ID");
|
if (manualAssets && mode.value === "first_last_frame" && selectedAssets.images.length !== 2) return toast("error", "素材 ID 数量不正确", "首尾帧生视频需要填写两个图片素材 ID");
|
||||||
if (manualAssets && mode.value === "multimodal" && !Object.values(selectedAssets).some((items) => items.length)) return toast("error", "缺少素材 ID", "请至少填写一个图片、视频或音频素材 ID");
|
if (manualAssets && mode.value === "multimodal" && !Object.values(selectedAssets).some((items) => items.length)) return toast("error", "缺少素材 ID", "请至少填写一个图片、视频或音频素材 ID");
|
||||||
|
if (manualAssets && videoOnly && selectedAssets.videos.length !== 1) return toast("error", "素材 ID 数量不正确", "视频编辑和视频延长需要填写一个视频素材 ID");
|
||||||
if (!manualAssets && mode.value === "first_frame" && !media.first_frame) return toast("error", "缺少首帧", "请选择一张首帧图片");
|
if (!manualAssets && mode.value === "first_frame" && !media.first_frame) return toast("error", "缺少首帧", "请选择一张首帧图片");
|
||||||
if (!manualAssets && mode.value === "first_last_frame" && (!media.first_frame || !media.last_frame)) return toast("error", "缺少图片", "请选择首帧和尾帧图片");
|
if (!manualAssets && mode.value === "first_last_frame" && (!media.first_frame || !media.last_frame)) return toast("error", "缺少图片", "请选择首帧和尾帧图片");
|
||||||
|
if (!manualAssets && videoOnly && (media.reference_videos || []).length !== 1) return toast("error", "缺少参考视频", "视频编辑和视频延长需要上传一段参考视频");
|
||||||
const automaticMedia = mode.value === "text"
|
const automaticMedia = mode.value === "text"
|
||||||
? {}
|
? {}
|
||||||
: mode.value === "first_frame"
|
: mode.value === "first_frame"
|
||||||
? { first_frame: media.first_frame }
|
? { first_frame: media.first_frame }
|
||||||
: mode.value === "first_last_frame"
|
: mode.value === "first_last_frame"
|
||||||
? { first_frame: media.first_frame, last_frame: media.last_frame }
|
? { first_frame: media.first_frame, last_frame: media.last_frame }
|
||||||
: { reference_images: media.reference_images || [], reference_videos: media.reference_videos || [], reference_audios: media.reference_audios || [] };
|
: videoOnly
|
||||||
const manualRequestAssets = mode.value === "multimodal"
|
? { reference_videos: media.reference_videos || [] }
|
||||||
? selectedAssets
|
: { reference_images: media.reference_images || [], reference_videos: media.reference_videos || [], reference_audios: media.reference_audios || [] };
|
||||||
: { images: selectedAssets.images, videos: [], audios: [] };
|
const manualRequestAssets = videoOnly
|
||||||
|
? { images: [], videos: selectedAssets.videos, audios: [] }
|
||||||
|
: mode.value === "multimodal"
|
||||||
|
? selectedAssets
|
||||||
|
: { images: selectedAssets.images, videos: [], audios: [] };
|
||||||
const request = {
|
const request = {
|
||||||
provider: "seedance",
|
provider: "seedance",
|
||||||
model: model.value,
|
model: model.value,
|
||||||
route: route.value,
|
route: route.value,
|
||||||
generation_mode: mode.value,
|
generation_mode: mode.value,
|
||||||
asset_creation_mode: manualAssets ? "manual" : "auto",
|
asset_creation_mode: manualAssets ? "manual" : (assetCreation.value === "auto" ? "auto" : "direct"),
|
||||||
prompt: prompt.value,
|
prompt: prompt.value,
|
||||||
resolution: resolution.value,
|
resolution: resolution.value,
|
||||||
aspect_ratio: ratio.value,
|
aspect_ratio: ratio.value,
|
||||||
|
|||||||
@@ -10,13 +10,24 @@ const LIMITED_RESOLUTION_MODELS = new Set([
|
|||||||
"seedance 2.0 fast",
|
"seedance 2.0 fast",
|
||||||
"seedance 2.0 mini",
|
"seedance 2.0 mini",
|
||||||
]);
|
]);
|
||||||
|
const NO_4K_RESOLUTIONS = ["480p", "720p", "1080p"];
|
||||||
const RESOLUTION_FALLBACK = "720p";
|
const RESOLUTION_FALLBACK = "720p";
|
||||||
|
const DRAFT_OFF = "关闭";
|
||||||
|
const DRAFT_PREVIEW = "生成样片";
|
||||||
|
const DRAFT_FINAL = "按样片生成";
|
||||||
|
const DRAFT_PREVIEW_RESOLUTION = "480p";
|
||||||
|
|
||||||
|
function resolutionsForModel(model) {
|
||||||
|
if (LIMITED_RESOLUTION_MODELS.has(model)) return LIMITED_RESOLUTIONS;
|
||||||
|
if (model === MODEL_25) return NO_4K_RESOLUTIONS;
|
||||||
|
return ALL_RESOLUTIONS;
|
||||||
|
}
|
||||||
const ID_WIDGET_GROUPS = [
|
const ID_WIDGET_GROUPS = [
|
||||||
{ prefix: "图片素材ID", maximum: 30 },
|
{ prefix: "图片素材ID", maximum: 30 },
|
||||||
{ prefix: "视频素材ID", maximum: 10 },
|
{ prefix: "视频素材ID", maximum: 10 },
|
||||||
{ prefix: "音频素材ID", maximum: 10 },
|
{ prefix: "音频素材ID", maximum: 10 },
|
||||||
];
|
];
|
||||||
const UNAVAILABLE_WIDGETS = ["联网搜索", "返回末帧图片"];
|
const UNAVAILABLE_WIDGETS = ["联网搜索"];
|
||||||
|
|
||||||
const durationOptions = (maximum) => [
|
const durationOptions = (maximum) => [
|
||||||
"自动",
|
"自动",
|
||||||
@@ -50,23 +61,32 @@ function inputOptions(input) {
|
|||||||
function syncModeInputs(node) {
|
function syncModeInputs(node) {
|
||||||
const state = node.__o1keyAutoPassModeInputs;
|
const state = node.__o1keyAutoPassModeInputs;
|
||||||
if (!state || state.syncing) return;
|
if (!state || state.syncing) return;
|
||||||
const frameMode = findWidget(node, "生成模式")?.value === "首尾帧";
|
const mode = findWidget(node, "生成模式")?.value;
|
||||||
|
const frameMode = mode === "首尾帧";
|
||||||
|
// 按样片生成不再读取任何素材,隐藏全部媒体插座避免误解。
|
||||||
|
const draftFinal = findWidget(node, "样片模式")?.value === DRAFT_FINAL;
|
||||||
const autogrow = node.comfyDynamic.autogrow;
|
const autogrow = node.comfyDynamic.autogrow;
|
||||||
state.syncing = true;
|
state.syncing = true;
|
||||||
try {
|
try {
|
||||||
// Suspend native Autogrow before removing its sockets; otherwise a
|
// 官方 2.5 的视频编辑/延长同样接受参考图和参考音频,只有首尾帧模式需要替换插座。
|
||||||
// disconnect callback can recreate an inactive reference input.
|
|
||||||
for (const group of REFERENCE_GROUPS) {
|
for (const group of REFERENCE_GROUPS) {
|
||||||
if (frameMode) delete autogrow[group];
|
const active = !frameMode && !draftFinal;
|
||||||
else autogrow[group] = state.groups[group];
|
if (active) autogrow[group] = state.groups[group];
|
||||||
|
else delete autogrow[group];
|
||||||
}
|
}
|
||||||
for (let index = node.inputs.length - 1; index >= 0; index--) {
|
for (let index = node.inputs.length - 1; index >= 0; index--) {
|
||||||
const input = node.inputs[index];
|
const input = node.inputs[index];
|
||||||
if (frameMode ? isReferenceInput(input) : FRAME_INPUTS.includes(input.name)) {
|
let removable = false;
|
||||||
node.removeInput(index);
|
if (draftFinal) {
|
||||||
|
removable = isReferenceInput(input) || FRAME_INPUTS.includes(input.name);
|
||||||
|
} else if (frameMode) {
|
||||||
|
removable = isReferenceInput(input);
|
||||||
|
} else {
|
||||||
|
removable = FRAME_INPUTS.includes(input.name);
|
||||||
}
|
}
|
||||||
|
if (removable) node.removeInput(index);
|
||||||
}
|
}
|
||||||
const templates = frameMode ? state.frames : state.references;
|
const templates = draftFinal ? [] : (frameMode ? state.frames : state.references);
|
||||||
for (const template of templates) {
|
for (const template of templates) {
|
||||||
const exists = frameMode
|
const exists = frameMode
|
||||||
? node.inputs.some((input) => input.name === template.name)
|
? node.inputs.some((input) => input.name === template.name)
|
||||||
@@ -107,7 +127,7 @@ function guardModeInputs(node) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// 与 SeedanceMultiModal 相同:保留控件和值的序列化顺序,仅渐进显隐单行 ID。
|
// 与 SeedanceMultiModal 相同:保留控件和值的序列化顺序,仅渐进显隐单行 ID。
|
||||||
function setIdWidgetHidden(widget, hidden) {
|
function setWidgetHidden(widget, hidden) {
|
||||||
if (!widget || (widget.__o1keyAutoPassIdHidden === hidden
|
if (!widget || (widget.__o1keyAutoPassIdHidden === hidden
|
||||||
&& widget.hidden === hidden && widget.options?.hidden === hidden)) return;
|
&& widget.hidden === hidden && widget.options?.hidden === hidden)) return;
|
||||||
widget.__o1keyAutoPassIdHidden = hidden;
|
widget.__o1keyAutoPassIdHidden = hidden;
|
||||||
@@ -129,7 +149,16 @@ function setIdWidgetHidden(widget, hidden) {
|
|||||||
function syncIdWidgets(node) {
|
function syncIdWidgets(node) {
|
||||||
if (node.comfyClass !== "SeedanceAutoPass") return;
|
if (node.comfyClass !== "SeedanceAutoPass") return;
|
||||||
// Temporarily unavailable controls stay serialized for saved workflows.
|
// Temporarily unavailable controls stay serialized for saved workflows.
|
||||||
for (const name of UNAVAILABLE_WIDGETS) setIdWidgetHidden(findWidget(node, name), true);
|
for (const name of UNAVAILABLE_WIDGETS) setWidgetHidden(findWidget(node, name), true);
|
||||||
|
// 样片任务 ID:只有「按样片生成」且没有连线时才需要手填。
|
||||||
|
const draftIdLinked = node.inputs?.some(
|
||||||
|
(input) => input.name === "样片任务ID输入"
|
||||||
|
&& input.link !== null && input.link !== undefined,
|
||||||
|
);
|
||||||
|
setWidgetHidden(
|
||||||
|
findWidget(node, "样片任务ID"),
|
||||||
|
findWidget(node, "样片模式")?.value !== DRAFT_FINAL || Boolean(draftIdLinked),
|
||||||
|
);
|
||||||
const assetMode = findAssetModeWidget(node);
|
const assetMode = findAssetModeWidget(node);
|
||||||
// 该开关自身始终显示,只控制下方 ID 行。
|
// 该开关自身始终显示,只控制下方 ID 行。
|
||||||
if (assetMode) {
|
if (assetMode) {
|
||||||
@@ -145,7 +174,7 @@ function syncIdWidgets(node) {
|
|||||||
if (typeof widget?.value === "string" && widget.value.trim()) highestFilled = index;
|
if (typeof widget?.value === "string" && widget.value.trim()) highestFilled = index;
|
||||||
});
|
});
|
||||||
const visibleCount = manual ? Math.min(maximum, Math.max(1, highestFilled + 2)) : 0;
|
const visibleCount = manual ? Math.min(maximum, Math.max(1, highestFilled + 2)) : 0;
|
||||||
widgets.forEach((widget, index) => setIdWidgetHidden(widget, index >= visibleCount));
|
widgets.forEach((widget, index) => setWidgetHidden(widget, index >= visibleCount));
|
||||||
}
|
}
|
||||||
if (typeof node.computeSize === "function" && typeof node.setSize === "function") {
|
if (typeof node.computeSize === "function" && typeof node.setSize === "function") {
|
||||||
const size = node.computeSize([...node.size]);
|
const size = node.computeSize([...node.size]);
|
||||||
@@ -173,6 +202,18 @@ function guardIdWidgets(node) {
|
|||||||
syncIdWidgets(node);
|
syncIdWidgets(node);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 样片任务 ID 支持连线:连上后隐藏手填框,断开后恢复。
|
||||||
|
function guardDraftIdInput(node) {
|
||||||
|
if (node.comfyClass !== "SeedanceAutoPass" || node.__o1keyDraftIdGuard) return;
|
||||||
|
node.__o1keyDraftIdGuard = true;
|
||||||
|
const originalConnectionsChange = node.onConnectionsChange;
|
||||||
|
node.onConnectionsChange = function () {
|
||||||
|
const result = originalConnectionsChange?.apply(this, arguments);
|
||||||
|
syncIdWidgets(node);
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
function notify(detail) {
|
function notify(detail) {
|
||||||
app.extensionManager?.toast?.add({
|
app.extensionManager?.toast?.add({
|
||||||
severity: "info",
|
severity: "info",
|
||||||
@@ -193,24 +234,45 @@ function updateDynamicParameters(node, silent = false) {
|
|||||||
const routeWidget = findWidget(node, "模型线路");
|
const routeWidget = findWidget(node, "模型线路");
|
||||||
const resolutionWidget = findWidget(node, "分辨率");
|
const resolutionWidget = findWidget(node, "分辨率");
|
||||||
const durationWidget = findWidget(node, "时长");
|
const durationWidget = findWidget(node, "时长");
|
||||||
|
const draftWidget = findWidget(node, "样片模式");
|
||||||
if (!modelWidget || !routeWidget || !resolutionWidget || !durationWidget) return;
|
if (!modelWidget || !routeWidget || !resolutionWidget || !durationWidget) return;
|
||||||
|
|
||||||
const is25 = modelWidget.value === MODEL_25;
|
const is25 = modelWidget.value === MODEL_25;
|
||||||
const hasLimitedResolution = LIMITED_RESOLUTION_MODELS.has(modelWidget.value);
|
|
||||||
|
// 样片模式仅 2.5 可用:其他模型直接隐藏,并强制回到「关闭」。
|
||||||
|
if (draftWidget) {
|
||||||
|
setWidgetHidden(draftWidget, !is25);
|
||||||
|
if (!is25 && draftWidget.value !== DRAFT_OFF) {
|
||||||
|
setWidgetValue(draftWidget, DRAFT_OFF);
|
||||||
|
if (!silent) notify("样片模式仅支持 Seedance 2.5,已关闭样片模式。");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
const draftValue = draftWidget?.value ?? DRAFT_OFF;
|
||||||
|
const draftPreview = draftValue === DRAFT_PREVIEW;
|
||||||
|
|
||||||
|
const allowedResolutions = draftPreview
|
||||||
|
? [DRAFT_PREVIEW_RESOLUTION]
|
||||||
|
: resolutionsForModel(modelWidget.value);
|
||||||
|
const fallbackResolution = draftPreview ? DRAFT_PREVIEW_RESOLUTION : RESOLUTION_FALLBACK;
|
||||||
const maximumDuration = is25 ? 30 : 15;
|
const maximumDuration = is25 ? 30 : 15;
|
||||||
durationWidget.options ??= {};
|
durationWidget.options ??= {};
|
||||||
durationWidget.options.values = is25 ? DURATIONS_25 : DURATIONS_20;
|
durationWidget.options.values = is25 ? DURATIONS_25 : DURATIONS_20;
|
||||||
resolutionWidget.options ??= {};
|
resolutionWidget.options ??= {};
|
||||||
resolutionWidget.options.values = hasLimitedResolution ? LIMITED_RESOLUTIONS : ALL_RESOLUTIONS;
|
resolutionWidget.options.values = allowedResolutions;
|
||||||
|
|
||||||
if (LEGACY_MODEL_ROUTES.has(routeWidget.value)) {
|
if (LEGACY_MODEL_ROUTES.has(routeWidget.value)) {
|
||||||
setWidgetValue(routeWidget, OVERSEAS_ROUTE);
|
setWidgetValue(routeWidget, OVERSEAS_ROUTE);
|
||||||
}
|
}
|
||||||
|
|
||||||
if (hasLimitedResolution && !LIMITED_RESOLUTIONS.includes(resolutionWidget.value)) {
|
if (!allowedResolutions.includes(resolutionWidget.value)) {
|
||||||
setWidgetValue(resolutionWidget, RESOLUTION_FALLBACK);
|
setWidgetValue(resolutionWidget, fallbackResolution);
|
||||||
if (!silent) {
|
if (!silent) {
|
||||||
notify(`${modelWidget.value} 仅支持 480p/720p,已自动切换为 ${RESOLUTION_FALLBACK}。`);
|
notify(
|
||||||
|
draftPreview
|
||||||
|
? "样片模式只输出 480p 预览,已自动切换为 480p。"
|
||||||
|
: `${modelWidget.value} 仅支持 ${allowedResolutions.join(" / ")},`
|
||||||
|
+ `已自动切换为 ${fallbackResolution}。`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -222,6 +284,9 @@ function updateDynamicParameters(node, silent = false) {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// 样片模式/ID 行隐藏后需要重算节点高度。
|
||||||
|
syncIdWidgets(node);
|
||||||
|
|
||||||
node.setDirtyCanvas?.(true, true);
|
node.setDirtyCanvas?.(true, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -254,9 +319,10 @@ function guardNode(node) {
|
|||||||
|
|
||||||
const originalResolutionCallback = resolutionWidget.callback;
|
const originalResolutionCallback = resolutionWidget.callback;
|
||||||
resolutionWidget.callback = function (value) {
|
resolutionWidget.callback = function (value) {
|
||||||
if (LIMITED_RESOLUTION_MODELS.has(modelWidget.value) && !LIMITED_RESOLUTIONS.includes(value)) {
|
const allowedResolutions = resolutionsForModel(modelWidget.value);
|
||||||
|
if (!allowedResolutions.includes(value)) {
|
||||||
resolutionWidget.value = RESOLUTION_FALLBACK;
|
resolutionWidget.value = RESOLUTION_FALLBACK;
|
||||||
notify(`${modelWidget.value} 仅支持 480p/720p。`);
|
notify(`${modelWidget.value} 仅支持 ${allowedResolutions.join(" / ")}。`);
|
||||||
node.setDirtyCanvas?.(true, true);
|
node.setDirtyCanvas?.(true, true);
|
||||||
return originalResolutionCallback?.call(this, RESOLUTION_FALLBACK);
|
return originalResolutionCallback?.call(this, RESOLUTION_FALLBACK);
|
||||||
}
|
}
|
||||||
@@ -277,6 +343,21 @@ function guardNode(node) {
|
|||||||
return originalDurationCallback?.apply(this, arguments);
|
return originalDurationCallback?.apply(this, arguments);
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const draftWidget = findWidget(node, "样片模式");
|
||||||
|
if (draftWidget) {
|
||||||
|
const originalDraftCallback = draftWidget.callback;
|
||||||
|
draftWidget.callback = function () {
|
||||||
|
const result = originalDraftCallback?.apply(this, arguments);
|
||||||
|
updateDynamicParameters(node);
|
||||||
|
syncModeInputs(node);
|
||||||
|
syncIdWidgets(node);
|
||||||
|
if (draftWidget.value === DRAFT_FINAL) {
|
||||||
|
notify("按样片生成只提交样片任务 ID,提示词、素材和参数都会复用样片。");
|
||||||
|
}
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
updateDynamicParameters(node, true);
|
updateDynamicParameters(node, true);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -287,6 +368,7 @@ app.registerExtension({
|
|||||||
if (!NODE_TYPES.has(node.comfyClass)) return;
|
if (!NODE_TYPES.has(node.comfyClass)) return;
|
||||||
guardNode(node);
|
guardNode(node);
|
||||||
guardIdWidgets(node);
|
guardIdWidgets(node);
|
||||||
|
guardDraftIdInput(node);
|
||||||
guardModeInputs(node);
|
guardModeInputs(node);
|
||||||
},
|
},
|
||||||
|
|
||||||
@@ -294,6 +376,7 @@ app.registerExtension({
|
|||||||
if (!NODE_TYPES.has(node.comfyClass)) return;
|
if (!NODE_TYPES.has(node.comfyClass)) return;
|
||||||
updateDynamicParameters(node, true);
|
updateDynamicParameters(node, true);
|
||||||
guardIdWidgets(node);
|
guardIdWidgets(node);
|
||||||
|
guardDraftIdInput(node);
|
||||||
guardModeInputs(node);
|
guardModeInputs(node);
|
||||||
syncModeInputs(node);
|
syncModeInputs(node);
|
||||||
syncIdWidgets(node);
|
syncIdWidgets(node);
|
||||||
|
|||||||
@@ -2,7 +2,7 @@ import { app } from "../../../scripts/app.js";
|
|||||||
|
|
||||||
// ── Seedance 多模态节点参数联动 ───────────────────────────────────────────────
|
// ── Seedance 多模态节点参数联动 ───────────────────────────────────────────────
|
||||||
//
|
//
|
||||||
// fast、mini 不支持 1080p / 4k;2.5 支持全部分辨率和最长 30 秒。
|
// fast、mini 不支持 1080p / 4k;2.5 最高 1080p,且支持最长 30 秒。
|
||||||
// 当用户切换到受限模型,或选择不支持的分辨率时,
|
// 当用户切换到受限模型,或选择不支持的分辨率时,
|
||||||
// 弹 toast 报错并把分辨率回退到 720p,避免提交后才在后端报错浪费一次调用。
|
// 弹 toast 报错并把分辨率回退到 720p,避免提交后才在后端报错浪费一次调用。
|
||||||
//
|
//
|
||||||
@@ -16,7 +16,14 @@ const isLimitedModel = (v) => LIMITED_MODELS.has(v);
|
|||||||
const MODEL_25 = "seedance 2.5";
|
const MODEL_25 = "seedance 2.5";
|
||||||
const ALL_RESOLUTIONS = ["720p", "1080p", "4k", "480p"];
|
const ALL_RESOLUTIONS = ["720p", "1080p", "4k", "480p"];
|
||||||
const LIMITED_RESOLUTIONS = ["720p", "480p"];
|
const LIMITED_RESOLUTIONS = ["720p", "480p"];
|
||||||
|
const NO_4K_RESOLUTIONS = ["720p", "1080p", "480p"];
|
||||||
const RESOLUTION_FALLBACK = "720p";
|
const RESOLUTION_FALLBACK = "720p";
|
||||||
|
|
||||||
|
function resolutionsForModel(model) {
|
||||||
|
if (isLimitedModel(model)) return LIMITED_RESOLUTIONS;
|
||||||
|
if (model === MODEL_25) return NO_4K_RESOLUTIONS;
|
||||||
|
return ALL_RESOLUTIONS;
|
||||||
|
}
|
||||||
const durationOptions = (maximum) => [
|
const durationOptions = (maximum) => [
|
||||||
"自动",
|
"自动",
|
||||||
...Array.from({ length: maximum - 3 }, (_, index) => `${index + 4}秒`),
|
...Array.from({ length: maximum - 3 }, (_, index) => `${index + 4}秒`),
|
||||||
@@ -51,17 +58,20 @@ function updateDynamicParameters(node, silent = false) {
|
|||||||
const durationWidget = findWidget(node, "时长");
|
const durationWidget = findWidget(node, "时长");
|
||||||
if (!modelWidget || !resWidget || !durationWidget) return;
|
if (!modelWidget || !resWidget || !durationWidget) return;
|
||||||
|
|
||||||
const limited = isLimitedModel(modelWidget.value);
|
|
||||||
const maximumDuration = modelWidget.value === MODEL_25 ? 30 : 15;
|
const maximumDuration = modelWidget.value === MODEL_25 ? 30 : 15;
|
||||||
|
const allowedResolutions = resolutionsForModel(modelWidget.value);
|
||||||
resWidget.options ??= {};
|
resWidget.options ??= {};
|
||||||
resWidget.options.values = limited ? LIMITED_RESOLUTIONS : ALL_RESOLUTIONS;
|
resWidget.options.values = allowedResolutions;
|
||||||
durationWidget.options ??= {};
|
durationWidget.options ??= {};
|
||||||
durationWidget.options.values = maximumDuration === 30 ? DURATIONS_25 : DURATIONS_20;
|
durationWidget.options.values = maximumDuration === 30 ? DURATIONS_25 : DURATIONS_20;
|
||||||
|
|
||||||
if (limited && !LIMITED_RESOLUTIONS.includes(resWidget.value)) {
|
if (!allowedResolutions.includes(resWidget.value)) {
|
||||||
setWidgetValue(resWidget, RESOLUTION_FALLBACK);
|
setWidgetValue(resWidget, RESOLUTION_FALLBACK);
|
||||||
if (!silent) {
|
if (!silent) {
|
||||||
notify(`${modelWidget.value} 仅支持 480p/720p,已自动切换为 ${RESOLUTION_FALLBACK}。`);
|
notify(
|
||||||
|
`${modelWidget.value} 仅支持 ${allowedResolutions.join(" / ")},`
|
||||||
|
+ `已自动切换为 ${RESOLUTION_FALLBACK}。`,
|
||||||
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -94,9 +104,10 @@ function guardNode(node) {
|
|||||||
|
|
||||||
const origResCb = resWidget.callback;
|
const origResCb = resWidget.callback;
|
||||||
resWidget.callback = function (value) {
|
resWidget.callback = function (value) {
|
||||||
if (isLimitedModel(modelWidget.value) && !LIMITED_RESOLUTIONS.includes(value)) {
|
const allowedResolutions = resolutionsForModel(modelWidget.value);
|
||||||
|
if (!allowedResolutions.includes(value)) {
|
||||||
resWidget.value = RESOLUTION_FALLBACK;
|
resWidget.value = RESOLUTION_FALLBACK;
|
||||||
notify(`${modelWidget.value} 仅支持 480p/720p。`);
|
notify(`${modelWidget.value} 仅支持 ${allowedResolutions.join(" / ")}。`);
|
||||||
node.setDirtyCanvas?.(true, true);
|
node.setDirtyCanvas?.(true, true);
|
||||||
return origResCb?.call(this, RESOLUTION_FALLBACK);
|
return origResCb?.call(this, RESOLUTION_FALLBACK);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user