Spaces:
Runtime error
Runtime error
Download infrastructure/vision/plugin_router.py from Jyotsna574/medyx-v1: direct link, hf CLI and curl.
- Browser
- Download file 9.94 kB
-
https://huggingface.co/spaces/Jyotsna574/medyx-v1/resolve/main/infrastructure/vision/plugin_router.py
- Command line
-
hf download hf://spaces/Jyotsna574/medyx-v1/infrastructure/vision/plugin_router.py
-
curl -L -o plugin_router.py https://huggingface.co/spaces/Jyotsna574/medyx-v1/resolve/main/infrastructure/vision/plugin_router.py
9.94 kB
| """Vision plugin router. | |
| Selects the most appropriate vision backend by modality/target region and | |
| returns a backend instance + plugin metadata. | |
| """ | |
| from __future__ import annotations | |
| from dataclasses import dataclass | |
| from typing import Any, Optional | |
| import os | |
| from config.settings import load_yaml_config | |
| from infrastructure.vision.vision_provider import ( | |
| MedAIVisionBackend, | |
| MONAIVisionBackend, | |
| PlaceholderVisionBackend, | |
| VisionBackend, | |
| ) | |
| class PluginSelection: | |
| plugin_id: str | |
| backend: VisionBackend | |
| description: str | |
| backend_type: str | |
| class PluginSelectionMeta: | |
| """YAML-only resolution (no backend import). For UI previews and logging.""" | |
| plugin_id: str | |
| backend_type: str | |
| description: str | |
| class VisionPluginRouter: | |
| """Route incoming cases to vision plugins.""" | |
| def __init__(self, config_name: str = "vision_plugins.yaml"): | |
| self._cfg = load_yaml_config(config_name) or {} | |
| self._plugins = self._cfg.get("plugins", {}) | |
| self._default = self._cfg.get("default_plugin", "") | |
| def _norm(value: str | None) -> str: | |
| return (value or "").strip().lower() | |
| def _resolve_cfg_value(value: Any) -> Any: | |
| """ | |
| Allow simple indirection in YAML without changing YAML loader: | |
| - "env:VARNAME" -> os.getenv("VARNAME") | |
| - "$VARNAME" -> os.getenv("VARNAME") | |
| """ | |
| if isinstance(value, str): | |
| v = value.strip() | |
| if v.lower().startswith("env:"): | |
| return os.getenv(v.split(":", 1)[1].strip(), "") | |
| if v.startswith("$") and len(v) > 1: | |
| return os.getenv(v[1:], "") | |
| return value | |
| def resolve_metadata(self, modality: str, target_region: str) -> PluginSelectionMeta: | |
| """Which plugin YAML would match (does not instantiate torch/MONAI).""" | |
| modality_n = self._norm(modality) | |
| region_n = self._norm(target_region) | |
| for pid, cfg in self._plugins.items(): | |
| if not cfg.get("enabled", True): | |
| continue | |
| if self._matches(cfg, modality_n, region_n): | |
| return PluginSelectionMeta( | |
| plugin_id=pid, | |
| backend_type=str(cfg.get("backend", "placeholder")), | |
| description=str(cfg.get("description", "")), | |
| ) | |
| if self._default and self._default in self._plugins: | |
| cfg = self._plugins[self._default] | |
| return PluginSelectionMeta( | |
| plugin_id=self._default, | |
| backend_type=str(cfg.get("backend", "placeholder")), | |
| description=str(cfg.get("description", "")), | |
| ) | |
| # Prefer MedCLIP as a general fallback for UI preview. | |
| for pid, cfg in self._plugins.items(): | |
| if not cfg.get("enabled", True): | |
| continue | |
| b = str(cfg.get("backend", "")).strip().lower() | |
| if "medclip" in b or "medclip" in pid.lower(): | |
| return PluginSelectionMeta( | |
| plugin_id=pid, | |
| backend_type=str(cfg.get("backend", "medclip")), | |
| description=str(cfg.get("description", "")), | |
| ) | |
| return PluginSelectionMeta( | |
| plugin_id="placeholder", | |
| backend_type="placeholder", | |
| description="No matching plugin; using placeholder backend.", | |
| ) | |
| def _matches(self, plugin_cfg: dict[str, Any], modality: str, target_region: str) -> bool: | |
| match = plugin_cfg.get("match", {}) or {} | |
| allowed_modality = [self._norm(x) for x in match.get("modality", [])] | |
| allowed_region = [self._norm(x) for x in match.get("target_region", [])] | |
| # Optional alternate keys for routing convenience. | |
| if not allowed_modality and plugin_cfg.get("modalities"): | |
| allowed_modality = [self._norm(x) for x in plugin_cfg.get("modalities", [])] | |
| if not allowed_region and plugin_cfg.get("regions"): | |
| allowed_region = [self._norm(x) for x in plugin_cfg.get("regions", [])] | |
| modality_ok = (not allowed_modality) or any(x in modality for x in allowed_modality) | |
| region_ok = (not allowed_region) or any(x in target_region for x in allowed_region) | |
| return modality_ok and region_ok | |
| def _build_backend(self, plugin_cfg: dict[str, Any]) -> VisionBackend: | |
| backend_type = plugin_cfg.get("backend", "placeholder") | |
| backend_type_n = str(backend_type).strip().lower() | |
| if backend_type_n == "medai_torchxray": | |
| return MedAIVisionBackend( | |
| model_weights=plugin_cfg.get("model_weights", "densenet121-res224-all") | |
| ) | |
| if backend_type_n == "monai": | |
| spatial_size = plugin_cfg.get("spatial_size", [224, 224]) | |
| bundle_dir = self._resolve_cfg_value(plugin_cfg.get("bundle_dir")) | |
| checkpoint_path = self._resolve_cfg_value(plugin_cfg.get("checkpoint_path")) | |
| return MONAIVisionBackend( | |
| bundle_dir=bundle_dir or None, | |
| checkpoint_path=checkpoint_path or None, | |
| class_names=plugin_cfg.get("class_names"), | |
| spatial_size=(int(spatial_size[0]), int(spatial_size[1])), | |
| ) | |
| if "medclip" in backend_type_n: | |
| model_id = self._resolve_cfg_value(plugin_cfg.get("model_id")) | |
| fallback_model_id = self._resolve_cfg_value(plugin_cfg.get("fallback_model_id")) | |
| # Lazy import to avoid heavy transformer imports at UI startup. | |
| from infrastructure.vision.backends.medclip_backend import MedCLIPVisionBackend | |
| return MedCLIPVisionBackend( | |
| model_id=model_id or None, | |
| fallback_model_id=fallback_model_id or None, | |
| ) | |
| return PlaceholderVisionBackend() | |
| def select(self, modality: str, target_region: str) -> PluginSelection: | |
| modality_n = self._norm(modality) | |
| region_n = self._norm(target_region) | |
| # Select the best match among plugins; if none match and a MedCLIP plugin exists, | |
| # fall back to it so we still produce a general-purpose vision-language signal. | |
| # 1) explicit matching plugins | |
| for pid, cfg in self._plugins.items(): | |
| if not cfg.get("enabled", True): | |
| continue | |
| if self._matches(cfg, modality_n, region_n): | |
| backend = self._build_backend(cfg) | |
| return PluginSelection( | |
| plugin_id=pid, | |
| backend=backend, | |
| description=cfg.get("description", ""), | |
| backend_type=cfg.get("backend", "placeholder"), | |
| ) | |
| # 2) default plugin | |
| if self._default and self._default in self._plugins: | |
| cfg = self._plugins[self._default] | |
| backend = self._build_backend(cfg) | |
| return PluginSelection( | |
| plugin_id=self._default, | |
| backend=backend, | |
| description=cfg.get("description", ""), | |
| backend_type=cfg.get("backend", "placeholder"), | |
| ) | |
| # 3) hard fallback | |
| # Prefer MedCLIP as an always-available general-purpose signal. | |
| medclip_selection: Optional[PluginSelection] = None | |
| for pid, cfg in self._plugins.items(): | |
| if not cfg.get("enabled", True): | |
| continue | |
| b = str(cfg.get("backend", "")).strip().lower() | |
| if "medclip" in b or "medclip" in pid.lower(): | |
| medclip_selection = PluginSelection( | |
| plugin_id=pid, | |
| backend=self._build_backend(cfg), | |
| description=cfg.get("description", ""), | |
| backend_type=cfg.get("backend", "medclip"), | |
| ) | |
| break | |
| if medclip_selection is not None: | |
| return medclip_selection | |
| return PluginSelection( | |
| plugin_id="placeholder", | |
| backend=PlaceholderVisionBackend(), | |
| description="No matching plugin; using placeholder backend.", | |
| backend_type="placeholder", | |
| ) | |
| def select_multi(self, modality: str, target_region: str) -> list[PluginSelection]: | |
| """Return multiple selections (modality-specific + optional MedCLIP fusion). | |
| - Always includes the best primary match (or placeholder if none). | |
| - If `ENABLE_MEDCLIP_COMBINE=1`, also includes `medclip_general` when available. | |
| """ | |
| primary = self.select(modality, target_region) | |
| # If the primary is placeholder, return just medclip if available (select() already did fallback). | |
| # Default to enabling fusion so MedCLIP provides robust fallback evidence | |
| # when modality-specific backends are unavailable/untrained. | |
| enable_fuse = os.getenv("ENABLE_MEDCLIP_COMBINE", "1").strip() == "1" | |
| if not enable_fuse: | |
| return [primary] | |
| # Find medclip plugin if it isn't already the primary. | |
| if "medclip" in str(primary.plugin_id).lower() or "medclip" in str(primary.backend_type).lower(): | |
| return [primary] | |
| medclip: Optional[PluginSelection] = None | |
| for pid, cfg in self._plugins.items(): | |
| if not cfg.get("enabled", True): | |
| continue | |
| b = str(cfg.get("backend", "")).strip().lower() | |
| if "medclip" in b or "medclip" in pid.lower(): | |
| medclip = PluginSelection( | |
| plugin_id=pid, | |
| backend=self._build_backend(cfg), | |
| description=cfg.get("description", ""), | |
| backend_type=cfg.get("backend", "medclip"), | |
| ) | |
| break | |
| if medclip is None: | |
| return [primary] | |
| # Combine: modality-specific + medclip. | |
| return [primary, medclip] | |