"""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 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 GENERATION_MODES = { "text": "文生视频", "keyframes": "关键帧", "omni": "全能参考", } _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", }, } _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: """Return the wire value for a displayed Kling 4.0 generation mode.""" if value in GENERATION_MODES: return value for wire_value, display_value in GENERATION_MODES.items(): if value == display_value: return wire_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( *, generation_mode: str, prompt: str, model: str = "v4", negative_prompt: str = "", 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, video_reference_type: str = "特征参考", audio: str = "native", watermark_enabled: bool = False, ) -> dict: """Build an official Kling 4.0 / Flash request body. 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) 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 []) reference_videos = list(reference_videos or []) if len(middle_frames) > 8: raise ValueError("Kling 4.0 最多支持 8 张中间关键帧") if len(reference_images) > 10: raise ValueError("Kling 4.0 最多支持 10 张参考图") if len(reference_videos) > 5: raise ValueError("Kling 4.0 最多支持 5 段参考视频") body: dict[str, Any] = { "options": {"watermark_info": {"enabled": bool(watermark_enabled)}}, } if mode == "text": if first_frame or middle_frames or last_frame or reference_images or reference_videos: 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("关键帧模式不能同时使用全能参考素材") 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: 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 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