Kling 节点接入官方 4.0 / Flash(文生/图生/Omni)

This commit is contained in:
Jony
2026-11-10 12:50:52 +08:00
parent b4ddd35a6c
commit af300996b9
8 changed files with 974 additions and 179 deletions
+1 -1
View File
@@ -247,7 +247,7 @@ Nano Banana 与 GPT Image 2 的最终 UTF-8 JSON 请求体(含 Base64)都按
### K 视频生成 / Kling 4.0 ### K 视频生成 / Kling 4.0
`K 视频生成` 保留原有 `K3Video` 节点 ID,并在模型下拉框追加 `v4`。选择 `v4` 后显示“文生视频 / 关键帧 / 全能参考”生成模式:文生只提交提示词;关键帧使用首帧,可再连接最多 8 张中间帧和 1 张尾帧;全能参考使用最多 10 张参考图和 5 段参考视频。Kling 4.0 支持 3~30 秒、720p/1080p,以及智能、16:9、9:16、1:1、21:9 宽高比;关键帧模式按首帧比例提交,原生音频由 Kling 4.0 默认生成。素材会先上传到当前 O1Key 线路,再通过对应的 Kling `/text2video`、`/image2video` 或 `/omni-video` 任务接口提交、轮询和下载。旧 v3、v2.6 和 v3-omni 分支的输入顺序与请求行为保持兼容。 `K 视频生成` 保留原有 `K3Video` 节点 ID。模型下拉框在原有 v3 / v2.6 / v3-omni 之后追加 `Kling 4.0` 与 `Kling 4.0 Flash`(内部取值仍为 `v4` / `v4-flash`,旧工作流里的 `v4` 可继续使用)。选择后显示“文生视频 / 关键帧 / 全能参考”:文生只提交提示词;关键帧至少一张关键帧,可再连接最多 8 张中间帧和 1 张尾帧;全能参考使用最多 10 张参考图和 5 段参考视频。4.0 支持 3~30 秒、720p/1080p(默认 1080p);Flash 请求体与 4.0 相同,只换路径,时长 3~20 秒且仅 720p(默认 720p)。文生宽高比为 21:9、16:9、9:16、1:1(默认 16:9,界面中的“智能”按 16:9 提交);全能参考另支持 adaptive(界面“智能”按 adaptive 提交);图生视频不传宽高比。素材先上传到当前 O1Key 线路,再经官方路径 `/kling/text-to-video/kling-4.0`、`/kling/image-to-video/kling-4.0`、`/kling/omni-video/kling-4.0`(Flash 把 `kling-4.0` 换成 `kling-4.0-flash`)提交,并用 4.0 的 `{code, message, request_id, data}` 响应轮询 `data[].outputs[].url`。请求体不传 `model`。旧 v3、v2.6 和 v3-omni 分支的输入顺序与请求行为保持兼容。动作模仿节点仍只走 3.0,没有 4.0 路径。
### 视频裁剪 ### 视频裁剪
+334 -68
View File
@@ -1,13 +1,15 @@
"""Kling 4.0 request helpers. """Kling 4.0 / Flash request helpers and official result parsers.
The released K video node still owns the HTTP task lifecycle. This module The released K video node still owns the HTTP task lifecycle. This module
keeps the Kling 4.0 capability matrix and request shape in one testable place keeps the official Kling 4.0 and Kling 4.0 Flash capability matrix, request
so the node only has to upload media and call the existing poll/download shape, and query envelope in one testable place. The model is selected by
pipeline. path; request bodies must not include a `model` field.
""" """
from __future__ import annotations from __future__ import annotations
from typing import Any
KlingV4GenerationMode = str KlingV4GenerationMode = str
@@ -17,14 +19,53 @@ GENERATION_MODES = {
"omni": "全能参考", "omni": "全能参考",
} }
ENDPOINTS = { _MODEL_SPECS = {
"text": ("/kling/v1/videos/text2video", "/kling/v1/videos/text2video/{task_id}"), "v4": {
"keyframes": ("/kling/v1/videos/image2video", "/kling/v1/videos/image2video/{task_id}"), "id": "v4",
"omni": ("/kling/v1/videos/omni-video", "/kling/v1/videos/omni-video/{task_id}"), "slug": "kling-4.0",
"display_name": "Kling 4.0",
"min_duration": 3,
"max_duration": 30,
"resolutions": ("720p", "1080p"),
"default_resolution": "1080p",
},
"v4-flash": {
"id": "v4-flash",
"slug": "kling-4.0-flash",
"display_name": "Kling 4.0 Flash",
"min_duration": 3,
"max_duration": 20,
"resolutions": ("720p",),
"default_resolution": "720p",
},
} }
_RESOLUTION_MODE = {"720p": "std", "1080p": "pro"} _MODEL_ALIASES = {
_ASPECT_RATIOS = {"智能", "16:9", "9:16", "1:1", "21:9"} "v4": "v4",
"kling-4.0": "v4",
"kling 4.0": "v4",
"kling-v4": "v4",
"v4-flash": "v4-flash",
"kling-4.0-flash": "v4-flash",
"kling 4.0 flash": "v4-flash",
}
# Display names are registered as aliases so either the wire id or the label works.
_MODEL_ALIASES.update({spec["display_name"].lower(): model_id for model_id, spec in _MODEL_SPECS.items()})
_ENDPOINT_TEMPLATES = {
"text": "/kling/text-to-video/{slug}",
"keyframes": "/kling/image-to-video/{slug}",
"omni": "/kling/omni-video/{slug}",
}
_TEXT_ASPECT_RATIOS = {"16:9", "9:16", "1:1", "21:9"}
_OMNI_ASPECT_RATIOS = _TEXT_ASPECT_RATIOS | {"adaptive"}
_AUDIO_VALUES = {"native", "original"}
_SUCCESS_STATUSES = {"succeeded"}
_FAILURE_STATUSES = {"failed"}
_PROMPT_ENGLISH_LIMIT = 26000
_PROMPT_NON_ENGLISH_LIMIT = 11000
def canonical_generation_mode(value: str) -> str: def canonical_generation_mode(value: str) -> str:
@@ -38,43 +79,239 @@ def canonical_generation_mode(value: str) -> str:
raise ValueError(f"不支持的 Kling 4.0 生成模式:{value}") raise ValueError(f"不支持的 Kling 4.0 生成模式:{value}")
def canonical_kling_v4_model(value: str) -> str:
"""Return the wire id (`v4` or `v4-flash`) for a displayed or stored model."""
raw = str(value or "").strip()
if not raw:
raise ValueError("未指定 Kling 4.0 模型")
if raw in _MODEL_SPECS:
return raw
mapped = _MODEL_ALIASES.get(raw.lower())
if mapped:
return mapped
raise ValueError(f"不支持的 Kling 4.0 模型:{value}")
def is_kling_v4_model(value: str) -> bool:
"""Return True when the value is a Kling 4.0 or Flash model selector."""
try:
canonical_kling_v4_model(value)
return True
except ValueError:
return False
def kling_v4_model_spec(value: str) -> dict:
"""Return the capability record for a Kling 4.0 or Flash model."""
return dict(_MODEL_SPECS[canonical_kling_v4_model(value)])
def endpoint_for(generation_mode: str, model: str = "v4") -> tuple[str, str]:
"""Return official create/status paths for a mode and model."""
spec = kling_v4_model_spec(model)
create_path = _ENDPOINT_TEMPLATES[canonical_generation_mode(generation_mode)].format(
slug=spec["slug"]
)
return create_path, f"{create_path}/{{task_id}}"
def validate_kling_v4_prompt(text: str, *, label: str = "提示词") -> str:
"""Validate official English/non-English prompt length mixing rules."""
prompt = str(text or "")
if not prompt.strip():
raise ValueError(f"{label}不能为空")
english = sum(1 for char in prompt if ord(char) < 128)
non_english = len(prompt) - english
if (english / _PROMPT_ENGLISH_LIMIT) + (non_english / _PROMPT_NON_ENGLISH_LIMIT) > 1:
raise ValueError(
f"{label}超出官方长度限制:纯英文最多 {_PROMPT_ENGLISH_LIMIT} 字符,"
f"纯非英文最多 {_PROMPT_NON_ENGLISH_LIMIT} 字符,混合须满足 "
f"E/{_PROMPT_ENGLISH_LIMIT} + N/{_PROMPT_NON_ENGLISH_LIMIT} ≤ 1"
)
return prompt
def _as_dict(value: Any) -> dict[str, Any]:
return value if isinstance(value, dict) else {}
def _task_entries(payload: Any) -> list[dict[str, Any]]:
root = _as_dict(payload)
data = root.get("data")
if isinstance(data, list):
return [_as_dict(item) for item in data]
if isinstance(data, dict):
result = data.get("result")
if isinstance(result, list):
return [_as_dict(item) for item in result]
return [data]
return []
def extract_kling_v4_task_id(payload: Any) -> str | None:
"""Return `data.id` from an official create envelope."""
for task in _task_entries(payload):
task_id = task.get("id")
if task_id:
return str(task_id)
return None
def extract_kling_v4_status(payload: Any) -> str:
"""Return the official lowercase task status from a 4.0/Flash query."""
root = _as_dict(payload)
if root.get("code") not in (None, 0, "0"):
return "failed"
for task in _task_entries(payload):
status = str(task.get("status") or "").strip().lower()
if status:
return status
return ""
def extract_kling_v4_error_message(payload: Any, default: str = "未知错误") -> str:
"""Return the official failure message without falling back to 3.0 fields."""
root = _as_dict(payload)
if root.get("code") not in (None, 0, "0"):
message = root.get("message") or root.get("msg")
if message:
return str(message)
for task in _task_entries(payload):
message = task.get("message") or task.get("msg")
if message:
return str(message)
message = root.get("message") or root.get("msg")
return str(message) if message else default
def extract_kling_v4_video_url(payload: Any) -> str | None:
"""Return `data[].outputs[].url` from an official succeeded task."""
for task in _task_entries(payload):
outputs = task.get("outputs")
if not isinstance(outputs, list):
continue
for item in outputs:
item = _as_dict(item)
url = item.get("url")
if url:
return str(url)
return None
def is_kling_v4_success_status(status: str) -> bool:
return str(status or "").strip().lower() in _SUCCESS_STATUSES
def is_kling_v4_failure_status(status: str, payload: Any | None = None) -> bool:
if str(status or "").strip().lower() in _FAILURE_STATUSES:
return True
if payload is None:
return False
root = _as_dict(payload)
return root.get("code") not in (None, 0, "0")
def _normalize_aspect_ratio(mode: str, aspect_ratio: str) -> str | None:
raw = str(aspect_ratio or "").strip()
if raw in {"智能", "adaptive"}:
raw = "adaptive"
if mode == "keyframes":
return None
if mode == "text":
if raw in {"", "adaptive"}:
return "16:9"
if raw not in _TEXT_ASPECT_RATIOS:
raise ValueError(f"Kling 4.0 文生视频不支持宽高比:{aspect_ratio}")
return raw
if raw in {"", "adaptive"}:
return "adaptive"
if raw not in _OMNI_ASPECT_RATIOS:
raise ValueError(f"Kling 4.0 全能参考不支持宽高比:{aspect_ratio}")
return raw
def _normalize_audio(audio: str) -> str:
raw = str(audio or "").strip().lower()
aliases = {
"native": "native",
"原始生成": "native",
"原生音频": "native",
"否": "native",
"original": "original",
"保留原声": "original",
"保留视频原声": "original",
"是": "original",
}
mapped = aliases.get(raw, raw)
if mapped not in _AUDIO_VALUES:
raise ValueError(f"Kling 4.0 不支持音频选项:{audio}")
return mapped
def _content_id(prefix: str, index: int) -> str:
return f"{prefix}_{index}"
def build_kling_v4_body( def build_kling_v4_body(
*, *,
generation_mode: str, generation_mode: str,
prompt: str, prompt: str,
model: str = "v4",
negative_prompt: str = "", negative_prompt: str = "",
duration: int = 5, duration: int | None = None,
resolution: str = "720p", resolution: str | None = None,
aspect_ratio: str = "智能", aspect_ratio: str = "智能",
first_frame: str | None = None, first_frame: str | None = None,
middle_frames: list[str] | None = None, middle_frames: list[str] | None = None,
last_frame: str | None = None, last_frame: str | None = None,
reference_images: list[str] | None = None, reference_images: list[str] | None = None,
reference_videos: list[str] | None = None, reference_videos: list[str] | None = None,
keep_original_sound: bool = False, video_reference_type: str = "特征参考",
audio: str = "native",
watermark_enabled: bool = False,
) -> dict: ) -> dict:
"""Build a Kling 4.0 proxy request without credentials or media bytes. """Build an official Kling 4.0 / Flash request body.
The proxy accepts the legacy Kling envelope (`model_name`, `mode`, and The body uses `contents` / `settings` / `options` and never includes `model`.
`metadata`) and maps the metadata fields to the official Kling 4.0 Keyframes cannot send `settings.aspect_ratio` or `settings.audio`. Flash
contents/settings representation. Keyframes and Omni references are only accepts `720p` and 3–20 second durations.
mutually exclusive at the provider boundary.
""" """
mode = canonical_generation_mode(generation_mode) mode = canonical_generation_mode(generation_mode)
prompt = str(prompt or "").strip() spec = kling_v4_model_spec(model)
if not prompt: prompt_text = str(prompt or "").strip()
raise ValueError("Kling 4.0 生成模式下提示词不能为空") negative = str(negative_prompt or "").strip()
if resolution not in _RESOLUTION_MODE: if negative:
raise ValueError("Kling 4.0 仅支持 720p 或 1080p") prompt_text = f"{prompt_text}\n负向:{negative}" if prompt_text else f"负向:{negative}"
prompt_text = validate_kling_v4_prompt(prompt_text)
if resolution in (None, ""):
resolution = spec["default_resolution"]
if resolution not in spec["resolutions"]:
allowed = " 或 ".join(spec["resolutions"])
raise ValueError(f"{spec['display_name']} 仅支持 {allowed}")
settings: dict[str, Any] = {"resolution": resolution}
if duration is not None and duration != "":
try: try:
duration = int(duration) duration = int(duration)
except (TypeError, ValueError): except (TypeError, ValueError):
raise ValueError("Kling 4.0 时长必须是整数秒") from None raise ValueError(f"{spec['display_name']} 时长必须是整数秒") from None
if duration < 3 or duration > 30: if duration < spec["min_duration"] or duration > spec["max_duration"]:
raise ValueError("Kling 4.0 时长必须在 3~30 秒之间") raise ValueError(
if aspect_ratio not in _ASPECT_RATIOS: f"{spec['display_name']} 时长必须在 "
raise ValueError(f"Kling 4.0 不支持宽高比:{aspect_ratio}") f"{spec['min_duration']}~{spec['max_duration']} 秒之间"
)
settings["duration"] = duration
middle_frames = list(middle_frames or []) middle_frames = list(middle_frames or [])
reference_images = list(reference_images or []) reference_images = list(reference_images or [])
@@ -86,59 +323,88 @@ def build_kling_v4_body(
if len(reference_videos) > 5: if len(reference_videos) > 5:
raise ValueError("Kling 4.0 最多支持 5 段参考视频") raise ValueError("Kling 4.0 最多支持 5 段参考视频")
body = { body: dict[str, Any] = {
"model_name": "kling-v4", "options": {"watermark_info": {"enabled": bool(watermark_enabled)}},
"prompt": prompt,
"duration": duration,
"mode": _RESOLUTION_MODE[resolution],
"watermark_info": {"enabled": False},
} }
if negative_prompt and str(negative_prompt).strip():
body["negative_prompt"] = str(negative_prompt).strip()
if mode == "text": if mode == "text":
if first_frame or middle_frames or last_frame or reference_images or reference_videos: if first_frame or middle_frames or last_frame or reference_images or reference_videos:
raise ValueError("文生视频模式不能连接图片或视频素材") raise ValueError("文生视频模式不能连接图片或视频素材")
elif mode == "keyframes": body["prompt"] = prompt_text
if not first_frame: settings["aspect_ratio"] = _normalize_aspect_ratio(mode, aspect_ratio)
raise ValueError("关键帧模式必须提供首帧图片") body["settings"] = settings
return body
if mode == "keyframes":
if reference_images or reference_videos: if reference_images or reference_videos:
raise ValueError("关键帧模式不能同时使用全能参考素材") raise ValueError("关键帧模式不能同时使用全能参考素材")
if last_frame and not first_frame: keyframes = []
raise ValueError("尾帧必须与首帧一起提供") if first_frame:
if len([first_frame, *middle_frames, last_frame] if last_frame else [first_frame, *middle_frames]) > 10: keyframes.append(("first_frame", first_frame, "first"))
raise ValueError("Kling 4.0 关键帧总数不能超过 10 张") for index, url in enumerate(middle_frames, start=1):
metadata = {"first_frame": first_frame} keyframes.append(("middle_frame", url, _content_id("middle", index)))
if middle_frames:
metadata["middle_frames"] = middle_frames
if last_frame: if last_frame:
metadata["last_frame"] = last_frame keyframes.append(("last_frame", last_frame, "last"))
body["metadata"] = metadata if not keyframes:
else: raise ValueError("关键帧模式至少需要一张关键帧图片")
if len(keyframes) > 10:
raise ValueError("Kling 4.0 关键帧总数不能超过 10 张")
contents: list[dict[str, Any]] = [{"type": "prompt", "text": prompt_text}]
require_middle_ids = sum(1 for item_type, _, _ in keyframes if item_type == "middle_frame") > 1
for item_type, url, item_id in keyframes:
item = {"type": item_type, "url": url}
if item_type == "middle_frame" and require_middle_ids:
item["id"] = item_id
elif item_type != "middle_frame" or require_middle_ids:
# Always attach ids so prompts can use @first / @middle / @last.
item["id"] = item_id
contents.append(item)
# Official rule: multiple middle frames must each have an id. We also
# attach ids for first/last so @id references in the prompt stay valid.
if require_middle_ids:
for item in contents:
if item.get("type") == "middle_frame" and not item.get("id"):
raise ValueError("多个中间帧时必须为每张图指定 ID")
body["contents"] = contents
body["settings"] = settings
return body
if first_frame or middle_frames or last_frame: if first_frame or middle_frames or last_frame:
raise ValueError("全能参考模式不能同时使用关键帧") raise ValueError("全能参考模式不能同时使用关键帧")
if not reference_images and not reference_videos: if not reference_images and not reference_videos:
raise ValueError("全能参考模式至少需要一张参考图或一段参考视频") raise ValueError("全能参考模式至少需要一张参考图或一段参考视频")
if len(reference_images) + len(reference_videos) > 15: if len(reference_images) + len(reference_videos) > 15:
raise ValueError("Kling 4.0 全能参考素材总数不能超过 15 个") raise ValueError("Kling 4.0 全能参考素材总数不能超过 15 个")
metadata = {}
if reference_images:
metadata["refer_images"] = reference_images
if reference_videos:
metadata["videos"] = reference_videos
if keep_original_sound:
body["keep_original_sound"] = True
body["metadata"] = metadata
# The first frame determines the output shape. For text/Omni requests, audio_value = _normalize_audio(audio)
# "智能" is represented by the provider's adaptive ratio value. reference_kind = str(video_reference_type or "特征参考").strip()
if mode != "keyframes": if reference_kind not in {"特征参考", "待编辑视频", "feature_video", "base_video"}:
body["aspect_ratio"] = "adaptive" if aspect_ratio == "智能" else aspect_ratio raise ValueError(f"Kling 4.0 不支持的视频参考类型:{video_reference_type}")
use_base_video = reference_kind in {"待编辑视频", "base_video"}
if use_base_video and not reference_videos:
raise ValueError("待编辑视频模式必须提供至少一段参考视频")
if audio_value == "original" and not reference_videos:
raise ValueError("保留原声需要至少一段 base_video 或 feature_video")
contents = [{"type": "prompt", "text": prompt_text}]
require_image_ids = len(reference_images) > 1
for index, url in enumerate(reference_images, start=1):
item = {"type": "refer_image", "url": url, "id": _content_id("image", index)}
if not require_image_ids and index == 1:
item["id"] = "image_1"
contents.append(item)
for index, url in enumerate(reference_videos, start=1):
if use_base_video and index == 1:
item_type = "base_video"
item_id = "video_1"
else:
item_type = "feature_video"
item_id = _content_id("video", index)
contents.append({"type": item_type, "url": url, "id": item_id})
settings["aspect_ratio"] = _normalize_aspect_ratio(mode, aspect_ratio)
if audio_value != "native":
settings["audio"] = audio_value
body["contents"] = contents
body["settings"] = settings
return body return body
def endpoint_for(generation_mode: str) -> tuple[str, str]:
"""Return create/status paths for a canonical or displayed mode."""
return ENDPOINTS[canonical_generation_mode(generation_mode)]
+15 -8
View File
@@ -87,18 +87,25 @@ invalid model, duration, resolution, mode, media count, or edit clip length
cannot consume an upload or paid generation request. Saved workflows retain the cannot consume an upload or paid generation request. Saved workflows retain the
`O1keyGrokVideo` ID and are migrated according to [ADR 0006](decisions/0006-grok-video-api-and-workflow-migration.md). `O1keyGrokVideo` ID and are migrated according to [ADR 0006](decisions/0006-grok-video-api-and-workflow-migration.md).
`K3Video` keeps its released node ID and appends a `v4` DynamicCombo branch. The `K3Video` keeps its released node ID and appends `v4` and `v4-flash`
branch adds a generation-mode selector with text-to-video, keyframes, and Omni DynamicCombo branches, displayed as `Kling 4.0` and `Kling 4.0 Flash`. The
branches add a generation-mode selector with text-to-video, keyframes, and Omni
reference paths. Existing v3/v2.6/v3-omni branches retain their original reference paths. Existing v3/v2.6/v3-omni branches retain their original
DynamicCombo option order and positional widgets. Kling 4.0 keyframe sockets DynamicCombo option order and positional widgets. Kling 4.0 keyframe sockets
and additional Omni reference sockets are appended after the released widget and additional Omni reference sockets are appended after the released widget
block, so saved workflows do not shift their values. `clients/kling_video_client.py` block, so saved workflows do not shift their values. `clients/kling_video_client.py`
owns the v4 capability checks and builds the proxy-compatible `model_name`, owns the official 4.0 / Flash capability checks and builds `contents`,
resolution `mode`, `aspect_ratio`, and `metadata` fields; the node reuses the `settings`, and `options` bodies; the model is taken from the path
existing R2 upload and interruption-aware task lifecycle. Keyframes use (`/kling/text-to-video/kling-4.0`, `/kling/image-to-video/kling-4.0`,
`metadata.first_frame`, `metadata.middle_frames`, and `metadata.last_frame`; `/kling/omni-video/kling-4.0`, or the `kling-4.0-flash` variants) and is never
Omni references use `metadata.refer_images` and `metadata.videos`. The shared sent in the request body. Flash accepts only `720p` and 3–20 second durations,
video result parser also accepts Kling 4.0's `output.media[].url` envelope. and the frontend clamps a leftover 1080p value when switching from 4.0.
Keyframes omit `settings.aspect_ratio`; text defaults to `16:9` and Omni to
`adaptive`. The node reuses R2 upload and interruption-aware downloads, but
polls the official `{code, message, request_id, data}` envelope, reads
`data.id` as the task id, and takes the result from `data[].outputs[].url`
rather than the 3.0 Omni `video_url` parser. `K3MotionControl` remains a 3.0
motion-control path only.
### Shared utilities ### Shared utilities
@@ -38,3 +38,14 @@ because the released node has no compatible AUDIO or element-ID sockets.
`tests/test_kling_video.py` covers all three payload shapes, capability limits, `tests/test_kling_video.py` covers all three payload shapes, capability limits,
mutual exclusions, endpoint selection, and the Kling 4.0 result envelope. mutual exclusions, endpoint selection, and the Kling 4.0 result envelope.
## Official path update (2026-11-10)
The first integration used a proxy-compatible `model_name` / `metadata`
envelope and `/kling/v1/videos/*` paths. The published O1Key Kling 4.0 / Flash
docs now require official paths, `contents` / `settings` / `options` bodies,
and the `{code, message, request_id, data}` query envelope. The `v4` option is
retained as the stored Kling 4.0 value; `v4-flash` is appended, and both are
shown with Chinese display names. Flash is limited to 720p and 3–20 seconds.
Element and voice management remain outside this integration unless the
caller already has IDs.
+2
View File
@@ -30,6 +30,8 @@ For `O1keyPromptMultiFunction`, keep the original first two widgets unchanged an
For Omni Flash, keep `O1keyOmniFlashVideo` as the sole node ID. Its `execute` validates all modes and media before upload or paid submission, then returns a native `VIDEO`. Ordinary generation hard-codes `omni_flash_10s`; edit mode uses `omni_flash_abra_edit`. If changing the widget schema, keep the migration that removes the former model value at index 2 so saved workflows remain aligned. The button only queues the current node using ComfyUI's native queue. O1Key's JSON `/v1/videos` gateway requires `input_reference` to be a string for one image; send several references as repeated multipart fields, never a JSON array under `input_reference`. Keep provider URLs and credentials out of widgets, workflow metadata, and logs. Use `tests/test_omni_flash.py` and `tests/test_omni_flash_frontend.mjs` for offline regression coverage. For Omni Flash, keep `O1keyOmniFlashVideo` as the sole node ID. Its `execute` validates all modes and media before upload or paid submission, then returns a native `VIDEO`. Ordinary generation hard-codes `omni_flash_10s`; edit mode uses `omni_flash_abra_edit`. If changing the widget schema, keep the migration that removes the former model value at index 2 so saved workflows remain aligned. The button only queues the current node using ComfyUI's native queue. O1Key's JSON `/v1/videos` gateway requires `input_reference` to be a string for one image; send several references as repeated multipart fields, never a JSON array under `input_reference`. Keep provider URLs and credentials out of widgets, workflow metadata, and logs. Use `tests/test_omni_flash.py` and `tests/test_omni_flash_frontend.mjs` for offline regression coverage.
For `K3Video`, keep the released node ID and the existing v3 / v2.6 / v3-omni widget order. Official Kling 4.0 and Kling 4.0 Flash are stored as `v4` and `v4-flash` with frontend display names; accept the `v4` alias so saved workflows keep working. Build official `contents` / `settings` / `options` bodies in `clients/kling_video_client.py`, choose the path by model and generation mode, and never send a `model` field. Use a dedicated 4.0 query parser (`data.id`, `submitted` / `processing` / `succeeded` / `failed`, `data[].outputs[].url`) and do not route 4.0 tasks through the 3.0 Omni `video_url` parser. Flash must reject `1080p` and durations above 20 seconds in both the backend and `web/js/klingV4ParameterGuard.js`. Do not invent a 4.0 motion-control path on `K3MotionControl`. Run `tests/test_kling_video.py` after changing this contract.
- Normalize authentication and base URL selection through `utils/config.py`. - Normalize authentication and base URL selection through `utils/config.py`.
- Use shared retry, interruption, polling, upload, and download helpers before creating provider-local variants. - Use shared retry, interruption, polling, upload, and download helpers before creating provider-local variants.
- Convert provider-specific failures into actionable messages without printing secrets or full payloads. - Convert provider-specific failures into actionable messages without printing secrets or full payloads.
+224 -51
View File
@@ -28,6 +28,14 @@ from comfy_api.latest import io
from ..clients.kling_video_client import ( from ..clients.kling_video_client import (
build_kling_v4_body, build_kling_v4_body,
endpoint_for as kling_v4_endpoint_for, endpoint_for as kling_v4_endpoint_for,
extract_kling_v4_error_message,
extract_kling_v4_status,
extract_kling_v4_task_id,
extract_kling_v4_video_url,
is_kling_v4_failure_status,
is_kling_v4_model,
is_kling_v4_success_status,
kling_v4_model_spec,
) )
from ..utils.config import get_api_key_or_raise, get_base_url_by_route from ..utils.config import get_api_key_or_raise, get_base_url_by_route
from ..utils.image_utils import tensor_to_pil from ..utils.image_utils import tensor_to_pil
@@ -110,9 +118,14 @@ _REFERENCE_VIDEO_MIN_RATIO = 1 / 2.5
_REFERENCE_VIDEO_MAX_RATIO = 2.5 _REFERENCE_VIDEO_MAX_RATIO = 2.5
_V4_REFERENCE_VIDEO_MAX_BYTES = 300 * 1024 * 1024 _V4_REFERENCE_VIDEO_MAX_BYTES = 300 * 1024 * 1024
_V4_REFERENCE_VIDEO_MIN_DURATION = 3.0 _V4_REFERENCE_VIDEO_MIN_DURATION = 3.0
_V4_REFERENCE_VIDEO_MAX_DURATION = 30.0
_V4_REFERENCE_VIDEO_MIN_RATIO = 2 / 5 _V4_REFERENCE_VIDEO_MIN_RATIO = 2 / 5
_V4_REFERENCE_VIDEO_MAX_RATIO = 5 / 2 _V4_REFERENCE_VIDEO_MAX_RATIO = 5 / 2
_V4_REFERENCE_VIDEO_MIN_SIZE = 700
_V4_REFERENCE_VIDEO_MAX_SIZE = 4553
_V4_REFERENCE_VIDEO_MAX_PIXELS = 8294400
_V4_REFERENCE_VIDEO_MIN_FPS = 24.0
_V4_REFERENCE_VIDEO_MAX_FPS = 60.0
_V4_IMAGE_MAX_BYTES = 30 * 1024 * 1024
# ── 工具函数 ─────────────────────────────────────────────────────────────────── # ── 工具函数 ───────────────────────────────────────────────────────────────────
@@ -133,13 +146,14 @@ def _extract_elements(text: str):
return text, names return text, names
def _prepare_image_for_upload(tensor): def _prepare_image_for_upload(tensor, max_bytes: int = 10 * 1024 * 1024):
"""转换并校验图片,不符合约束时自动等比缩放后返回 PIL Image。""" """转换并校验图片,不符合约束时自动等比缩放后返回 PIL Image。"""
import io as _io import io as _io
pil_list = tensor_to_pil(tensor) pil_list = tensor_to_pil(tensor)
img = pil_list[0].convert("RGB") img = pil_list[0].convert("RGB")
w, h = img.size w, h = img.size
max_bytes = int(max_bytes)
# 1. 宽高比校验(无法通过等比缩放修复,直接报错) # 1. 宽高比校验(无法通过等比缩放修复,直接报错)
ratio = w / h ratio = w / h
@@ -153,8 +167,8 @@ def _prepare_image_for_upload(tensor):
scale = max(300 / w, 300 / h) scale = max(300 / w, 300 / h)
img = img.resize((int(w * scale), int(h * scale)), resample=1) # LANCZOS=1 img = img.resize((int(w * scale), int(h * scale)), resample=1) # LANCZOS=1
# 3. 文件大小:循环等比缩小直到 ≤ 10MB # 3. 文件大小:循环等比缩小直到不超过上限
MAX_BYTES = 10 * 1024 * 1024 MAX_BYTES = max_bytes
for _ in range(20): # 最多迭代 20 次,防止死循环 for _ in range(20): # 最多迭代 20 次,防止死循环
buf = _io.BytesIO() buf = _io.BytesIO()
img.save(buf, format="PNG") img.save(buf, format="PNG")
@@ -165,11 +179,13 @@ def _prepare_image_for_upload(tensor):
new_h = int(img.height * scale) new_h = int(img.height * scale)
if new_w < 300 or new_h < 300: if new_w < 300 or new_h < 300:
raise RuntimeError( raise RuntimeError(
f"图片压缩至 10MB 以内后尺寸({new_w}x{new_h})低于最小限制 300px,无法同时满足两项约束。" f"图片压缩至 {MAX_BYTES / 1024 / 1024:.0f}MB 以内后尺寸({new_w}x{new_h})低于最小限制 300px,无法同时满足两项约束。"
) )
img = img.resize((new_w, new_h), resample=1) img = img.resize((new_w, new_h), resample=1)
else: else:
raise RuntimeError("图片经过 20 次缩放仍超过 10MB,请检查原始图片。") raise RuntimeError(
f"图片经过 20 次缩放仍超过 {MAX_BYTES / 1024 / 1024:.0f}MB,请检查原始图片。"
)
return img return img
@@ -437,27 +453,49 @@ def _validate_reference_video(video_path: str, model: str) -> None:
) )
def _validate_kling_v4_reference_video(video_path: str) -> float: def _validate_kling_v4_reference_video(video_path: str, model: str = "v4") -> float:
"""Validate one Kling 4.0 Omni reference clip and return its duration.""" """Validate one Kling 4.0 / Flash Omni reference clip and return its duration."""
spec = kling_v4_model_spec(model)
ext = os.path.splitext(video_path)[1].lower() ext = os.path.splitext(video_path)[1].lower()
if ext not in (".mp4", ".mov"): if ext not in (".mp4", ".mov"):
raise RuntimeError(f"Kling 4.0 参考视频仅支持 MP4/MOV,当前为 {ext or '无扩展名'}。") raise RuntimeError(f"{spec['display_name']} 参考视频仅支持 MP4/MOV,当前为 {ext or '无扩展名'}。")
size = os.path.getsize(video_path) size = os.path.getsize(video_path)
if size > _V4_REFERENCE_VIDEO_MAX_BYTES: if size > _V4_REFERENCE_VIDEO_MAX_BYTES:
raise RuntimeError( raise RuntimeError(
f"Kling 4.0 参考视频不能超过 300MB,当前为 {size / 1024 / 1024:.1f}MB。" f"{spec['display_name']} 参考视频不能超过 300MB,当前为 {size / 1024 / 1024:.1f}MB。"
) )
meta = _probe_video_with_ffprobe(video_path) or _probe_video_with_cv2(video_path) meta = _probe_video_with_ffprobe(video_path) or _probe_video_with_cv2(video_path)
if not meta or not meta.get("width") or not meta.get("height") or not meta.get("duration"): if not meta or not meta.get("width") or not meta.get("height") or not meta.get("duration"):
raise RuntimeError("无法读取 Kling 4.0 参考视频的尺寸和时长。") raise RuntimeError(f"无法读取 {spec['display_name']} 参考视频的尺寸和时长。")
width = int(meta["width"])
height = int(meta["height"])
duration = float(meta["duration"]) duration = float(meta["duration"])
if not _V4_REFERENCE_VIDEO_MIN_DURATION <= duration <= _V4_REFERENCE_VIDEO_MAX_DURATION: fps = meta.get("fps")
max_duration = float(spec["max_duration"])
if not _V4_REFERENCE_VIDEO_MIN_DURATION <= duration <= max_duration:
raise RuntimeError( raise RuntimeError(
f"Kling 4.0 单段参考视频时长需在 3~30 秒之间,当前为 {duration:.2f} 秒。" f"{spec['display_name']} 单段参考视频时长需在 3~{spec['max_duration']} 秒之间,当前为 {duration:.2f} 秒。"
) )
ratio = float(meta["width"]) / float(meta["height"]) if not (
_V4_REFERENCE_VIDEO_MIN_SIZE <= width <= _V4_REFERENCE_VIDEO_MAX_SIZE
and _V4_REFERENCE_VIDEO_MIN_SIZE <= height <= _V4_REFERENCE_VIDEO_MAX_SIZE
):
raise RuntimeError(
f"{spec['display_name']} 参考视频宽高需在 700~4553px 之间,当前为 {width}x{height}。"
)
if width * height > _V4_REFERENCE_VIDEO_MAX_PIXELS:
raise RuntimeError(
f"{spec['display_name']} 参考视频总像素不能超过 8,294,400,当前为 {width * height}。"
)
if not fps:
raise RuntimeError(f"无法读取 {spec['display_name']} 参考视频的帧率。")
if not _V4_REFERENCE_VIDEO_MIN_FPS <= float(fps) <= _V4_REFERENCE_VIDEO_MAX_FPS:
raise RuntimeError(
f"{spec['display_name']} 参考视频帧率需在 24~60fps 之间,当前为 {float(fps):.2f}fps。"
)
ratio = width / height
if not _V4_REFERENCE_VIDEO_MIN_RATIO <= ratio <= _V4_REFERENCE_VIDEO_MAX_RATIO: if not _V4_REFERENCE_VIDEO_MIN_RATIO <= ratio <= _V4_REFERENCE_VIDEO_MAX_RATIO:
raise RuntimeError("Kling 4.0 参考视频宽高比需在 2:5~5:2 之间。") raise RuntimeError(f"{spec['display_name']} 参考视频宽高比需在 2:5~5:2 之间。")
return duration return duration
@@ -610,6 +648,95 @@ async def _run_video_task(base_url: str, headers: dict, body: dict,
return save_path return save_path
async def _run_kling_v4_task(base_url: str, headers: dict, body: dict,
create_path: str, status_path: str, prefix: str):
"""Submit, poll, and download using the official Kling 4.0 / Flash envelope."""
try:
from comfy.utils import ProgressBar
pbar = ProgressBar(100)
except Exception:
pbar = None
def _stage(s: str):
if s == "submitting":
print("[Kling 4.0] 提交中...")
if pbar: pbar.update_absolute(0, 100)
elif s.startswith("submitted:"):
print(f"[Kling 4.0] 任务已提交 → {s.split(':', 1)[1]}")
if pbar: pbar.update_absolute(5, 100)
elif s == "downloading":
print("[Kling 4.0] 下载视频...")
if pbar: pbar.update_absolute(99, 100)
elif s == "done":
print("[Kling 4.0] 完成")
if pbar: pbar.update_absolute(100, 100)
def _progress(pct: int):
if pbar: pbar.update_absolute(5 + int(pct * 0.94), 100)
tmp_fd, save_path = tempfile.mkstemp(suffix=".mp4", prefix="k3_")
connector = aiohttp.TCPConnector(ssl=False, force_close=True)
async with aiohttp.ClientSession(connector=connector) as session:
check_interrupt()
_stage("submitting")
create_url = f"{base_url}{create_path}"
resp = await run_with_interrupt(async_request_with_retry(
session, "POST", create_url, json=body, headers=headers, prefix=prefix
))
check_interrupt()
create_resp = json.loads(await resp.text())
if create_resp.get("code") not in (None, 0, "0"):
raise RuntimeError(f"Kling 4.0 提交失败:{extract_kling_v4_error_message(create_resp)}")
task_id = extract_kling_v4_task_id(create_resp)
if not task_id:
raise RuntimeError(f"API 未返回任务 ID,响应:{create_resp}")
_stage(f"submitted:{task_id}")
status_url = f"{base_url}{status_path.format(task_id=task_id)}"
interval = _POLL_INIT
deadline = PollDeadline(label="Kling 4.0")
video_url = None
while True:
deadline.check()
check_interrupt()
async with session.get(status_url, headers=headers) as resp:
text_body = await resp.text()
if resp.status != 200:
try:
err = json.loads(text_body)
msg = extract_kling_v4_error_message(err, default=text_body)
except Exception:
msg = text_body
raise RuntimeError(f"状态查询失败 ({resp.status}): {msg}")
sr = json.loads(text_body)
status = extract_kling_v4_status(sr)
print(f"[Kling 4.0] 生成中 status={status or 'unknown'}")
_progress(50 if status == "processing" else 10)
if is_kling_v4_success_status(status):
video_url = extract_kling_v4_video_url(sr)
break
if is_kling_v4_failure_status(status, sr):
raise RuntimeError(f"Kling 4.0 生成失败:{extract_kling_v4_error_message(sr)}")
await interruptible_sleep(interval)
interval = min(interval * 1.5, _POLL_MAX)
if not video_url:
raise RuntimeError(f"API 未返回视频 URL,响应:{sr}")
check_interrupt()
_stage("downloading")
os.close(tmp_fd)
await download_video_to_file(session, video_url, save_path, label="Kling 4.0")
_stage("done")
return save_path
# ── 模型 DynamicCombo 选项构建 ──────────────────────────────────────────────── # ── 模型 DynamicCombo 选项构建 ────────────────────────────────────────────────
def _v3_omni_subs(): def _v3_omni_subs():
@@ -638,38 +765,70 @@ def _v3_omni_subs():
] ]
def _v4_subs(): def _v4_common_subs(*, max_duration: int, resolutions: list[str], default_resolution: str, tooltip_prefix: str):
"""Kling 4.0 generation mode and its capability-limited parameters.""" """Shared Kling 4.0 / Flash generation-mode parameters."""
return [ return [
io.Combo.Input( io.Combo.Input(
"生成模式", "生成模式",
options=["文生视频", "关键帧", "全能参考"], options=["文生视频", "关键帧", "全能参考"],
default="文生视频", default="文生视频",
tooltip="文生视频:只使用提示词;关键帧:首帧可加中间帧和尾帧;全能参考:使用参考图或参考视频。", tooltip="文生视频:只使用提示词;关键帧:至少一张关键帧,可加中间帧和尾帧;全能参考:使用参考图或参考视频。",
), ),
io.Int.Input( io.Int.Input(
"时长", "时长",
default=5, default=10,
min=3, min=3,
max=30, max=max_duration,
display_mode=io.NumberDisplay.slider, display_mode=io.NumberDisplay.slider,
tooltip="Kling 4.0 支持 3~30 秒。", tooltip=f"{tooltip_prefix} 支持 3~{max_duration} 秒。",
), ),
io.Combo.Input( io.Combo.Input(
"模式", "模式",
options=["720p", "1080p"], options=resolutions,
default="720p", default=default_resolution,
tooltip="Kling 4.0 支持 720p 和 1080p。", tooltip=f"{tooltip_prefix} 支持 {' / '.join(resolutions)},默认 {default_resolution}。",
), ),
io.Combo.Input( io.Combo.Input(
"宽高比", "宽高比",
options=["智能", "16:9", "9:16", "1:1", "21:9"], options=["智能", "16:9", "9:16", "1:1", "21:9"],
default="智能", default="智能",
tooltip="关键帧模式跟随首帧比例;文生和全能参考支持智能、16:9、9:16、1:1、21:9。", tooltip="文生视频默认 16:9(智能按 16:9 提交);全能参考默认 adaptive;图生视频不传宽高比。",
),
io.Combo.Input(
"视频参考类型",
options=["特征参考", "待编辑视频"],
default="特征参考",
tooltip="仅全能参考:特征参考对应 feature_video;待编辑视频把第一段参考视频作为 base_video。",
),
io.Combo.Input(
"音频",
options=["原生音频", "保留原声"],
default="原生音频",
tooltip="仅全能参考:原生音频按画面生成声音;保留原声需提供 base_video 或 feature_video。",
), ),
] ]
def _v4_subs():
"""Kling 4.0 generation mode and its capability-limited parameters."""
return _v4_common_subs(
max_duration=30,
resolutions=["720p", "1080p"],
default_resolution="1080p",
tooltip_prefix="Kling 4.0",
)
def _v4_flash_subs():
"""Kling 4.0 Flash parameters: 720p only, 3-20 seconds."""
return _v4_common_subs(
max_duration=20,
resolutions=["720p"],
default_resolution="720p",
tooltip_prefix="Kling 4.0 Flash",
)
def _build_model_input(): def _build_model_input():
"""构建「模型」DynamicCombo,把「时长」「模式」作为随模型变化的子输入。 """构建「模型」DynamicCombo,把「时长」「模式」作为随模型变化的子输入。
@@ -677,6 +836,7 @@ def _build_model_input():
- v3:时长 3~15s;模式 720p/1080p/4K - v3:时长 3~15s;模式 720p/1080p/4K
- v2-6:时长 5/10s;模式 720p/1080p(无 4K) - v2-6:时长 5/10s;模式 720p/1080p(无 4K)
- v3-omni:时长 3~15s;模式 720p/1080p/4K;支持多模态参考 - v3-omni:时长 3~15s;模式 720p/1080p/4K;支持多模态参考
- v4 / v4-flash:文生、关键帧、全能参考;4.0 为 3~30s、默认 1080p,Flash 为 3~20s、仅 720p
""" """
def _v3_subs(): def _v3_subs():
return [ return [
@@ -702,11 +862,13 @@ def _build_model_input():
io.DynamicCombo.Option("v3-omni", _v3_omni_subs()), io.DynamicCombo.Option("v3-omni", _v3_omni_subs()),
io.DynamicCombo.Option("v2-6", _v26_subs()), io.DynamicCombo.Option("v2-6", _v26_subs()),
io.DynamicCombo.Option("v3", _v3_subs()), io.DynamicCombo.Option("v3", _v3_subs()),
# Append the new branch so existing DynamicCombo option order and # Append the new branches so existing DynamicCombo option order and
# saved v3/v2.6 workflows remain unchanged. # saved v3/v2.6 workflows remain unchanged. "v4" is the stored
# value for Kling 4.0; the frontend shows a Chinese display name.
io.DynamicCombo.Option("v4", _v4_subs()), io.DynamicCombo.Option("v4", _v4_subs()),
io.DynamicCombo.Option("v4-flash", _v4_flash_subs()),
], ],
tooltip="v2-6: 5/10s; v3: 3-15s; v3-omni: 多模态参考、视频编辑、主体管理;v4: 文生、关键帧、全能参考,3-30s。", tooltip="v2-6: 5/10s; v3: 3-15s; v3-omni: 多模态参考、视频编辑、主体管理;Kling 4.0: 文生、关键帧、全能参考,3-30s,默认 1080p;Kling 4.0 Flash: 同路径结构,3-20s,仅 720p。",
) )
@@ -778,22 +940,22 @@ class K3Video(io.ComfyNode):
# positional widgets in existing K3Video workflows do not move. # positional widgets in existing K3Video workflows do not move.
*[ *[
io.Image.Input(f"中间帧{i}", optional=True, io.Image.Input(f"中间帧{i}", optional=True,
tooltip="Kling 4.0 关键帧模式使用;按连接顺序插入首帧与尾帧之间。") tooltip="Kling 4.0 / Flash 关键帧模式使用;按连接顺序插入首帧与尾帧之间。")
for i in range(1, 9) for i in range(1, 9)
], ],
*[ *[
io.Image.Input(f"参考图{i}", optional=True, io.Image.Input(f"参考图{i}", optional=True,
tooltip="Kling 4.0 全能参考模式使用;最多 10 张参考图。") tooltip="Kling 4.0 / Flash 全能参考模式使用;最多 10 张参考图。")
for i in range(6, 11) for i in range(6, 11)
], ],
io.Image.Input( io.Image.Input(
"参考图1", "参考图1",
optional=True, optional=True,
tooltip="Kling 4.0 全能参考模式使用;最多 10 张参考图。", tooltip="Kling 4.0 / Flash 全能参考模式使用;最多 10 张参考图。",
), ),
*[ *[
io.Video.Input(f"参考视频{i}", optional=True, io.Video.Input(f"参考视频{i}", optional=True,
tooltip="Kling 4.0 全能参考模式使用;最多 5 段参考视频。") tooltip="Kling 4.0 / Flash 全能参考模式使用;最多 5 段参考视频。")
for i in range(2, 6) for i in range(2, 6)
], ],
], ],
@@ -820,7 +982,7 @@ class K3Video(io.ComfyNode):
"Content-Type": "application/json", "Content-Type": "application/json",
} }
shots = _collect_shots(分镜模式, 时长) shots = _collect_shots(分镜模式, 时长)
if 模型代号 == "v4": if is_kling_v4_model(模型代号):
generation_mode = 模型.get("生成模式", "文生视频") generation_mode = 模型.get("生成模式", "文生视频")
middle_frames = [ middle_frames = [
_kwargs.get(f"中间帧{i}") _kwargs.get(f"中间帧{i}")
@@ -859,6 +1021,9 @@ class K3Video(io.ComfyNode):
reference_images, reference_images,
reference_videos, reference_videos,
shots, shots,
模型代号,
模型.get("视频参考类型", "特征参考"),
模型.get("音频", "原生音频"),
) )
if _FOLDER_PATHS_OK: if _FOLDER_PATHS_OK:
return io.NodeOutput(InputImpl.VideoFromFile(save_path)) return io.NodeOutput(InputImpl.VideoFromFile(save_path))
@@ -1178,24 +1343,34 @@ class K3Video(io.ComfyNode):
reference_image_inputs, reference_image_inputs,
reference_video_inputs, reference_video_inputs,
shots, shots,
model="v4",
video_reference_type="特征参考",
audio="原生音频",
): ):
"""Build and run one Kling 4.0 text/keyframe/Omni task.""" """Build and run one official Kling 4.0 / Flash text, keyframe, or Omni task."""
from ..utils.r2_uploader import upload_video from ..utils.r2_uploader import upload_video
spec = kling_v4_model_spec(model)
async def upload_frame(image, label): async def upload_frame(image, label):
if image is None: if image is None:
return None return None
print(f"[Kling 4.0] uploading {label}...") print(f"[{spec['display_name']}] uploading {label}...")
return await upload_image(_prepare_image_for_upload(image), base_url=base_url) return await upload_image(
_prepare_image_for_upload(image, max_bytes=_V4_IMAGE_MAX_BYTES),
base_url=base_url,
)
validated_video_paths = [] validated_video_paths = []
reference_video_seconds = 0.0 reference_video_seconds = 0.0
for video in reference_video_inputs: for video in reference_video_inputs:
video_path = _resolve_reference_video_path(video) video_path = _resolve_reference_video_path(video)
reference_video_seconds += _validate_kling_v4_reference_video(video_path) reference_video_seconds += _validate_kling_v4_reference_video(video_path, model)
validated_video_paths.append(video_path) validated_video_paths.append(video_path)
if reference_video_seconds > _V4_REFERENCE_VIDEO_MAX_DURATION: if reference_video_seconds > spec["max_duration"]:
raise RuntimeError("Kling 4.0 参考视频总时长不能超过 30 秒。") raise RuntimeError(
f"{spec['display_name']} 参考视频总时长不能超过 {spec['max_duration']} 秒。"
)
first_url = await upload_frame(first_frame, "first frame") first_url = await upload_frame(first_frame, "first frame")
middle_urls = [ middle_urls = [
@@ -1210,12 +1385,16 @@ class K3Video(io.ComfyNode):
] ]
reference_video_urls = [] reference_video_urls = []
for index, video_path in enumerate(validated_video_paths, start=1): for index, video_path in enumerate(validated_video_paths, start=1):
print(f"[Kling 4.0] uploading reference video {index}...") print(f"[{spec['display_name']}] uploading reference video {index}...")
reference_video_urls.append(await upload_video(video_path, base_url=base_url)) reference_video_urls.append(await upload_video(video_path, base_url=base_url))
if shots:
prompt = "\n".join(str(shot["prompt"]).strip() for shot in shots if shot.get("prompt"))
body = build_kling_v4_body( body = build_kling_v4_body(
generation_mode=generation_mode, generation_mode=generation_mode,
prompt=prompt, prompt=prompt,
model=model,
negative_prompt=negative_prompt, negative_prompt=negative_prompt,
duration=duration, duration=duration,
resolution=resolution, resolution=resolution,
@@ -1225,26 +1404,20 @@ class K3Video(io.ComfyNode):
last_frame=last_url, last_frame=last_url,
reference_images=reference_image_urls, reference_images=reference_image_urls,
reference_videos=reference_video_urls, reference_videos=reference_video_urls,
video_reference_type=video_reference_type,
audio=audio,
) )
if shots:
body["multi_shot"] = True
body["shot_type"] = "customize"
body["multi_prompt"] = [
{"index": shot["index"], "prompt": shot["prompt"], "duration": shot["duration"]}
for shot in shots
]
create_path, status_path = kling_v4_endpoint_for(generation_mode) create_path, status_path = kling_v4_endpoint_for(generation_mode, model)
return await _run_video_task( return await _run_kling_v4_task(
base_url, base_url,
headers, headers,
body, body,
create_path, create_path,
status_path, status_path,
f"Kling 4.0 {generation_mode} submit: ", f"{spec['display_name']} {generation_mode} submit: ",
) )
@classmethod
async def _build_standard(cls, 模型, base_url, headers, 起始帧, 提示词, 负向提示词, 时长, 生成音频, 模式, shots, 尾帧=None): async def _build_standard(cls, 模型, base_url, headers, 起始帧, 提示词, 负向提示词, 时长, 生成音频, 模式, shots, 尾帧=None):
"""标准图生视频接口:POST /kling/v1/videos/image2video """标准图生视频接口:POST /kling/v1/videos/image2video
+170 -41
View File
@@ -1,4 +1,4 @@
"""Offline regression tests for the Kling 4.0 request contract.""" """Offline regression tests for the official Kling 4.0 / Flash contract."""
import sys import sys
import types import types
@@ -21,13 +21,31 @@ sys.modules.setdefault("comfyui_o1key.utils", utils)
from comfyui_o1key.clients.kling_video_client import ( # noqa: E402 from comfyui_o1key.clients.kling_video_client import ( # noqa: E402
build_kling_v4_body, build_kling_v4_body,
canonical_kling_v4_model,
endpoint_for, endpoint_for,
extract_kling_v4_error_message,
extract_kling_v4_status,
extract_kling_v4_task_id,
extract_kling_v4_video_url,
is_kling_v4_failure_status,
is_kling_v4_model,
is_kling_v4_success_status,
kling_v4_model_spec,
) )
from comfyui_o1key.utils.video_task import extract_video_url # noqa: E402
class KlingV4RequestTests(unittest.TestCase): class KlingV4RequestTests(unittest.TestCase):
def test_text_mode_uses_resolution_mode_and_adaptive_ratio(self): def test_model_catalog_and_aliases(self):
self.assertEqual(canonical_kling_v4_model("v4"), "v4")
self.assertEqual(canonical_kling_v4_model("Kling 4.0"), "v4")
self.assertEqual(canonical_kling_v4_model("Kling 4.0 Flash"), "v4-flash")
self.assertTrue(is_kling_v4_model("v4-flash"))
self.assertFalse(is_kling_v4_model("v3-omni"))
self.assertEqual(kling_v4_model_spec("v4")["default_resolution"], "1080p")
self.assertEqual(kling_v4_model_spec("v4-flash")["default_resolution"], "720p")
self.assertEqual(kling_v4_model_spec("v4-flash")["max_duration"], 20)
def test_text_mode_uses_official_path_and_settings(self):
body = build_kling_v4_body( body = build_kling_v4_body(
generation_mode="文生视频", generation_mode="文生视频",
prompt="A slow dolly shot through a rainy market", prompt="A slow dolly shot through a rainy market",
@@ -36,12 +54,49 @@ class KlingV4RequestTests(unittest.TestCase):
aspect_ratio="智能", aspect_ratio="智能",
) )
self.assertEqual(body["model_name"], "kling-v4") self.assertNotIn("model", body)
self.assertEqual(body["duration"], 30) self.assertNotIn("model_name", body)
self.assertEqual(body["mode"], "pro") self.assertEqual(body["prompt"], "A slow dolly shot through a rainy market")
self.assertEqual(body["aspect_ratio"], "adaptive") self.assertEqual(body["settings"]["duration"], 30)
self.assertNotIn("metadata", body) self.assertEqual(body["settings"]["resolution"], "1080p")
self.assertEqual(endpoint_for("文生视频")[0], "/kling/v1/videos/text2video") self.assertEqual(body["settings"]["aspect_ratio"], "16:9")
self.assertEqual(body["options"]["watermark_info"]["enabled"], False)
self.assertNotIn("contents", body)
self.assertEqual(
endpoint_for("文生视频", "v4"),
("/kling/text-to-video/kling-4.0", "/kling/text-to-video/kling-4.0/{task_id}"),
)
self.assertEqual(
endpoint_for("文生视频", "Kling 4.0 Flash")[0],
"/kling/text-to-video/kling-4.0-flash",
)
def test_text_mode_defaults_resolution_by_model(self):
standard = build_kling_v4_body(generation_mode="text", prompt="harbor sunrise")
flash = build_kling_v4_body(
generation_mode="text",
prompt="harbor sunrise",
model="v4-flash",
)
self.assertEqual(standard["settings"]["resolution"], "1080p")
self.assertEqual(flash["settings"]["resolution"], "720p")
def test_flash_rejects_1080p_and_long_duration(self):
with self.assertRaisesRegex(ValueError, "仅支持 720p"):
build_kling_v4_body(
generation_mode="文生视频",
prompt="harbor sunrise",
model="v4-flash",
resolution="1080p",
)
with self.assertRaisesRegex(ValueError, "3~20 秒"):
build_kling_v4_body(
generation_mode="文生视频",
prompt="harbor sunrise",
model="v4-flash",
duration=21,
resolution="720p",
)
def test_keyframes_keep_frame_order_and_omit_aspect_ratio(self): def test_keyframes_keep_frame_order_and_omit_aspect_ratio(self):
body = build_kling_v4_body( body = build_kling_v4_body(
@@ -53,41 +108,69 @@ class KlingV4RequestTests(unittest.TestCase):
"https://cdn.example.invalid/middle-2.png", "https://cdn.example.invalid/middle-2.png",
], ],
last_frame="https://cdn.example.invalid/last.png", last_frame="https://cdn.example.invalid/last.png",
aspect_ratio="16:9",
) )
self.assertEqual(body["metadata"], { self.assertEqual(
"first_frame": "https://cdn.example.invalid/first.png", [item["type"] for item in body["contents"]],
"middle_frames": [ ["prompt", "first_frame", "middle_frame", "middle_frame", "last_frame"],
"https://cdn.example.invalid/middle-1.png", )
"https://cdn.example.invalid/middle-2.png", self.assertEqual(body["contents"][1]["url"], "https://cdn.example.invalid/first.png")
], self.assertEqual(body["contents"][2]["id"], "middle_1")
"last_frame": "https://cdn.example.invalid/last.png", self.assertEqual(body["contents"][3]["id"], "middle_2")
}) self.assertNotIn("aspect_ratio", body["settings"])
self.assertNotIn("aspect_ratio", body) self.assertNotIn("audio", body["settings"])
self.assertEqual(endpoint_for("关键帧")[0], "/kling/v1/videos/image2video") self.assertEqual(
endpoint_for("关键帧")[0],
"/kling/image-to-video/kling-4.0",
)
def test_omni_mode_uses_reference_metadata_and_caps_inputs(self): def test_keyframes_allow_any_single_frame(self):
body = build_kling_v4_body(
generation_mode="关键帧",
prompt="Hold on the ending pose",
last_frame="https://cdn.example.invalid/last.png",
)
self.assertEqual(body["contents"][1]["type"], "last_frame")
def test_omni_mode_uses_official_contents_and_optional_original_audio(self):
body = build_kling_v4_body( body = build_kling_v4_body(
generation_mode="全能参考", generation_mode="全能参考",
prompt="Use the character from @Image1 and the movement from @Video1", prompt="Use the character from @image_1 and the movement from @video_1",
reference_images=["https://cdn.example.invalid/character.png"], reference_images=["https://cdn.example.invalid/character.png"],
reference_videos=["https://cdn.example.invalid/motion.mp4"], reference_videos=["https://cdn.example.invalid/motion.mp4"],
keep_original_sound=True, audio="保留原声",
aspect_ratio="21:9", aspect_ratio="21:9",
) )
self.assertEqual(body["metadata"]["refer_images"], [ types = [item["type"] for item in body["contents"]]
"https://cdn.example.invalid/character.png", self.assertEqual(types, ["prompt", "refer_image", "feature_video"])
]) self.assertEqual(body["contents"][1]["id"], "image_1")
self.assertEqual(body["metadata"]["videos"], [ self.assertEqual(body["contents"][2]["id"], "video_1")
self.assertEqual(body["settings"]["audio"], "original")
self.assertEqual(body["settings"]["aspect_ratio"], "21:9")
self.assertEqual(endpoint_for("全能参考")[0], "/kling/omni-video/kling-4.0")
self.assertEqual(
endpoint_for("全能参考", "v4-flash")[0],
"/kling/omni-video/kling-4.0-flash",
)
def test_omni_base_video_uses_first_clip(self):
body = build_kling_v4_body(
generation_mode="全能参考",
prompt="Edit @video_1 while following @video_2",
reference_videos=[
"https://cdn.example.invalid/source.mp4",
"https://cdn.example.invalid/motion.mp4", "https://cdn.example.invalid/motion.mp4",
]) ],
self.assertTrue(body["keep_original_sound"]) video_reference_type="待编辑视频",
self.assertEqual(body["aspect_ratio"], "21:9") )
self.assertEqual(endpoint_for("全能参考")[0], "/kling/v1/videos/omni-video") self.assertEqual(body["contents"][1]["type"], "base_video")
self.assertEqual(body["contents"][2]["type"], "feature_video")
self.assertNotIn("audio", body["settings"])
def test_modes_reject_invalid_combinations_before_upload(self): def test_modes_reject_invalid_combinations_before_upload(self):
with self.assertRaisesRegex(ValueError, "关键帧模式必须提供"): with self.assertRaisesRegex(ValueError, "至少需要一张关键帧"):
build_kling_v4_body(generation_mode="关键帧", prompt="move") build_kling_v4_body(generation_mode="关键帧", prompt="move")
with self.assertRaisesRegex(ValueError, "不能连接图片或视频"): with self.assertRaisesRegex(ValueError, "不能连接图片或视频"):
build_kling_v4_body( build_kling_v4_body(
@@ -97,21 +180,67 @@ class KlingV4RequestTests(unittest.TestCase):
) )
with self.assertRaisesRegex(ValueError, "至少需要一张参考图"): with self.assertRaisesRegex(ValueError, "至少需要一张参考图"):
build_kling_v4_body(generation_mode="全能参考", prompt="move") build_kling_v4_body(generation_mode="全能参考", prompt="move")
with self.assertRaisesRegex(ValueError, "保留原声需要至少一段"):
build_kling_v4_body(
generation_mode="全能参考",
prompt="move",
reference_images=["https://cdn.example.invalid/character.png"],
audio="original",
)
def test_v4_output_envelope_is_read_by_shared_parser(self): def test_v4_query_parser_reads_official_task_array(self):
self.assertEqual( created = {
extract_video_url({ "code": 0,
"data": { "message": "",
"request_id": "req_xxxxxxxxxx",
"data": {"id": "task_xxxxxxxxxx", "status": "submitted"},
}
self.assertEqual(extract_kling_v4_task_id(created), "task_xxxxxxxxxx")
succeeded = {
"code": 0,
"message": "",
"request_id": "req_xxxxxxxxxx",
"data": [
{
"id": "task_xxxxxxxxxx",
"status": "succeeded", "status": "succeeded",
"output": { "message": "",
"media": [{"type": "video", "url": "https://cdn.example.invalid/result.mp4"}], "outputs": [
}, {
}, "type": "video",
}), "url": "https://cdn.example.invalid/result.mp4",
"watermark_url": "https://cdn.example.invalid/watermark.mp4",
"duration": "10.2",
}
],
"usage": {"output_duration": "10"},
}
],
}
self.assertEqual(extract_kling_v4_status(succeeded), "succeeded")
self.assertTrue(is_kling_v4_success_status(extract_kling_v4_status(succeeded)))
self.assertEqual(
extract_kling_v4_video_url(succeeded),
"https://cdn.example.invalid/result.mp4", "https://cdn.example.invalid/result.mp4",
) )
failed = {
"code": 0,
"data": [{"id": "task_xxxxxxxxxx", "status": "failed", "message": "内容审核未通过"}],
}
self.assertTrue(is_kling_v4_failure_status(extract_kling_v4_status(failed), failed))
self.assertEqual(extract_kling_v4_error_message(failed), "内容审核未通过")
# A 3.0 Omni envelope must not be treated as a 4.0 success URL.
legacy = {
"task_id": "task_omni_xxxxxxxxxx",
"status": "SUCCESS",
"video_url": "https://cdn.example.invalid/legacy.mp4",
}
self.assertEqual(extract_kling_v4_status(legacy), "")
self.assertIsNone(extract_kling_v4_video_url(legacy))
if __name__ == "__main__": if __name__ == "__main__":
unittest.main() unittest.main()
+207
View File
@@ -0,0 +1,207 @@
import { app } from "../../../scripts/app.js";
// Kling 4.0 / Flash: display names stay as labels, stored values remain
// `v4` / `v4-flash` so older workflows that saved `v4` keep working.
// Switching to Flash clamps 1080p back to 720p and caps duration at 20s.
const NODE_TYPE = "K3Video";
const MODEL_LABELS = Object.freeze({
v4: "Kling 4.0",
"v4-flash": "Kling 4.0 Flash",
});
const FLASH_MODELS = new Set(["v4-flash", "Kling 4.0 Flash"]);
const STANDARD_V4_MODELS = new Set(["v4", "Kling 4.0"]);
const FLASH_RESOLUTIONS = ["720p"];
const STANDARD_RESOLUTIONS = ["720p", "1080p"];
const RESOLUTION_FALLBACK = "720p";
const FLASH_MAX_DURATION = 20;
const STANDARD_MAX_DURATION = 30;
const INSTALLED_FLAG = "o1keyKlingV4ParameterGuardInstalled";
const LABEL_FLAG = "o1keyKlingV4ModelLabelsInstalled";
function notify(detail) {
app.extensionManager?.toast?.add({
severity: "warn",
summary: "Kling 参数已调整",
detail,
life: 4000,
});
}
function collectWidgets(root, found = []) {
const widgets = root?.widgets || root?.childWidgets || [];
for (const widget of widgets) {
found.push(widget);
if (widget?.widgets || widget?.childWidgets) {
collectWidgets(widget, found);
}
}
return found;
}
function findWidget(node, name) {
return collectWidgets(node).find((widget) => widget?.name === name);
}
function modelValueFrom(node, modelWidget) {
const value = modelWidget?.value;
if (value && typeof value === "object") {
return value.模型 ?? value.model ?? "";
}
return value ?? "";
}
function isFlashModel(model) {
return FLASH_MODELS.has(String(model || ""));
}
function isKlingV4Family(model) {
const raw = String(model || "");
return FLASH_MODELS.has(raw) || STANDARD_V4_MODELS.has(raw);
}
function setWidgetValue(widget, value) {
if (!widget || widget.value === value) return;
widget.value = value;
widget.callback?.(value);
}
function clampDuration(value, maximum) {
const duration = Number.parseInt(value, 10);
if (Number.isFinite(duration) && duration > maximum) return maximum;
return value;
}
function applyModelLabels(widget) {
if (!widget?.options || widget.options[LABEL_FLAG]) return;
const previousGetOptionLabel = widget.options.getOptionLabel;
widget.options.getOptionLabel = (value) => {
const normalized = value == null ? "" : String(value);
if (MODEL_LABELS[normalized]) return MODEL_LABELS[normalized];
return previousGetOptionLabel?.(value) ?? normalized;
};
widget.options[LABEL_FLAG] = true;
}
function updateDynamicParameters(node, silent = false) {
const modelWidget = findWidget(node, "模型");
if (!modelWidget) return;
applyModelLabels(modelWidget);
const model = modelValueFrom(node, modelWidget);
if (!isKlingV4Family(model)) return;
const resWidget = findWidget(node, "模式");
const durationWidget = findWidget(node, "时长");
const flash = isFlashModel(model);
const allowedResolutions = flash ? FLASH_RESOLUTIONS : STANDARD_RESOLUTIONS;
const maximumDuration = flash ? FLASH_MAX_DURATION : STANDARD_MAX_DURATION;
if (resWidget) {
resWidget.options ??= {};
resWidget.options.values = allowedResolutions;
const current = String(resWidget.value ?? "");
if (!allowedResolutions.includes(current)) {
setWidgetValue(resWidget, RESOLUTION_FALLBACK);
if (!silent) {
notify(`${MODEL_LABELS[model] || model} 仅支持 ${allowedResolutions.join(" / ")},已自动切换为 ${RESOLUTION_FALLBACK}。`);
}
}
}
if (durationWidget) {
durationWidget.options ??= {};
if (durationWidget.options.max != null) durationWidget.options.max = maximumDuration;
if (durationWidget.max != null) durationWidget.max = maximumDuration;
const clamped = clampDuration(durationWidget.value, maximumDuration);
if (clamped !== durationWidget.value) {
setWidgetValue(durationWidget, clamped);
if (!silent) {
notify(`${MODEL_LABELS[model] || model} 的最大时长为 ${maximumDuration} 秒,已自动调整。`);
}
}
}
if (modelWidget.value && typeof modelWidget.value === "object") {
const current = modelWidget.value;
let changed = false;
if (resWidget && current.模式 && !allowedResolutions.includes(String(current.模式))) {
current.模式 = RESOLUTION_FALLBACK;
changed = true;
}
if (current.时长 != null) {
const next = clampDuration(current.时长, maximumDuration);
if (next !== current.时长) {
current.时长 = next;
changed = true;
}
}
if (changed && !silent) {
notify(`${MODEL_LABELS[model] || model} 的分辨率或时长已按官方范围调整。`);
}
}
node.setDirtyCanvas?.(true, true);
}
function guardNode(node) {
if (!node || node.comfyClass !== NODE_TYPE || node[INSTALLED_FLAG]) return;
node[INSTALLED_FLAG] = true;
const modelWidget = findWidget(node, "模型");
if (!modelWidget) return;
applyModelLabels(modelWidget);
const origModelCb = modelWidget.callback;
modelWidget.callback = function () {
const ret = origModelCb?.apply(this, arguments);
updateDynamicParameters(node);
return ret;
};
const resWidget = findWidget(node, "模式");
if (resWidget) {
const origResCb = resWidget.callback;
resWidget.callback = function (value) {
const model = modelValueFrom(node, modelWidget);
if (isFlashModel(model) && value === "1080p") {
resWidget.value = RESOLUTION_FALLBACK;
notify("Kling 4.0 Flash 仅支持 720p,已自动切换为 720p。");
node.setDirtyCanvas?.(true, true);
return origResCb?.call(this, RESOLUTION_FALLBACK);
}
return origResCb?.apply(this, arguments);
};
}
const durationWidget = findWidget(node, "时长");
if (durationWidget) {
const origDurationCb = durationWidget.callback;
durationWidget.callback = function (value) {
const model = modelValueFrom(node, modelWidget);
const maximum = isFlashModel(model) ? FLASH_MAX_DURATION : STANDARD_MAX_DURATION;
const clamped = clampDuration(value, maximum);
if (clamped !== value) {
durationWidget.value = clamped;
notify(`${MODEL_LABELS[model] || model} 的最大时长为 ${maximum} 秒。`);
node.setDirtyCanvas?.(true, true);
return origDurationCb?.call(this, clamped);
}
return origDurationCb?.apply(this, arguments);
};
}
updateDynamicParameters(node, true);
}
app.registerExtension({
name: "o1key.klingV4ParameterGuard",
nodeCreated(node) {
if (node?.comfyClass === NODE_TYPE) guardNode(node);
},
loadedGraphNode(node) {
if (node?.comfyClass !== NODE_TYPE) return;
guardNode(node);
updateDynamicParameters(node, true);
},
});