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
|
7bc756c5
tangwang
优化 ES 查询构建
|
15
|
import re
|
1556989b
tangwang
query翻译等待超时逻辑
|
16
|
from concurrent.futures import ThreadPoolExecutor, wait
|
be52af70
tangwang
first commit
|
17
|
|
07cf5a93
tangwang
START_EMBEDDING=...
|
18
|
from embeddings.text_encoder import TextEmbeddingEncoder
|
9f96d6f3
tangwang
短query不用语义搜索
|
19
|
from config import SearchConfig
|
0fd2f875
tangwang
translate
|
20
|
from translation import create_translation_client
|
be52af70
tangwang
first commit
|
21
|
from .language_detector import LanguageDetector
|
be52af70
tangwang
first commit
|
22
23
|
from .query_rewriter import QueryRewriter, QueryNormalizer
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
24
25
|
logger = logging.getLogger(__name__)
|
484adbfe
tangwang
adapt ubuntu; con...
|
26
27
28
29
|
try:
import hanlp # type: ignore
except Exception: # pragma: no cover
hanlp = None
|
be52af70
tangwang
first commit
|
30
|
|
00c8ddb9
tangwang
suggest rank opti...
|
31
32
33
|
def simple_tokenize_query(text: str) -> List[str]:
"""
|
ef5baa86
tangwang
混杂语言处理
|
34
|
Lightweight tokenizer for suggestion-side heuristics only.
|
00c8ddb9
tangwang
suggest rank opti...
|
35
36
37
38
39
40
41
42
43
44
|
- Consecutive CJK characters form one token
- Latin / digit runs (with internal hyphens) form tokens
"""
if not text:
return []
pattern = re.compile(r"[\u4e00-\u9fff]+|[A-Za-z0-9_]+(?:-[A-Za-z0-9_]+)*")
return pattern.findall(text)
|
ef5baa86
tangwang
混杂语言处理
|
45
|
@dataclass(slots=True)
|
be52af70
tangwang
first commit
|
46
|
class ParsedQuery:
|
ef5baa86
tangwang
混杂语言处理
|
47
48
49
50
51
52
53
54
55
56
57
|
"""Container for query parser facts."""
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
query_tokens: List[str] = field(default_factory=list)
contains_chinese: bool = False
contains_english: bool = False
|
be52af70
tangwang
first commit
|
58
59
60
|
def to_dict(self) -> Dict[str, Any]:
"""Convert to dictionary representation."""
|
ef5baa86
tangwang
混杂语言处理
|
61
|
return {
|
be52af70
tangwang
first commit
|
62
|
"original_query": self.original_query,
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
63
|
"query_normalized": self.query_normalized,
|
be52af70
tangwang
first commit
|
64
65
66
|
"rewritten_query": self.rewritten_query,
"detected_language": self.detected_language,
"translations": self.translations,
|
ef5baa86
tangwang
混杂语言处理
|
67
68
69
|
"query_tokens": self.query_tokens,
"contains_chinese": self.contains_chinese,
"contains_english": self.contains_english,
|
be52af70
tangwang
first commit
|
70
|
}
|
be52af70
tangwang
first commit
|
71
72
73
74
75
76
77
78
|
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
混杂语言处理
|
79
|
4. Translation to caller-provided target languages
|
be52af70
tangwang
first commit
|
80
81
82
83
84
|
5. Text embedding generation (for semantic search)
"""
def __init__(
self,
|
9f96d6f3
tangwang
短query不用语义搜索
|
85
|
config: SearchConfig,
|
950a640e
tangwang
embeddings
|
86
|
text_encoder: Optional[TextEmbeddingEncoder] = None,
|
ef5baa86
tangwang
混杂语言处理
|
87
88
|
translator: Optional[Any] = None,
tokenizer: Optional[Callable[[str], Any]] = None,
|
be52af70
tangwang
first commit
|
89
90
91
92
93
|
):
"""
Initialize query parser.
Args:
|
9f96d6f3
tangwang
短query不用语义搜索
|
94
|
config: SearchConfig instance
|
26b910bd
tangwang
refactor service ...
|
95
96
|
text_encoder: Text embedding encoder (initialized at startup if not provided)
translator: Translator instance (initialized at startup if not provided)
|
be52af70
tangwang
first commit
|
97
|
"""
|
9f96d6f3
tangwang
短query不用语义搜索
|
98
|
self.config = config
|
be52af70
tangwang
first commit
|
99
100
101
102
103
104
|
self._text_encoder = text_encoder
self._translator = translator
# Initialize components
self.normalizer = QueryNormalizer()
self.language_detector = LanguageDetector()
|
9f96d6f3
tangwang
短query不用语义搜索
|
105
|
self.rewriter = QueryRewriter(config.query_config.rewrite_dictionary)
|
ef5baa86
tangwang
混杂语言处理
|
106
|
self._tokenizer = tokenizer or self._build_tokenizer()
|
be52af70
tangwang
first commit
|
107
|
|
26b910bd
tangwang
refactor service ...
|
108
109
110
111
112
113
114
|
# 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()
if self._translator is None:
from config.services_config import get_translation_config
cfg = get_translation_config()
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
115
116
|
logger.info(
"Initializing translator client at QueryParser construction (service_url=%s, default_model=%s)...",
|
a8261ece
tangwang
检索效果优化
|
117
118
|
cfg.get("service_url"),
cfg.get("default_model"),
|
5e4dc8e4
tangwang
翻译架构按“一个翻译服务 +
|
119
|
)
|
0fd2f875
tangwang
translate
|
120
|
self._translator = create_translation_client()
|
26b910bd
tangwang
refactor service ...
|
121
|
|
be52af70
tangwang
first commit
|
122
|
@property
|
950a640e
tangwang
embeddings
|
123
|
def text_encoder(self) -> TextEmbeddingEncoder:
|
26b910bd
tangwang
refactor service ...
|
124
|
"""Return pre-initialized text encoder."""
|
be52af70
tangwang
first commit
|
125
126
127
|
return self._text_encoder
@property
|
42e3aea6
tangwang
tidy
|
128
|
def translator(self) -> Any:
|
26b910bd
tangwang
refactor service ...
|
129
|
"""Return pre-initialized translator."""
|
be52af70
tangwang
first commit
|
130
|
return self._translator
|
484adbfe
tangwang
adapt ubuntu; con...
|
131
|
|
ef5baa86
tangwang
混杂语言处理
|
132
133
134
135
136
137
138
139
140
141
|
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
|
142
|
@staticmethod
|
77bfa7e3
tangwang
query translate
|
143
144
|
def _pick_query_translation_model(source_lang: str, target_lang: str, config: SearchConfig) -> str:
"""Pick the translation capability for query-time translation (configurable)."""
|
e56fbdc1
tangwang
query trans
|
145
146
|
src = str(source_lang or "").strip().lower()
tgt = str(target_lang or "").strip().lower()
|
77bfa7e3
tangwang
query translate
|
147
148
|
# Use dedicated models for zh<->en if configured
|
e56fbdc1
tangwang
query trans
|
149
|
if src == "zh" and tgt == "en":
|
77bfa7e3
tangwang
query translate
|
150
|
return config.query_config.zh_to_en_model
|
e56fbdc1
tangwang
query trans
|
151
|
if src == "en" and tgt == "zh":
|
77bfa7e3
tangwang
query translate
|
152
153
154
155
156
|
return config.query_config.en_to_zh_model
# For any other language pairs, fall back to the configurable default model.
# By default this is `nllb-200-distilled-600m` (multi-lingual local model).
return config.query_config.default_translation_model
|
e56fbdc1
tangwang
query trans
|
157
|
|
ef5baa86
tangwang
混杂语言处理
|
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
|
@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."""
if not tokenizer_result:
return []
if isinstance(tokenizer_result, str):
token = tokenizer_result.strip()
return [token] if token else []
tokens: List[str] = []
for item in tokenizer_result:
token: Optional[str] = None
if isinstance(item, str):
token = item
elif isinstance(item, (list, tuple)) and item:
token = str(item[0])
elif item is not None:
token = str(item)
if token is None:
continue
token = token.strip()
if token:
tokens.append(token)
return tokens
|
ea118f2b
tangwang
build_query:根据 qu...
|
195
196
|
def _get_query_tokens(self, query: str) -> List[str]:
|
ef5baa86
tangwang
混杂语言处理
|
197
|
return self._extract_tokens(self._tokenizer(query))
|
be52af70
tangwang
first commit
|
198
|
|
a8261ece
tangwang
检索效果优化
|
199
200
201
202
203
204
|
@staticmethod
def _contains_cjk(text: str) -> bool:
"""Whether query contains any CJK ideograph."""
return bool(re.search(r"[\u4e00-\u9fff]", text or ""))
@staticmethod
|
6823fe3e
tangwang
feat(search): 混合语...
|
205
206
207
208
209
210
211
212
213
|
def _is_pure_english_word_token(token: str) -> bool:
"""
A tokenizer token counts as English iff it is letters only (optional internal hyphens)
and length >= 3.
"""
if not token or len(token) < 3:
return False
return bool(re.fullmatch(r"[A-Za-z]+(?:-[A-Za-z]+)*", token))
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
214
215
216
217
218
|
def parse(
self,
query: str,
tenant_id: Optional[str] = None,
generate_vector: bool = True,
|
ef5baa86
tangwang
混杂语言处理
|
219
220
|
context: Optional[Any] = None,
target_languages: Optional[List[str]] = None,
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
221
|
) -> ParsedQuery:
|
be52af70
tangwang
first commit
|
222
223
224
225
226
|
"""
Parse query through all processing stages.
Args:
query: Raw query string
|
ef5baa86
tangwang
混杂语言处理
|
227
228
|
tenant_id: Deprecated and ignored by QueryParser. Kept temporarily
to avoid a wider refactor in this first step.
|
be52af70
tangwang
first commit
|
229
|
generate_vector: Whether to generate query embedding
|
16c42787
tangwang
feat: implement r...
|
230
|
context: Optional request context for tracking and logging
|
ef5baa86
tangwang
混杂语言处理
|
231
|
target_languages: Translation target languages decided by the caller
|
be52af70
tangwang
first commit
|
232
233
234
235
|
Returns:
ParsedQuery object with all processing results
"""
|
16c42787
tangwang
feat: implement r...
|
236
|
# Initialize logger if context provided
|
950a640e
tangwang
embeddings
|
237
238
239
|
active_logger = context.logger if context else logger
if context and hasattr(context, "logger"):
context.logger.info(
|
70dab99f
tangwang
add logs
|
240
|
f"Starting query parsing | Original query: '{query}' | Generate vector: {generate_vector}",
|
16c42787
tangwang
feat: implement r...
|
241
242
243
|
extra={'reqid': context.reqid, 'uid': context.uid}
)
|
16c42787
tangwang
feat: implement r...
|
244
|
def log_info(msg):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
245
246
|
if context and hasattr(context, 'logger'):
context.logger.info(msg, extra={'reqid': context.reqid, 'uid': context.uid})
|
16c42787
tangwang
feat: implement r...
|
247
|
else:
|
950a640e
tangwang
embeddings
|
248
|
active_logger.info(msg)
|
16c42787
tangwang
feat: implement r...
|
249
250
|
def log_debug(msg):
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
251
252
|
if context and hasattr(context, 'logger'):
context.logger.debug(msg, extra={'reqid': context.reqid, 'uid': context.uid})
|
16c42787
tangwang
feat: implement r...
|
253
|
else:
|
950a640e
tangwang
embeddings
|
254
|
active_logger.debug(msg)
|
be52af70
tangwang
first commit
|
255
256
257
|
# Stage 1: Normalize
normalized = self.normalizer.normalize(query)
|
70dab99f
tangwang
add logs
|
258
|
log_debug(f"Normalization completed | '{query}' -> '{normalized}'")
|
16c42787
tangwang
feat: implement r...
|
259
|
if context:
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
260
|
context.store_intermediate_result('query_normalized', normalized)
|
be52af70
tangwang
first commit
|
261
|
|
be52af70
tangwang
first commit
|
262
|
# Stage 2: Query rewriting
|
ef5baa86
tangwang
混杂语言处理
|
263
264
|
query_text = normalized
rewritten = normalized
|
9f96d6f3
tangwang
短query不用语义搜索
|
265
|
if self.config.query_config.rewrite_dictionary: # Enable rewrite if dictionary exists
|
be52af70
tangwang
first commit
|
266
267
|
rewritten = self.rewriter.rewrite(query_text)
if rewritten != query_text:
|
70dab99f
tangwang
add logs
|
268
|
log_info(f"Query rewritten | '{query_text}' -> '{rewritten}'")
|
be52af70
tangwang
first commit
|
269
|
query_text = rewritten
|
16c42787
tangwang
feat: implement r...
|
270
271
|
if context:
context.store_intermediate_result('rewritten_query', rewritten)
|
70dab99f
tangwang
add logs
|
272
|
context.add_warning(f"Query was rewritten: {query_text}")
|
be52af70
tangwang
first commit
|
273
274
275
|
# Stage 3: Language detection
detected_lang = self.language_detector.detect(query_text)
|
a5a6bab8
tangwang
多语言查询优化
|
276
277
278
|
# 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
|
279
|
log_info(f"Language detection | Detected language: {detected_lang}")
|
16c42787
tangwang
feat: implement r...
|
280
281
|
if context:
context.store_intermediate_result('detected_language', detected_lang)
|
ef5baa86
tangwang
混杂语言处理
|
282
283
284
285
286
287
288
289
290
291
292
293
294
|
# Stage 4: Query analysis (tokenization + script flags)
query_tokens = self._get_query_tokens(query_text)
contains_chinese = self._contains_cjk(query_text)
contains_english = any(self._is_pure_english_word_token(t) for t in query_tokens)
log_debug(
f"Query analysis | Query tokens: {query_tokens} | "
f"contains_chinese={contains_chinese} | contains_english={contains_english}"
)
if context:
context.store_intermediate_result('query_tokens', query_tokens)
context.store_intermediate_result('contains_chinese', contains_chinese)
context.store_intermediate_result('contains_english', contains_english)
|
be52af70
tangwang
first commit
|
295
|
|
ef5baa86
tangwang
混杂语言处理
|
296
297
|
# Stage 5: Translation + embedding. Parser only coordinates async enrichment work; the
# caller decides translation targets and later search-field planning.
|
1556989b
tangwang
query翻译等待超时逻辑
|
298
|
translations: Dict[str, str] = {}
|
ef5baa86
tangwang
混杂语言处理
|
299
300
|
future_to_task: Dict[Any, Tuple[str, Optional[str]]] = {}
async_executor: Optional[ThreadPoolExecutor] = None
|
1556989b
tangwang
query翻译等待超时逻辑
|
301
|
detected_norm = str(detected_lang or "").strip().lower()
|
ef5baa86
tangwang
混杂语言处理
|
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
|
normalized_targets = self._normalize_language_codes(target_languages)
translation_targets = [lang for lang in normalized_targets if lang != detected_norm]
# Stage 6: Text embedding - async execution
query_vector = None
should_generate_embedding = (
generate_vector and
self.config.query_config.enable_text_embedding
)
task_count = len(translation_targets) + (1 if should_generate_embedding else 0)
if task_count > 0:
async_executor = ThreadPoolExecutor(
max_workers=max(1, min(task_count, 4)),
thread_name_prefix="query-enrichment",
)
|
1556989b
tangwang
query翻译等待超时逻辑
|
318
|
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
319
|
try:
|
ef5baa86
tangwang
混杂语言处理
|
320
321
|
if async_executor is not None:
for lang in translation_targets:
|
1556989b
tangwang
query翻译等待超时逻辑
|
322
323
324
325
|
model_name = self._pick_query_translation_model(detected_lang, lang, self.config)
log_debug(
f"Submitting query translation | source={detected_lang} target={lang} model={model_name}"
)
|
ef5baa86
tangwang
混杂语言处理
|
326
|
future = async_executor.submit(
|
1556989b
tangwang
query翻译等待超时逻辑
|
327
328
329
330
331
332
333
|
self.translator.translate,
query_text,
lang,
detected_lang,
"ecommerce_search_query",
model_name,
)
|
ef5baa86
tangwang
混杂语言处理
|
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
|
future_to_task[future] = ("translation", lang)
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]:
arr = self.text_encoder.encode([query_text], priority=1)
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)
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
352
|
except Exception as e:
|
ef5baa86
tangwang
混杂语言处理
|
353
|
error_msg = f"Async query enrichment submission failed | Error: {str(e)}"
|
345d960b
tangwang
1. 删除全局 enable_tr...
|
354
355
356
|
log_info(error_msg)
if context:
context.add_warning(error_msg)
|
ef5baa86
tangwang
混杂语言处理
|
357
358
359
360
|
if async_executor is not None:
async_executor.shutdown(wait=False)
async_executor = None
future_to_task.clear()
|
be52af70
tangwang
first commit
|
361
|
|
ef5baa86
tangwang
混杂语言处理
|
362
363
|
# Wait for translation + embedding concurrently; shared budget depends on whether
# the detected language belongs to caller-provided target_languages.
|
1556989b
tangwang
query翻译等待超时逻辑
|
364
|
qc = self.config.query_config
|
ef5baa86
tangwang
混杂语言处理
|
365
|
source_in_target_languages = bool(normalized_targets) and detected_norm in normalized_targets
|
1556989b
tangwang
query翻译等待超时逻辑
|
366
367
|
budget_ms = (
qc.translation_embedding_wait_budget_ms_source_in_index
|
ef5baa86
tangwang
混杂语言处理
|
368
|
if source_in_target_languages
|
1556989b
tangwang
query翻译等待超时逻辑
|
369
370
371
372
|
else qc.translation_embedding_wait_budget_ms_source_not_in_index
)
budget_sec = max(0.0, float(budget_ms) / 1000.0)
|
ef5baa86
tangwang
混杂语言处理
|
373
|
if translation_targets:
|
1556989b
tangwang
query翻译等待超时逻辑
|
374
375
|
log_info(
f"Translation+embedding shared wait budget | budget_ms={budget_ms} | "
|
ef5baa86
tangwang
混杂语言处理
|
376
377
|
f"source_in_target_languages={source_in_target_languages} | "
f"translation_targets={translation_targets}"
|
1556989b
tangwang
query翻译等待超时逻辑
|
378
379
|
)
|
ef5baa86
tangwang
混杂语言处理
|
380
|
if future_to_task:
|
1556989b
tangwang
query翻译等待超时逻辑
|
381
382
|
log_debug(
f"Waiting for async tasks (translation+embedding) | budget_ms={budget_ms} | "
|
ef5baa86
tangwang
混杂语言处理
|
383
|
f"source_in_target_languages={source_in_target_languages}"
|
1556989b
tangwang
query翻译等待超时逻辑
|
384
385
|
)
|
ef5baa86
tangwang
混杂语言处理
|
386
|
done, not_done = wait(list(future_to_task.keys()), timeout=budget_sec)
|
d4cadc13
tangwang
翻译重构
|
387
|
for future in done:
|
ef5baa86
tangwang
混杂语言处理
|
388
|
task_type, lang = future_to_task[future]
|
3ec5bfe6
tangwang
1. get_translatio...
|
389
390
|
try:
result = future.result()
|
1556989b
tangwang
query翻译等待超时逻辑
|
391
|
if task_type == "translation":
|
3ec5bfe6
tangwang
1. get_translatio...
|
392
393
|
if result:
translations[lang] = result
|
d4cadc13
tangwang
翻译重构
|
394
|
log_info(
|
1556989b
tangwang
query翻译等待超时逻辑
|
395
396
|
f"Translation completed | Query text: '{query_text}' | "
f"Target language: {lang} | Translation result: '{result}'"
|
d4cadc13
tangwang
翻译重构
|
397
|
)
|
3ec5bfe6
tangwang
1. get_translatio...
|
398
|
if context:
|
1556989b
tangwang
query翻译等待超时逻辑
|
399
400
|
context.store_intermediate_result(f"translation_{lang}", result)
elif task_type == "embedding":
|
3ec5bfe6
tangwang
1. get_translatio...
|
401
|
query_vector = result
|
b2e50710
tangwang
BgeEncoder.encode...
|
402
|
if query_vector is not None:
|
70dab99f
tangwang
add logs
|
403
|
log_debug(f"Query vector generation completed | Shape: {query_vector.shape}")
|
b2e50710
tangwang
BgeEncoder.encode...
|
404
|
if context:
|
1556989b
tangwang
query翻译等待超时逻辑
|
405
|
context.store_intermediate_result("query_vector_shape", query_vector.shape)
|
b2e50710
tangwang
BgeEncoder.encode...
|
406
|
else:
|
1556989b
tangwang
query翻译等待超时逻辑
|
407
408
409
|
log_info(
"Query vector generation completed but result is None, will process without vector"
)
|
3ec5bfe6
tangwang
1. get_translatio...
|
410
|
except Exception as e:
|
1556989b
tangwang
query翻译等待超时逻辑
|
411
|
if task_type == "translation":
|
70dab99f
tangwang
add logs
|
412
|
error_msg = f"Translation failed | Language: {lang} | Error: {str(e)}"
|
3ec5bfe6
tangwang
1. get_translatio...
|
413
|
else:
|
70dab99f
tangwang
add logs
|
414
|
error_msg = f"Query vector generation failed | Error: {str(e)}"
|
3ec5bfe6
tangwang
1. get_translatio...
|
415
416
417
|
log_info(error_msg)
if context:
context.add_warning(error_msg)
|
d4cadc13
tangwang
翻译重构
|
418
|
|
d4cadc13
tangwang
翻译重构
|
419
420
|
if not_done:
for future in not_done:
|
ef5baa86
tangwang
混杂语言处理
|
421
|
task_type, lang = future_to_task[future]
|
1556989b
tangwang
query翻译等待超时逻辑
|
422
|
if task_type == "translation":
|
d4cadc13
tangwang
翻译重构
|
423
|
timeout_msg = (
|
1556989b
tangwang
query翻译等待超时逻辑
|
424
|
f"Translation timeout (>{budget_ms}ms) | Language: {lang} | "
|
d4cadc13
tangwang
翻译重构
|
425
426
427
|
f"Query text: '{query_text}'"
)
else:
|
1556989b
tangwang
query翻译等待超时逻辑
|
428
429
430
|
timeout_msg = (
f"Query vector generation timeout (>{budget_ms}ms), proceeding without embedding result"
)
|
d4cadc13
tangwang
翻译重构
|
431
432
433
434
|
log_info(timeout_msg)
if context:
context.add_warning(timeout_msg)
|
ef5baa86
tangwang
混杂语言处理
|
435
436
|
if async_executor:
async_executor.shutdown(wait=False)
|
1556989b
tangwang
query翻译等待超时逻辑
|
437
|
|
3ec5bfe6
tangwang
1. get_translatio...
|
438
|
if translations and context:
|
1556989b
tangwang
query翻译等待超时逻辑
|
439
|
context.store_intermediate_result("translations", translations)
|
be52af70
tangwang
first commit
|
440
441
442
443
|
# Build result
result = ParsedQuery(
original_query=query,
|
3a5fda00
tangwang
1. ES字段 skus的 ima...
|
444
|
query_normalized=normalized,
|
ef5baa86
tangwang
混杂语言处理
|
445
|
rewritten_query=query_text,
|
be52af70
tangwang
first commit
|
446
447
448
|
detected_language=detected_lang,
translations=translations,
query_vector=query_vector,
|
bd96cead
tangwang
1. 动态多语言字段与统一策略配置
|
449
|
query_tokens=query_tokens,
|
6823fe3e
tangwang
feat(search): 混合语...
|
450
451
|
contains_chinese=contains_chinese,
contains_english=contains_english,
|
be52af70
tangwang
first commit
|
452
453
|
)
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
454
455
|
if context and hasattr(context, 'logger'):
context.logger.info(
|
70dab99f
tangwang
add logs
|
456
|
f"Query parsing completed | Original query: '{query}' | Final query: '{rewritten or query_text}' | "
|
70dab99f
tangwang
add logs
|
457
|
f"Translation count: {len(translations)} | Vector: {'yes' if query_vector is not None else 'no'}",
|
16c42787
tangwang
feat: implement r...
|
458
459
460
|
extra={'reqid': context.reqid, 'uid': context.uid}
)
else:
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
461
|
logger.info(
|
70dab99f
tangwang
add logs
|
462
|
f"Query parsing completed | Original query: '{query}' | Final query: '{rewritten or query_text}' | "
|
ef5baa86
tangwang
混杂语言处理
|
463
|
f"Language: {detected_lang}"
|
325eec03
tangwang
1. 日志、配置基础设施,使用优化
|
464
|
)
|
16c42787
tangwang
feat: implement r...
|
465
|
|
be52af70
tangwang
first commit
|
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
|
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...
|
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
|
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"
|