Blame view

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