Blame view

search/sku_intent_selector.py 16.4 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
      normalized_selection_text: str
      intent_values: Dict[str, str]
6adbf18a   tangwang   reranker提示词优化
44
      normalized_intent_values: Dict[str, str]
2efad04b   tangwang   意图匹配的性能优化:
45
46
47
48
49
50
51
52
53
54
  
  
  @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
55
56
57
58
59
60
61
62
63
64
  
  
  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
65
66
67
      ) -> None:
          self.registry = registry
          self._text_encoder_getter = text_encoder_getter
cda1cd62   tangwang   意图分析&应用 baseline
68
69
70
71
72
73
74
75
76
77
78
  
      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   意图匹配的性能优化:
79
          selection_context = self._build_selection_context(parsed_query, style_profile)
cda1cd62   tangwang   意图分析&应用 baseline
80
81
82
83
84
85
86
87
88
  
          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   意图匹配的性能优化:
89
                  selection_context=selection_context,
cda1cd62   tangwang   意图分析&应用 baseline
90
91
92
93
              )
              if decision is None:
                  continue
  
cda1cd62   tangwang   意图分析&应用 baseline
94
95
              if decision.rerank_suffix:
                  hit["_style_rerank_suffix"] = decision.rerank_suffix
2efad04b   tangwang   意图匹配的性能优化:
96
97
              else:
                  hit.pop("_style_rerank_suffix", None)
cda1cd62   tangwang   意图分析&应用 baseline
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
125
  
              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   意图匹配的性能优化:
126
127
              else:
                  hit.pop("_style_rerank_suffix", None)
cda1cd62   tangwang   意图分析&应用 baseline
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
176
  
      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   意图匹配的性能优化:
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
      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
200
201
202
203
204
      def _get_text_encoder(self) -> Any:
          if self._text_encoder_getter is None:
              return None
          return self._text_encoder_getter()
  
cda1cd62   tangwang   意图分析&应用 baseline
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
232
      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   意图匹配的性能优化:
233
234
235
          if not resolved_dimensions or any(not field_name for field_name in resolved_dimensions.values()):
              return []
  
cda1cd62   tangwang   意图分析&应用 baseline
236
237
          candidates: List[_SkuCandidate] = []
          for index, sku in enumerate(skus):
2efad04b   tangwang   意图匹配的性能优化:
238
              intent_values: Dict[str, str] = {}
6adbf18a   tangwang   reranker提示词优化
239
              normalized_intent_values: Dict[str, str] = {}
cda1cd62   tangwang   意图分析&应用 baseline
240
              for intent_type, field_name in resolved_dimensions.items():
2efad04b   tangwang   意图匹配的性能优化:
241
242
                  if not field_name:
                      continue
6adbf18a   tangwang   reranker提示词优化
243
244
245
                  raw = str(sku.get(field_name) or "").strip()
                  intent_values[intent_type] = raw
                  normalized_intent_values[intent_type] = normalize_query_text(raw)
cda1cd62   tangwang   意图分析&应用 baseline
246
247
  
              selection_parts: List[str] = []
6adbf18a   tangwang   reranker提示词优化
248
249
250
251
252
              norm_parts: List[str] = []
              seen: set[str] = set()
              for intent_type, raw in intent_values.items():
                  nv = normalized_intent_values[intent_type]
                  if not nv or nv in seen:
cda1cd62   tangwang   意图分析&应用 baseline
253
                      continue
6adbf18a   tangwang   reranker提示词优化
254
255
256
                  seen.add(nv)
                  selection_parts.append(raw)
                  norm_parts.append(nv)
cda1cd62   tangwang   意图分析&应用 baseline
257
  
2efad04b   tangwang   意图匹配的性能优化:
258
              selection_text = " ".join(selection_parts).strip()
6adbf18a   tangwang   reranker提示词优化
259
              normalized_selection_text = " ".join(norm_parts).strip()
cda1cd62   tangwang   意图分析&应用 baseline
260
261
262
263
264
265
              candidates.append(
                  _SkuCandidate(
                      index=index,
                      sku_id=str(sku.get("sku_id") or ""),
                      sku=sku,
                      selection_text=selection_text,
6adbf18a   tangwang   reranker提示词优化
266
                      normalized_selection_text=normalized_selection_text,
2efad04b   tangwang   意图匹配的性能优化:
267
                      intent_values=intent_values,
6adbf18a   tangwang   reranker提示词优化
268
                      normalized_intent_values=normalized_intent_values,
cda1cd62   tangwang   意图分析&应用 baseline
269
270
271
272
273
                  )
              )
          return candidates
  
      @staticmethod
2efad04b   tangwang   意图匹配的性能优化:
274
275
276
277
278
279
280
281
282
283
284
285
286
      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
287
          self,
2efad04b   tangwang   意图匹配的性能优化:
288
289
290
          intent_type: str,
          value: str,
          selection_context: _SelectionContext,
6adbf18a   tangwang   reranker提示词优化
291
292
          *,
          normalized_value: Optional[str] = None,
cda1cd62   tangwang   意图分析&应用 baseline
293
      ) -> bool:
6adbf18a   tangwang   reranker提示词优化
294
295
          if normalized_value is None:
              normalized_value = normalize_query_text(value)
2efad04b   tangwang   意图匹配的性能优化:
296
          if not normalized_value:
cda1cd62   tangwang   意图分析&应用 baseline
297
298
              return False
  
2efad04b   tangwang   意图匹配的性能优化:
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
          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(
6adbf18a   tangwang   reranker提示词优化
321
322
323
324
325
326
                  self._is_text_match(
                      intent_type,
                      value,
                      selection_context,
                      normalized_value=candidate.normalized_intent_values[intent_type],
                  )
2efad04b   tangwang   意图匹配的性能优化:
327
328
329
330
                  for intent_type, value in candidate.intent_values.items()
              ):
                  return candidate
          return None
cda1cd62   tangwang   意图分析&应用 baseline
331
332
333
334
  
      def _select_by_embedding(
          self,
          candidates: Sequence[_SkuCandidate],
2efad04b   tangwang   意图匹配的性能优化:
335
          selection_context: _SelectionContext,
cda1cd62   tangwang   意图分析&应用 baseline
336
337
338
339
      ) -> Tuple[Optional[_SkuCandidate], Optional[float]]:
          if not candidates:
              return None, None
          text_encoder = self._get_text_encoder()
2efad04b   tangwang   意图匹配的性能优化:
340
341
          if selection_context.query_vector is None or text_encoder is None:
              return None, None
cda1cd62   tangwang   意图分析&应用 baseline
342
343
344
  
          unique_texts = list(
              dict.fromkeys(
2efad04b   tangwang   意图匹配的性能优化:
345
                  candidate.normalized_selection_text
cda1cd62   tangwang   意图分析&应用 baseline
346
                  for candidate in candidates
2efad04b   tangwang   意图匹配的性能优化:
347
348
                  if candidate.normalized_selection_text
                  and candidate.normalized_selection_text not in selection_context.selection_vector_cache
cda1cd62   tangwang   意图分析&应用 baseline
349
350
              )
          )
2efad04b   tangwang   意图匹配的性能优化:
351
352
353
354
355
356
          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
357
358
359
  
          best_candidate: Optional[_SkuCandidate] = None
          best_score: Optional[float] = None
2efad04b   tangwang   意图匹配的性能优化:
360
          query_vector_array = np.asarray(selection_context.query_vector, dtype=np.float32)
cda1cd62   tangwang   意图分析&应用 baseline
361
          for candidate in candidates:
2efad04b   tangwang   意图匹配的性能优化:
362
363
364
365
366
367
368
369
370
371
372
373
374
375
              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
376
                  continue
cda1cd62   tangwang   意图分析&应用 baseline
377
378
379
380
              if best_score is None or score > best_score:
                  best_candidate = candidate
                  best_score = score
  
2efad04b   tangwang   意图匹配的性能优化:
381
          return best_candidate, best_score
cda1cd62   tangwang   意图分析&应用 baseline
382
383
384
385
386
387
  
      def _select_for_source(
          self,
          source: Dict[str, Any],
          *,
          style_profile: StyleIntentProfile,
2efad04b   tangwang   意图匹配的性能优化:
388
          selection_context: _SelectionContext,
cda1cd62   tangwang   意图分析&应用 baseline
389
390
391
392
393
394
      ) -> 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   意图匹配的性能优化:
395
396
397
          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
398
399
          candidates = self._build_candidates(skus, resolved_dimensions)
          if not candidates:
2efad04b   tangwang   意图匹配的性能优化:
400
              return self._empty_decision(resolved_dimensions, matched_stage="no_candidates")
cda1cd62   tangwang   意图分析&应用 baseline
401
  
2efad04b   tangwang   意图匹配的性能优化:
402
403
404
          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
405
  
2efad04b   tangwang   意图匹配的性能优化:
406
          chosen, similarity_score = self._select_by_embedding(candidates, selection_context)
cda1cd62   tangwang   意图分析&应用 baseline
407
          if chosen is None:
2efad04b   tangwang   意图匹配的性能优化:
408
              return self._empty_decision(resolved_dimensions, matched_stage="no_match")
cda1cd62   tangwang   意图分析&应用 baseline
409
410
411
          return self._build_decision(
              chosen,
              resolved_dimensions,
2efad04b   tangwang   意图匹配的性能优化:
412
              matched_stage="embedding",
cda1cd62   tangwang   意图分析&应用 baseline
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
              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