Blame view

embeddings/text_encoder.py 6.69 KB
950a640e   tangwang   embeddings
1
  """Text embedding client for the local embedding HTTP service."""
be52af70   tangwang   first commit
2
  
950a640e   tangwang   embeddings
3
  import logging
950a640e   tangwang   embeddings
4
5
  from datetime import timedelta
  from typing import Any, List, Optional, Union
be52af70   tangwang   first commit
6
  
be52af70   tangwang   first commit
7
  import numpy as np
950a640e   tangwang   embeddings
8
  import requests
325eec03   tangwang   1. 日志、配置基础设施,使用优化
9
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
14
  from config.services_config import get_embedding_text_base_url
  from embeddings.cache_keys import build_text_cache_key
4a37d233   tangwang   1. embedding cach...
15
  from embeddings.redis_embedding_cache import RedisEmbeddingCache
42e3aea6   tangwang   tidy
16
  
7214c2e7   tangwang   mplemented**
17
  
950a640e   tangwang   embeddings
18
  class TextEmbeddingEncoder:
be52af70   tangwang   first commit
19
      """
950a640e   tangwang   embeddings
20
      Text embedding encoder using network service.
be52af70   tangwang   first commit
21
      """
be52af70   tangwang   first commit
22
  
950a640e   tangwang   embeddings
23
      def __init__(self, service_url: Optional[str] = None):
af03fdef   tangwang   embedding模块代码整理
24
          resolved_url = service_url or get_embedding_text_base_url()
86d8358b   tangwang   config optimize
25
          redis_config = get_app_config().infrastructure.redis
950a640e   tangwang   embeddings
26
27
          self.service_url = str(resolved_url).rstrip("/")
          self.endpoint = f"{self.service_url}/embed/text"
86d8358b   tangwang   config optimize
28
29
          self.expire_time = timedelta(days=redis_config.cache_expire_days)
          self.cache_prefix = str(redis_config.embedding_cache_prefix).strip() or "embedding"
950a640e   tangwang   embeddings
30
31
          logger.info("Creating TextEmbeddingEncoder instance with service URL: %s", self.service_url)
  
4a37d233   tangwang   1. embedding cach...
32
33
34
35
36
          self.cache = RedisEmbeddingCache(
              key_prefix=self.cache_prefix,
              namespace="",
              expire_time=self.expire_time,
          )
be52af70   tangwang   first commit
37
  
200fdddf   tangwang   embed norm
38
      def _call_service(self, request_data: List[str], normalize_embeddings: bool = True) -> List[Any]:
325eec03   tangwang   1. 日志、配置基础设施,使用优化
39
40
41
42
          """
          Call the embedding service API.
  
          Args:
7bfb9946   tangwang   向量化模块
43
              request_data: List of texts
325eec03   tangwang   1. 日志、配置基础设施,使用优化
44
45
  
          Returns:
7bfb9946   tangwang   向量化模块
46
              List of embeddings (list[float]) or nulls (None), aligned to input order
325eec03   tangwang   1. 日志、配置基础设施,使用优化
47
48
49
50
          """
          try:
              response = requests.post(
                  self.endpoint,
200fdddf   tangwang   embed norm
51
                  params={"normalize": "true" if normalize_embeddings else "false"},
325eec03   tangwang   1. 日志、配置基础设施,使用优化
52
53
54
55
56
57
                  json=request_data,
                  timeout=60
              )
              response.raise_for_status()
              return response.json()
          except requests.exceptions.RequestException as e:
950a640e   tangwang   embeddings
58
              logger.error(f"TextEmbeddingEncoder service request failed: {e}", exc_info=True)
325eec03   tangwang   1. 日志、配置基础设施,使用优化
59
60
              raise
  
be52af70   tangwang   first commit
61
62
63
64
      def encode(
          self,
          sentences: Union[str, List[str]],
          normalize_embeddings: bool = True,
325eec03   tangwang   1. 日志、配置基础设施,使用优化
65
          device: str = 'cpu',
be52af70   tangwang   first commit
66
67
68
          batch_size: int = 32
      ) -> np.ndarray:
          """
453992a8   tangwang   需求:
69
          Encode text into embeddings via network service with Redis caching.
be52af70   tangwang   first commit
70
71
72
  
          Args:
              sentences: Single string or list of strings to encode
200fdddf   tangwang   embed norm
73
              normalize_embeddings: Whether to request normalized embeddings from service
325eec03   tangwang   1. 日志、配置基础设施,使用优化
74
75
              device: Device parameter ignored for service compatibility
              batch_size: Batch size for processing (used for service requests)
be52af70   tangwang   first commit
76
77
  
          Returns:
ed948666   tangwang   tidy
78
79
              numpy array of dtype=object,元素均为有效 np.ndarray 向量。
              若任一输入无法生成向量,将直接抛出异常。
be52af70   tangwang   first commit
80
          """
325eec03   tangwang   1. 日志、配置基础设施,使用优化
81
82
83
          # Convert single string to list
          if isinstance(sentences, str):
              sentences = [sentences]
be52af70   tangwang   first commit
84
  
453992a8   tangwang   需求:
85
          # Check cache first
b2e50710   tangwang   BgeEncoder.encode...
86
87
          uncached_indices: List[int] = []
          uncached_texts: List[str] = []
453992a8   tangwang   需求:
88
          
70a318c6   tangwang   fix bug
89
          embeddings: List[Optional[np.ndarray]] = [None] * len(sentences)
70a318c6   tangwang   fix bug
90
          for i, text in enumerate(sentences):
7214c2e7   tangwang   mplemented**
91
              cached = self._get_cached_embedding(text, normalize_embeddings=normalize_embeddings)
70a318c6   tangwang   fix bug
92
93
94
95
96
97
98
              if cached is not None:
                  embeddings[i] = cached
              else:
                  uncached_indices.append(i)
                  uncached_texts.append(text)
          
          # Prepare request data for uncached texts (after cache check)
7bfb9946   tangwang   向量化模块
99
          request_data = list(uncached_texts)
453992a8   tangwang   需求:
100
101
102
          
          # If there are uncached texts, call service
          if uncached_texts:
200fdddf   tangwang   embed norm
103
              response_data = self._call_service(request_data, normalize_embeddings=normalize_embeddings)
453992a8   tangwang   需求:
104
  
ed948666   tangwang   tidy
105
106
107
108
109
110
111
              # Process response
              for i, text in enumerate(uncached_texts):
                  original_idx = uncached_indices[i]
                  if response_data and i < len(response_data):
                      embedding = response_data[i]
                  else:
                      embedding = None
7bfb9946   tangwang   向量化模块
112
  
ed948666   tangwang   tidy
113
114
115
116
                  if embedding is not None:
                      embedding_array = np.array(embedding, dtype=np.float32)
                      if self._is_valid_embedding(embedding_array):
                          embeddings[original_idx] = embedding_array
7214c2e7   tangwang   mplemented**
117
118
119
120
121
                          self._set_cached_embedding(
                              text,
                              embedding_array,
                              normalize_embeddings=normalize_embeddings,
                          )
325eec03   tangwang   1. 日志、配置基础设施,使用优化
122
                      else:
ed948666   tangwang   tidy
123
124
125
126
127
                          raise ValueError(
                              f"Invalid embedding returned from service for text index {original_idx}"
                          )
                  else:
                      raise ValueError(f"No embedding found for text index {original_idx}: {text[:50]}...")
453992a8   tangwang   需求:
128
          
77516841   tangwang   tidy embeddings
129
          # 返回 numpy 数组(dtype=object),元素均为有效 np.ndarray 向量
b2e50710   tangwang   BgeEncoder.encode...
130
          return np.array(embeddings, dtype=object)
3d588bef   tangwang   embeddings
131
          
b2e50710   tangwang   BgeEncoder.encode...
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
      def _is_valid_embedding(self, embedding: np.ndarray) -> bool:
          """
          Check if embedding is valid (not None, correct shape, no NaN/Inf).
          
          Args:
              embedding: Embedding array to validate
              
          Returns:
              True if valid, False otherwise
          """
          if embedding is None:
              return False
          if not isinstance(embedding, np.ndarray):
              return False
          if embedding.size == 0:
              return False
          # Check for NaN or Inf values
          if not np.isfinite(embedding).all():
              return False
          return True
      
200fdddf   tangwang   embed norm
153
154
      def _get_cached_embedding(
          self,
4a37d233   tangwang   1. embedding cach...
155
          query: str,
7214c2e7   tangwang   mplemented**
156
157
          *,
          normalize_embeddings: bool,
200fdddf   tangwang   embed norm
158
      ) -> Optional[np.ndarray]:
4a37d233   tangwang   1. embedding cach...
159
          """Get embedding from cache if exists (with sliding expiration)."""
5bac9649   tangwang   文本 embedding 与图片 ...
160
161
          cache_key = build_text_cache_key(query, normalize=normalize_embeddings)
          embedding = self.cache.get(cache_key)
4a37d233   tangwang   1. embedding cach...
162
          if embedding is not None:
7214c2e7   tangwang   mplemented**
163
              logger.debug(
5bac9649   tangwang   文本 embedding 与图片 ...
164
                  "Cache hit for text embedding | normalize=%s query=%s key=%s",
7214c2e7   tangwang   mplemented**
165
166
                  normalize_embeddings,
                  query,
5bac9649   tangwang   文本 embedding 与图片 ...
167
                  cache_key,
7214c2e7   tangwang   mplemented**
168
              )
4a37d233   tangwang   1. embedding cach...
169
          return embedding
453992a8   tangwang   需求:
170
      
200fdddf   tangwang   embed norm
171
172
173
      def _set_cached_embedding(
          self,
          query: str,
200fdddf   tangwang   embed norm
174
          embedding: np.ndarray,
7214c2e7   tangwang   mplemented**
175
176
          *,
          normalize_embeddings: bool,
200fdddf   tangwang   embed norm
177
      ) -> bool:
4a37d233   tangwang   1. embedding cach...
178
          """Store embedding in cache."""
7214c2e7   tangwang   mplemented**
179
          ok = self.cache.set(build_text_cache_key(query, normalize=normalize_embeddings), embedding)
4a37d233   tangwang   1. embedding cach...
180
          if ok:
7214c2e7   tangwang   mplemented**
181
182
183
184
185
              logger.debug(
                  "Successfully cached text embedding | normalize=%s query=%s",
                  normalize_embeddings,
                  query,
              )
4a37d233   tangwang   1. embedding cach...
186
          return ok