be52af70
tangwang
first commit
|
1
2
3
|
"""
Query parser - main module for query processing.
|
ef5baa86
tangwang
混杂语言处理
|
4
5
6
7
8
|
Responsibilities are intentionally narrow:
- normalize and rewrite the incoming query
- detect language and tokenize with HanLP
- run translation and embedding requests concurrently
- return parser facts, not Elasticsearch language-planning data
|
be52af70
tangwang
first commit
|
9
10
|
"""
|
ef5baa86
tangwang
混杂语言处理
|
11
12
|
from dataclasses import dataclass, field
from typing import Any, Callable, Dict, List, Optional, Tuple
|
be52af70
tangwang
first commit
|
13
|
import numpy as np
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
14
|
import logging
|
db9c469c
tangwang
log optimize
|
15
|
import time
|
1556989b
tangwang
query翻译等待超时逻辑
|
16
|
from concurrent.futures import ThreadPoolExecutor, wait
|
be52af70
tangwang
first commit
|
17
|
|
dc403578
tangwang
多模态搜索
|
18
|
from embeddings.image_encoder import CLIPImageEncoder
|
07cf5a93
tangwang
START_EMBEDDING=...
|
19
|
from embeddings.text_encoder import TextEmbeddingEncoder
|
9f96d6f3
tangwang
短query不用语义搜索
|
20
|
from config import SearchConfig
|
0fd2f875
tangwang
translate
|
21
|
from translation import create_translation_client
|
be52af70
tangwang
first commit
|
22
|
from .language_detector import LanguageDetector
|
74fdf9bd
tangwang
1.
|
23
24
25
26
27
|
from .product_title_exclusion import (
ProductTitleExclusionDetector,
ProductTitleExclusionProfile,
ProductTitleExclusionRegistry,
)
|
be52af70
tangwang
first commit
|
28
|
from .query_rewriter import QueryRewriter, QueryNormalizer
|
cda1cd62
tangwang
意图分析&应用 baseline
|
29
30
|
from .style_intent import StyleIntentDetector, StyleIntentProfile, StyleIntentRegistry
from .tokenization import extract_token_strings, simple_tokenize_query
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
31
|
from .keyword_extractor import KeywordExtractor, collect_keywords_queries
|
be52af70
tangwang
first commit
|
32
|
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
33
34
|
logger = logging.getLogger(__name__)
|
86d0e83d
tangwang
query翻译,根据源语言是否在索...
|
35
|
import hanlp # type: ignore
|
be52af70
tangwang
first commit
|
36
|
|
00c8ddb9
tangwang
suggest rank opti...
|
37
|
|
db9c469c
tangwang
log optimize
|
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
def _async_enrichment_result_summary(
task_type: str, lang: Optional[str], result: Any
) -> str:
"""One-line description of a completed translation/embedding task for logging."""
if task_type == "translation":
if result:
return f"lang={lang} translated={result!r}"
return f"lang={lang} empty_translation"
if task_type in ("embedding", "image_embedding"):
if result is not None:
return f"vector_shape={tuple(result.shape)}"
return "no_vector" if task_type == "embedding" else "no_image_vector"
return f"unexpected_task_type={task_type!r}"
def _async_enrichment_failure_warning(task_type: str, lang: Optional[str], err: BaseException) -> str:
"""Warning text aligned with historical messages for context.add_warning."""
msg = str(err)
if task_type == "translation":
return f"Translation failed | Language: {lang} | Error: {msg}"
if task_type == "image_embedding":
return f"CLIP text query vector generation failed | Error: {msg}"
return f"Query vector generation failed | Error: {msg}"
def _log_async_enrichment_finished(
log_info: Callable[[str], None],
*,
task_type: str,
summary: str,
elapsed_ms: float,
) -> None:
log_info(
f"Async enrichment task finished | task_type={task_type} | "
f"summary={summary} | elapsed_ms={elapsed_ms:.1f}"
)
|
74fdf9bd
tangwang
1.
|
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
|
def rerank_query_text(
original_query: str,
*,
detected_language: Optional[str] = None,
translations: Optional[Dict[str, str]] = None,
) -> str:
"""
Text substituted for ``{query}`` when calling the reranker.
Chinese and English queries use the original string. For any other detected
language, prefer the English translation, then Chinese; if neither exists,
fall back to the original query.
"""
lang = (detected_language or "").strip().lower()
if lang in ("zh", "en"):
return original_query
trans = translations or {}
for key in ("en", "zh"):
t = (trans.get(key) or "").strip()
if t:
return t
return original_query
|
ef5baa86
tangwang
混杂语言处理
|
100
|
@dataclass(slots=True)
|
be52af70
tangwang
first commit
|
101
|
class ParsedQuery:
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
102
103
104
105
106
107
108
109
|
"""
Container for query parser facts.
``keywords_queries`` parallels text variants: key ``base`` (see
``keyword_extractor.KEYWORDS_QUERY_BASE_KEY``) for ``rewritten_query``,
and the same language codes as ``translations`` for each translated string.
Entries with no extracted nouns are omitted.
"""
|
ef5baa86
tangwang
混杂语言处理
|
110
111
112
113
114
115
116
|
original_query: str
query_normalized: str
rewritten_query: str
detected_language: Optional[str] = None
translations: Dict[str, str] = field(default_factory=dict)
query_vector: Optional[np.ndarray] = None
|
dc403578
tangwang
多模态搜索
|
117
|
image_query_vector: Optional[np.ndarray] = None
|
ef5baa86
tangwang
混杂语言处理
|
118
|
query_tokens: List[str] = field(default_factory=list)
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
119
|
keywords_queries: Dict[str, str] = field(default_factory=dict)
|
cda1cd62
tangwang
意图分析&应用 baseline
|
120
|
style_intent_profile: Optional[StyleIntentProfile] = None
|
74fdf9bd
tangwang
1.
|
121
122
123
124
125
126
127
128
129
|
product_title_exclusion_profile: Optional[ProductTitleExclusionProfile] = None
def text_for_rerank(self) -> str:
"""See :func:`rerank_query_text`."""
return rerank_query_text(
self.original_query,
detected_language=self.detected_language,
translations=self.translations,
)
|
be52af70
tangwang
first commit
|
130
131
132
|
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary representation."""
|
ef5baa86
tangwang
混杂语言处理
|
133
|
return {
|
be52af70
tangwang
first commit
|
134
|
"original_query": self.original_query,
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
135
|
"query_normalized": self.query_normalized,
|
be52af70
tangwang
first commit
|
136
137
138
|
"rewritten_query": self.rewritten_query,
"detected_language": self.detected_language,
"translations": self.translations,
|
dc403578
tangwang
多模态搜索
|
139
140
|
"has_query_vector": self.query_vector is not None,
"has_image_query_vector": self.image_query_vector is not None,
|
ef5baa86
tangwang
混杂语言处理
|
141
|
"query_tokens": self.query_tokens,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
142
|
"keywords_queries": dict(self.keywords_queries),
|
cda1cd62
tangwang
意图分析&应用 baseline
|
143
144
145
|
"style_intent_profile": (
self.style_intent_profile.to_dict() if self.style_intent_profile is not None else None
),
|
74fdf9bd
tangwang
1.
|
146
147
148
149
150
|
"product_title_exclusion_profile": (
self.product_title_exclusion_profile.to_dict()
if self.product_title_exclusion_profile is not None
else None
),
|
be52af70
tangwang
first commit
|
151
|
}
|
be52af70
tangwang
first commit
|
152
153
154
155
156
157
158
159
|
class QueryParser:
"""
Main query parser that processes queries through multiple stages:
1. Normalization
2. Query rewriting (brand/category mappings, synonyms)
3. Language detection
|
ef5baa86
tangwang
混杂语言处理
|
160
|
4. Translation to caller-provided target languages
|
be52af70
tangwang
first commit
|
161
162
163
164
165
|
5. Text embedding generation (for semantic search)
"""
def __init__(
self,
|
9f96d6f3
tangwang
短query不用语义搜索
|
166
|
config: SearchConfig,
|
950a640e
tangwang
embeddings
|
167
|
text_encoder: Optional[TextEmbeddingEncoder] = None,
|
dc403578
tangwang
多模态搜索
|
168
|
image_encoder: Optional[CLIPImageEncoder] = None,
|
ef5baa86
tangwang
混杂语言处理
|
169
170
|
translator: Optional[Any] = None,
tokenizer: Optional[Callable[[str], Any]] = None,
|
be52af70
tangwang
first commit
|
171
172
173
174
175
|
):
"""
Initialize query parser.
Args:
|
9f96d6f3
tangwang
短query不用语义搜索
|
176
|
config: SearchConfig instance
|
26b910bd
tangwang
refactor service ...
|
177
178
|
text_encoder: Text embedding encoder (initialized at startup if not provided)
translator: Translator instance (initialized at startup if not provided)
|
be52af70
tangwang
first commit
|
179
|
"""
|
9f96d6f3
tangwang
短query不用语义搜索
|
180
|
self.config = config
|
be52af70
tangwang
first commit
|
181
|
self._text_encoder = text_encoder
|
dc403578
tangwang
多模态搜索
|
182
|
self._image_encoder = image_encoder
|
be52af70
tangwang
first commit
|
183
184
185
186
187
|
self._translator = translator
# Initialize components
self.normalizer = QueryNormalizer()
self.language_detector = LanguageDetector()
|
9f96d6f3
tangwang
短query不用语义搜索
|
188
|
self.rewriter = QueryRewriter(config.query_config.rewrite_dictionary)
|
ef5baa86
tangwang
混杂语言处理
|
189
|
self._tokenizer = tokenizer or self._build_tokenizer()
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
190
|
self._keyword_extractor = KeywordExtractor(tokenizer=self._tokenizer)
|
cda1cd62
tangwang
意图分析&应用 baseline
|
191
192
193
194
195
|
self.style_intent_registry = StyleIntentRegistry.from_query_config(config.query_config)
self.style_intent_detector = StyleIntentDetector(
self.style_intent_registry,
tokenizer=self._tokenizer,
)
|
74fdf9bd
tangwang
1.
|
196
197
198
199
200
201
202
|
self.product_title_exclusion_registry = ProductTitleExclusionRegistry.from_query_config(
config.query_config
)
self.product_title_exclusion_detector = ProductTitleExclusionDetector(
self.product_title_exclusion_registry,
tokenizer=self._tokenizer,
)
|
be52af70
tangwang
first commit
|
203
|
|
26b910bd
tangwang
refactor service ...
|
204
205
206
207
|
# Eager initialization (startup-time failure visibility, no lazy init in request path)
if self.config.query_config.enable_text_embedding and self._text_encoder is None:
logger.info("Initializing text encoder at QueryParser construction...")
self._text_encoder = TextEmbeddingEncoder()
|
dc403578
tangwang
多模态搜索
|
208
209
210
|
if self.config.query_config.image_embedding_field and self._image_encoder is None:
logger.info("Initializing image encoder at QueryParser construction...")
self._image_encoder = CLIPImageEncoder()
|
26b910bd
tangwang
refactor service ...
|
211
212
213
|
if self._translator is None:
from config.services_config import get_translation_config
cfg = get_translation_config()
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
214
215
|
logger.info(
"Initializing translator client at QueryParser construction (service_url=%s, default_model=%s)...",
|
a8261ece
tangwang
检索效果优化
|
216
217
|
cfg.get("service_url"),
cfg.get("default_model"),
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
218
|
)
|
0fd2f875
tangwang
translate
|
219
|
self._translator = create_translation_client()
|
26b910bd
tangwang
refactor service ...
|
220
|
|
be52af70
tangwang
first commit
|
221
|
@property
|
950a640e
tangwang
embeddings
|
222
|
def text_encoder(self) -> TextEmbeddingEncoder:
|
26b910bd
tangwang
refactor service ...
|
223
|
"""Return pre-initialized text encoder."""
|
be52af70
tangwang
first commit
|
224
225
226
|
return self._text_encoder
@property
|
42e3aea6
tangwang
tidy
|
227
|
def translator(self) -> Any:
|
26b910bd
tangwang
refactor service ...
|
228
|
"""Return pre-initialized translator."""
|
be52af70
tangwang
first commit
|
229
|
return self._translator
|
484adbfe
tangwang
adapt ubuntu; con...
|
230
|
|
dc403578
tangwang
多模态搜索
|
231
232
233
234
235
|
@property
def image_encoder(self) -> Optional[CLIPImageEncoder]:
"""Return pre-initialized image encoder for CLIP text embeddings."""
return self._image_encoder
|
ef5baa86
tangwang
混杂语言处理
|
236
237
238
239
240
241
242
243
244
245
|
def _build_tokenizer(self) -> Callable[[str], Any]:
"""Build the tokenizer used by query parsing. No fallback path by design."""
if hanlp is None:
raise RuntimeError("HanLP is required for QueryParser tokenization")
logger.info("Initializing HanLP tokenizer...")
tokenizer = hanlp.load(hanlp.pretrained.tok.CTB9_TOK_ELECTRA_BASE_CRF)
tokenizer.config.output_spans = True
logger.info("HanLP tokenizer initialized")
return tokenizer
|
e56fbdc1
tangwang
query trans
|
246
|
@staticmethod
|
86d0e83d
tangwang
query翻译,根据源语言是否在索...
|
247
248
249
250
251
252
|
def _pick_query_translation_model(
source_lang: str,
target_lang: str,
config: SearchConfig,
source_language_in_index: bool,
) -> str:
|
77bfa7e3
tangwang
query translate
|
253
|
"""Pick the translation capability for query-time translation (configurable)."""
|
e56fbdc1
tangwang
query trans
|
254
255
|
src = str(source_lang or "").strip().lower()
tgt = str(target_lang or "").strip().lower()
|
86d0e83d
tangwang
query翻译,根据源语言是否在索...
|
256
257
258
259
260
261
262
263
|
qc = config.query_config
if source_language_in_index:
if src == "zh" and tgt == "en":
return qc.zh_to_en_model
if src == "en" and tgt == "zh":
return qc.en_to_zh_model
return qc.default_translation_model
|
77bfa7e3
tangwang
query translate
|
264
|
|
e56fbdc1
tangwang
query trans
|
265
|
if src == "zh" and tgt == "en":
|
86d0e83d
tangwang
query翻译,根据源语言是否在索...
|
266
|
return qc.zh_to_en_model_source_not_in_index or qc.zh_to_en_model
|
e56fbdc1
tangwang
query trans
|
267
|
if src == "en" and tgt == "zh":
|
86d0e83d
tangwang
query翻译,根据源语言是否在索...
|
268
269
|
return qc.en_to_zh_model_source_not_in_index or qc.en_to_zh_model
return qc.default_translation_model_source_not_in_index or qc.default_translation_model
|
e56fbdc1
tangwang
query trans
|
270
|
|
ef5baa86
tangwang
混杂语言处理
|
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
|
@staticmethod
def _normalize_language_codes(languages: Optional[List[str]]) -> List[str]:
normalized: List[str] = []
seen = set()
for language in languages or []:
token = str(language or "").strip().lower()
if not token or token in seen:
continue
seen.add(token)
normalized.append(token)
return normalized
@staticmethod
def _extract_tokens(tokenizer_result: Any) -> List[str]:
"""Normalize tokenizer output into a flat token string list."""
|
cda1cd62
tangwang
意图分析&应用 baseline
|
286
|
return extract_token_strings(tokenizer_result)
|
ea118f2b
tangwang
build_query:根据 qu...
|
287
288
|
def _get_query_tokens(self, query: str) -> List[str]:
|
ef5baa86
tangwang
混杂语言处理
|
289
|
return self._extract_tokens(self._tokenizer(query))
|
be52af70
tangwang
first commit
|
290
|
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
291
292
293
294
295
|
def parse(
self,
query: str,
tenant_id: Optional[str] = None,
generate_vector: bool = True,
|
ef5baa86
tangwang
混杂语言处理
|
296
297
|
context: Optional[Any] = None,
target_languages: Optional[List[str]] = None,
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
298
|
) -> ParsedQuery:
|
be52af70
tangwang
first commit
|
299
300
301
302
303
|
"""
Parse query through all processing stages.
Args:
query: Raw query string
|
ef5baa86
tangwang
混杂语言处理
|
304
305
|
tenant_id: Deprecated and ignored by QueryParser. Kept temporarily
to avoid a wider refactor in this first step.
|
be52af70
tangwang
first commit
|
306
|
generate_vector: Whether to generate query embedding
|
16c42787
tangwang
feat: implement r...
|
307
|
context: Optional request context for tracking and logging
|
ef5baa86
tangwang
混杂语言处理
|
308
|
target_languages: Translation target languages decided by the caller
|
be52af70
tangwang
first commit
|
309
310
311
312
|
Returns:
ParsedQuery object with all processing results
"""
|
16c42787
tangwang
feat: implement r...
|
313
|
# Initialize logger if context provided
|
950a640e
tangwang
embeddings
|
314
315
316
|
active_logger = context.logger if context else logger
if context and hasattr(context, "logger"):
context.logger.info(
|
70dab99f
tangwang
add logs
|
317
|
f"Starting query parsing | Original query: '{query}' | Generate vector: {generate_vector}",
|
16c42787
tangwang
feat: implement r...
|
318
319
320
|
extra={'reqid': context.reqid, 'uid': context.uid}
)
|
16c42787
tangwang
feat: implement r...
|
321
|
def log_info(msg):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
322
323
|
if context and hasattr(context, 'logger'):
context.logger.info(msg, extra={'reqid': context.reqid, 'uid': context.uid})
|
16c42787
tangwang
feat: implement r...
|
324
|
else:
|
950a640e
tangwang
embeddings
|
325
|
active_logger.info(msg)
|
16c42787
tangwang
feat: implement r...
|
326
327
|
def log_debug(msg):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
328
329
|
if context and hasattr(context, 'logger'):
context.logger.debug(msg, extra={'reqid': context.reqid, 'uid': context.uid})
|
16c42787
tangwang
feat: implement r...
|
330
|
else:
|
950a640e
tangwang
embeddings
|
331
|
active_logger.debug(msg)
|
be52af70
tangwang
first commit
|
332
333
334
|
# Stage 1: Normalize
normalized = self.normalizer.normalize(query)
|
70dab99f
tangwang
add logs
|
335
|
log_debug(f"Normalization completed | '{query}' -> '{normalized}'")
|
16c42787
tangwang
feat: implement r...
|
336
|
if context:
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
337
|
context.store_intermediate_result('query_normalized', normalized)
|
be52af70
tangwang
first commit
|
338
|
|
be52af70
tangwang
first commit
|
339
|
# Stage 2: Query rewriting
|
ef5baa86
tangwang
混杂语言处理
|
340
341
|
query_text = normalized
rewritten = normalized
|
9f96d6f3
tangwang
短query不用语义搜索
|
342
|
if self.config.query_config.rewrite_dictionary: # Enable rewrite if dictionary exists
|
be52af70
tangwang
first commit
|
343
344
|
rewritten = self.rewriter.rewrite(query_text)
if rewritten != query_text:
|
70dab99f
tangwang
add logs
|
345
|
log_info(f"Query rewritten | '{query_text}' -> '{rewritten}'")
|
be52af70
tangwang
first commit
|
346
|
query_text = rewritten
|
16c42787
tangwang
feat: implement r...
|
347
348
|
if context:
context.store_intermediate_result('rewritten_query', rewritten)
|
70dab99f
tangwang
add logs
|
349
|
context.add_warning(f"Query was rewritten: {query_text}")
|
be52af70
tangwang
first commit
|
350
351
352
|
# Stage 3: Language detection
detected_lang = self.language_detector.detect(query_text)
|
a5a6bab8
tangwang
多语言查询优化
|
353
354
355
|
# Use default language if detection failed (None or "unknown")
if not detected_lang or detected_lang == "unknown":
detected_lang = self.config.query_config.default_language
|
70dab99f
tangwang
add logs
|
356
|
log_info(f"Language detection | Detected language: {detected_lang}")
|
16c42787
tangwang
feat: implement r...
|
357
358
|
if context:
context.store_intermediate_result('detected_language', detected_lang)
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
359
|
# Stage 4: Query analysis (tokenization)
|
ef5baa86
tangwang
混杂语言处理
|
360
|
query_tokens = self._get_query_tokens(query_text)
|
ef5baa86
tangwang
混杂语言处理
|
361
|
|
35da3813
tangwang
中英混写query的优化逻辑,不适...
|
362
|
log_debug(f"Query analysis | Query tokens: {query_tokens}")
|
ef5baa86
tangwang
混杂语言处理
|
363
364
|
if context:
context.store_intermediate_result('query_tokens', query_tokens)
|
be52af70
tangwang
first commit
|
365
|
|
ef5baa86
tangwang
混杂语言处理
|
366
367
|
# Stage 5: Translation + embedding. Parser only coordinates async enrichment work; the
# caller decides translation targets and later search-field planning.
|
1556989b
tangwang
query翻译等待超时逻辑
|
368
|
translations: Dict[str, str] = {}
|
ef5baa86
tangwang
混杂语言处理
|
369
|
future_to_task: Dict[Any, Tuple[str, Optional[str]]] = {}
|
db9c469c
tangwang
log optimize
|
370
|
future_submit_at: Dict[Any, float] = {}
|
ef5baa86
tangwang
混杂语言处理
|
371
|
async_executor: Optional[ThreadPoolExecutor] = None
|
1556989b
tangwang
query翻译等待超时逻辑
|
372
|
detected_norm = str(detected_lang or "").strip().lower()
|
ef5baa86
tangwang
混杂语言处理
|
373
374
|
normalized_targets = self._normalize_language_codes(target_languages)
translation_targets = [lang for lang in normalized_targets if lang != detected_norm]
|
86d0e83d
tangwang
query翻译,根据源语言是否在索...
|
375
|
source_language_in_index = bool(normalized_targets) and detected_norm in normalized_targets
|
ef5baa86
tangwang
混杂语言处理
|
376
377
378
|
# Stage 6: Text embedding - async execution
query_vector = None
|
dc403578
tangwang
多模态搜索
|
379
|
image_query_vector = None
|
ef5baa86
tangwang
混杂语言处理
|
380
381
382
383
|
should_generate_embedding = (
generate_vector and
self.config.query_config.enable_text_embedding
)
|
dc403578
tangwang
多模态搜索
|
384
385
386
387
|
should_generate_image_embedding = (
generate_vector and
bool(self.config.query_config.image_embedding_field)
)
|
ef5baa86
tangwang
混杂语言处理
|
388
|
|
dc403578
tangwang
多模态搜索
|
389
390
391
392
393
|
task_count = (
len(translation_targets)
+ (1 if should_generate_embedding else 0)
+ (1 if should_generate_image_embedding else 0)
)
|
ef5baa86
tangwang
混杂语言处理
|
394
395
396
397
398
|
if task_count > 0:
async_executor = ThreadPoolExecutor(
max_workers=max(1, min(task_count, 4)),
thread_name_prefix="query-enrichment",
)
|
1556989b
tangwang
query翻译等待超时逻辑
|
399
|
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
400
|
try:
|
ef5baa86
tangwang
混杂语言处理
|
401
402
|
if async_executor is not None:
for lang in translation_targets:
|
86d0e83d
tangwang
query翻译,根据源语言是否在索...
|
403
404
405
406
407
408
|
model_name = self._pick_query_translation_model(
detected_lang,
lang,
self.config,
source_language_in_index,
)
|
1556989b
tangwang
query翻译等待超时逻辑
|
409
410
411
|
log_debug(
f"Submitting query translation | source={detected_lang} target={lang} model={model_name}"
)
|
ef5baa86
tangwang
混杂语言处理
|
412
|
future = async_executor.submit(
|
1556989b
tangwang
query翻译等待超时逻辑
|
413
414
415
416
417
418
419
|
self.translator.translate,
query_text,
lang,
detected_lang,
"ecommerce_search_query",
model_name,
)
|
ef5baa86
tangwang
混杂语言处理
|
420
|
future_to_task[future] = ("translation", lang)
|
db9c469c
tangwang
log optimize
|
421
|
future_submit_at[future] = time.perf_counter()
|
ef5baa86
tangwang
混杂语言处理
|
422
423
424
425
426
427
428
|
if should_generate_embedding:
if self.text_encoder is None:
raise RuntimeError("Text embedding is enabled but text encoder is not initialized")
log_debug("Submitting query vector generation")
def _encode_query_vector() -> Optional[np.ndarray]:
|
4650fcec
tangwang
日志优化、日志串联(uid rqid)
|
429
430
431
432
433
434
|
arr = self.text_encoder.encode(
[query_text],
priority=1,
request_id=(context.reqid if context else None),
user_id=(context.uid if context else None),
)
|
ef5baa86
tangwang
混杂语言处理
|
435
436
437
438
439
440
441
442
443
|
if arr is None or len(arr) == 0:
return None
vec = arr[0]
if vec is None:
return None
return np.asarray(vec, dtype=np.float32)
future = async_executor.submit(_encode_query_vector)
future_to_task[future] = ("embedding", None)
|
db9c469c
tangwang
log optimize
|
444
|
future_submit_at[future] = time.perf_counter()
|
dc403578
tangwang
多模态搜索
|
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
|
if should_generate_image_embedding:
if self.image_encoder is None:
raise RuntimeError(
"Image embedding field is configured but image encoder is not initialized"
)
log_debug("Submitting CLIP text query vector generation")
def _encode_image_query_vector() -> Optional[np.ndarray]:
vec = self.image_encoder.encode_clip_text(
query_text,
normalize_embeddings=True,
priority=1,
request_id=(context.reqid if context else None),
user_id=(context.uid if context else None),
)
if vec is None:
return None
return np.asarray(vec, dtype=np.float32)
future = async_executor.submit(_encode_image_query_vector)
future_to_task[future] = ("image_embedding", None)
|
db9c469c
tangwang
log optimize
|
467
|
future_submit_at[future] = time.perf_counter()
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
468
|
except Exception as e:
|
ef5baa86
tangwang
混杂语言处理
|
469
|
error_msg = f"Async query enrichment submission failed | Error: {str(e)}"
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
470
471
472
|
log_info(error_msg)
if context:
context.add_warning(error_msg)
|
ef5baa86
tangwang
混杂语言处理
|
473
474
475
476
|
if async_executor is not None:
async_executor.shutdown(wait=False)
async_executor = None
future_to_task.clear()
|
db9c469c
tangwang
log optimize
|
477
|
future_submit_at.clear()
|
be52af70
tangwang
first commit
|
478
|
|
ef5baa86
tangwang
混杂语言处理
|
479
480
|
# Wait for translation + embedding concurrently; shared budget depends on whether
# the detected language belongs to caller-provided target_languages.
|
1556989b
tangwang
query翻译等待超时逻辑
|
481
|
qc = self.config.query_config
|
ef5baa86
tangwang
混杂语言处理
|
482
|
source_in_target_languages = bool(normalized_targets) and detected_norm in normalized_targets
|
1556989b
tangwang
query翻译等待超时逻辑
|
483
484
|
budget_ms = (
qc.translation_embedding_wait_budget_ms_source_in_index
|
ef5baa86
tangwang
混杂语言处理
|
485
|
if source_in_target_languages
|
1556989b
tangwang
query翻译等待超时逻辑
|
486
487
488
489
|
else qc.translation_embedding_wait_budget_ms_source_not_in_index
)
budget_sec = max(0.0, float(budget_ms) / 1000.0)
|
ef5baa86
tangwang
混杂语言处理
|
490
|
if translation_targets:
|
1556989b
tangwang
query翻译等待超时逻辑
|
491
492
|
log_info(
f"Translation+embedding shared wait budget | budget_ms={budget_ms} | "
|
ef5baa86
tangwang
混杂语言处理
|
493
494
|
f"source_in_target_languages={source_in_target_languages} | "
f"translation_targets={translation_targets}"
|
1556989b
tangwang
query翻译等待超时逻辑
|
495
496
|
)
|
ef5baa86
tangwang
混杂语言处理
|
497
|
if future_to_task:
|
1556989b
tangwang
query翻译等待超时逻辑
|
498
499
|
log_debug(
f"Waiting for async tasks (translation+embedding) | budget_ms={budget_ms} | "
|
ef5baa86
tangwang
混杂语言处理
|
500
|
f"source_in_target_languages={source_in_target_languages}"
|
1556989b
tangwang
query翻译等待超时逻辑
|
501
502
|
)
|
ef5baa86
tangwang
混杂语言处理
|
503
|
done, not_done = wait(list(future_to_task.keys()), timeout=budget_sec)
|
d4cadc13
tangwang
翻译重构
|
504
|
for future in done:
|
ef5baa86
tangwang
混杂语言处理
|
505
|
task_type, lang = future_to_task[future]
|
db9c469c
tangwang
log optimize
|
506
507
|
t0 = future_submit_at.pop(future, None)
elapsed_ms = (time.perf_counter() - t0) * 1000.0 if t0 is not None else 0.0
|
3ec5bfe6
tangwang
1. get_translatio...
|
508
509
|
try:
result = future.result()
|
1556989b
tangwang
query翻译等待超时逻辑
|
510
|
if task_type == "translation":
|
3ec5bfe6
tangwang
1. get_translatio...
|
511
512
|
if result:
translations[lang] = result
|
3ec5bfe6
tangwang
1. get_translatio...
|
513
|
if context:
|
1556989b
tangwang
query翻译等待超时逻辑
|
514
515
|
context.store_intermediate_result(f"translation_{lang}", result)
elif task_type == "embedding":
|
3ec5bfe6
tangwang
1. get_translatio...
|
516
|
query_vector = result
|
db9c469c
tangwang
log optimize
|
517
518
|
if query_vector is not None and context:
context.store_intermediate_result("query_vector_shape", query_vector.shape)
|
dc403578
tangwang
多模态搜索
|
519
520
|
elif task_type == "image_embedding":
image_query_vector = result
|
db9c469c
tangwang
log optimize
|
521
522
523
524
|
if image_query_vector is not None and context:
context.store_intermediate_result(
"image_query_vector_shape",
image_query_vector.shape,
|
dc403578
tangwang
多模态搜索
|
525
|
)
|
db9c469c
tangwang
log optimize
|
526
527
528
529
530
531
|
_log_async_enrichment_finished(
log_info,
task_type=task_type,
summary=_async_enrichment_result_summary(task_type, lang, result),
elapsed_ms=elapsed_ms,
)
|
3ec5bfe6
tangwang
1. get_translatio...
|
532
|
except Exception as e:
|
db9c469c
tangwang
log optimize
|
533
534
535
536
537
538
|
_log_async_enrichment_finished(
log_info,
task_type=task_type,
summary=f"error={e!s}",
elapsed_ms=elapsed_ms,
)
|
3ec5bfe6
tangwang
1. get_translatio...
|
539
|
if context:
|
db9c469c
tangwang
log optimize
|
540
|
context.add_warning(_async_enrichment_failure_warning(task_type, lang, e))
|
d4cadc13
tangwang
翻译重构
|
541
|
|
d4cadc13
tangwang
翻译重构
|
542
543
|
if not_done:
for future in not_done:
|
db9c469c
tangwang
log optimize
|
544
|
future_submit_at.pop(future, None)
|
ef5baa86
tangwang
混杂语言处理
|
545
|
task_type, lang = future_to_task[future]
|
1556989b
tangwang
query翻译等待超时逻辑
|
546
|
if task_type == "translation":
|
d4cadc13
tangwang
翻译重构
|
547
|
timeout_msg = (
|
1556989b
tangwang
query翻译等待超时逻辑
|
548
|
f"Translation timeout (>{budget_ms}ms) | Language: {lang} | "
|
d4cadc13
tangwang
翻译重构
|
549
550
|
f"Query text: '{query_text}'"
)
|
dc403578
tangwang
多模态搜索
|
551
552
553
554
555
|
elif task_type == "image_embedding":
timeout_msg = (
f"CLIP text query vector generation timeout (>{budget_ms}ms), "
"proceeding without image embedding result"
)
|
d4cadc13
tangwang
翻译重构
|
556
|
else:
|
1556989b
tangwang
query翻译等待超时逻辑
|
557
558
559
|
timeout_msg = (
f"Query vector generation timeout (>{budget_ms}ms), proceeding without embedding result"
)
|
d4cadc13
tangwang
翻译重构
|
560
561
562
563
|
log_info(timeout_msg)
if context:
context.add_warning(timeout_msg)
|
ef5baa86
tangwang
混杂语言处理
|
564
565
|
if async_executor:
async_executor.shutdown(wait=False)
|
1556989b
tangwang
query翻译等待超时逻辑
|
566
|
|
3ec5bfe6
tangwang
1. get_translatio...
|
567
|
if translations and context:
|
1556989b
tangwang
query翻译等待超时逻辑
|
568
|
context.store_intermediate_result("translations", translations)
|
be52af70
tangwang
first commit
|
569
|
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
570
571
572
573
574
575
576
577
578
579
|
keywords_queries: Dict[str, str] = {}
try:
keywords_queries = collect_keywords_queries(
self._keyword_extractor,
query_text,
translations,
)
except Exception as e:
log_info(f"Keyword extraction failed | Error: {e}")
|
be52af70
tangwang
first commit
|
580
|
# Build result
|
cda1cd62
tangwang
意图分析&应用 baseline
|
581
582
583
584
585
586
587
|
base_result = ParsedQuery(
original_query=query,
query_normalized=normalized,
rewritten_query=query_text,
detected_language=detected_lang,
translations=translations,
query_vector=query_vector,
|
dc403578
tangwang
多模态搜索
|
588
|
image_query_vector=image_query_vector,
|
cda1cd62
tangwang
意图分析&应用 baseline
|
589
|
query_tokens=query_tokens,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
590
|
keywords_queries=keywords_queries,
|
cda1cd62
tangwang
意图分析&应用 baseline
|
591
592
|
)
style_intent_profile = self.style_intent_detector.detect(base_result)
|
74fdf9bd
tangwang
1.
|
593
|
product_title_exclusion_profile = self.product_title_exclusion_detector.detect(base_result)
|
cda1cd62
tangwang
意图分析&应用 baseline
|
594
595
596
597
598
|
if context:
context.store_intermediate_result(
"style_intent_profile",
style_intent_profile.to_dict(),
)
|
74fdf9bd
tangwang
1.
|
599
600
601
602
|
context.store_intermediate_result(
"product_title_exclusion_profile",
product_title_exclusion_profile.to_dict(),
)
|
cda1cd62
tangwang
意图分析&应用 baseline
|
603
|
|
be52af70
tangwang
first commit
|
604
605
|
result = ParsedQuery(
original_query=query,
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
606
|
query_normalized=normalized,
|
ef5baa86
tangwang
混杂语言处理
|
607
|
rewritten_query=query_text,
|
be52af70
tangwang
first commit
|
608
609
610
|
detected_language=detected_lang,
translations=translations,
query_vector=query_vector,
|
dc403578
tangwang
多模态搜索
|
611
|
image_query_vector=image_query_vector,
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
612
|
query_tokens=query_tokens,
|
ceaf6d03
tangwang
召回限定:must条件补充主干词命...
|
613
|
keywords_queries=keywords_queries,
|
cda1cd62
tangwang
意图分析&应用 baseline
|
614
|
style_intent_profile=style_intent_profile,
|
74fdf9bd
tangwang
1.
|
615
|
product_title_exclusion_profile=product_title_exclusion_profile,
|
be52af70
tangwang
first commit
|
616
617
|
)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
618
619
|
if context and hasattr(context, 'logger'):
context.logger.info(
|
70dab99f
tangwang
add logs
|
620
|
f"Query parsing completed | Original query: '{query}' | Final query: '{rewritten or query_text}' | "
|
dc403578
tangwang
多模态搜索
|
621
622
|
f"Translation count: {len(translations)} | Vector: {'yes' if query_vector is not None else 'no'} | "
f"Image vector: {'yes' if image_query_vector is not None else 'no'}",
|
16c42787
tangwang
feat: implement r...
|
623
624
625
|
extra={'reqid': context.reqid, 'uid': context.uid}
)
else:
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
626
|
logger.info(
|
70dab99f
tangwang
add logs
|
627
|
f"Query parsing completed | Original query: '{query}' | Final query: '{rewritten or query_text}' | "
|
ef5baa86
tangwang
混杂语言处理
|
628
|
f"Language: {detected_lang}"
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
629
|
)
|
16c42787
tangwang
feat: implement r...
|
630
|
|
be52af70
tangwang
first commit
|
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
|
return result
def get_search_queries(self, parsed_query: ParsedQuery) -> List[str]:
"""
Get list of queries to search (original + translations).
Args:
parsed_query: Parsed query object
Returns:
List of query strings to search
"""
queries = [parsed_query.rewritten_query]
# Add translations
for lang, translation in parsed_query.translations.items():
if translation and translation != parsed_query.rewritten_query:
queries.append(translation)
return queries
|
00c8ddb9
tangwang
suggest rank opti...
|
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
|
def detect_text_language_for_suggestions(
text: str,
*,
index_languages: Optional[List[str]] = None,
primary_language: str = "en",
) -> Tuple[str, float, str]:
"""
Language detection for short strings (mixed-language tags, query-log fallback).
Uses the same ``LanguageDetector`` as :class:`QueryParser`. Returns a language
code present in ``index_languages`` when possible, otherwise the tenant primary.
Returns:
(lang, confidence, source) where source is ``detector``, ``fallback``, or ``default``.
"""
langs_list = [x for x in (index_languages or []) if x]
langs_set = set(langs_list)
def _norm_lang(raw: Optional[str]) -> Optional[str]:
if not raw:
return None
token = str(raw).strip().lower().replace("-", "_")
if not token:
return None
if token in {"zh_tw", "pt_br"}:
return token
return token.split("_")[0]
primary = _norm_lang(primary_language) or "en"
if primary not in langs_set and langs_list:
primary = _norm_lang(langs_list[0]) or langs_list[0]
if not text or not str(text).strip():
return primary, 0.0, "default"
raw_code = LanguageDetector().detect(str(text).strip())
if not raw_code or raw_code == "unknown":
return primary, 0.35, "default"
def _index_lang_base(cand: str) -> str:
t = str(cand).strip().lower().replace("-", "_")
return t.split("_")[0] if t else ""
def _resolve_index_lang(code: str) -> Optional[str]:
if code in langs_set:
return code
for cand in langs_list:
if _index_lang_base(cand) == code:
return cand
return None
if langs_list:
resolved = _resolve_index_lang(raw_code)
if resolved is None:
return primary, 0.5, "fallback"
return resolved, 0.92, "detector"
return raw_code, 0.92, "detector"
|