Blame view

embeddings/image_encoder.py 6.32 KB
950a640e   tangwang   embeddings
1
  """Image embedding client for the local embedding HTTP service."""
be52af70   tangwang   first commit
2
  
be52af70   tangwang   first commit
3
  import os
950a640e   tangwang   embeddings
4
5
6
  import logging
  from typing import Any, List, Optional, Union
  
be52af70   tangwang   first commit
7
  import numpy as np
950a640e   tangwang   embeddings
8
  import requests
be52af70   tangwang   first commit
9
  from PIL import Image
be52af70   tangwang   first commit
10
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
11
  logger = logging.getLogger(__name__)
be52af70   tangwang   first commit
12
  
42e3aea6   tangwang   tidy
13
  from config.services_config import get_embedding_base_url
4a37d233   tangwang   1. embedding cach...
14
15
  from config.env_config import REDIS_CONFIG
  from embeddings.redis_embedding_cache import RedisEmbeddingCache
42e3aea6   tangwang   tidy
16
  
be52af70   tangwang   first commit
17
18
19
  
  class CLIPImageEncoder:
      """
325eec03   tangwang   1. 日志、配置基础设施,使用优化
20
      Image Encoder for generating image embeddings using network service.
be52af70   tangwang   first commit
21
  
950a640e   tangwang   embeddings
22
      This client is stateless and safe to instantiate per caller.
be52af70   tangwang   first commit
23
24
      """
  
950a640e   tangwang   embeddings
25
26
27
28
      def __init__(self, service_url: Optional[str] = None):
          resolved_url = service_url or os.getenv("EMBEDDING_SERVICE_URL") or get_embedding_base_url()
          self.service_url = str(resolved_url).rstrip("/")
          self.endpoint = f"{self.service_url}/embed/image"
4a37d233   tangwang   1. embedding cach...
29
30
          # Reuse embedding cache prefix, but separate namespace for images to avoid collisions.
          self.cache_prefix = str(REDIS_CONFIG.get("embedding_cache_prefix", "embedding")).strip() or "embedding"
950a640e   tangwang   embeddings
31
          logger.info("Creating CLIPImageEncoder instance with service URL: %s", self.service_url)
4a37d233   tangwang   1. embedding cach...
32
33
34
35
          self.cache = RedisEmbeddingCache(
              key_prefix=self.cache_prefix,
              namespace="image",
          )
be52af70   tangwang   first commit
36
  
200fdddf   tangwang   embed norm
37
      def _call_service(self, request_data: List[str], normalize_embeddings: bool = True) -> List[Any]:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
38
39
          """
          Call the embedding service API.
be52af70   tangwang   first commit
40
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
41
          Args:
7bfb9946   tangwang   向量化模块
42
              request_data: List of image URLs / local file paths
be52af70   tangwang   first commit
43
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
44
          Returns:
7bfb9946   tangwang   向量化模块
45
              List of embeddings (list[float]) or nulls (None), aligned to input order
325eec03   tangwang   1. 日志、配置基础设施,使用优化
46
          """
be52af70   tangwang   first commit
47
          try:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
48
49
              response = requests.post(
                  self.endpoint,
200fdddf   tangwang   embed norm
50
                  params={"normalize": "true" if normalize_embeddings else "false"},
325eec03   tangwang   1. 日志、配置基础设施,使用优化
51
52
53
54
55
56
57
58
                  json=request_data,
                  timeout=60
              )
              response.raise_for_status()
              return response.json()
          except requests.exceptions.RequestException as e:
              logger.error(f"CLIPImageEncoder service request failed: {e}", exc_info=True)
              raise
be52af70   tangwang   first commit
59
  
ed948666   tangwang   tidy
60
      def encode_image(self, image: Image.Image) -> np.ndarray:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
61
62
          """
          Encode image to embedding vector using network service.
be52af70   tangwang   first commit
63
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
64
65
          Note: This method is kept for compatibility but the service only works with URLs.
          """
ed948666   tangwang   tidy
66
          raise NotImplementedError("encode_image with PIL Image is not supported by embedding service")
be52af70   tangwang   first commit
67
  
200fdddf   tangwang   embed norm
68
      def encode_image_from_url(self, url: str, normalize_embeddings: bool = True) -> np.ndarray:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
69
70
          """
          Generate image embedding via network service using URL.
be52af70   tangwang   first commit
71
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
72
73
          Args:
              url: Image URL to process
be52af70   tangwang   first commit
74
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
75
          Returns:
ed948666   tangwang   tidy
76
              Embedding vector
325eec03   tangwang   1. 日志、配置基础设施,使用优化
77
          """
4a37d233   tangwang   1. embedding cach...
78
79
80
81
          cached = self.cache.get(url)
          if cached is not None:
              return cached
  
200fdddf   tangwang   embed norm
82
          response_data = self._call_service([url], normalize_embeddings=normalize_embeddings)
ed948666   tangwang   tidy
83
84
85
86
87
          if not response_data or len(response_data) != 1 or response_data[0] is None:
              raise RuntimeError(f"No image embedding returned for URL: {url}")
          vec = np.array(response_data[0], dtype=np.float32)
          if vec.ndim != 1 or vec.size == 0 or not np.isfinite(vec).all():
              raise RuntimeError(f"Invalid image embedding returned for URL: {url}")
4a37d233   tangwang   1. embedding cach...
88
          self.cache.set(url, vec)
ed948666   tangwang   tidy
89
          return vec
be52af70   tangwang   first commit
90
91
92
93
  
      def encode_batch(
          self,
          images: List[Union[str, Image.Image]],
200fdddf   tangwang   embed norm
94
95
          batch_size: int = 8,
          normalize_embeddings: bool = True,
ed948666   tangwang   tidy
96
      ) -> List[np.ndarray]:
be52af70   tangwang   first commit
97
          """
325eec03   tangwang   1. 日志、配置基础设施,使用优化
98
          Encode a batch of images efficiently via network service.
be52af70   tangwang   first commit
99
100
101
  
          Args:
              images: List of image URLs or PIL Images
325eec03   tangwang   1. 日志、配置基础设施,使用优化
102
              batch_size: Batch size for processing (used for service requests)
be52af70   tangwang   first commit
103
104
  
          Returns:
ed948666   tangwang   tidy
105
              List of embeddings
be52af70   tangwang   first commit
106
          """
325eec03   tangwang   1. 日志、配置基础设施,使用优化
107
          for i, img in enumerate(images):
ed948666   tangwang   tidy
108
109
110
111
112
113
              if isinstance(img, Image.Image):
                  raise NotImplementedError(f"PIL Image at index {i} is not supported by service")
              if not isinstance(img, str) or not img.strip():
                  raise ValueError(f"Invalid image URL/path at index {i}: {img!r}")
  
          results: List[np.ndarray] = []
4a37d233   tangwang   1. embedding cach...
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
          pending_urls: List[str] = []
          pending_positions: List[int] = []
  
          normalized_urls = [str(u).strip() for u in images]  # type: ignore[list-item]
          for pos, url in enumerate(normalized_urls):
              cached = self.cache.get(url)
              if cached is not None:
                  results.append(cached)
              else:
                  results.append(np.array([], dtype=np.float32))  # placeholder
                  pending_positions.append(pos)
                  pending_urls.append(url)
  
          for i in range(0, len(pending_urls), batch_size):
              batch_urls = pending_urls[i : i + batch_size]
200fdddf   tangwang   embed norm
129
              response_data = self._call_service(batch_urls, normalize_embeddings=normalize_embeddings)
ed948666   tangwang   tidy
130
131
132
133
134
135
136
137
138
139
140
141
              if not response_data or len(response_data) != len(batch_urls):
                  raise RuntimeError(
                      f"Image embedding response length mismatch: expected {len(batch_urls)}, "
                      f"got {0 if response_data is None else len(response_data)}"
                  )
              for j, url in enumerate(batch_urls):
                  embedding = response_data[j]
                  if embedding is None:
                      raise RuntimeError(f"No image embedding returned for URL: {url}")
                  vec = np.array(embedding, dtype=np.float32)
                  if vec.ndim != 1 or vec.size == 0 or not np.isfinite(vec).all():
                      raise RuntimeError(f"Invalid image embedding returned for URL: {url}")
4a37d233   tangwang   1. embedding cach...
142
143
144
                  self.cache.set(url, vec)
                  pos = pending_positions[i + j]
                  results[pos] = vec
be52af70   tangwang   first commit
145
146
  
          return results
e7a2c0b7   tangwang   img encode
147
148
149
150
151
  
      def encode_image_urls(
          self,
          urls: List[str],
          batch_size: Optional[int] = None,
200fdddf   tangwang   embed norm
152
          normalize_embeddings: bool = True,
ed948666   tangwang   tidy
153
      ) -> List[np.ndarray]:
e7a2c0b7   tangwang   img encode
154
155
156
157
158
159
160
161
          """
           ClipImageModel / ClipAsServiceImageEncoder 一致的接口,供索引器 document_transformer 调用。
  
          Args:
              urls: 图片 URL 列表
              batch_size: 批大小(默认 8
  
          Returns:
ed948666   tangwang   tidy
162
               urls 等长的向量列表
e7a2c0b7   tangwang   img encode
163
          """
200fdddf   tangwang   embed norm
164
165
166
167
168
          return self.encode_batch(
              urls,
              batch_size=batch_size or 8,
              normalize_embeddings=normalize_embeddings,
          )