Source code for reli.perception.detectors

"""Open-vocabulary proposal back-ends: ``sam3`` (default, masks), ``grounding_dino``,
``owlv2`` and ``yolo_world`` (boxes). Each proposal carries the prompt that produced it.
"""

from __future__ import annotations

import logging

import numpy as np

from ..config import PerceptionConfig
from .base import Detector, Proposal, label_match

log = logging.getLogger(__name__)

DEFAULT_MODELS = {
    "sam3": "facebook/sam3",
    "grounding_dino": "IDEA-Research/grounding-dino-base",
    "owlv2": "google/owlv2-base-patch16-ensemble",
    "yolo_world": "yolov8x-worldv2.pt",
}


def resolve_device(pref: str) -> str:
    if pref != "auto":
        return pref
    try:
        import torch

        if torch.cuda.is_available():
            return "cuda"
        if getattr(torch.backends, "mps", None) and torch.backends.mps.is_available():
            return "mps"
    except ImportError:
        pass
    return "cpu"


def _pil(image_bgr: np.ndarray):
    from PIL import Image

    return Image.fromarray(np.ascontiguousarray(image_bgr[:, :, ::-1]))


def _box(values) -> tuple[float, float, float, float]:
    x1, y1, x2, y2 = (float(v) for v in values)
    return x1, y1, x2, y2


class Sam3Detector(Detector):
    def __init__(self, cfg: PerceptionConfig, device: str):
        import torch
        from transformers import Sam3Model, Sam3Processor

        model_id = cfg.model or DEFAULT_MODELS["sam3"]
        self.cfg = cfg
        self.device = device
        self.torch = torch
        self.processor = Sam3Processor.from_pretrained(model_id)
        self.model = Sam3Model.from_pretrained(model_id).to(device).eval()
        log.info("SAM 3 (%s) loaded on %s", model_id, device)

    def detect(self, image_bgr: np.ndarray, prompts: list[str]) -> list[Proposal]:
        image = _pil(image_bgr)
        img_inputs = self.processor(images=image, return_tensors="pt").to(self.device)
        out: list[Proposal] = []
        with self.torch.no_grad():
            # Encode the image once and reuse it for every text prompt.
            vision = self.model.get_vision_features(pixel_values=img_inputs.pixel_values)
            for prompt in prompts:
                txt = self.processor(text=prompt, return_tensors="pt").to(self.device)
                outputs = self.model(vision_embeds=vision, **txt)
                res = self.processor.post_process_instance_segmentation(
                    outputs,
                    threshold=self.cfg.score_threshold,
                    mask_threshold=self.cfg.mask_threshold,
                    target_sizes=img_inputs.get("original_sizes").tolist(),
                )[0]
                for mask, box, score in zip(
                    res["masks"], res["boxes"], res["scores"], strict=False
                ):
                    out.append(
                        Proposal(
                            prompt,
                            float(score),
                            _box(box.tolist()),
                            mask.cpu().numpy().astype(bool),
                        )
                    )
        return _top(out, self.cfg.max_detections)


class GroundingDinoDetector(Detector):
    def __init__(self, cfg: PerceptionConfig, device: str):
        import torch
        from transformers import AutoModelForZeroShotObjectDetection, AutoProcessor

        model_id = cfg.model or DEFAULT_MODELS["grounding_dino"]
        self.cfg = cfg
        self.device = device
        self.torch = torch
        self.processor = AutoProcessor.from_pretrained(model_id)
        self.model = AutoModelForZeroShotObjectDetection.from_pretrained(model_id).to(device).eval()
        log.info("Grounding DINO (%s) loaded on %s", model_id, device)

    def detect(self, image_bgr: np.ndarray, prompts: list[str]) -> list[Proposal]:
        image = _pil(image_bgr)
        labels = [p.lower() for p in prompts]
        inputs = self.processor(images=image, text=[labels], return_tensors="pt").to(self.device)
        with self.torch.no_grad():
            outputs = self.model(**inputs)
        res = self.processor.post_process_grounded_object_detection(
            outputs,
            inputs.input_ids,
            threshold=self.cfg.score_threshold,
            text_threshold=self.cfg.score_threshold,
            target_sizes=[image.size[::-1]],
        )[0]
        out = []
        for box, score, phrase in zip(
            res["boxes"], res["scores"], res["text_labels"], strict=False
        ):
            # Decoded phrases can be partial; map them back to the closest prompt.
            best = max(prompts, key=lambda p: label_match(p, str(phrase)))
            if label_match(best, str(phrase)) > 0:
                out.append(Proposal(best, float(score), _box(box.tolist())))
        return _top(out, self.cfg.max_detections)


class Owlv2Detector(Detector):
    def __init__(self, cfg: PerceptionConfig, device: str):
        import torch
        from transformers import Owlv2ForObjectDetection, Owlv2Processor

        model_id = cfg.model or DEFAULT_MODELS["owlv2"]
        self.cfg = cfg
        self.device = device
        self.torch = torch
        self.processor = Owlv2Processor.from_pretrained(model_id)
        self.model = Owlv2ForObjectDetection.from_pretrained(model_id).to(device).eval()
        log.info("OWLv2 (%s) loaded on %s", model_id, device)

    def detect(self, image_bgr: np.ndarray, prompts: list[str]) -> list[Proposal]:
        image = _pil(image_bgr)
        h, w = image_bgr.shape[:2]
        inputs = self.processor(text=[prompts], images=image, return_tensors="pt").to(self.device)
        with self.torch.no_grad():
            outputs = self.model(**inputs)
        # OWLv2 pads images to a square; boxes are relative to the padded image.
        side = max(h, w)
        res = self.processor.post_process_grounded_object_detection(
            outputs,
            threshold=self.cfg.score_threshold,
            target_sizes=[(side, side)],
            text_labels=[prompts],
        )[0]
        out = []
        for box, score, label in zip(res["boxes"], res["scores"], res["labels"], strict=False):
            x1, y1, x2, y2 = box.tolist()
            out.append(
                Proposal(
                    prompts[int(label)],
                    float(score),
                    (max(0.0, x1), max(0.0, y1), min(float(w), x2), min(float(h), y2)),
                )
            )
        return _top(out, self.cfg.max_detections)


class YoloWorldDetector(Detector):
    def __init__(self, cfg: PerceptionConfig, device: str):
        from ultralytics import YOLO

        checkpoint = cfg.model or DEFAULT_MODELS["yolo_world"]
        self.cfg = cfg
        self.device = device
        self.model = YOLO(checkpoint)
        self._classes: list[str] = []
        log.info("YOLO-World (%s) loaded", checkpoint)

    def detect(self, image_bgr: np.ndarray, prompts: list[str]) -> list[Proposal]:
        if prompts != self._classes:  # re-encoding text is costly; only on change
            self.model.set_classes(prompts)
            self._classes = list(prompts)
        results = self.model.predict(
            image_bgr,
            conf=self.cfg.score_threshold,
            device=self.device,
            verbose=False,
            max_det=self.cfg.max_detections,
        )
        out = []
        for r in results:
            for b in r.boxes:
                out.append(
                    Proposal(
                        r.names[int(b.cls.item())], float(b.conf.item()), _box(b.xyxy[0].tolist())
                    )
                )
        return out


def _top(proposals: list[Proposal], k: int) -> list[Proposal]:
    return sorted(proposals, key=lambda p: p.score, reverse=True)[:k]


[docs] def build_detector(cfg: PerceptionConfig) -> Detector: device = resolve_device(cfg.device) cls = { "sam3": Sam3Detector, "grounding_dino": GroundingDinoDetector, "owlv2": Owlv2Detector, "yolo_world": YoloWorldDetector, }.get(cfg.detector) if cls is None: raise ValueError(f"detector {cfg.detector!r} has no image back-end") try: return cls(cfg, device) except ImportError as exc: extra = "yolo" if cfg.detector == "yolo_world" else "vision" raise ImportError( f"perception.detector '{cfg.detector}' needs: pip install 'reli-robot[{extra}]' ({exc})" ) from exc