|
| 1 | +from __future__ import annotations |
| 2 | + |
| 3 | +from collections.abc import Callable |
| 4 | +from dataclasses import dataclass |
| 5 | +from pathlib import Path |
| 6 | + |
| 7 | +from torch import nn |
| 8 | + |
| 9 | + |
| 10 | +@dataclass(frozen=True) |
| 11 | +class BuildConfig: |
| 12 | + in_channels: int |
| 13 | + num_classes: int |
| 14 | + width_mult: float = 1.0 |
| 15 | + |
| 16 | + |
| 17 | +class UnknownLocalArch(KeyError): |
| 18 | + pass |
| 19 | + |
| 20 | + |
| 21 | +def _split_arch_id(arch_id: str) -> tuple[str, str]: |
| 22 | + arch_id = str(arch_id).strip() |
| 23 | + if ":" not in arch_id: |
| 24 | + return "dldet", arch_id |
| 25 | + |
| 26 | + prefix, name = arch_id.split(":", 1) |
| 27 | + prefix = prefix.strip().lower() |
| 28 | + name = name.strip() |
| 29 | + if not prefix or not name: |
| 30 | + raise ValueError(f"Invalid arch id: {arch_id!r}") |
| 31 | + return prefix, name |
| 32 | + |
| 33 | + |
| 34 | +Builder = Callable[[BuildConfig], nn.Module] |
| 35 | + |
| 36 | + |
| 37 | +def _extract_variants_from_source(src: str) -> list[str] | None: |
| 38 | + """Extract `_VARIANTS` keys from a module source without importing it.""" |
| 39 | + |
| 40 | + import ast |
| 41 | + |
| 42 | + try: |
| 43 | + tree = ast.parse(src) |
| 44 | + except SyntaxError: |
| 45 | + return None |
| 46 | + |
| 47 | + for node in tree.body: |
| 48 | + target_name: str | None = None |
| 49 | + value = None |
| 50 | + |
| 51 | + if isinstance(node, ast.AnnAssign) and isinstance(node.target, ast.Name): |
| 52 | + target_name = node.target.id |
| 53 | + value = node.value |
| 54 | + elif isinstance(node, ast.Assign): |
| 55 | + for t in node.targets: |
| 56 | + if isinstance(t, ast.Name): |
| 57 | + target_name = t.id |
| 58 | + break |
| 59 | + value = node.value |
| 60 | + |
| 61 | + if target_name != "_VARIANTS" or not isinstance(value, ast.Dict): |
| 62 | + continue |
| 63 | + |
| 64 | + keys: list[str] = [] |
| 65 | + for k in value.keys: |
| 66 | + if isinstance(k, ast.Constant) and isinstance(k.value, str): |
| 67 | + keys.append(k.value) |
| 68 | + return keys or None |
| 69 | + |
| 70 | + return None |
| 71 | + |
| 72 | + |
| 73 | +def _extract_builder_name_from_source(src: str) -> str | None: |
| 74 | + """Extract the first `build_*_detector` function name without importing.""" |
| 75 | + |
| 76 | + import ast |
| 77 | + |
| 78 | + try: |
| 79 | + tree = ast.parse(src) |
| 80 | + except SyntaxError: |
| 81 | + return None |
| 82 | + |
| 83 | + for node in tree.body: |
| 84 | + if not isinstance(node, ast.FunctionDef): |
| 85 | + continue |
| 86 | + name = str(node.name) |
| 87 | + if name.startswith("build_") and name.endswith("_detector"): |
| 88 | + return name |
| 89 | + return None |
| 90 | + |
| 91 | + |
| 92 | +def _make_lazy_detector_builder(module_name: str, *, builder_name: str, variant: str) -> Builder: |
| 93 | + module_name = str(module_name).strip() |
| 94 | + builder_name = str(builder_name).strip() |
| 95 | + variant = str(variant).strip() |
| 96 | + |
| 97 | + def _builder(cfg: BuildConfig) -> nn.Module: |
| 98 | + import importlib |
| 99 | + import inspect |
| 100 | + |
| 101 | + mod = importlib.import_module(f"dlhub.vision.detection.{module_name}") |
| 102 | + fn = getattr(mod, builder_name, None) |
| 103 | + if fn is None: |
| 104 | + raise RuntimeError(f"Detection module {module_name!r} missing {builder_name}()") |
| 105 | + |
| 106 | + kwargs: dict[str, object] = { |
| 107 | + "in_channels": int(cfg.in_channels), |
| 108 | + "num_classes": int(cfg.num_classes), |
| 109 | + "variant": str(variant), |
| 110 | + "width_mult": float(cfg.width_mult), |
| 111 | + } |
| 112 | + |
| 113 | + try: |
| 114 | + sig = inspect.signature(fn) |
| 115 | + except (TypeError, ValueError): |
| 116 | + sig = None |
| 117 | + |
| 118 | + if sig is not None: |
| 119 | + params = set(sig.parameters) |
| 120 | + kwargs = {k: v for k, v in kwargs.items() if k in params} |
| 121 | + |
| 122 | + return fn(**kwargs) |
| 123 | + |
| 124 | + return _builder |
| 125 | + |
| 126 | + |
| 127 | +def _extend_registry_with_discovered_detectors(r: dict[str, Builder]) -> None: |
| 128 | + """Discover detector variants under `dlhub/vision/detection/*.py`.""" |
| 129 | + |
| 130 | + here = Path(__file__).resolve().parent |
| 131 | + det_dir = here / "detection" |
| 132 | + |
| 133 | + if not det_dir.exists(): |
| 134 | + return |
| 135 | + |
| 136 | + hidden = {"__init__"} |
| 137 | + |
| 138 | + for py in sorted(det_dir.glob("*.py")): |
| 139 | + module_name = py.stem |
| 140 | + if module_name in hidden or module_name.startswith("_"): |
| 141 | + continue |
| 142 | + |
| 143 | + try: |
| 144 | + src = py.read_text(encoding="utf-8") |
| 145 | + except OSError: |
| 146 | + continue |
| 147 | + |
| 148 | + if "_VARIANTS" not in src or "def build_" not in src: |
| 149 | + continue |
| 150 | + |
| 151 | + variants = _extract_variants_from_source(src) |
| 152 | + if not variants: |
| 153 | + continue |
| 154 | + |
| 155 | + builder_name = _extract_builder_name_from_source(src) |
| 156 | + if builder_name is None: |
| 157 | + continue |
| 158 | + |
| 159 | + for v in variants: |
| 160 | + name = str(v).lower().strip() |
| 161 | + if not name or name in r: |
| 162 | + continue |
| 163 | + r[name] = _make_lazy_detector_builder(module_name, builder_name=builder_name, variant=name) |
| 164 | + |
| 165 | + |
| 166 | +def _registry() -> dict[str, Builder]: |
| 167 | + r: dict[str, Builder] = {} |
| 168 | + _extend_registry_with_discovered_detectors(r) |
| 169 | + return r |
| 170 | + |
| 171 | + |
| 172 | +_REGISTRY = _registry() |
| 173 | + |
| 174 | + |
| 175 | +def list_local_arches() -> list[str]: |
| 176 | + """List all available local detection architecture ids (e.g. `dldet:ssd_tiny`).""" |
| 177 | + |
| 178 | + return [f"dldet:{name}" for name in sorted(_REGISTRY)] |
| 179 | + |
| 180 | + |
| 181 | +def build_local_model( |
| 182 | + arch_id: str, |
| 183 | + *, |
| 184 | + in_channels: int, |
| 185 | + num_classes: int, |
| 186 | + width_mult: float = 1.0, |
| 187 | +) -> nn.Module: |
| 188 | + """Build a local detection model by architecture id. |
| 189 | +
|
| 190 | + Architecture ids are variants extracted from each detector module's `_VARIANTS`, |
| 191 | + namespaced with `dldet:` (e.g. `dldet:ssd_tiny`). |
| 192 | + """ |
| 193 | + |
| 194 | + prefix, name = _split_arch_id(arch_id) |
| 195 | + if prefix == "det": |
| 196 | + prefix = "dldet" |
| 197 | + if prefix not in {"dldet", "local"}: |
| 198 | + raise ValueError(f"Unsupported detection prefix: {prefix!r} (arch_id={arch_id!r})") |
| 199 | + |
| 200 | + builder = _REGISTRY.get(str(name).lower().strip()) |
| 201 | + if builder is None: |
| 202 | + raise UnknownLocalArch(f"Unknown detection arch: {arch_id!r}. Tip: run `python scripts/detection_zoo.py --list`.") |
| 203 | + |
| 204 | + return builder( |
| 205 | + BuildConfig( |
| 206 | + in_channels=int(in_channels), |
| 207 | + num_classes=int(num_classes), |
| 208 | + width_mult=float(width_mult), |
| 209 | + ) |
| 210 | + ) |
| 211 | + |
| 212 | + |
| 213 | +__all__ = [ |
| 214 | + "BuildConfig", |
| 215 | + "UnknownLocalArch", |
| 216 | + "build_local_model", |
| 217 | + "list_local_arches", |
| 218 | +] |
| 219 | + |
0 commit comments