Kling 节点接入官方 4.0 / Flash(文生/图生/Omni)
This commit is contained in:
+343
-77
@@ -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
|
||||
keeps the Kling 4.0 capability matrix and request shape in one testable place
|
||||
so the node only has to upload media and call the existing poll/download
|
||||
pipeline.
|
||||
keeps the official Kling 4.0 and Kling 4.0 Flash capability matrix, request
|
||||
shape, and query envelope in one testable place. The model is selected by
|
||||
path; request bodies must not include a `model` field.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
|
||||
KlingV4GenerationMode = str
|
||||
|
||||
@@ -17,14 +19,53 @@ GENERATION_MODES = {
|
||||
"omni": "全能参考",
|
||||
}
|
||||
|
||||
ENDPOINTS = {
|
||||
"text": ("/kling/v1/videos/text2video", "/kling/v1/videos/text2video/{task_id}"),
|
||||
"keyframes": ("/kling/v1/videos/image2video", "/kling/v1/videos/image2video/{task_id}"),
|
||||
"omni": ("/kling/v1/videos/omni-video", "/kling/v1/videos/omni-video/{task_id}"),
|
||||
_MODEL_SPECS = {
|
||||
"v4": {
|
||||
"id": "v4",
|
||||
"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"}
|
||||
_ASPECT_RATIOS = {"智能", "16:9", "9:16", "1:1", "21:9"}
|
||||
_MODEL_ALIASES = {
|
||||
"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:
|
||||
@@ -38,43 +79,239 @@ def canonical_generation_mode(value: str) -> str:
|
||||
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(
|
||||
*,
|
||||
generation_mode: str,
|
||||
prompt: str,
|
||||
model: str = "v4",
|
||||
negative_prompt: str = "",
|
||||
duration: int = 5,
|
||||
resolution: str = "720p",
|
||||
duration: int | None = None,
|
||||
resolution: str | None = None,
|
||||
aspect_ratio: str = "智能",
|
||||
first_frame: str | None = None,
|
||||
middle_frames: list[str] | None = None,
|
||||
last_frame: str | None = None,
|
||||
reference_images: 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:
|
||||
"""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
|
||||
`metadata`) and maps the metadata fields to the official Kling 4.0
|
||||
contents/settings representation. Keyframes and Omni references are
|
||||
mutually exclusive at the provider boundary.
|
||||
The body uses `contents` / `settings` / `options` and never includes `model`.
|
||||
Keyframes cannot send `settings.aspect_ratio` or `settings.audio`. Flash
|
||||
only accepts `720p` and 3–20 second durations.
|
||||
"""
|
||||
|
||||
mode = canonical_generation_mode(generation_mode)
|
||||
prompt = str(prompt or "").strip()
|
||||
if not prompt:
|
||||
raise ValueError("Kling 4.0 生成模式下提示词不能为空")
|
||||
if resolution not in _RESOLUTION_MODE:
|
||||
raise ValueError("Kling 4.0 仅支持 720p 或 1080p")
|
||||
try:
|
||||
duration = int(duration)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError("Kling 4.0 时长必须是整数秒") from None
|
||||
if duration < 3 or duration > 30:
|
||||
raise ValueError("Kling 4.0 时长必须在 3~30 秒之间")
|
||||
if aspect_ratio not in _ASPECT_RATIOS:
|
||||
raise ValueError(f"Kling 4.0 不支持宽高比:{aspect_ratio}")
|
||||
spec = kling_v4_model_spec(model)
|
||||
prompt_text = str(prompt or "").strip()
|
||||
negative = str(negative_prompt or "").strip()
|
||||
if negative:
|
||||
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:
|
||||
duration = int(duration)
|
||||
except (TypeError, ValueError):
|
||||
raise ValueError(f"{spec['display_name']} 时长必须是整数秒") from None
|
||||
if duration < spec["min_duration"] or duration > spec["max_duration"]:
|
||||
raise ValueError(
|
||||
f"{spec['display_name']} 时长必须在 "
|
||||
f"{spec['min_duration']}~{spec['max_duration']} 秒之间"
|
||||
)
|
||||
settings["duration"] = duration
|
||||
|
||||
middle_frames = list(middle_frames or [])
|
||||
reference_images = list(reference_images or [])
|
||||
@@ -86,59 +323,88 @@ def build_kling_v4_body(
|
||||
if len(reference_videos) > 5:
|
||||
raise ValueError("Kling 4.0 最多支持 5 段参考视频")
|
||||
|
||||
body = {
|
||||
"model_name": "kling-v4",
|
||||
"prompt": prompt,
|
||||
"duration": duration,
|
||||
"mode": _RESOLUTION_MODE[resolution],
|
||||
"watermark_info": {"enabled": False},
|
||||
body: dict[str, Any] = {
|
||||
"options": {"watermark_info": {"enabled": bool(watermark_enabled)}},
|
||||
}
|
||||
if negative_prompt and str(negative_prompt).strip():
|
||||
body["negative_prompt"] = str(negative_prompt).strip()
|
||||
|
||||
if mode == "text":
|
||||
if first_frame or middle_frames or last_frame or reference_images or reference_videos:
|
||||
raise ValueError("文生视频模式不能连接图片或视频素材")
|
||||
elif mode == "keyframes":
|
||||
if not first_frame:
|
||||
raise ValueError("关键帧模式必须提供首帧图片")
|
||||
body["prompt"] = prompt_text
|
||||
settings["aspect_ratio"] = _normalize_aspect_ratio(mode, aspect_ratio)
|
||||
body["settings"] = settings
|
||||
return body
|
||||
|
||||
if mode == "keyframes":
|
||||
if reference_images or reference_videos:
|
||||
raise ValueError("关键帧模式不能同时使用全能参考素材")
|
||||
if last_frame and not first_frame:
|
||||
raise ValueError("尾帧必须与首帧一起提供")
|
||||
if len([first_frame, *middle_frames, last_frame] if last_frame else [first_frame, *middle_frames]) > 10:
|
||||
raise ValueError("Kling 4.0 关键帧总数不能超过 10 张")
|
||||
metadata = {"first_frame": first_frame}
|
||||
if middle_frames:
|
||||
metadata["middle_frames"] = middle_frames
|
||||
keyframes = []
|
||||
if first_frame:
|
||||
keyframes.append(("first_frame", first_frame, "first"))
|
||||
for index, url in enumerate(middle_frames, start=1):
|
||||
keyframes.append(("middle_frame", url, _content_id("middle", index)))
|
||||
if last_frame:
|
||||
metadata["last_frame"] = last_frame
|
||||
body["metadata"] = metadata
|
||||
else:
|
||||
if first_frame or middle_frames or last_frame:
|
||||
raise ValueError("全能参考模式不能同时使用关键帧")
|
||||
if not reference_images and not reference_videos:
|
||||
raise ValueError("全能参考模式至少需要一张参考图或一段参考视频")
|
||||
if len(reference_images) + len(reference_videos) > 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
|
||||
keyframes.append(("last_frame", last_frame, "last"))
|
||||
if not keyframes:
|
||||
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
|
||||
|
||||
# The first frame determines the output shape. For text/Omni requests,
|
||||
# "智能" is represented by the provider's adaptive ratio value.
|
||||
if mode != "keyframes":
|
||||
body["aspect_ratio"] = "adaptive" if aspect_ratio == "智能" else aspect_ratio
|
||||
if first_frame or middle_frames or last_frame:
|
||||
raise ValueError("全能参考模式不能同时使用关键帧")
|
||||
if not reference_images and not reference_videos:
|
||||
raise ValueError("全能参考模式至少需要一张参考图或一段参考视频")
|
||||
if len(reference_images) + len(reference_videos) > 15:
|
||||
raise ValueError("Kling 4.0 全能参考素材总数不能超过 15 个")
|
||||
|
||||
audio_value = _normalize_audio(audio)
|
||||
reference_kind = str(video_reference_type or "特征参考").strip()
|
||||
if reference_kind not in {"特征参考", "待编辑视频", "feature_video", "base_video"}:
|
||||
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
|
||||
|
||||
|
||||
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)]
|
||||
|
||||
|
||||
Reference in New Issue
Block a user