Blame view

embeddings/image_encoder.py 7.03 KB
950a640e   tangwang   embeddings
1
  """Image embedding client for the local embedding HTTP service."""
be52af70   tangwang   first commit
2
  
950a640e   tangwang   embeddings
3
4
5
  import logging
  from typing import Any, List, Optional, Union
  
be52af70   tangwang   first commit
6
  import numpy as np
950a640e   tangwang   embeddings
7
  import requests
be52af70   tangwang   first commit
8
  from PIL import Image
be52af70   tangwang   first commit
9
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
10
  logger = logging.getLogger(__name__)
be52af70   tangwang   first commit
11
  
86d8358b   tangwang   config optimize
12
  from config.loader import get_app_config
7214c2e7   tangwang   mplemented**
13
  from config.services_config import get_embedding_image_base_url
7214c2e7   tangwang   mplemented**
14
  from embeddings.cache_keys import build_image_cache_key
4a37d233   tangwang   1. embedding cach...
15
  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
      def __init__(self, service_url: Optional[str] = None):
af03fdef   tangwang   embedding模块代码整理
26
          resolved_url = service_url or get_embedding_image_base_url()
86d8358b   tangwang   config optimize
27
          redis_config = get_app_config().infrastructure.redis
950a640e   tangwang   embeddings
28
29
          self.service_url = str(resolved_url).rstrip("/")
          self.endpoint = f"{self.service_url}/embed/image"
4a37d233   tangwang   1. embedding cach...
30
          # Reuse embedding cache prefix, but separate namespace for images to avoid collisions.
86d8358b   tangwang   config optimize
31
          self.cache_prefix = str(redis_config.embedding_cache_prefix).strip() or "embedding"
950a640e   tangwang   embeddings
32
          logger.info("Creating CLIPImageEncoder instance with service URL: %s", self.service_url)
4a37d233   tangwang   1. embedding cach...
33
34
35
36
          self.cache = RedisEmbeddingCache(
              key_prefix=self.cache_prefix,
              namespace="image",
          )
be52af70   tangwang   first commit
37
  
b754fd41   tangwang   图片向量化支持优先级参数
38
39
40
41
42
43
      def _call_service(
          self,
          request_data: List[str],
          normalize_embeddings: bool = True,
          priority: int = 0,
      ) -> List[Any]:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
44
45
          """
          Call the embedding service API.
be52af70   tangwang   first commit
46
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
47
          Args:
7bfb9946   tangwang   向量化模块
48
              request_data: List of image URLs / local file paths
be52af70   tangwang   first commit
49
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
50
          Returns:
7bfb9946   tangwang   向量化模块
51
              List of embeddings (list[float]) or nulls (None), aligned to input order
325eec03   tangwang   1. 日志、配置基础设施,使用优化
52
          """
be52af70   tangwang   first commit
53
          try:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
54
55
              response = requests.post(
                  self.endpoint,
b754fd41   tangwang   图片向量化支持优先级参数
56
57
58
59
                  params={
                      "normalize": "true" if normalize_embeddings else "false",
                      "priority": max(0, int(priority)),
                  },
325eec03   tangwang   1. 日志、配置基础设施,使用优化
60
61
62
63
64
65
66
67
                  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
68
  
ed948666   tangwang   tidy
69
      def encode_image(self, image: Image.Image) -> np.ndarray:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
70
71
          """
          Encode image to embedding vector using network service.
be52af70   tangwang   first commit
72
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
73
74
          Note: This method is kept for compatibility but the service only works with URLs.
          """
ed948666   tangwang   tidy
75
          raise NotImplementedError("encode_image with PIL Image is not supported by embedding service")
be52af70   tangwang   first commit
76
  
b754fd41   tangwang   图片向量化支持优先级参数
77
78
79
80
81
82
      def encode_image_from_url(
          self,
          url: str,
          normalize_embeddings: bool = True,
          priority: int = 0,
      ) -> np.ndarray:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
83
84
          """
          Generate image embedding via network service using URL.
be52af70   tangwang   first commit
85
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
86
87
          Args:
              url: Image URL to process
be52af70   tangwang   first commit
88
  
325eec03   tangwang   1. 日志、配置基础设施,使用优化
89
          Returns:
ed948666   tangwang   tidy
90
              Embedding vector
325eec03   tangwang   1. 日志、配置基础设施,使用优化
91
          """
7214c2e7   tangwang   mplemented**
92
93
          cache_key = build_image_cache_key(url, normalize=normalize_embeddings)
          cached = self.cache.get(cache_key)
4a37d233   tangwang   1. embedding cach...
94
95
96
          if cached is not None:
              return cached
  
b754fd41   tangwang   图片向量化支持优先级参数
97
98
99
100
101
          response_data = self._call_service(
              [url],
              normalize_embeddings=normalize_embeddings,
              priority=priority,
          )
ed948666   tangwang   tidy
102
103
104
105
106
          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}")
7214c2e7   tangwang   mplemented**
107
          self.cache.set(cache_key, vec)
ed948666   tangwang   tidy
108
          return vec
be52af70   tangwang   first commit
109
110
111
112
  
      def encode_batch(
          self,
          images: List[Union[str, Image.Image]],
200fdddf   tangwang   embed norm
113
114
          batch_size: int = 8,
          normalize_embeddings: bool = True,
b754fd41   tangwang   图片向量化支持优先级参数
115
          priority: int = 0,
ed948666   tangwang   tidy
116
      ) -> List[np.ndarray]:
be52af70   tangwang   first commit
117
          """
325eec03   tangwang   1. 日志、配置基础设施,使用优化
118
          Encode a batch of images efficiently via network service.
be52af70   tangwang   first commit
119
120
121
  
          Args:
              images: List of image URLs or PIL Images
325eec03   tangwang   1. 日志、配置基础设施,使用优化
122
              batch_size: Batch size for processing (used for service requests)
be52af70   tangwang   first commit
123
124
  
          Returns:
ed948666   tangwang   tidy
125
              List of embeddings
be52af70   tangwang   first commit
126
          """
325eec03   tangwang   1. 日志、配置基础设施,使用优化
127
          for i, img in enumerate(images):
ed948666   tangwang   tidy
128
129
130
131
132
133
              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...
134
135
136
137
138
          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):
7214c2e7   tangwang   mplemented**
139
140
              cache_key = build_image_cache_key(url, normalize=normalize_embeddings)
              cached = self.cache.get(cache_key)
4a37d233   tangwang   1. embedding cach...
141
142
              if cached is not None:
                  results.append(cached)
5bac9649   tangwang   文本 embedding 与图片 ...
143
144
145
146
                  continue
              results.append(np.array([], dtype=np.float32))  # placeholder
              pending_positions.append(pos)
              pending_urls.append(url)
4a37d233   tangwang   1. embedding cach...
147
148
149
  
          for i in range(0, len(pending_urls), batch_size):
              batch_urls = pending_urls[i : i + batch_size]
b754fd41   tangwang   图片向量化支持优先级参数
150
151
152
153
154
              response_data = self._call_service(
                  batch_urls,
                  normalize_embeddings=normalize_embeddings,
                  priority=priority,
              )
ed948666   tangwang   tidy
155
156
157
158
159
160
161
162
163
164
165
166
              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}")
7214c2e7   tangwang   mplemented**
167
                  self.cache.set(build_image_cache_key(url, normalize=normalize_embeddings), vec)
4a37d233   tangwang   1. embedding cach...
168
169
                  pos = pending_positions[i + j]
                  results[pos] = vec
be52af70   tangwang   first commit
170
171
  
          return results
e7a2c0b7   tangwang   img encode
172
173
174
175
176
  
      def encode_image_urls(
          self,
          urls: List[str],
          batch_size: Optional[int] = None,
200fdddf   tangwang   embed norm
177
          normalize_embeddings: bool = True,
b754fd41   tangwang   图片向量化支持优先级参数
178
          priority: int = 0,
ed948666   tangwang   tidy
179
      ) -> List[np.ndarray]:
e7a2c0b7   tangwang   img encode
180
181
182
183
184
185
186
187
          """
           ClipImageModel / ClipAsServiceImageEncoder 一致的接口,供索引器 document_transformer 调用。
  
          Args:
              urls: 图片 URL 列表
              batch_size: 批大小(默认 8
  
          Returns:
ed948666   tangwang   tidy
188
               urls 等长的向量列表
e7a2c0b7   tangwang   img encode
189
          """
200fdddf   tangwang   embed norm
190
191
192
193
          return self.encode_batch(
              urls,
              batch_size=batch_size or 8,
              normalize_embeddings=normalize_embeddings,
b754fd41   tangwang   图片向量化支持优先级参数
194
              priority=priority,
200fdddf   tangwang   embed norm
195
          )