Blame view

search/sku_intent_selector.py 15.8 KB
cda1cd62   tangwang   意图分析&应用 baseline
1
2
3
4
5
6
7
  """
  SKU selection for style-intent-aware search results.
  """
  
  from __future__ import annotations
  
  from dataclasses import dataclass, field
2efad04b   tangwang   意图匹配的性能优化:
8
  from typing import Any, Callable, Dict, List, Optional, Sequence, Tuple
cda1cd62   tangwang   意图分析&应用 baseline
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
  
  import numpy as np
  
  from query.style_intent import StyleIntentProfile, StyleIntentRegistry
  from query.tokenization import normalize_query_text
  
  
  @dataclass(frozen=True)
  class SkuSelectionDecision:
      selected_sku_id: Optional[str]
      rerank_suffix: str
      selected_text: str
      matched_stage: str
      similarity_score: Optional[float] = None
      resolved_dimensions: Dict[str, Optional[str]] = field(default_factory=dict)
  
      def to_dict(self) -> Dict[str, Any]:
          return {
              "selected_sku_id": self.selected_sku_id,
              "rerank_suffix": self.rerank_suffix,
              "selected_text": self.selected_text,
              "matched_stage": self.matched_stage,
              "similarity_score": self.similarity_score,
              "resolved_dimensions": dict(self.resolved_dimensions),
          }
  
  
  @dataclass
  class _SkuCandidate:
      index: int
      sku_id: str
      sku: Dict[str, Any]
      selection_text: str
2efad04b   tangwang   意图匹配的性能优化:
42
43
44
45
46
47
48
49
50
51
52
53
      normalized_selection_text: str
      intent_values: Dict[str, str]
  
  
  @dataclass
  class _SelectionContext:
      query_texts: Tuple[str, ...]
      matched_terms_by_intent: Dict[str, Tuple[str, ...]]
      query_vector: Optional[np.ndarray]
      text_match_cache: Dict[Tuple[str, str], bool] = field(default_factory=dict)
      selection_vector_cache: Dict[str, Optional[np.ndarray]] = field(default_factory=dict)
      similarity_cache: Dict[str, Optional[float]] = field(default_factory=dict)
cda1cd62   tangwang   意图分析&应用 baseline
54
55
56
57
58
59
60
61
62
63
  
  
  class StyleSkuSelector:
      """Selects the best SKU for an SPU based on detected style intent."""
  
      def __init__(
          self,
          registry: StyleIntentRegistry,
          *,
          text_encoder_getter: Optional[Callable[[], Any]] = None,
cda1cd62   tangwang   意图分析&应用 baseline
64
65
66
      ) -> None:
          self.registry = registry
          self._text_encoder_getter = text_encoder_getter
cda1cd62   tangwang   意图分析&应用 baseline
67
68
69
70
71
72
73
74
75
76
77
  
      def prepare_hits(
          self,
          es_hits: List[Dict[str, Any]],
          parsed_query: Any,
      ) -> Dict[str, SkuSelectionDecision]:
          decisions: Dict[str, SkuSelectionDecision] = {}
          style_profile = getattr(parsed_query, "style_intent_profile", None)
          if not isinstance(style_profile, StyleIntentProfile) or not style_profile.is_active:
              return decisions
  
2efad04b   tangwang   意图匹配的性能优化:
78
          selection_context = self._build_selection_context(parsed_query, style_profile)
cda1cd62   tangwang   意图分析&应用 baseline
79
80
81
82
83
84
85
86
87
  
          for hit in es_hits:
              source = hit.get("_source")
              if not isinstance(source, dict):
                  continue
  
              decision = self._select_for_source(
                  source,
                  style_profile=style_profile,
2efad04b   tangwang   意图匹配的性能优化:
88
                  selection_context=selection_context,
cda1cd62   tangwang   意图分析&应用 baseline
89
90
91
92
              )
              if decision is None:
                  continue
  
cda1cd62   tangwang   意图分析&应用 baseline
93
94
              if decision.rerank_suffix:
                  hit["_style_rerank_suffix"] = decision.rerank_suffix
2efad04b   tangwang   意图匹配的性能优化:
95
96
              else:
                  hit.pop("_style_rerank_suffix", None)
cda1cd62   tangwang   意图分析&应用 baseline
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
  
              doc_id = hit.get("_id")
              if doc_id is not None:
                  decisions[str(doc_id)] = decision
  
          return decisions
  
      def apply_precomputed_decisions(
          self,
          es_hits: List[Dict[str, Any]],
          decisions: Dict[str, SkuSelectionDecision],
      ) -> None:
          if not es_hits or not decisions:
              return
  
          for hit in es_hits:
              doc_id = hit.get("_id")
              if doc_id is None:
                  continue
              decision = decisions.get(str(doc_id))
              if decision is None:
                  continue
              source = hit.get("_source")
              if not isinstance(source, dict):
                  continue
              self._apply_decision_to_source(source, decision)
              if decision.rerank_suffix:
                  hit["_style_rerank_suffix"] = decision.rerank_suffix
2efad04b   tangwang   意图匹配的性能优化:
125
126
              else:
                  hit.pop("_style_rerank_suffix", None)
cda1cd62   tangwang   意图分析&应用 baseline
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
  
      def _build_query_texts(
          self,
          parsed_query: Any,
          style_profile: StyleIntentProfile,
      ) -> List[str]:
          texts = [variant.normalized_text for variant in style_profile.query_variants if variant.normalized_text]
          if texts:
              return list(dict.fromkeys(texts))
  
          fallbacks: List[str] = []
          for value in (
              getattr(parsed_query, "original_query", None),
              getattr(parsed_query, "query_normalized", None),
              getattr(parsed_query, "rewritten_query", None),
          ):
              normalized = normalize_query_text(value)
              if normalized:
                  fallbacks.append(normalized)
          translations = getattr(parsed_query, "translations", {}) or {}
          if isinstance(translations, dict):
              for value in translations.values():
                  normalized = normalize_query_text(value)
                  if normalized:
                      fallbacks.append(normalized)
          return list(dict.fromkeys(fallbacks))
  
      def _get_query_vector(self, parsed_query: Any) -> Optional[np.ndarray]:
          query_vector = getattr(parsed_query, "query_vector", None)
          if query_vector is not None:
              return np.asarray(query_vector, dtype=np.float32)
  
          text_encoder = self._get_text_encoder()
          if text_encoder is None:
              return None
  
          query_text = (
              getattr(parsed_query, "rewritten_query", None)
              or getattr(parsed_query, "query_normalized", None)
              or getattr(parsed_query, "original_query", None)
          )
          if not query_text:
              return None
  
          vectors = text_encoder.encode([query_text], priority=1)
          if vectors is None or len(vectors) == 0 or vectors[0] is None:
              return None
          return np.asarray(vectors[0], dtype=np.float32)
  
2efad04b   tangwang   意图匹配的性能优化:
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
      def _build_selection_context(
          self,
          parsed_query: Any,
          style_profile: StyleIntentProfile,
      ) -> _SelectionContext:
          matched_terms_by_intent: Dict[str, List[str]] = {}
          for intent in style_profile.intents:
              normalized_term = normalize_query_text(intent.matched_term)
              if not normalized_term:
                  continue
              matched_terms = matched_terms_by_intent.setdefault(intent.intent_type, [])
              if normalized_term not in matched_terms:
                  matched_terms.append(normalized_term)
  
          return _SelectionContext(
              query_texts=tuple(self._build_query_texts(parsed_query, style_profile)),
              matched_terms_by_intent={
                  intent_type: tuple(terms)
                  for intent_type, terms in matched_terms_by_intent.items()
              },
              query_vector=self._get_query_vector(parsed_query),
          )
  
cda1cd62   tangwang   意图分析&应用 baseline
199
200
201
202
203
      def _get_text_encoder(self) -> Any:
          if self._text_encoder_getter is None:
              return None
          return self._text_encoder_getter()
  
cda1cd62   tangwang   意图分析&应用 baseline
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
      def _resolve_dimensions(
          self,
          source: Dict[str, Any],
          style_profile: StyleIntentProfile,
      ) -> Dict[str, Optional[str]]:
          option_names = {
              "option1_value": normalize_query_text(source.get("option1_name")),
              "option2_value": normalize_query_text(source.get("option2_name")),
              "option3_value": normalize_query_text(source.get("option3_name")),
          }
          resolved: Dict[str, Optional[str]] = {}
          for intent in style_profile.intents:
              if intent.intent_type in resolved:
                  continue
              aliases = set(intent.dimension_aliases or self.registry.get_dimension_aliases(intent.intent_type))
              matched_field = None
              for field_name, option_name in option_names.items():
                  if option_name and option_name in aliases:
                      matched_field = field_name
                      break
              resolved[intent.intent_type] = matched_field
          return resolved
  
      def _build_candidates(
          self,
          skus: List[Dict[str, Any]],
          resolved_dimensions: Dict[str, Optional[str]],
      ) -> List[_SkuCandidate]:
2efad04b   tangwang   意图匹配的性能优化:
232
233
234
          if not resolved_dimensions or any(not field_name for field_name in resolved_dimensions.values()):
              return []
  
cda1cd62   tangwang   意图分析&应用 baseline
235
236
          candidates: List[_SkuCandidate] = []
          for index, sku in enumerate(skus):
2efad04b   tangwang   意图匹配的性能优化:
237
              intent_values: Dict[str, str] = {}
cda1cd62   tangwang   意图分析&应用 baseline
238
              for intent_type, field_name in resolved_dimensions.items():
2efad04b   tangwang   意图匹配的性能优化:
239
240
241
                  if not field_name:
                      continue
                  intent_values[intent_type] = str(sku.get(field_name) or "").strip()
cda1cd62   tangwang   意图分析&应用 baseline
242
243
244
  
              selection_parts: List[str] = []
              seen = set()
2efad04b   tangwang   意图匹配的性能优化:
245
              for value in intent_values.values():
cda1cd62   tangwang   意图分析&应用 baseline
246
247
248
249
                  normalized = normalize_query_text(value)
                  if not normalized or normalized in seen:
                      continue
                  seen.add(normalized)
2efad04b   tangwang   意图匹配的性能优化:
250
                  selection_parts.append(value)
cda1cd62   tangwang   意图分析&应用 baseline
251
  
2efad04b   tangwang   意图匹配的性能优化:
252
              selection_text = " ".join(selection_parts).strip()
cda1cd62   tangwang   意图分析&应用 baseline
253
254
255
256
257
258
              candidates.append(
                  _SkuCandidate(
                      index=index,
                      sku_id=str(sku.get("sku_id") or ""),
                      sku=sku,
                      selection_text=selection_text,
2efad04b   tangwang   意图匹配的性能优化:
259
260
                      normalized_selection_text=normalize_query_text(selection_text),
                      intent_values=intent_values,
cda1cd62   tangwang   意图分析&应用 baseline
261
262
263
264
265
                  )
              )
          return candidates
  
      @staticmethod
2efad04b   tangwang   意图匹配的性能优化:
266
267
268
269
270
271
272
273
274
275
276
277
278
      def _empty_decision(
          resolved_dimensions: Dict[str, Optional[str]],
          matched_stage: str,
      ) -> SkuSelectionDecision:
          return SkuSelectionDecision(
              selected_sku_id=None,
              rerank_suffix="",
              selected_text="",
              matched_stage=matched_stage,
              resolved_dimensions=dict(resolved_dimensions),
          )
  
      def _is_text_match(
cda1cd62   tangwang   意图分析&应用 baseline
279
          self,
2efad04b   tangwang   意图匹配的性能优化:
280
281
282
          intent_type: str,
          value: str,
          selection_context: _SelectionContext,
cda1cd62   tangwang   意图分析&应用 baseline
283
      ) -> bool:
2efad04b   tangwang   意图匹配的性能优化:
284
285
          normalized_value = normalize_query_text(value)
          if not normalized_value:
cda1cd62   tangwang   意图分析&应用 baseline
286
287
              return False
  
2efad04b   tangwang   意图匹配的性能优化:
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
          cache_key = (intent_type, normalized_value)
          cached = selection_context.text_match_cache.get(cache_key)
          if cached is not None:
              return cached
  
          matched_terms = selection_context.matched_terms_by_intent.get(intent_type, ())
          has_term_match = any(term in normalized_value for term in matched_terms if term)
          query_contains_value = any(
              normalized_value in query_text
              for query_text in selection_context.query_texts
          )
          matched = bool(has_term_match or query_contains_value)
          selection_context.text_match_cache[cache_key] = matched
          return matched
  
      def _find_first_text_match(
          self,
          candidates: Sequence[_SkuCandidate],
          selection_context: _SelectionContext,
      ) -> Optional[_SkuCandidate]:
          for candidate in candidates:
              if candidate.intent_values and all(
                  self._is_text_match(intent_type, value, selection_context)
                  for intent_type, value in candidate.intent_values.items()
              ):
                  return candidate
          return None
cda1cd62   tangwang   意图分析&应用 baseline
315
316
317
318
  
      def _select_by_embedding(
          self,
          candidates: Sequence[_SkuCandidate],
2efad04b   tangwang   意图匹配的性能优化:
319
          selection_context: _SelectionContext,
cda1cd62   tangwang   意图分析&应用 baseline
320
321
322
323
      ) -> Tuple[Optional[_SkuCandidate], Optional[float]]:
          if not candidates:
              return None, None
          text_encoder = self._get_text_encoder()
2efad04b   tangwang   意图匹配的性能优化:
324
325
          if selection_context.query_vector is None or text_encoder is None:
              return None, None
cda1cd62   tangwang   意图分析&应用 baseline
326
327
328
  
          unique_texts = list(
              dict.fromkeys(
2efad04b   tangwang   意图匹配的性能优化:
329
                  candidate.normalized_selection_text
cda1cd62   tangwang   意图分析&应用 baseline
330
                  for candidate in candidates
2efad04b   tangwang   意图匹配的性能优化:
331
332
                  if candidate.normalized_selection_text
                  and candidate.normalized_selection_text not in selection_context.selection_vector_cache
cda1cd62   tangwang   意图分析&应用 baseline
333
334
              )
          )
2efad04b   tangwang   意图匹配的性能优化:
335
336
337
338
339
340
          if unique_texts:
              vectors = text_encoder.encode(unique_texts, priority=1)
              for key, vector in zip(unique_texts, vectors):
                  selection_context.selection_vector_cache[key] = (
                      np.asarray(vector, dtype=np.float32) if vector is not None else None
                  )
cda1cd62   tangwang   意图分析&应用 baseline
341
342
343
  
          best_candidate: Optional[_SkuCandidate] = None
          best_score: Optional[float] = None
2efad04b   tangwang   意图匹配的性能优化:
344
          query_vector_array = np.asarray(selection_context.query_vector, dtype=np.float32)
cda1cd62   tangwang   意图分析&应用 baseline
345
          for candidate in candidates:
2efad04b   tangwang   意图匹配的性能优化:
346
347
348
349
350
351
352
353
354
355
356
357
358
359
              normalized_text = candidate.normalized_selection_text
              if not normalized_text:
                  continue
  
              score = selection_context.similarity_cache.get(normalized_text)
              if score is None:
                  candidate_vector = selection_context.selection_vector_cache.get(normalized_text)
                  if candidate_vector is None:
                      selection_context.similarity_cache[normalized_text] = None
                      continue
                  score = float(np.inner(query_vector_array, candidate_vector))
                  selection_context.similarity_cache[normalized_text] = score
  
              if score is None:
cda1cd62   tangwang   意图分析&应用 baseline
360
                  continue
cda1cd62   tangwang   意图分析&应用 baseline
361
362
363
364
              if best_score is None or score > best_score:
                  best_candidate = candidate
                  best_score = score
  
2efad04b   tangwang   意图匹配的性能优化:
365
          return best_candidate, best_score
cda1cd62   tangwang   意图分析&应用 baseline
366
367
368
369
370
371
  
      def _select_for_source(
          self,
          source: Dict[str, Any],
          *,
          style_profile: StyleIntentProfile,
2efad04b   tangwang   意图匹配的性能优化:
372
          selection_context: _SelectionContext,
cda1cd62   tangwang   意图分析&应用 baseline
373
374
375
376
377
378
      ) -> Optional[SkuSelectionDecision]:
          skus = source.get("skus")
          if not isinstance(skus, list) or not skus:
              return None
  
          resolved_dimensions = self._resolve_dimensions(source, style_profile)
2efad04b   tangwang   意图匹配的性能优化:
379
380
381
          if not resolved_dimensions or any(not field_name for field_name in resolved_dimensions.values()):
              return self._empty_decision(resolved_dimensions, matched_stage="unresolved")
  
cda1cd62   tangwang   意图分析&应用 baseline
382
383
          candidates = self._build_candidates(skus, resolved_dimensions)
          if not candidates:
2efad04b   tangwang   意图匹配的性能优化:
384
              return self._empty_decision(resolved_dimensions, matched_stage="no_candidates")
cda1cd62   tangwang   意图分析&应用 baseline
385
  
2efad04b   tangwang   意图匹配的性能优化:
386
387
388
          text_match = self._find_first_text_match(candidates, selection_context)
          if text_match is not None:
              return self._build_decision(text_match, resolved_dimensions, matched_stage="text")
cda1cd62   tangwang   意图分析&应用 baseline
389
  
2efad04b   tangwang   意图匹配的性能优化:
390
          chosen, similarity_score = self._select_by_embedding(candidates, selection_context)
cda1cd62   tangwang   意图分析&应用 baseline
391
          if chosen is None:
2efad04b   tangwang   意图匹配的性能优化:
392
              return self._empty_decision(resolved_dimensions, matched_stage="no_match")
cda1cd62   tangwang   意图分析&应用 baseline
393
394
395
          return self._build_decision(
              chosen,
              resolved_dimensions,
2efad04b   tangwang   意图匹配的性能优化:
396
              matched_stage="embedding",
cda1cd62   tangwang   意图分析&应用 baseline
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
              similarity_score=similarity_score,
          )
  
      @staticmethod
      def _build_decision(
          candidate: _SkuCandidate,
          resolved_dimensions: Dict[str, Optional[str]],
          *,
          matched_stage: str,
          similarity_score: Optional[float] = None,
      ) -> SkuSelectionDecision:
          return SkuSelectionDecision(
              selected_sku_id=candidate.sku_id or None,
              rerank_suffix=str(candidate.selection_text or "").strip(),
              selected_text=str(candidate.selection_text or "").strip(),
              matched_stage=matched_stage,
              similarity_score=similarity_score,
              resolved_dimensions=dict(resolved_dimensions),
          )
  
      @staticmethod
      def _apply_decision_to_source(source: Dict[str, Any], decision: SkuSelectionDecision) -> None:
          skus = source.get("skus")
          if not isinstance(skus, list) or not skus or not decision.selected_sku_id:
              return
  
          selected_index = None
          for index, sku in enumerate(skus):
              if str(sku.get("sku_id") or "") == decision.selected_sku_id:
                  selected_index = index
                  break
          if selected_index is None:
              return
  
          selected_sku = skus.pop(selected_index)
          skus.insert(0, selected_sku)
  
          image_src = selected_sku.get("image_src") or selected_sku.get("imageSrc")
          if image_src:
              source["image_url"] = image_src