"""能力声明、默认值与提交参数校验,不执行模型任务。""" from __future__ import annotations import math import re from app.domain.errors import MediaError as ProviderError from app.domain.tasks import GPU_TYPES as GPU_TASKS from app.domain import video_generation as video_profiles LANGUAGES = ["zh", "en", "ja", "ko", "de", "fr", "es", "ru", "ar", "pt", "it", "auto"] REFERENCE_PROFILES = { "qwen-image-edit-2511-v1": ("Qwen-Image-Edit-2511", 3), "qwen-image-edit-2509-v1": ("Qwen-Image-Edit-2509", 3), "qwen-image-edit-2511-experimental-4-v1": ("Qwen-Image-Edit-2511", 4), } H3_CERTIFIED_REVISION = "12253298adb81e36757eabebb81d2ba1c0cc70cc" H3_CERTIFICATION_REASON = "上游H3视频生成未完成正式认证或模型版本不匹配。" H3_TP2_CERTIFICATION_REASON = "上游H3双卡视频生成未完成正式认证或能力合同不匹配。" H3_TP2_RUNTIME_REVISION = "423ab90580b2847998591669b8326f47b6d14d8b" def h3_tp2_certified(certificate): """双卡认证独立于v1/v2;PoC、旧证书和数值真值均不能开放业务入口。""" return ( isinstance(certificate, dict) and certificate.get("available") is True and certificate.get("profile") == video_profiles.H3_TP2_PROFILE and certificate.get("revision") == H3_CERTIFIED_REVISION and certificate.get("adapter_contract_version") == "h3-fl2va-tp2-v1" and type(certificate.get("gpu_count")) is int and certificate["gpu_count"] == 2 and certificate.get("runtime_revision") == H3_TP2_RUNTIME_REVISION and certificate.get("input_modes") == ["first_frame"] and certificate.get("output_policy") == "crop_requested" and type(certificate.get("fps")) is int and certificate["fps"] == 24 and certificate.get("canvases") == [[1344, 768], [768, 1344]] and all(type(value) is int for canvas in certificate["canvases"] for value in canvas) and certificate.get("upscale") is False and type(certificate.get("max_requested_frames")) is int and certificate["max_requested_frames"] == video_profiles.H3_TP2_MAX_REQUESTED_FRAMES and type(certificate.get("max_source_seconds")) is int and certificate["max_source_seconds"] == video_profiles.H3_TP2_MAX_SOURCE_SECONDS ) async def h3_tp2_available(provider, settings): if not getattr(settings, "inference_base_url", ""): return False try: snapshot = await provider.upstream_capabilities() upstream = snapshot.get("video_generation") if isinstance(snapshot, dict) else None return h3_tp2_certified(upstream.get("tp2") if isinstance(upstream, dict) else None) except Exception: return False def reference_capability(settings): profile = getattr(settings, "reference_generation_profile", "qwen-image-edit-2511-v1") model, maximum = REFERENCE_PROFILES.get(profile, ("Unrecognized edit profile", 0)) maximum = min(maximum, getattr(settings, "reference_max_images", 3)) return { "profile": profile, "model": model, "max_reference_images": maximum, "available": bool( maximum and getattr(settings, "reference_generation_enabled", False) and getattr(settings, "inference_base_url", "") ), } def _invalid(message="任务输入或参数无效。"): return ProviderError("invalid_input", message) def _keys(value, allowed): if not isinstance(value, dict) or set(value) - set(allowed): raise _invalid("包含不支持的输入或参数。") def _int(value, low, high, step=1): if type(value) is not int or not low <= value <= high or value % step: raise _invalid("整数参数超出范围或步长不正确。") return value def _float(value, low, high): if isinstance(value, bool) or not isinstance(value, (float, int)): raise _invalid("数值参数无效。") try: normalized = float(value) except (ValueError, OverflowError): raise _invalid("数值参数无效。") from None if not math.isfinite(normalized) or not low <= normalized <= high: raise _invalid("数值参数超出范围。") return normalized def _string(value, maximum=8000, *, required=True): if not isinstance(value, str) or len(value) > maximum or (required and not value.strip()): raise _invalid("文字内容为空或超出长度限制。") return value def _voices(settings): values = getattr(settings, "tts_voices", ["zf_xiaobei", "zm_yunxi"]) if isinstance(values, str): values = [item.strip() for item in values.split(",") if item.strip()] return [ value for value in values if isinstance(value, str) and re.fullmatch(r"[A-Za-z0-9_-]{1,64}", value) ] def capabilities(settings) -> list[dict]: from app.core.runtime_policy import read_runtime_policy compose_limit = read_runtime_policy(settings)["workflow_max_shots"] image_defaults = { "width": 1024, "height": 1024, "num_inference_steps": 50, "seed": 42, "guidance_scale": 4.0, } image_limits = { "width": {"min": 256, "max": 2048, "step": 16}, "height": {"min": 256, "max": 2048, "step": 16}, "num_inference_steps": {"min": 1, "max": 100}, "guidance_scale": {"min": 1, "max": 20}, "seed": {"min": 0, "max": 2**32 - 1}, "count": {"min": 1, "max": 4}, "max_pixels": 2048 * 2048, } selected_video_profile = getattr( settings, "video_generation_profile", video_profiles.LEGACY_PROFILE ) video_defaults = video_profiles.defaults(selected_video_profile) video_limits = video_profiles.constraints(selected_video_profile) configured = bool(getattr(settings, "inference_base_url", "")) qwen = bool(getattr(settings, "qwen_base_url", "") and getattr(settings, "qwen_model", "")) speech = bool( getattr(settings, "tts_base_url", "") and getattr(settings, "tts_model", "") and _voices(settings) ) reference = reference_capability(settings) def item( task_type, label, model, available, types, defaults, constraints, description, **extra ): return dict( task_type=task_type, label=label, model=model, available=available, input_types=types, defaults=defaults, constraints=constraints, description=description, **extra, ) from app.domain.video_editing import video_capability, video_defaults as edit_defaults edit = video_capability(settings) story_tasks = [ *[ item( task, label, edit["model"], edit["available"], ["video"], edit_defaults(task, settings), {k: edit[k] for k in ("max_seconds", "max_people", "max_pixels", "fps")}, edit["reason"] or "按视频实例选择多人替换,保留未选人物与背景。", ) for task, label in ( ("video.people.analyze", "识别视频人物"), ("video.replace", "视频多人替换"), ) ], item( "image.reference.generate", "多图锚定首帧", reference["model"], reference["available"], ["text", "images"], { "profile": reference["profile"], "width": 1280, "height": 704, "num_inference_steps": 40, "seed": 42, "guidance_scale": 1.0, "true_cfg_scale": 4.0, "max_sequence_length": 1024, }, { "max_reference_images": reference["max_reference_images"], "sizes": [[1280, 704], [704, 1280], [1024, 1024]], "count": {"min": 1, "max": 4}, "max_sequence_length": {"min": 1, "max": 1024}, "num_inference_steps": {"min": 1, "max": 100}, "guidance_scale": {"min": 1, "max": 20}, "true_cfg_scale": {"min": 1, "max": 20}, "seed": {"min": 0, "max": 2**32 - 1}, }, "按顺序使用全部真实参考图片;需完成服务端认证,缺图不会降级文生图。", ), item( "image.prepare_frame", "首帧规范化", "Pillow CPU", True, ["image"], {"width": 1280, "height": 704, "fit": "contain"}, { "width": {"min": 256, "max": 2048, "step": 16}, "height": {"min": 256, "max": 2048, "step": 16}, "fit": {"values": ["contain", "cover"]}, }, "生成独立RGB PNG,按指定尺寸留边或居中裁剪,不覆盖原素材。", ), ] # 旧快速创作依赖首项为文生图,新增内部阶段追加在原能力之后。 return [ item( "image.generate", "图像生成", "Qwen-Image", configured, ["text"], image_defaults, image_limits, "文字生成图片;不包含图像编辑或风格 LoRA 管理。", ), item( "video.generate", "视频生成", "MiniMax H3 FL2VA TP2(双卡)" if selected_video_profile == video_profiles.H3_TP2_PROFILE else "MiniMax H3 FL2VA + Real-ESRGAN" if selected_video_profile in video_profiles.H3_PROFILES else "Wan2.2-TI2V-5B + Real-ESRGAN", configured and selected_video_profile not in video_profiles.H3_PROFILES, ["text", "image"], video_defaults, video_limits, "首帧生成1–6秒静音片段;等待两张空闲GPU一起开始,不支持画质增强" if selected_video_profile == video_profiles.H3_TP2_PROFILE else "H3单镜头1–14秒、24fps静音视频;历史Wan任务保留原配置,可选1080p增强。", video_profiles=[ { "profile": profile, # 配置了地址不代表H3通过认证;服务层核对上游证书后才能开放。 "available": configured and profile not in video_profiles.H3_PROFILES, "reason": H3_TP2_CERTIFICATION_REASON if profile == video_profiles.H3_TP2_PROFILE else H3_CERTIFICATION_REASON if profile in video_profiles.H3_PROFILES else None, "model": "MiniMax H3 FL2VA TP2(双卡)" if profile == video_profiles.H3_TP2_PROFILE else "MiniMax H3 FL2VA" if profile in video_profiles.H3_PROFILES else "Wan2.2-TI2V-5B", "defaults": video_profiles.defaults(profile), "constraints": video_profiles.constraints(profile), "description": "首帧生成1–6秒静音片段;等待两张空闲GPU一起开始,不支持画质增强" if profile == video_profiles.H3_TP2_PROFILE else "124–345 原生帧,步长17" if profile == video_profiles.H3_V2_PROFILE else "1–14秒静音片段;不使用CFG或负提示词" if profile in video_profiles.H3_PROFILES else "保留历史1–15秒视频配置", } for profile in (*video_profiles.H3_PROFILES, video_profiles.LEGACY_PROFILE) ], ), item( "defect.generate", "条件样本生成", "SDXL + Canny ControlNet", configured, ["text", "image"], dict( image_defaults, guidance_scale=7.5, controlnet_conditioning_scale=0.8, canny_low=100, canny_high=200, ), { **image_limits, "controlnet_conditioning_scale": {"min": 0, "max": 2}, "canny_low": {"min": 0, "max": 255}, "canny_high": {"min": 0, "max": 255}, }, "参考图片提供边缘结构;输出控制图不是缺陷真值掩膜。", ), item( "audio.transcribe", "语音转写", "Whisper-large-v3-turbo", configured, ["audio", "video"], {"language": "zh", "max_audio_seconds": 1800}, {"language": {"values": LANGUAGES}, "max_audio_seconds": {"min": 1, "max": 1800}}, "支持音频和有声视频;时间戳为30秒块边界,不是字词对齐。", ), item( "math.solve", "数学推演", getattr(settings, "qwen_model", ""), qwen, ["text"], {"max_tokens": 2048, "enable_thinking": False}, {"max_tokens": {"min": 1, "max": 4096}}, "调用现有文本服务给出解答,未集成形式化证明或准确率评测。", ), item( "media.structure", "素材理解", getattr(settings, "qwen_model", ""), qwen, ["image", "video"], {"frame_count": 6}, {"frame_count": {"min": 1, "max": 12}}, "视频均匀抽帧后理解画面、文字和标签;不承诺镜头切分准确率。", ), item( "video.compose", "成片编排", "FFmpeg CPU", True, ["video", "audio"], {"width": 1280, "height": 720, "fps": 24}, { "width": {"min": 256, "max": 3840, "step": 2}, "height": {"min": 256, "max": 2160, "step": 2}, "fps": {"values": [24, 25, 30, 60]}, "clips": {"min": 1, "max": compose_limit}, "source_duration_seconds": {"min": 0.05, "max": 86400}, }, "按顺序裁剪拼接片段,支持上传音轨和人工字幕;无热度预测。", ), item( "audio.speech", "中文配音", getattr(settings, "tts_model", "") or "尚未配置", speech, ["text"], {"voice": (_voices(settings) or [""])[0], "speed": 1.0}, { "voice": {"values": _voices(settings)}, "speed": {"min": 0.5, "max": 2}, "text": {"max": 2000}, }, "仅在配置真实语音服务后可用;输出 WAV,不提供音乐生成。", ), item( "text.script.generate", "镜头旁白文案", getattr(settings, "qwen_model", ""), qwen, ["text"], {}, {"max_shots": 1000}, "按稳定镜头ID生成可编辑的简短旁白。", ), item( "audio.assemble", "旁白音轨装配", "FFmpeg", True, ["audio"], {"fps": 24}, {"max_segments": 1000}, "将已选用配音段按24fps位置装配为单音轨。", ), item( "text.story.plan", "剧情连续性规划", getattr(settings, "qwen_model", ""), qwen, ["text"], {}, {"max_shots": 60}, "保留作者已有设定,补全镜头起止剧情状态。", ), item( "audio.normalize", "音频样本归一化", "FFmpeg", True, ["audio"], {}, {"sample_rate": {"values": [48000]}}, "生成48k立体声PCM并记录真实样本数。", ), item( "audio.mix", "音频图层混音", "FFmpeg", True, ["audio"], {"ducking": True}, {"max_segments": 128, "sample_rate": {"values": [48000]}}, "按整数样本裁剪、偏移和混合旁白、音乐及音效。", ), item( "video.continuity.inspect", "镜头连续性质检", getattr(settings, "qwen_model", ""), qwen and bool(getattr(settings, "continuity_quality_certified", False)), ["video"], {}, {"verdicts": ["pass", "reject", "indeterminate"]}, "检查真实选段与入边,未认证或证据不足时进入待处理。", ), *story_tasks, ] def validate_arguments(task_type: str, inputs: dict, parameters: dict, settings=None) -> None: """Pure submission validation: no HTTP, file decoding, mkdir or model work.""" p = parameters if task_type == "text.story.plan": from .story_planning import validate validate(inputs, parameters) return if task_type in {"audio.normalize", "audio.mix"}: from .audio_timeline import validate validate(task_type, inputs, parameters) return if task_type == "video.continuity.inspect": from .continuity_media import validate validate(inputs, parameters) return if task_type in {"text.script.generate", "audio.assemble"}: from .editor_media import validate validate(task_type, inputs, parameters) return if task_type == "image.prepare_frame": _keys(inputs, {"image_asset_id"}) _keys(p, {"width", "height", "fit"}) _string(inputs.get("image_asset_id"), 64) for name in ("width", "height"): _int(p.get(name, 1280 if name == "width" else 704), 256, 2048, 16) if p.get("fit", "contain") not in {"contain", "cover"}: raise _invalid("首帧适配方式无效。") return if task_type in {"video.people.analyze", "video.replace"}: from app.domain.video_editing import validate_video_arguments validate_video_arguments(task_type, inputs, p, settings) return if task_type == "video.generate": from .video_generation import normalize try: normalize(p, inputs) except ValueError as exc: raise _invalid(str(exc)) from None return if task_type == "image.reference.generate": reference = reference_capability(settings) if not reference["available"]: raise ProviderError("capability_unavailable", "多图参考生成尚未通过认证或未启用。") _keys(inputs, {"prompt", "negative_prompt", "reference_asset_ids"}) _string(inputs.get("prompt")) _string(inputs.get("negative_prompt", ""), required=False) defaults = next( i["defaults"] for i in capabilities(settings) if i["task_type"] == task_type ) _keys(p, set(defaults)) p = {**defaults, **p} if p["profile"] != reference["profile"]: raise _invalid("参考生成必须使用已配置且认证的模型版本。") ids = inputs.get("reference_asset_ids") if not isinstance(ids, list) or not 1 <= len(ids) <= reference["max_reference_images"]: raise _invalid("参考图片数量超出已认证范围。") if any(not isinstance(v, str) for v in ids) or len(set(ids)) != len(ids): raise _invalid("参考图片不能重复。") for asset_id in ids: _string(asset_id, 64) if (p["width"], p["height"]) not in {(1280, 704), (704, 1280), (1024, 1024)}: raise _invalid("参考图仅支持1280×704、704×1280或1024×1024。") _int(p["num_inference_steps"], 1, 100) _int(p["seed"], 0, 2**32 - 1) _int(p["max_sequence_length"], 1, 1024) _float(p["guidance_scale"], 1, 20) _float(p["true_cfg_scale"], 1, 20) return if task_type in GPU_TASKS: allowed = ( {"audio_asset_id", "asset_id"} if task_type == "audio.transcribe" else {"prompt", "negative_prompt"} ) if task_type in {"video.generate", "defect.generate"}: allowed.add("image_asset_id") _keys(inputs, allowed) defaults = next( item["defaults"] for item in capabilities(settings) if item["task_type"] == task_type ) _keys( p, set(defaults) | ({"negative_prompt"} if task_type != "audio.transcribe" else set()) ) p = {**defaults, **p} if task_type == "audio.transcribe": if not (inputs.get("audio_asset_id") or inputs.get("asset_id")): raise _invalid("请选择转写素材。") if ( inputs.get("audio_asset_id") and inputs.get("asset_id") and inputs["audio_asset_id"] != inputs["asset_id"] ): raise _invalid("请仅选择一个转写素材。") if p["language"] not in LANGUAGES: raise _invalid("不支持此转写语言。") _int(p["max_audio_seconds"], 1, 1800) return _string(inputs.get("prompt")) _string(inputs.get("negative_prompt", ""), required=False) if "negative_prompt" in p: _string(p["negative_prompt"], required=False) video = task_type == "video.generate" for key in ("width", "height"): _int(p[key], 256, 1280 if video else 2048, 32 if video else 16) if p["width"] * p["height"] > (1280 * 704 if video else 2048 * 2048): raise _invalid("画面像素总数超出服务限制。") _int(p["num_inference_steps"], 1, 100) _int(p["seed"], 0, 2**32 - 1) _float(p["guidance_scale"], 1, 20) if task_type == "defect.generate": if not inputs.get("image_asset_id"): raise _invalid("条件样本任务需要参考图片。") _float(p["controlnet_conditioning_scale"], 0, 2) _int(p["canny_low"], 0, 255) _int(p["canny_high"], 0, 255) if p["canny_low"] >= p["canny_high"]: raise _invalid("Canny低阈值必须小于高阈值。") if video: _int(p["num_frames"], 5, 361) if ( p["num_frames"] % 4 != 1 or type(p["fps"]) is not int or p["fps"] != 24 or type(p["upscale"]) is not bool ): raise _invalid("视频帧数、帧率或增强开关无效。") _int(p["upscale_width"], 256, 3840, 2) _int(p["upscale_height"], 256, 2160, 2) _int(p["tile_size"], 64, 256, 16) return if task_type == "math.solve": _keys(inputs, {"prompt"}) _keys(p, {"max_tokens", "enable_thinking"}) _string(inputs.get("prompt")) _int(p.get("max_tokens", 2048), 1, 4096) if type(p.get("enable_thinking", False)) is not bool: raise _invalid("思考开关必须为布尔值。") return if task_type == "media.structure": _keys(inputs, {"asset_id", "image_asset_id"}) _keys(p, {"frame_count"}) if not (inputs.get("asset_id") or inputs.get("image_asset_id")): raise _invalid("请选择待理解素材。") if ( inputs.get("asset_id") and inputs.get("image_asset_id") and inputs["asset_id"] != inputs["image_asset_id"] ): raise _invalid("请选择一个待理解素材。") _int(p.get("frame_count", 6), 1, 12) return if task_type == "audio.speech": _keys(inputs, {"prompt"}) _keys(p, {"voice", "speed", "model"}) if p.get("model", getattr(settings, "tts_model", "")) != getattr(settings, "tts_model", ""): raise ProviderError("capability_changed", "配音模型配置已变化,请重新生成执行计划") _string(inputs.get("prompt"), 2000) voices = _voices(settings) if not voices or p.get("voice", voices[0]) not in voices: raise _invalid("请选择已配置的中文音色。") _float(p.get("speed", 1), 0.5, 2) return if task_type == "video.compose": if "story_spec" in p: from app.domain.stories import compile_story_render _keys(inputs, {"asset_ids", "audio_asset_id"}) _keys(p, {"story_spec", "render_inputs", "clips"}) try: plan = compile_story_render(p["story_spec"], p["render_inputs"]) except (ValueError, KeyError, TypeError): raise _invalid("Invalid frozen story timeline.") from None if inputs.get("asset_ids") != [c["asset_id"] for c in plan.clips] or p.get("clips") != [ {"asset_id": c["asset_id"]} for c in plan.clips ]: raise _invalid("Story clip order differs.") audio = plan.spec["render"]["audio"] if inputs.get("audio_asset_id") != (audio["asset_id"] if audio else None): raise _invalid("Story audio differs.") return if "workflow_spec" in p: from app.domain.timeline import WorkflowSpec _keys(inputs, {"asset_ids", "audio_asset_id"}) _keys(p, {"workflow_spec", "clips"}) try: spec = WorkflowSpec.model_validate(p["workflow_spec"]) except ValueError: raise _invalid("Invalid frozen workflow timeline.") from None clips = p.get("clips") if not isinstance(clips, list) or len(clips) != len(spec.shots): raise _invalid("Workflow clips must match the frozen shot count.") for clip in clips: _keys(clip, {"asset_id"}) _string(clip.get("asset_id"), 64) if inputs.get("asset_ids") != [c["asset_id"] for c in clips]: raise _invalid("Workflow clip order differs.") if inputs.get("audio_asset_id") != ( spec.render.audio.asset_id if spec.render.audio else None ): raise _invalid("Workflow audio differs.") return _keys(inputs, {"asset_ids", "audio_asset_id"}) _keys(p, {"clips", "audio_asset_id", "subtitles", "width", "height", "fps"}) clips = p.get("clips") if not isinstance(clips, list) or not 1 <= len(clips) <= 1000: raise _invalid("请选择1至1000个视频片段,并遵守当前配置的资源上限。") for clip in clips: _keys(clip, {"asset_id", "start_seconds", "end_seconds"}) _string(clip.get("asset_id"), 64) start = _float(clip.get("start_seconds", 0), 0, 86400) if ( clip.get("end_seconds") is not None and _float(clip["end_seconds"], 0, 86400) <= start ): raise _invalid("片段结束时间必须大于开始时间。") if "asset_ids" in inputs and inputs["asset_ids"] != [clip["asset_id"] for clip in clips]: raise _invalid("素材顺序应与编排片段一致。") if ( inputs.get("audio_asset_id") and p.get("audio_asset_id") and inputs["audio_asset_id"] != p["audio_asset_id"] ): raise _invalid("请只选择一个成片音轨。") _int(p.get("width", 1280), 256, 3840, 2) _int(p.get("height", 720), 256, 2160, 2) if type(p.get("fps", 24)) is not int or p.get("fps", 24) not in {24, 25, 30, 60}: raise _invalid("不支持此成片帧率。") cues = p.get("subtitles", []) if not isinstance(cues, list) or len(cues) > 1000: raise _invalid("人工字幕数量超出限制。") for cue in cues: _keys(cue, {"start", "end", "text"}) start, end = ( _float(cue.get("start"), 0, 86400 * 1000), _float(cue.get("end"), 0, 86400 * 1000), ) text = _string(cue.get("text"), 2000) if end <= start or "\n\n" in text or re.search(r"[\\{}\x00-\x08\x0b-\x1f]", text): raise _invalid("字幕时间或纯文本内容无效;不支持ASS控制语法。") return raise _invalid("不支持此任务类型。")