"""Normalize prompt planning output for workflow generation nodes.""" from __future__ import annotations from copy import deepcopy from typing import Any from backend.dto.workflow_dto import WorkflowNode from engines.character_flow import canonical_gradual_node_key PROMPT_PLAN_SCHEMA_VERSION = "2026-07-09.prompt-plan-schema.v1" TARGET_NODE_KEYS: dict[str, tuple[str, ...]] = { "portrait": ("headshot", "fast_candidates"), "headshot": ("headshot", "fast_candidates"), "face": ("headshot", "fast_candidates"), "bust": ("upper_body",), "halfbody": ("upper_body",), "half_body": ("upper_body",), "upper_body": ("upper_body",), "lower_body": ("lower_body",), "fullbody": ("full_body",), "full_body": ("full_body",), "body": ("full_body",), "sheet": ("turnaround", "design_sheet"), "design_sheet": ("design_sheet",), "turnaround": ("turnaround",), "expression_sheet": ("turnaround",), "pose_sheet": ("design_sheet",), "all": ("headshot", "fast_candidates", "upper_body", "lower_body", "full_body", "turnaround", "design_sheet"), } TARGET_TITLES: dict[str, str] = { "portrait": "Portrait/headshot", "bust": "Half body", "fullbody": "Full body", "sheet": "Design sheet", "all": "All generation nodes", } def normalize_prompt_plan( payload: Any, workflow_nodes: list[WorkflowNode] | None = None, ) -> dict[str, Any]: if isinstance(payload, dict) and payload.get("schema_version") == PROMPT_PLAN_SCHEMA_VERSION: normalized = deepcopy(payload) if workflow_nodes: matrix = normalized.get("matrix") if isinstance(normalized.get("matrix"), list) else [] normalized["by_node_id"] = _index_by_node_id(matrix, workflow_nodes) normalized["node_parameters"] = normalized["by_node_id"] return normalized source = _extract_source_payload(payload) matrix = [ _normalize_matrix_item(item, index + 1) for index, item in enumerate(_matrix_items(source)) if isinstance(item, dict) ] guardrails = _normalize_guardrails(source, matrix) conflicts = _collect_conflicts(matrix, guardrails) by_target = {item["target_id"]: item for item in matrix} by_node_key = _index_by_node_key(matrix) by_node_id = _index_by_node_id(matrix, workflow_nodes or []) return { "schema_version": PROMPT_PLAN_SCHEMA_VERSION, "target_prompt_language": "en", "profile_id": _optional_text(source.get("profile_id")), "profile_name": _optional_text(source.get("profile_name")), "matrix": matrix, "guardrails": guardrails, "conflicts": conflicts, "by_target": by_target, "by_node_key": by_node_key, "by_node_id": by_node_id, "node_parameters": by_node_id, "prompt_context": _prompt_context(matrix), "summary": { "target_count": len(matrix), "ready_count": len([item for item in matrix if item["status"] == "ready"]), "review_count": len([item for item in matrix if item["status"] == "review"]), "conflict_count": len(conflicts), "negative_prompt": guardrails["negative_prompt"], "target_node_keys": sorted(by_node_key), }, } def prompt_plan_for_node( workflow_metadata: dict[str, Any], node: WorkflowNode, workflow_nodes: list[WorkflowNode] | None = None, ) -> dict[str, Any]: normalized = normalize_prompt_plan(workflow_metadata.get("prompt_plan"), workflow_nodes) return node_prompt_plan_view(normalized, node) def node_prompt_plan_view(normalized: dict[str, Any], node: WorkflowNode) -> dict[str, Any]: by_node_id = normalized.get("by_node_id") if isinstance(normalized.get("by_node_id"), dict) else {} by_node_key = normalized.get("by_node_key") if isinstance(normalized.get("by_node_key"), dict) else {} node_view = by_node_id.get(node.node_id) if not isinstance(node_view, dict): canonical_key = canonical_gradual_node_key(node.node_key) node_view = _node_view(by_node_key.get(canonical_key, []), node.node_id, canonical_key, node.title) return { "schema_version": normalized.get("schema_version", PROMPT_PLAN_SCHEMA_VERSION), "target_prompt_language": normalized.get("target_prompt_language", "en"), "summary": normalized.get("summary", {}), "guardrails": normalized.get("guardrails", _normalize_guardrails({}, [])), "conflicts": normalized.get("conflicts", []), "target_node_id": node.node_id, "target_node_key": node.node_key, "target_node_title": node.title, **node_view, } def _extract_source_payload(payload: Any) -> dict[str, Any]: if not isinstance(payload, dict): return {} for key in ("prompt_plan", "prompt_matrix"): value = payload.get(key) if isinstance(value, dict): return value return payload def _matrix_items(source: dict[str, Any]) -> list[Any]: for key in ("matrix", "items", "targets", "updates"): value = source.get(key) if isinstance(value, list): return value return [] def _normalize_matrix_item(item: dict[str, Any], ordinal: int) -> dict[str, Any]: raw_target = _optional_text(item.get("target") or item.get("target_id") or item.get("id")) or f"target_{ordinal:02d}" target_id = _canonical_target(raw_target) target_node_keys = _target_node_keys(item, target_id) positive_prompt = _optional_text( item.get("positive_prompt") or item.get("prompt") or item.get("positive_patch") or item.get("prompt_patch") ) negative_prompt = _optional_text(item.get("negative_prompt") or item.get("negative") or item.get("negative_patch")) conflicts = _string_list(item.get("conflicts") or item.get("conflict")) status = _status(item.get("status"), conflicts) return { "id": _optional_text(item.get("id")) or target_id, "target_id": target_id, "target_title": _optional_text(item.get("title") or item.get("target_title")) or TARGET_TITLES.get(target_id, raw_target), "target_label": _optional_text(item.get("target_label") or item.get("target")) or raw_target, "target_node_keys": target_node_keys, "positive_prompt": positive_prompt or "", "positive_patch": _optional_text(item.get("positive_patch") or item.get("prompt_patch")) or positive_prompt or "", "negative_prompt": negative_prompt or "", "negative_patch": _optional_text(item.get("negative_patch")) or negative_prompt or "", "weight_suggestions": _weight_suggestions(item), "weight_basis": _optional_text(item.get("weight_basis") or item.get("weightBasis")) or "", "inheritance_fields": _string_list(item.get("inheritance_fields") or item.get("inherits")), "inheritance_changes": _string_list(item.get("inheritance_changes")), "conflicts": conflicts, "status": status, "next_action": _optional_text(item.get("next_action")) or ("review_conflicts" if conflicts else "apply_prompt_plan"), } def _normalize_guardrails(source: dict[str, Any], matrix: list[dict[str, Any]]) -> dict[str, Any]: raw_guards = source.get("guardrails") or source.get("guards") or source.get("guard_checks") or [] guard_items = raw_guards if isinstance(raw_guards, list) else [] negative_prompt = _optional_text(source.get("negative_prompt") or source.get("negative")) if not negative_prompt: negative_prompt = next((item["negative_prompt"] for item in matrix if item.get("negative_prompt")), "") checks = [_normalize_guard_item(item) for item in guard_items if isinstance(item, dict)] if negative_prompt and not any(item["key"] == "negative_prompt" for item in checks): checks.insert( 0, { "key": "negative_prompt", "label": "Negative prompt", "value": negative_prompt, "status": "ready", "severity": "info", }, ) return { "negative_prompt": negative_prompt or "", "checks": checks, "language_policy": { "source_language": "auto", "target_prompt_language": "en", "translation_mode": "backend_llm", }, } def _normalize_guard_item(item: dict[str, Any]) -> dict[str, str]: label = _optional_text(item.get("label") or item.get("key")) or "Guard" status = _status(item.get("status"), _string_list(item.get("conflicts"))) return { "key": _key(label), "label": label, "value": _optional_text(item.get("value")) or "", "status": status, "severity": _optional_text(item.get("severity")) or ("warn" if status == "review" else "info"), } def _index_by_node_key(matrix: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]: result: dict[str, list[dict[str, Any]]] = {} for item in matrix: for node_key in item["target_node_keys"]: result.setdefault(canonical_gradual_node_key(node_key), []).append(item) return result def _index_by_node_id( matrix: list[dict[str, Any]], workflow_nodes: list[WorkflowNode], ) -> dict[str, dict[str, Any]]: by_node_key = _index_by_node_key(matrix) result: dict[str, dict[str, Any]] = {} for node in workflow_nodes: canonical_key = canonical_gradual_node_key(node.node_key) items = by_node_key.get(canonical_key) if items: result[node.node_id] = _node_view(items, node.node_id, canonical_key, node.title) return result def _node_view( items: list[dict[str, Any]], node_id: str | None, node_key: str, title: str, ) -> dict[str, Any]: positive_parts = [item["positive_patch"] for item in items if item.get("positive_patch")] negative_parts = [item["negative_patch"] for item in items if item.get("negative_patch")] return { "target_node_id": node_id, "target_node_key": node_key, "target_node_title": title, "has_prompt_plan": bool(items), "matrix_items": deepcopy(items), "positive_prompt_patches": positive_parts, "negative_prompt_patches": negative_parts, "prompt_context": ", ".join(positive_parts), "generation_params": { "prompt_patch": ", ".join(positive_parts), "negative_patch": ", ".join(negative_parts), "weight_suggestions": [suggestion for item in items for suggestion in item["weight_suggestions"]], "inheritance_fields": _unique_texts(field for item in items for field in item["inheritance_fields"]), }, } def _target_node_keys(item: dict[str, Any], target_id: str) -> list[str]: explicit = _string_list(item.get("target_node_keys") or item.get("node_keys")) if explicit: return [canonical_gradual_node_key(node_key) for node_key in explicit] return list(TARGET_NODE_KEYS.get(target_id, TARGET_NODE_KEYS.get("all", ()))) def _canonical_target(value: str) -> str: normalized = value.strip().lower().replace("-", "_").replace(" ", "_") aliases = { "头像": "portrait", "头像节点": "portrait", "portrait": "portrait", "headshot": "portrait", "face": "portrait", "半身": "bust", "半身节点": "bust", "bust": "bust", "halfbody": "bust", "half_body": "bust", "upper_body": "bust", "上半身": "bust", "下半身": "lower_body", "lower_body": "lower_body", "全身": "fullbody", "全身节点": "fullbody", "body": "fullbody", "fullbody": "fullbody", "full_body": "fullbody", "设定图": "sheet", "设定图节点": "sheet", "sheet": "sheet", "design_sheet": "sheet", "三视图": "turnaround", "turnaround": "turnaround", "all": "all", } return aliases.get(normalized, normalized) def _weight_suggestions(item: dict[str, Any]) -> list[dict[str, Any]]: raw = item.get("weight_suggestions") or item.get("weight_changes") or item.get("weight") if isinstance(raw, str): return [{"label": raw, "value": None, "reason": _optional_text(item.get("weight_basis") or item.get("weightBasis")) or ""}] if not isinstance(raw, list): return [] suggestions = [] for entry in raw: if isinstance(entry, dict): suggestions.append( { "label": _optional_text(entry.get("label") or entry.get("target")) or "weight", "value": entry.get("value"), "reason": _optional_text(entry.get("reason") or entry.get("basis")) or "", } ) else: text = _optional_text(entry) if text: suggestions.append({"label": text, "value": None, "reason": ""}) return suggestions def _collect_conflicts(matrix: list[dict[str, Any]], guardrails: dict[str, Any]) -> list[dict[str, str]]: conflicts = [ {"target_id": item["target_id"], "message": conflict, "severity": "warn"} for item in matrix for conflict in item["conflicts"] ] for guard in guardrails.get("checks", []): if guard.get("status") == "review": conflicts.append({"target_id": "guardrails", "message": guard.get("value", ""), "severity": "warn"}) return conflicts def _prompt_context(matrix: list[dict[str, Any]]) -> list[dict[str, str]]: return [ { "target_id": item["target_id"], "target_node_keys": ", ".join(item["target_node_keys"]), "positive_patch": item["positive_patch"], "negative_patch": item["negative_patch"], } for item in matrix if item.get("positive_patch") or item.get("negative_patch") ] def _status(value: Any, conflicts: list[str]) -> str: status = str(value or "").strip().lower() if status in {"ready", "review", "pending"}: return status return "review" if conflicts else "ready" def _string_list(value: Any) -> list[str]: if isinstance(value, str): return [value] if value.strip() else [] if not isinstance(value, list): return [] return _unique_texts(str(item).strip() for item in value if str(item or "").strip()) def _unique_texts(values: Any) -> list[str]: result: list[str] = [] for value in values: text = str(value or "").strip() if text and text not in result: result.append(text) return result def _optional_text(value: Any) -> str | None: if value is None: return None text = str(value).strip() return text or None def _key(value: str) -> str: return "_".join(value.lower().replace("/", " ").replace("-", " ").split()) or "guard"