"""Normalize workflow material binding payloads for generation nodes.""" from __future__ import annotations from copy import deepcopy from typing import Any from backend.dto.workflow_dto import WorkflowNode MATERIAL_BINDING_SCHEMA_VERSION = "2026-07-09.material-binding-schema.v1" REFERENCE_POLICY = { "mode": "explicit_only", "default_use_reference": False, "empty_material_means": "do_not_use_reference", } STAGE_NODE_KEYS: dict[str, tuple[str, ...]] = { "profile-prep": ("profile_brief", "prompt_plan", "material_bind"), "portrait-draft": ("headshot", "fast_candidates"), "halfbody-draft": ("half_body",), "body-sheet": ("full_body", "expression_sheet", "pose_sheet"), "review-archive": ("style_lock", "final_pack", "fast_final"), } STRENGTHS: dict[str, tuple[str, float]] = { "强": ("strong", 0.85), "strong": ("strong", 0.85), "high": ("strong", 0.85), "中": ("medium", 0.55), "medium": ("medium", 0.55), "mid": ("medium", 0.55), "弱": ("weak", 0.3), "weak": ("weak", 0.3), "low": ("weak", 0.3), } def normalize_material_bindings( payload: Any, workflow_nodes: list[WorkflowNode] | None = None, ) -> dict[str, Any]: if isinstance(payload, dict) and payload.get("schema_version") == MATERIAL_BINDING_SCHEMA_VERSION: normalized = deepcopy(payload) if workflow_nodes: rules = normalized.get("active_rules") if not isinstance(rules, list): rules = [ rule for rule in normalized.get("rules", []) if isinstance(rule, dict) and rule.get("use_reference") ] normalized["by_node_id"] = _index_by_node_id(rules, workflow_nodes) return normalized source = _extract_source_payload(payload) rules = [ _normalize_rule(rule, index + 1) for index, rule in enumerate(source.get("rules", []) if isinstance(source.get("rules"), list) else []) if isinstance(rule, dict) ] active_rules = [rule for rule in rules if rule["use_reference"]] by_stage = _index_by_stage(active_rules) by_node_key = _index_by_node_key(active_rules) by_node_id = _index_by_node_id(active_rules, workflow_nodes or []) selected_material_ids = _string_list(source.get("selected_material_ids")) if not selected_material_ids: selected_material_ids = [rule["material"]["material_id"] for rule in active_rules] return { "schema_version": MATERIAL_BINDING_SCHEMA_VERSION, "reference_policy": deepcopy(REFERENCE_POLICY), "profile_id": _optional_text(source.get("profile_id")), "profile_name": _optional_text(source.get("profile_name")), "selected_material_ids": _unique_texts(selected_material_ids), "rules": rules, "active_rules": active_rules, "by_stage": by_stage, "by_node_key": by_node_key, "by_node_id": by_node_id, "node_parameters": by_node_id, "prompt_context": _prompt_context(active_rules), "summary": { "rule_count": len(rules), "active_rule_count": len(active_rules), "has_references": bool(active_rules), "disabled_categories": [rule["category"] for rule in rules if not rule["use_reference"]], "target_stage_ids": sorted(by_stage), "target_node_keys": sorted(by_node_key), }, } def material_bindings_for_node( workflow_metadata: dict[str, Any], node: WorkflowNode, workflow_nodes: list[WorkflowNode] | None = None, ) -> dict[str, Any]: normalized = normalize_material_bindings(workflow_metadata.get("material_bindings"), workflow_nodes) return node_material_binding_view(normalized, node) def node_material_binding_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): node_view = _node_view( active_rules=by_node_key.get(node.node_key, []), node_id=node.node_id, node_key=node.node_key, title=node.title, ) return { "schema_version": normalized.get("schema_version", MATERIAL_BINDING_SCHEMA_VERSION), "reference_policy": normalized.get("reference_policy", deepcopy(REFERENCE_POLICY)), "summary": normalized.get("summary", {}), "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 {} material_bindings = payload.get("material_bindings") if isinstance(material_bindings, dict) and isinstance(material_bindings.get("rules"), list): return material_bindings if isinstance(payload.get("rules"), list): return payload return {} def _normalize_rule(rule: dict[str, Any], ordinal: int) -> dict[str, Any]: material_id = _optional_text(rule.get("material_id")) material_prompt = _optional_text(rule.get("material_prompt")) category = _optional_text(rule.get("category")) or "other" target_stages = _target_stages(rule.get("bind_to_stages")) target_node_keys = _unique_texts( node_key for stage in target_stages for node_key in STAGE_NODE_KEYS.get(stage["stage_id"], ()) ) strength_label = _optional_text(rule.get("reference_strength")) or "medium" strength_key, strength_weight = STRENGTHS.get(strength_label.lower(), STRENGTHS.get(strength_label, ("medium", 0.55))) use_reference = bool(material_id or material_prompt) return { "id": _optional_text(rule.get("id")) or f"material_binding_{ordinal:02d}", "category": category, "use_reference": use_reference, "required": bool(rule.get("required")), "status": _optional_text(rule.get("status")) or ("ready" if use_reference else "pending"), "conflict": _optional_text(rule.get("conflict")), "material": { "material_id": material_id, "label": _optional_text(rule.get("material_label")), "group": _optional_text(rule.get("material_group")), "prompt": material_prompt, "colors": _string_list(rule.get("material_colors")), }, "target_stages": target_stages, "target_node_keys": target_node_keys, "inheritance_rule": _optional_text(rule.get("inheritance_rule")) or "", "reference_strength": { "label": strength_label, "key": strength_key, "weight": strength_weight, }, "generation_params": { "reference_policy": "explicit_only" if use_reference else "do_not_use_reference", "reference_strength": strength_key if use_reference else "none", "reference_weight": strength_weight if use_reference else 0, }, "expand_to_nodes_later": True, } def _target_stages(value: Any) -> list[dict[str, str]]: if not isinstance(value, list): return [] stages: list[dict[str, str]] = [] for item in value: if not isinstance(item, dict): continue stage_id = _optional_text(item.get("stage_id") or item.get("id")) if not stage_id: continue stage = { "stage_id": stage_id, "stage_title": _optional_text(item.get("stage_title") or item.get("title")) or stage_id, } if stage not in stages: stages.append(stage) return stages def _index_by_stage(rules: list[dict[str, Any]]) -> dict[str, dict[str, Any]]: result: dict[str, dict[str, Any]] = {} for rule in rules: for stage in rule["target_stages"]: stage_id = stage["stage_id"] bucket = result.setdefault( stage_id, { "stage_id": stage_id, "stage_title": stage["stage_title"], "active_bindings": [], "material_prompts": [], }, ) bucket["active_bindings"].append(rule) if rule["material"]["prompt"]: bucket["material_prompts"].append(rule["material"]["prompt"]) return result def _index_by_node_key(rules: list[dict[str, Any]]) -> dict[str, list[dict[str, Any]]]: result: dict[str, list[dict[str, Any]]] = {} for rule in rules: for node_key in rule["target_node_keys"]: result.setdefault(node_key, []).append(rule) return result def _index_by_node_id( rules: list[dict[str, Any]], workflow_nodes: list[WorkflowNode], ) -> dict[str, dict[str, Any]]: by_node_key = _index_by_node_key(rules) return { node.node_id: _node_view(by_node_key.get(node.node_key, []), node.node_id, node.node_key, node.title) for node in workflow_nodes if by_node_key.get(node.node_key) } def _node_view( active_rules: list[dict[str, Any]], node_id: str | None, node_key: str, title: str, ) -> dict[str, Any]: prompts = [rule["material"]["prompt"] for rule in active_rules if rule["material"]["prompt"]] return { "target_node_id": node_id, "target_node_key": node_key, "target_node_title": title, "reference_policy": deepcopy(REFERENCE_POLICY), "has_references": bool(active_rules), "active_bindings": deepcopy(active_rules), "material_prompts": prompts, "prompt_context": ", ".join(prompts), "generation_params": { "reference_material_ids": [ rule["material"]["material_id"] for rule in active_rules if rule["material"]["material_id"] ], "reference_prompts": prompts, "reference_strengths": [rule["reference_strength"] for rule in active_rules], }, } def _prompt_context(rules: list[dict[str, Any]]) -> list[dict[str, str]]: return [ { "category": rule["category"], "material_id": rule["material"]["material_id"] or "", "prompt": rule["material"]["prompt"] or "", "target_node_keys": ", ".join(rule["target_node_keys"]), } for rule in rules if rule["material"]["prompt"] ] 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