"""Check and coerce studio form values against a workflow's input schema.""" from __future__ import annotations import math from pathlib import Path from typing import Any def _fmt(n: Any) -> str: return f"{n:g}" if isinstance(n, float) else str(n) def validate_input_values( schema: list[dict[str, Any]], values: dict[str, Any] ) -> tuple[dict[str, Any], list[str]]: """Return ``(clean_values, errors)``. Numbers are coerced to int/float per the schema entry (``integer``, ``min``/``max``); select values must be one of ``options``. Blank values are dropped so the workflow keeps its own value. Keys not in the schema pass through untouched (other callers patch extra keys, e.g. uploads). Auto-detected required entries (positive prompt, wired image slots, reference-image lists) must be present — tagged workflows mark every input required, and blank ones fall back to the workflow's value. """ by_key = {str(e.get("nodeId")): e for e in schema if isinstance(e, dict)} clean: dict[str, Any] = {} errors: list[str] = [] for key, raw in (values or {}).items(): entry = by_key.get(str(key)) if entry is None: clean[key] = raw continue if raw is None or (isinstance(raw, str) and not raw.strip()): continue label = str(entry.get("label") or key) kind = entry.get("kind") if kind == "number": if isinstance(raw, bool): errors.append(f"「{label}」必须是数字") continue try: num = float(raw) except (TypeError, ValueError): errors.append(f"「{label}」必须是数字") continue if not math.isfinite(num): errors.append(f"「{label}」必须是有限数字") continue if entry.get("integer"): if num != int(num): errors.append(f"「{label}」必须是整数") continue value: int | float = int(num) else: value = int(num) if isinstance(raw, int) else num lo, hi = entry.get("min"), entry.get("max") if lo is not None and value < lo: errors.append(f"「{label}」不能小于 {_fmt(lo)}") continue if hi is not None and value > hi: errors.append(f"「{label}」不能大于 {_fmt(hi)}") continue clean[key] = value elif kind in ("image_list", "video_list", "audio_list"): paths = [raw] if isinstance(raw, str) else raw if not isinstance(paths, list) or not all(isinstance(p, str) for p in paths): errors.append(f"「{label}」的取值格式不对,请重新上传") continue paths = [p for p in paths if p.strip()] unit = _LIST_UNITS[kind] noun = _LIST_NOUNS[kind] hi = entry.get("max") if hi is not None and len(paths) > hi: errors.append( f"{label}最多 {hi} {unit}(当前 {len(paths)} {unit}),请删除多余的{noun}" ) continue bad = [ f"{label} {i}:{msg}" for i, p in enumerate(paths, 1) if (msg := _media_file_problem(p, kind)) ] if bad: errors.extend(bad) continue if paths: clean[key] = paths elif kind == "select": options = entry.get("options") or [] if options and raw not in options: errors.append(f"「{label}」的取值「{raw}」不在工作流支持的选项中") continue clean[key] = raw else: clean[key] = raw for key, entry in by_key.items(): required = entry.get("auto") and entry.get("required") label = entry.get("label") or key if required and entry.get("role") == "prompt": has_fallback = str(entry.get("defaultValue") or "").strip() != "" if key not in clean and not has_fallback: errors.append(f"请填写「{label}」") elif required and entry.get("kind") in ("image_list", "video_list", "audio_list"): lo = entry.get("min") or 1 unit = _LIST_UNITS[entry.get("kind")] if len(clean.get(key) or []) < lo and not any(label in e for e in errors): errors.append(f"需要至少 {lo} {unit}{label}") elif required and entry.get("kind") == "image" and entry.get("role") != "mask": if key not in clean: errors.append(f"请上传{label}") return clean, errors _IMAGE_EXTS = frozenset({".png", ".jpg", ".jpeg", ".webp"}) _VIDEO_EXTS = frozenset({".mp4", ".webm", ".mov"}) _AUDIO_EXTS = frozenset({".mp3", ".wav", ".m4a"}) _LIST_UNITS = {"image_list": "张", "video_list": "段", "audio_list": "段"} _LIST_NOUNS = {"image_list": "图片", "video_list": "视频", "audio_list": "音频"} _LIST_EXTS = {"image_list": _IMAGE_EXTS, "video_list": _VIDEO_EXTS, "audio_list": _AUDIO_EXTS} _LIST_FORMAT_HINT = { "image_list": "格式不支持,请使用 PNG / JPG / WebP", "video_list": "格式不支持,请使用 MP4 / WebM / MOV", "audio_list": "格式不支持,请使用 MP3 / WAV / M4A", } def _media_file_problem(path: str, kind: str) -> str | None: """Why ``path`` cannot fill a media-list slot of this kind (None = fine).""" from calliope import config target = Path(path) if target.suffix.lower() not in _LIST_EXTS[kind]: return _LIST_FORMAT_HINT[kind] try: target.resolve().relative_to(config.settings.assets_dir.resolve()) except (ValueError, OSError): return f"只能使用在本页上传或从生成结果选入的{_LIST_NOUNS[kind]}" if not target.is_file(): return "文件已不存在,请重新上传" return None def _image_file_problem(path: str) -> str | None: return _media_file_problem(path, "image_list")