Blame view

embeddings/image_encoder.py 6.56 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
  
7214c2e7   tangwang   mplemented**
12
  from config.services_config import get_embedding_image_base_url
4a37d233   tangwang   1. embedding cach...
13
  from config.env_config import REDIS_CONFIG
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()
950a640e   tangwang   embeddings
27
28
          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
          """
7214c2e7   tangwang   mplemented**
78
79
          cache_key = build_image_cache_key(url, normalize=normalize_embeddings)
          cached = self.cache.get(cache_key)
4a37d233   tangwang   1. embedding cach...
80
81
82
          if cached is not None:
              return cached
  
200fdddf   tangwang   embed norm
83
          response_data = self._call_service([url], normalize_embeddings=normalize_embeddings)
ed948666   tangwang   tidy
84
85
86
87
88
          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**
89
          self.cache.set(cache_key, vec)
ed948666   tangwang   tidy
90
          return vec
be52af70   tangwang   first commit
91
92
93
94
  
      def encode_batch(
          self,
          images: List[Union[str, Image.Image]],
200fdddf   tangwang   embed norm
95
96
          batch_size: int = 8,
          normalize_embeddings: bool = True,
ed948666   tangwang   tidy
97
      ) -> List[np.ndarray]:
be52af70   tangwang   first commit
98
          """
325eec03   tangwang   1. 日志、配置基础设施,使用优化
99
          Encode a batch of images efficiently via network service.
be52af70   tangwang   first commit
100
101
102
  
          Args:
              images: List of image URLs or PIL Images
325eec03   tangwang   1. 日志、配置基础设施,使用优化
103
              batch_size: Batch size for processing (used for service requests)
be52af70   tangwang   first commit
104
105
  
          Returns:
ed948666   tangwang   tidy
106
              List of embeddings
be52af70   tangwang   first commit
107
          """
325eec03   tangwang   1. 日志、配置基础设施,使用优化
108
          for i, img in enumerate(images):
ed948666   tangwang   tidy
109
110
111
112
113
114
              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...
115
116
117
118
119
          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**
120
121
              cache_key = build_image_cache_key(url, normalize=normalize_embeddings)
              cached = self.cache.get(cache_key)
4a37d233   tangwang   1. embedding cach...
122
123
              if cached is not None:
                  results.append(cached)
5bac9649   tangwang   文本 embedding 与图片 ...
124
125
126
127
                  continue
              results.append(np.array([], dtype=np.float32))  # placeholder
              pending_positions.append(pos)
              pending_urls.append(url)
4a37d233   tangwang   1. embedding cach...
128
129
130
  
          for i in range(0, len(pending_urls), batch_size):
              batch_urls = pending_urls[i : i + batch_size]
200fdddf   tangwang   embed norm
131
              response_data = self._call_service(batch_urls, normalize_embeddings=normalize_embeddings)
ed948666   tangwang   tidy
132
133
134
135
136
137
138
139
140
141
142
143
              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**
144
                  self.cache.set(build_image_cache_key(url, normalize=normalize_embeddings), vec)
4a37d233   tangwang   1. embedding cach...
145
146
                  pos = pending_positions[i + j]
                  results[pos] = vec
be52af70   tangwang   first commit
147
148
  
          return results
e7a2c0b7   tangwang   img encode
149
150
151
152
153
  
      def encode_image_urls(
          self,
          urls: List[str],
          batch_size: Optional[int] = None,
200fdddf   tangwang   embed norm
154
          normalize_embeddings: bool = True,
ed948666   tangwang   tidy
155
      ) -> List[np.ndarray]:
e7a2c0b7   tangwang   img encode
156
157
158
159
160
161
162
163
          """
           ClipImageModel / ClipAsServiceImageEncoder 一致的接口,供索引器 document_transformer 调用。
  
          Args:
              urls: 图片 URL 列表
              batch_size: 批大小(默认 8
  
          Returns:
ed948666   tangwang   tidy
164
               urls 等长的向量列表
e7a2c0b7   tangwang   img encode
165
          """
200fdddf   tangwang   embed norm
166
167
168
169
170
          return self.encode_batch(
              urls,
              batch_size=batch_size or 8,
              normalize_embeddings=normalize_embeddings,
          )