"""Map semantic reference-image responsibilities to adapter-native inputs.""" from __future__ import annotations from typing import Any, Mapping class ReferenceBindingMapper: def map(self, bindings: list[dict[str, Any]], route_resolution: Mapping[str, Any]) -> dict[str, Any]: settings = route_resolution.get("settings") if isinstance(route_resolution.get("settings"), dict) else {} capabilities = route_resolution.get("capabilities") if isinstance(route_resolution.get("capabilities"), dict) else {} max_references = _positive_int(settings.get("max_reference_images") or capabilities.get("max_reference_images"), 8) ordered = sorted( [dict(item) for item in bindings if isinstance(item, dict)], key=lambda item: (-_float(item.get("weight"), 0.5), str(item.get("material_id") or item.get("image_uri") or "")), ) active, downgraded = ordered[:max_references], ordered[max_references:] supports_roles = bool(settings.get("supports_reference_roles", capabilities.get("supports_reference_roles", False))) dialect = str(settings.get("reference_dialect") or capabilities.get("reference_dialect") or "text_constraints") native: list[dict[str, Any]] = [] constraints: list[str] = [] for index, binding in enumerate(active): role = str(binding.get("role") or "reference") use_for = _strings(binding.get("use_for")) do_not = _strings(binding.get("do_not_inherit")) if supports_roles: native.append({ "index": index, "role": role, "use_for": use_for, "exclude": do_not, "weight": min(max(_float(binding.get("weight"), 0.5), 0.0), 1.0), "dialect": dialect, }) else: constraint = f"Reference image {index + 1} is for {', '.join(use_for) or role} only" if do_not: constraint += f"; do not inherit {', '.join(do_not)}" constraints.append(constraint) return { "dialect": dialect, "supports_native_roles": supports_roles, "native_bindings": native, "text_constraints": constraints, "active_count": len(active), "downgraded": [{"material_id": item.get("material_id"), "reason": "adapter_reference_limit", "fallback": "text_capsule"} for item in downgraded], } def _strings(value: Any) -> list[str]: if isinstance(value, str): value = value.split(",") if not isinstance(value, (list, tuple, set)): return [] return [str(item).strip() for item in value if str(item).strip()] def _float(value: Any, default: float) -> float: try: return float(value) except (TypeError, ValueError): return default def _positive_int(value: Any, default: int) -> int: try: return max(int(value), 0) except (TypeError, ValueError): return default