"""Backward-compatible two-source model route chains. The AstrBot configuration schema exposes model assignments as strings. Keep that stable while allowing each assignment to carry one ImageStudio route and one AstrBot-hosted fallback route. """ from __future__ import annotations import json from dataclasses import dataclass from typing import Any ROUTE_CHAIN_PREFIX = "route-chain:" @dataclass(frozen=True) class ModelRouteChain: plugin: str = "" astrbot: str = "" @property def candidates(self) -> tuple[str, ...]: values: list[str] = [] for value in (self.plugin, self.astrbot): route = str(value or "").strip() if route and route not in values: values.append(route) return tuple(values) def parse_model_route_chain(value: Any) -> ModelRouteChain: route = str(value or "").strip() if not route: return ModelRouteChain() if route.startswith(ROUTE_CHAIN_PREFIX): try: payload = json.loads(route[len(ROUTE_CHAIN_PREFIX) :]) except (TypeError, ValueError, json.JSONDecodeError): payload = None if isinstance(payload, dict): return ModelRouteChain( plugin=_text(payload.get("plugin")), astrbot=_astrbot_text(payload.get("astrbot")), ) if route.startswith("astrbot:"): return ModelRouteChain(astrbot=route) return ModelRouteChain(plugin=route) def encode_model_route_chain(plugin: Any = "", astrbot: Any = "") -> str: plugin_route = _text(plugin) astrbot_route = _astrbot_text(astrbot) if plugin_route and not astrbot_route: return plugin_route if astrbot_route and not plugin_route: return astrbot_route if not plugin_route and not astrbot_route: return "" return ROUTE_CHAIN_PREFIX + json.dumps( {"plugin": plugin_route, "astrbot": astrbot_route}, ensure_ascii=False, separators=(",", ":"), sort_keys=True, ) def model_route_candidates(value: Any) -> tuple[str, ...]: return parse_model_route_chain(value).candidates def _text(value: Any) -> str: return str(value or "").strip() def _astrbot_text(value: Any) -> str: route = _text(value) return route if not route or route.startswith("astrbot:") else ""