clip_as_service_encoder.py 4.42 KB
"""
Image encoder using third-party clip-as-service (Jina CLIP server).

Requires clip-as-service server to be running. The client is loaded from
third-party/clip-as-service/client so no separate pip install is needed
if that path is on sys.path or the package is installed in development mode.
"""

import logging
import os
import sys
from typing import List, Optional

import numpy as np

logger = logging.getLogger(__name__)

# Ensure third-party clip client is importable
def _ensure_clip_client_path():
    repo_root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    client_path = os.path.join(repo_root, "third-party", "clip-as-service", "client")
    if os.path.isdir(client_path) and client_path not in sys.path:
        sys.path.insert(0, client_path)
    # Skip client version check to avoid importing helper (pkg_resources); no conda/separate env
    os.environ.setdefault("NO_VERSION_CHECK", "1")


def _normalize_image_url(url: str) -> str:
    """Normalize image URL for clip-as-service (e.g. //host/path -> https://host/path)."""
    if not url or not isinstance(url, str):
        return ""
    url = url.strip()
    if url.startswith("//"):
        return "https:" + url
    return url


class ClipAsServiceImageEncoder:
    """
    Image embedding encoder using clip-as-service Client.
    Encodes image URLs in batch; returns 1024-dim vectors (server model must match).
    """

    def __init__(
        self,
        server: str = "grpc://127.0.0.1:51000",
        batch_size: int = 8,
        show_progress: bool = False,
    ):
        """
        Args:
            server: clip-as-service server URI (e.g. grpc://127.0.0.1:51000 or http://127.0.0.1:51000).
            batch_size: batch size for encode requests.
            show_progress: whether to show progress bar when encoding.
        """
        _ensure_clip_client_path()
        try:
            from clip_client import Client
        except ImportError as e:
            raise ImportError(
                "clip_client not found. Add third-party/clip-as-service/client to PYTHONPATH "
                "or run: pip install -e third-party/clip-as-service/client"
            ) from e

        self._server = server
        self._batch_size = batch_size
        self._show_progress = show_progress
        self._client = Client(server)

    def encode_image_urls(
        self,
        urls: List[str],
        batch_size: Optional[int] = None,
    ) -> List[Optional[np.ndarray]]:
        """
        Encode a list of image URLs to vectors.

        Args:
            urls: list of image URLs (http/https or //host/path).
            batch_size: override instance batch_size for this call.

        Returns:
            List of vectors (1024-dim float32) or None for failed items, same length as urls.
        """
        if not urls:
            return []

        normalized = [_normalize_image_url(u) for u in urls]
        valid_indices = [i for i, u in enumerate(normalized) if u]
        if not valid_indices:
            return [None] * len(urls)

        valid_urls = [normalized[i] for i in valid_indices]
        bs = batch_size if batch_size is not None else self._batch_size
        out: List[Optional[np.ndarray]] = [None] * len(urls)

        try:
            # Client.encode(iterable of str) returns np.ndarray [N, D] for string input
            arr = self._client.encode(
                valid_urls,
                batch_size=bs,
                show_progress=self._show_progress,
            )
            if arr is not None and hasattr(arr, "shape") and len(arr) == len(valid_indices):
                for j, idx in enumerate(valid_indices):
                    row = arr[j]
                    if row is not None and hasattr(row, "tolist"):
                        out[idx] = np.asarray(row, dtype=np.float32)
                    else:
                        out[idx] = np.array(row, dtype=np.float32)
            else:
                logger.warning(
                    "clip-as-service encode returned unexpected shape/length, "
                    "expected %d vectors", len(valid_indices)
                )
        except Exception as e:
            logger.warning("clip-as-service encode failed: %s", e, exc_info=True)

        return out

    def encode_image_from_url(self, url: str) -> Optional[np.ndarray]:
        """Encode a single image URL. Returns 1024-dim vector or None."""
        results = self.encode_image_urls([url], batch_size=1)
        return results[0] if results else None