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:
+322
-60
@@ -24,10 +24,11 @@ from ..clients.seedance_element_client import SeedanceElementClient
|
||||
from ..utils.config import get_base_url_by_route
|
||||
from ..utils.r2_uploader import upload_image, upload_video, upload_audio
|
||||
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 (
|
||||
SEEDANCE_CAPABILITIES,
|
||||
SEEDANCE_MODEL_MATRIX,
|
||||
SEEDANCE_REFERENCE_AUDIO_EXTENSIONS,
|
||||
SEEDANCE_REFERENCE_AUDIO_MAX_BYTES,
|
||||
SEEDANCE_REFERENCE_IMAGE_MAX_BYTES,
|
||||
SEEDANCE_REFERENCE_VIDEO_MAX_BYTES,
|
||||
@@ -35,6 +36,7 @@ from ..utils.o1key_video_catalog import (
|
||||
resolve_seedance_model,
|
||||
validate_seedance_media_counts,
|
||||
validate_seedance_reference_dimensions,
|
||||
validate_seedance_reference_durations,
|
||||
)
|
||||
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"]
|
||||
# 全能生成视频节点把最新的 2.5 放在模型选择最上方。
|
||||
_AUTOPASS_BASE_MODELS = ["seedance 2.5", "seedance 2.0", "seedance 2.0 fast", "seedance 2.0 mini"]
|
||||
_MODEL_ROUTES = ["海外", "国内"]
|
||||
_LEGACY_MODEL_ROUTES = {
|
||||
"海外HC": "海外",
|
||||
@@ -126,7 +130,14 @@ _GENERATION_MODES = [
|
||||
]
|
||||
_UI_MODE_MULTIMODAL = "多模态"
|
||||
_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 = {
|
||||
_MODE_MULTIMODAL: "multimodal",
|
||||
_MODE_FIRST_FRAME: "first_frame",
|
||||
@@ -134,11 +145,20 @@ _CANONICAL_GENERATION_MODES = {
|
||||
_MODE_TEXT: "text",
|
||||
_UI_MODE_MULTIMODAL: "multimodal",
|
||||
_UI_MODE_FIRST_LAST: "first_last_frame",
|
||||
_UI_MODE_EDIT: "edit",
|
||||
_UI_MODE_EXTEND: "extend",
|
||||
}
|
||||
|
||||
_ASSET_MODE_AUTO = "关闭"
|
||||
_ASSET_MODE_MANUAL = "打开"
|
||||
_ASSET_MODES = [_ASSET_MODE_AUTO, _ASSET_MODE_MANUAL]
|
||||
_ASSET_MODE_DIRECT = "关闭"
|
||||
_ASSET_MODE_AUTO = "自动创建"
|
||||
_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"}
|
||||
_FAILURE_STATUSES = {"failed", "fail", "failure", "error", "expired", "cancelled", "canceled"}
|
||||
@@ -152,17 +172,23 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
return io.Schema(
|
||||
node_id="SeedanceAutoPass",
|
||||
display_name="Seedance 全能生成视频",
|
||||
description="支持多模态(含文生视频)和首尾帧(尾帧可选)两种生成模式。",
|
||||
description="支持多模态(含文生视频)、首尾帧、视频编辑与视频延长;视频编辑/延长以一段参考视频为底片,可附带参考图和参考音频;2.5 支持样片模式(480p 预览 → 1080p 成片)。",
|
||||
category="comfyui_o1key/Seedance",
|
||||
inputs=[
|
||||
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(
|
||||
"生成模式",
|
||||
options=_UI_GENERATION_MODES,
|
||||
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=_RESOLUTIONS, default="720p"),
|
||||
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.String.Input(
|
||||
"样片任务ID输入",
|
||||
display_name="样片任务ID(连线)",
|
||||
optional=True,
|
||||
force_input=True,
|
||||
tooltip="接入上一步输出的「样片任务ID」;连线优先于下方手填值。",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"素材创建模式",
|
||||
options=_ASSET_MODES,
|
||||
default=_ASSET_MODE_AUTO,
|
||||
tooltip="关闭:隐藏素材 ID 并自动创建连接的素材;打开:显示并使用已有素材 ID。",
|
||||
default=_ASSET_MODE_DIRECT,
|
||||
tooltip="关闭:直接上传并以公网 URL 提交;自动创建:按线路创建素材后提交;手动:使用下方素材 ID。",
|
||||
),
|
||||
*[
|
||||
io.String.Input(f"{prefix}{index}", default="", tooltip="手动模式使用;填写一个 Asset ID。")
|
||||
@@ -223,16 +256,29 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
default=0,
|
||||
min=0,
|
||||
max=0xffffffffffffffff,
|
||||
tooltip="仅用于触发重新执行,不会发送给接口;种子由 Seedance 自行生成。",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"返回末帧图片",
|
||||
options=["关闭", "打开"],
|
||||
default="关闭",
|
||||
),
|
||||
io.Combo.Input(
|
||||
"输出格式",
|
||||
options=["mp4", "mov"],
|
||||
default="mp4",
|
||||
tooltip="Seedance 2.5 专用;mov 更适合需要保留音画连续的延长任务。",
|
||||
),
|
||||
io.String.Input(
|
||||
"样片任务ID",
|
||||
default="",
|
||||
tooltip="按样片生成时填写 7 天内的样片任务 ID;可直接粘贴上一个节点输出的「样片任务ID」。",
|
||||
),
|
||||
],
|
||||
outputs=[
|
||||
io.Video.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):
|
||||
"""读取素材创建分支;旧工作流没有该控件时默认自动创建。"""
|
||||
|
||||
asset_inputs = kwargs.get("素材创建模式", kwargs.get("素材创建", _ASSET_MODE_AUTO))
|
||||
asset_inputs = kwargs.get("素材创建模式", kwargs.get("素材创建", _ASSET_MODE_DIRECT))
|
||||
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
|
||||
else:
|
||||
mode = asset_inputs
|
||||
inputs = kwargs
|
||||
if mode in {"manual", "手动", _ASSET_MODE_MANUAL}:
|
||||
if mode in {"manual", "打开", _ASSET_MODE_MANUAL}:
|
||||
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
|
||||
def _parse_asset_ids(value):
|
||||
@@ -311,9 +359,15 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
return "first_last_frame"
|
||||
if generation_mode in {_UI_MODE_FIRST_LAST}:
|
||||
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}:
|
||||
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
|
||||
raise ValueError(f"不支持的生成模式:{generation_mode}")
|
||||
|
||||
@@ -339,6 +393,15 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
raise ValueError("文生视频模式下提示词不能为空")
|
||||
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 generation_mode == _MODE_FIRST_FRAME and len(ref_images) != 1:
|
||||
raise ValueError("图生视频-首帧模式必须提供首帧图片")
|
||||
@@ -354,6 +417,8 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
raise ValueError("多模态模式下,提示词和参考素材不能同时为空")
|
||||
if base_model != "seedance 2.5" and ref_audios and not (ref_images or ref_videos):
|
||||
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
|
||||
|
||||
@staticmethod
|
||||
@@ -404,7 +469,6 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
duration_s,
|
||||
gen_audio,
|
||||
return_last,
|
||||
seed,
|
||||
asset_creation_mode="auto",
|
||||
):
|
||||
"""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_route = _CANONICAL_ROUTES[route]
|
||||
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]
|
||||
except KeyError as exc:
|
||||
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("秒"),
|
||||
"generate_audio": gen_audio,
|
||||
"return_last_frame": return_last,
|
||||
"seed": seed,
|
||||
})
|
||||
|
||||
@classmethod
|
||||
async def execute(cls, **kwargs):
|
||||
generation_mode, mode_inputs = cls._mode_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
|
||||
auto_assets = asset_mode == _ASSET_MODE_AUTO
|
||||
prompt = (kwargs.get("提示词", mode_inputs.get("提示词", "")) or "").strip()
|
||||
base_model = kwargs["主模型"]
|
||||
model_route = _normalize_model_route(kwargs["模型线路"])
|
||||
model = _resolve_model_matrix(base_model, model_route)
|
||||
resolution = kwargs["分辨率"]
|
||||
if draft_mode == _DRAFT_GENERATE:
|
||||
# 官方样片只允许 480p 预览,其他分辨率会直接报错。
|
||||
resolution = "480p"
|
||||
ratio = kwargs["宽高比"]
|
||||
duration_s = kwargs["时长"]
|
||||
gen_audio = kwargs["生成音频"] == "打开"
|
||||
web_search = kwargs.get("联网搜索", mode_inputs.get("联网搜索", "关闭")) == "打开"
|
||||
return_last = kwargs.get("返回末帧图片", "关闭") == "打开"
|
||||
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}:
|
||||
ref_images = cls._autogrow_values(mode_inputs, "参考图片", "参考图片", 30)
|
||||
ref_videos = 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}:
|
||||
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]
|
||||
elif generation_mode in {_UI_MODE_EDIT, _UI_MODE_EXTEND, _MODE_FIRST_FRAME, _MODE_FIRST_LAST, _UI_MODE_FIRST_LAST}:
|
||||
ref_images = []
|
||||
ref_videos = []
|
||||
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:
|
||||
ref_images = []
|
||||
ref_videos = []
|
||||
ref_audios = []
|
||||
|
||||
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:
|
||||
image_urls = cls._manual_asset_ids(asset_inputs, "图片素材ID", 30)
|
||||
video_urls = cls._manual_asset_ids(asset_inputs, "视频素材ID", 10)
|
||||
@@ -508,36 +616,46 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
duration_s,
|
||||
gen_audio,
|
||||
return_last,
|
||||
seed,
|
||||
"manual" if manual_assets else "auto",
|
||||
"manual" if manual_assets else ("auto" if auto_assets else "direct"),
|
||||
)
|
||||
if not manual_assets:
|
||||
cls._validate_reference_media(ref_images, ref_videos, ref_audios)
|
||||
|
||||
base_url = get_base_url_by_route()
|
||||
cls._validate_reference_media(base_model, ref_images, ref_videos, ref_audios)
|
||||
|
||||
if not manual_assets:
|
||||
image_urls, video_urls, audio_urls = await cls._create_assets(
|
||||
ref_images, ref_videos, ref_audios, base_url, create_mode
|
||||
)
|
||||
if auto_assets:
|
||||
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(
|
||||
model, prompt, resolution, ratio, duration_s,
|
||||
gen_audio, web_search, seed,
|
||||
model, prompt, resolution, normalized["aspect_ratio"], normalized["duration"],
|
||||
gen_audio, web_search,
|
||||
image_urls, video_urls, audio_urls,
|
||||
use_asset_protocol=True,
|
||||
generation_mode=canonical_mode,
|
||||
return_last_frame=normalized["return_last_frame"],
|
||||
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)
|
||||
print("[Seedance自动过审] ── 提交请求体 ─────────────────")
|
||||
print(f"[Seedance自动过审] POST {base_url}/v1/video/generations")
|
||||
print(pretty)
|
||||
if draft_mode == _DRAFT_GENERATE:
|
||||
body["draft"] = True
|
||||
|
||||
cls._print_request(base_url, body)
|
||||
|
||||
captured = {}
|
||||
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:
|
||||
message = format_seedance_generation_error(exc)
|
||||
if message == str(exc):
|
||||
@@ -546,16 +664,89 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
last_frame = None
|
||||
if return_last and 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
|
||||
def _build_body(model, prompt, resolution, ratio, duration_s,
|
||||
gen_audio, web_search, seed,
|
||||
gen_audio, web_search,
|
||||
image_urls, video_urls, audio_urls,
|
||||
use_asset_protocol=False,
|
||||
generation_mode=_MODE_MULTIMODAL,
|
||||
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(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"
|
||||
frame_mode = canonical_mode in {"first_frame", "first_last_frame"}
|
||||
prepared = {
|
||||
"first_frame": None if manual_assets else (image_urls[0] if image_urls else None),
|
||||
"last_frame": None if manual_assets else (image_urls[1] if len(image_urls) > 1 else None),
|
||||
"first_frame": (
|
||||
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": (
|
||||
[] 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_audios": [] if manual_assets else list(audio_urls),
|
||||
@@ -596,11 +803,11 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
"aspect_ratio": "auto" if ratio == "智能" else ratio,
|
||||
"generate_audio": bool(gen_audio),
|
||||
"return_last_frame": bool(return_last_frame),
|
||||
"seed": int(seed),
|
||||
"output_format": output_format,
|
||||
}, prepared)
|
||||
|
||||
@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 视频生成."""
|
||||
|
||||
file_handle, save_path = tempfile.mkstemp(
|
||||
@@ -610,12 +817,17 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
os.close(file_handle)
|
||||
client = SeedanceClient()
|
||||
client.base_url = base_url
|
||||
try:
|
||||
return await client.generate_async(
|
||||
body=body,
|
||||
save_path=save_path,
|
||||
use_new_format=True,
|
||||
call_kwargs = {
|
||||
"body": body,
|
||||
"save_path": save_path,
|
||||
"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:
|
||||
try:
|
||||
if os.path.isfile(save_path):
|
||||
@@ -702,7 +914,7 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
raise ValueError(f"无法读取{label}文件")
|
||||
|
||||
@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."""
|
||||
|
||||
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:
|
||||
raise ValueError(f"{label}文件大小必须在 1 字节到 30MB 之间")
|
||||
|
||||
video_seconds = []
|
||||
for index, video in enumerate(ref_videos, start=1):
|
||||
label = f"参考视频{index}"
|
||||
source = cls._video_source(video)
|
||||
size = cls._stream_size(source, label)
|
||||
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)):
|
||||
extension = os.path.splitext(os.fspath(source))[1].lower()
|
||||
if extension not in {".mp4", ".mov"}:
|
||||
raise ValueError(f"{label}格式须为 mp4 或 mov")
|
||||
seconds = None
|
||||
try:
|
||||
if hasattr(video, "get_dimensions"):
|
||||
width, height = video.get_dimensions()
|
||||
if hasattr(video, "get_duration"):
|
||||
seconds = float(video.get_duration())
|
||||
else:
|
||||
import av
|
||||
|
||||
@@ -742,6 +958,8 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
if stream is None:
|
||||
raise ValueError
|
||||
width, height = stream.width, stream.height
|
||||
if container.duration is not None:
|
||||
seconds = float(container.duration) / 1_000_000
|
||||
except Exception:
|
||||
raise ValueError(f"{label}不是可读取的视频") from None
|
||||
finally:
|
||||
@@ -753,15 +971,18 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
label,
|
||||
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):
|
||||
label = f"参考音频{index}"
|
||||
if isinstance(audio, (str, os.PathLike)):
|
||||
extension = os.path.splitext(os.fspath(audio))[1].lower()
|
||||
if extension not in supported_audio:
|
||||
raise ValueError(f"{label}格式须为 wav/mp3/m4a/aac/flac/ogg")
|
||||
if extension not in SEEDANCE_REFERENCE_AUDIO_EXTENSIONS:
|
||||
raise ValueError(f"{label}格式须为 wav 或 mp3")
|
||||
size = cls._stream_size(audio, label)
|
||||
seconds = cls._media_seconds(audio)
|
||||
elif isinstance(audio, dict) and audio.get("waveform") is not None:
|
||||
waveform = audio["waveform"]
|
||||
try:
|
||||
@@ -769,10 +990,35 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
except Exception:
|
||||
raise ValueError(f"{label}无法读取") from None
|
||||
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:
|
||||
raise ValueError(f"{label}无法读取")
|
||||
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
|
||||
async def _url_to_tensor(url):
|
||||
@@ -854,6 +1100,22 @@ class SeedanceAutoPass(io.ComfyNode):
|
||||
if not str(uploaded_url).startswith("https://"):
|
||||
raise ValueError(f"参考{label}上传后未获得 HTTPS 公网地址")
|
||||
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(
|
||||
name=name,
|
||||
asset_url=uploaded_url,
|
||||
|
||||
Reference in New Issue
Block a user