Blame view

indexer/product_enrich.py 29.9 KB
6f7840cf   tangwang   refactor: rename ...
1
2
3
4
5
6
7
8
9
10
11
  #!/usr/bin/env python3
  """
  商品内容理解与属性补充模块(product_enrich
  
  提供基于 LLM 的商品锚文本 / 语义属性 / 标签等分析能力,
   indexer  API 在内存中调用(不再负责 CSV 读写)。
  """
  
  import os
  import json
  import logging
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
12
  import re
6f7840cf   tangwang   refactor: rename ...
13
14
  import time
  import hashlib
41f0b2e9   tangwang   product_enrich支持并发
15
16
  import uuid
  import threading
a73a751f   tangwang   enrich
17
  from collections import OrderedDict
6f7840cf   tangwang   refactor: rename ...
18
  from datetime import datetime
41f0b2e9   tangwang   product_enrich支持并发
19
  from concurrent.futures import ThreadPoolExecutor
6f7840cf   tangwang   refactor: rename ...
20
21
22
23
24
25
  from typing import List, Dict, Tuple, Any, Optional
  
  import redis
  import requests
  from pathlib import Path
  
86d8358b   tangwang   config optimize
26
  from config.loader import get_app_config
6f7840cf   tangwang   refactor: rename ...
27
  from config.tenant_config_loader import SOURCE_LANG_CODE_MAP
a73a751f   tangwang   enrich
28
29
30
31
32
33
  from indexer.product_enrich_prompts import (
      SYSTEM_MESSAGE,
      USER_INSTRUCTION_TEMPLATE,
      LANGUAGE_MARKDOWN_TABLE_HEADERS,
      SHARED_ANALYSIS_INSTRUCTION,
  )
6f7840cf   tangwang   refactor: rename ...
34
35
36
  
  # 配置
  BATCH_SIZE = 20
41f0b2e9   tangwang   product_enrich支持并发
37
38
39
  # enrich-content LLM 批次并发 worker 上限(线程池;仅对 uncached batch 并发)
  _APP_CONFIG = get_app_config()
  CONTENT_UNDERSTANDING_MAX_WORKERS = int(_APP_CONFIG.product_enrich.max_workers)
6f7840cf   tangwang   refactor: rename ...
40
41
42
43
44
45
46
47
48
  # 华北2(北京):https://dashscope.aliyuncs.com/compatible-mode/v1
  # 新加坡:https://dashscope-intl.aliyuncs.com/compatible-mode/v1
  # 美国(弗吉尼亚):https://dashscope-us.aliyuncs.com/compatible-mode/v1
  API_BASE_URL = "https://dashscope-us.aliyuncs.com/compatible-mode/v1"
  MODEL_NAME = "qwen-flash"
  API_KEY = os.environ.get("DASHSCOPE_API_KEY")
  MAX_RETRIES = 3
  RETRY_DELAY = 5  # 秒
  REQUEST_TIMEOUT = 180  # 秒
a73a751f   tangwang   enrich
49
  LOGGED_SHARED_CONTEXT_CACHE_SIZE = 256
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
50
51
52
53
  PROMPT_INPUT_MIN_ZH_CHARS = 20
  PROMPT_INPUT_MAX_ZH_CHARS = 100
  PROMPT_INPUT_MIN_WORDS = 16
  PROMPT_INPUT_MAX_WORDS = 80
6f7840cf   tangwang   refactor: rename ...
54
55
56
57
58
59
60
61
62
63
  
  # 日志路径
  OUTPUT_DIR = Path("output_logs")
  LOG_DIR = OUTPUT_DIR / "logs"
  
  # 设置独立日志(不影响全局 indexer.log)
  LOG_DIR.mkdir(parents=True, exist_ok=True)
  timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
  log_file = LOG_DIR / f"product_enrich_{timestamp}.log"
  verbose_log_file = LOG_DIR / "product_enrich_verbose.log"
a73a751f   tangwang   enrich
64
  _logged_shared_context_keys: "OrderedDict[str, None]" = OrderedDict()
41f0b2e9   tangwang   product_enrich支持并发
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
  _logged_shared_context_lock = threading.Lock()
  
  _content_understanding_executor: Optional[ThreadPoolExecutor] = None
  _content_understanding_executor_lock = threading.Lock()
  
  
  def _get_content_understanding_executor() -> ThreadPoolExecutor:
      """
      使用模块级单例线程池,避免同一进程内多次请求叠加创建线程池导致并发失控。
      """
      global _content_understanding_executor
      with _content_understanding_executor_lock:
          if _content_understanding_executor is None:
              _content_understanding_executor = ThreadPoolExecutor(
                  max_workers=CONTENT_UNDERSTANDING_MAX_WORKERS,
                  thread_name_prefix="product-enrich-llm",
              )
          return _content_understanding_executor
6f7840cf   tangwang   refactor: rename ...
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
  
  # 主日志 logger:执行流程、批次信息等
  logger = logging.getLogger("product_enrich")
  logger.setLevel(logging.INFO)
  
  if not logger.handlers:
      formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
  
      file_handler = logging.FileHandler(log_file, encoding="utf-8")
      file_handler.setFormatter(formatter)
  
      stream_handler = logging.StreamHandler()
      stream_handler.setFormatter(formatter)
  
      logger.addHandler(file_handler)
      logger.addHandler(stream_handler)
  
      # 避免日志向根 logger 传播,防止写入 logs/indexer.log 等其他文件
      logger.propagate = False
  
  # 详尽日志 logger:专门记录 LLM 请求与响应
  verbose_logger = logging.getLogger("product_enrich_verbose")
  verbose_logger.setLevel(logging.INFO)
  
  if not verbose_logger.handlers:
      verbose_formatter = logging.Formatter("%(asctime)s - %(levelname)s - %(message)s")
      verbose_file_handler = logging.FileHandler(verbose_log_file, encoding="utf-8")
      verbose_file_handler.setFormatter(verbose_formatter)
      verbose_logger.addHandler(verbose_file_handler)
      verbose_logger.propagate = False
  
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
114
115
  logger.info("Verbose LLM logs are written to: %s", verbose_log_file)
  
6f7840cf   tangwang   refactor: rename ...
116
117
  
  # Redis 缓存(用于 anchors / 语义属性)
41f0b2e9   tangwang   product_enrich支持并发
118
  _REDIS_CONFIG = _APP_CONFIG.infrastructure.redis
86d8358b   tangwang   config optimize
119
120
  ANCHOR_CACHE_PREFIX = _REDIS_CONFIG.anchor_cache_prefix
  ANCHOR_CACHE_EXPIRE_DAYS = int(_REDIS_CONFIG.anchor_cache_expire_days)
6f7840cf   tangwang   refactor: rename ...
121
122
123
124
  _anchor_redis: Optional[redis.Redis] = None
  
  try:
      _anchor_redis = redis.Redis(
86d8358b   tangwang   config optimize
125
126
127
          host=_REDIS_CONFIG.host,
          port=_REDIS_CONFIG.port,
          password=_REDIS_CONFIG.password,
6f7840cf   tangwang   refactor: rename ...
128
          decode_responses=True,
86d8358b   tangwang   config optimize
129
130
131
          socket_timeout=_REDIS_CONFIG.socket_timeout,
          socket_connect_timeout=_REDIS_CONFIG.socket_connect_timeout,
          retry_on_timeout=_REDIS_CONFIG.retry_on_timeout,
6f7840cf   tangwang   refactor: rename ...
132
133
134
135
136
137
138
139
          health_check_interval=10,
      )
      _anchor_redis.ping()
      logger.info("Redis cache initialized for product anchors and semantic attributes")
  except Exception as e:
      logger.warning(f"Failed to initialize Redis for anchors cache: {e}")
      _anchor_redis = None
  
a73a751f   tangwang   enrich
140
141
142
143
144
  _missing_prompt_langs = sorted(set(SOURCE_LANG_CODE_MAP) - set(LANGUAGE_MARKDOWN_TABLE_HEADERS))
  if _missing_prompt_langs:
      raise RuntimeError(
          f"Missing product_enrich prompt config for languages: {_missing_prompt_langs}"
      )
6f7840cf   tangwang   refactor: rename ...
145
146
  
  
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
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
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
  def _normalize_space(text: str) -> str:
      return re.sub(r"\s+", " ", (text or "").strip())
  
  
  def _contains_cjk(text: str) -> bool:
      return bool(re.search(r"[\u3400-\u4dbf\u4e00-\u9fff\uf900-\ufaff]", text or ""))
  
  
  def _truncate_by_chars(text: str, max_chars: int) -> str:
      return text[:max_chars].strip()
  
  
  def _truncate_by_words(text: str, max_words: int) -> str:
      words = re.findall(r"\S+", text or "")
      return " ".join(words[:max_words]).strip()
  
  
  def _detect_prompt_input_lang(text: str) -> str:
      # 简化处理:包含 CJK 时按中文类文本处理,否则统一按空格分词类语言处理。
      return "zh" if _contains_cjk(text) else "en"
  
  
  def _build_prompt_input_text(product: Dict[str, Any]) -> str:
      """
      生成真正送入 prompt 的商品文本。
  
      规则:
      - 默认使用 title
      - 若文本过短,则依次补 brief / description
      - 若文本过长,则按语言粗粒度截断
      """
      fields = [
          _normalize_space(str(product.get("title") or "")),
          _normalize_space(str(product.get("brief") or "")),
          _normalize_space(str(product.get("description") or "")),
      ]
      parts: List[str] = []
  
      def join_parts() -> str:
          return " | ".join(part for part in parts if part).strip()
  
      for field in fields:
          if not field:
              continue
          if field not in parts:
              parts.append(field)
          candidate = join_parts()
          if _detect_prompt_input_lang(candidate) == "zh":
              if len(candidate) >= PROMPT_INPUT_MIN_ZH_CHARS:
                  return _truncate_by_chars(candidate, PROMPT_INPUT_MAX_ZH_CHARS)
          else:
              if len(re.findall(r"\S+", candidate)) >= PROMPT_INPUT_MIN_WORDS:
                  return _truncate_by_words(candidate, PROMPT_INPUT_MAX_WORDS)
  
      candidate = join_parts()
      if not candidate:
          return ""
      if _detect_prompt_input_lang(candidate) == "zh":
          return _truncate_by_chars(candidate, PROMPT_INPUT_MAX_ZH_CHARS)
      return _truncate_by_words(candidate, PROMPT_INPUT_MAX_WORDS)
  
  
6f7840cf   tangwang   refactor: rename ...
209
  def _make_anchor_cache_key(
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
210
      product: Dict[str, Any],
6f7840cf   tangwang   refactor: rename ...
211
      target_lang: str,
6f7840cf   tangwang   refactor: rename ...
212
  ) -> str:
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
213
214
215
216
      """构造缓存 key,仅由 prompt 实际输入文本内容 + 目标语言决定。"""
      prompt_input = _build_prompt_input_text(product)
      h = hashlib.md5(prompt_input.encode("utf-8")).hexdigest()
      return f"{ANCHOR_CACHE_PREFIX}:{target_lang}:{prompt_input[:4]}{h}"
6f7840cf   tangwang   refactor: rename ...
217
218
219
  
  
  def _get_cached_anchor_result(
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
220
      product: Dict[str, Any],
6f7840cf   tangwang   refactor: rename ...
221
      target_lang: str,
6f7840cf   tangwang   refactor: rename ...
222
223
224
225
  ) -> Optional[Dict[str, Any]]:
      if not _anchor_redis:
          return None
      try:
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
226
          key = _make_anchor_cache_key(product, target_lang)
6f7840cf   tangwang   refactor: rename ...
227
228
229
230
231
232
233
234
235
236
          raw = _anchor_redis.get(key)
          if not raw:
              return None
          return json.loads(raw)
      except Exception as e:
          logger.warning(f"Failed to get anchor cache: {e}")
          return None
  
  
  def _set_cached_anchor_result(
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
237
      product: Dict[str, Any],
6f7840cf   tangwang   refactor: rename ...
238
239
      target_lang: str,
      result: Dict[str, Any],
6f7840cf   tangwang   refactor: rename ...
240
241
242
243
  ) -> None:
      if not _anchor_redis:
          return
      try:
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
244
          key = _make_anchor_cache_key(product, target_lang)
6f7840cf   tangwang   refactor: rename ...
245
246
247
248
249
250
          ttl = ANCHOR_CACHE_EXPIRE_DAYS * 24 * 3600
          _anchor_redis.setex(key, ttl, json.dumps(result, ensure_ascii=False))
      except Exception as e:
          logger.warning(f"Failed to set anchor cache: {e}")
  
  
a73a751f   tangwang   enrich
251
252
253
254
  def _build_assistant_prefix(headers: List[str]) -> str:
      header_line = "| " + " | ".join(headers) + " |"
      separator_line = "|" + "----|" * len(headers)
      return f"{header_line}\n{separator_line}\n"
6f7840cf   tangwang   refactor: rename ...
255
  
6f7840cf   tangwang   refactor: rename ...
256
  
a73a751f   tangwang   enrich
257
258
  def _build_shared_context(products: List[Dict[str, str]]) -> str:
      shared_context = SHARED_ANALYSIS_INSTRUCTION
6f7840cf   tangwang   refactor: rename ...
259
      for idx, product in enumerate(products, 1):
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
260
261
          prompt_input = _build_prompt_input_text(product)
          shared_context += f"{idx}. {prompt_input}\n"
a73a751f   tangwang   enrich
262
      return shared_context
6f7840cf   tangwang   refactor: rename ...
263
  
6f7840cf   tangwang   refactor: rename ...
264
  
a73a751f   tangwang   enrich
265
266
267
268
269
  def _hash_text(text: str) -> str:
      return hashlib.md5((text or "").encode("utf-8")).hexdigest()[:12]
  
  
  def _mark_shared_context_logged_once(shared_context_key: str) -> bool:
41f0b2e9   tangwang   product_enrich支持并发
270
271
272
273
      with _logged_shared_context_lock:
          if shared_context_key in _logged_shared_context_keys:
              _logged_shared_context_keys.move_to_end(shared_context_key)
              return False
a73a751f   tangwang   enrich
274
  
41f0b2e9   tangwang   product_enrich支持并发
275
276
277
278
          _logged_shared_context_keys[shared_context_key] = None
          if len(_logged_shared_context_keys) > LOGGED_SHARED_CONTEXT_CACHE_SIZE:
              _logged_shared_context_keys.popitem(last=False)
          return True
6f7840cf   tangwang   refactor: rename ...
279
  
6f7840cf   tangwang   refactor: rename ...
280
  
a73a751f   tangwang   enrich
281
282
  def reset_logged_shared_context_keys() -> None:
      """测试辅助:清理已记录的共享 prompt key。"""
41f0b2e9   tangwang   product_enrich支持并发
283
284
      with _logged_shared_context_lock:
          _logged_shared_context_keys.clear()
6f7840cf   tangwang   refactor: rename ...
285
  
a73a751f   tangwang   enrich
286
287
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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
  
  def create_prompt(
      products: List[Dict[str, str]],
      target_lang: str = "zh",
  ) -> Tuple[str, str, str]:
      """根据目标语言创建共享上下文、本地化输出要求和 Partial Mode assistant 前缀。"""
      markdown_table_headers = LANGUAGE_MARKDOWN_TABLE_HEADERS.get(target_lang)
      if not markdown_table_headers:
          logger.warning(
              "Unsupported target_lang for markdown table headers: %s",
              target_lang,
          )
          return None, None, None
      shared_context = _build_shared_context(products)
      language_label = SOURCE_LANG_CODE_MAP.get(target_lang, target_lang)
      user_prompt = USER_INSTRUCTION_TEMPLATE.format(language=language_label).strip()
      assistant_prefix = _build_assistant_prefix(markdown_table_headers)
      return shared_context, user_prompt, assistant_prefix
  
  
  def _merge_partial_response(assistant_prefix: str, generated_content: str) -> str:
      """将 Partial Mode 的 assistant 前缀与补全文本拼成完整 markdown。"""
      generated = (generated_content or "").lstrip()
      prefix_lines = [line.strip() for line in assistant_prefix.strip().splitlines()]
      generated_lines = generated.splitlines()
  
      if generated_lines:
          first_line = generated_lines[0].strip()
          if prefix_lines and first_line == prefix_lines[0]:
              generated_lines = generated_lines[1:]
              if generated_lines and len(prefix_lines) > 1 and generated_lines[0].strip() == prefix_lines[1]:
                  generated_lines = generated_lines[1:]
          elif len(prefix_lines) > 1 and first_line == prefix_lines[1]:
              generated_lines = generated_lines[1:]
  
      suffix = "\n".join(generated_lines).lstrip("\n")
      if suffix:
          return f"{assistant_prefix}{suffix}"
      return assistant_prefix
  
  
  def call_llm(
      shared_context: str,
      user_prompt: str,
      assistant_prefix: str,
      target_lang: str = "zh",
  ) -> Tuple[str, str]:
      """调用大模型 API(带重试机制),使用 Partial Mode 强制 markdown 表格前缀。"""
6f7840cf   tangwang   refactor: rename ...
334
335
336
337
      headers = {
          "Authorization": f"Bearer {API_KEY}",
          "Content-Type": "application/json",
      }
a73a751f   tangwang   enrich
338
339
340
      shared_context_key = _hash_text(shared_context)
      localized_tail_key = _hash_text(f"{target_lang}\n{user_prompt}\n{assistant_prefix}")
      combined_user_prompt = f"{shared_context.rstrip()}\n\n{user_prompt.strip()}"
6f7840cf   tangwang   refactor: rename ...
341
342
343
344
345
346
  
      payload = {
          "model": MODEL_NAME,
          "messages": [
              {
                  "role": "system",
a73a751f   tangwang   enrich
347
                  "content": SYSTEM_MESSAGE,
6f7840cf   tangwang   refactor: rename ...
348
349
350
              },
              {
                  "role": "user",
a73a751f   tangwang   enrich
351
352
353
354
355
356
                  "content": combined_user_prompt,
              },
              {
                  "role": "assistant",
                  "content": assistant_prefix,
                  "partial": True,
6f7840cf   tangwang   refactor: rename ...
357
358
359
360
361
362
363
364
365
366
367
              },
          ],
          "temperature": 0.3,
          "top_p": 0.8,
      }
  
      request_data = {
          "headers": {k: v for k, v in headers.items() if k != "Authorization"},
          "payload": payload,
      }
  
a73a751f   tangwang   enrich
368
369
370
371
372
373
374
375
376
377
      if _mark_shared_context_logged_once(shared_context_key):
          logger.info(f"\n{'=' * 80}")
          logger.info(
              "LLM Shared Context [model=%s, shared_key=%s, chars=%s] (logged once per process key)",
              MODEL_NAME,
              shared_context_key,
              len(shared_context),
          )
          logger.info("\nSystem Message:\n%s", SYSTEM_MESSAGE)
          logger.info("\nShared Context:\n%s", shared_context)
6f7840cf   tangwang   refactor: rename ...
378
379
  
      verbose_logger.info(f"\n{'=' * 80}")
a73a751f   tangwang   enrich
380
381
382
383
384
385
386
      verbose_logger.info(
          "LLM Request [model=%s, lang=%s, shared_key=%s, tail_key=%s]:",
          MODEL_NAME,
          target_lang,
          shared_context_key,
          localized_tail_key,
      )
6f7840cf   tangwang   refactor: rename ...
387
      verbose_logger.info(json.dumps(request_data, ensure_ascii=False, indent=2))
a73a751f   tangwang   enrich
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
      verbose_logger.info(f"\nCombined User Prompt:\n{combined_user_prompt}")
      verbose_logger.info(f"\nShared Context:\n{shared_context}")
      verbose_logger.info(f"\nLocalized Requirement:\n{user_prompt}")
      verbose_logger.info(f"\nAssistant Prefix:\n{assistant_prefix}")
  
      logger.info(
          "\nLLM Request Variant [lang=%s, shared_key=%s, tail_key=%s, prompt_chars=%s, prefix_chars=%s]",
          target_lang,
          shared_context_key,
          localized_tail_key,
          len(user_prompt),
          len(assistant_prefix),
      )
      logger.info("\nLocalized Requirement:\n%s", user_prompt)
      logger.info("\nAssistant Prefix:\n%s", assistant_prefix)
6f7840cf   tangwang   refactor: rename ...
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
  
      # 创建session,禁用代理
      session = requests.Session()
      session.trust_env = False  # 忽略系统代理设置
  
      try:
          # 重试机制
          for attempt in range(MAX_RETRIES):
              try:
                  response = session.post(
                      f"{API_BASE_URL}/chat/completions",
                      headers=headers,
                      json=payload,
                      timeout=REQUEST_TIMEOUT,
                      proxies={"http": None, "https": None},  # 明确禁用代理
                  )
  
                  response.raise_for_status()
                  result = response.json()
a73a751f   tangwang   enrich
422
423
424
425
426
427
428
429
430
431
                  usage = result.get("usage") or {}
  
                  verbose_logger.info(
                      "\nLLM Response [model=%s, lang=%s, shared_key=%s, tail_key=%s]:",
                      MODEL_NAME,
                      target_lang,
                      shared_context_key,
                      localized_tail_key,
                  )
                  verbose_logger.info(json.dumps(result, ensure_ascii=False, indent=2))
6f7840cf   tangwang   refactor: rename ...
432
  
a73a751f   tangwang   enrich
433
434
                  generated_content = result["choices"][0]["message"]["content"]
                  full_markdown = _merge_partial_response(assistant_prefix, generated_content)
6f7840cf   tangwang   refactor: rename ...
435
  
a73a751f   tangwang   enrich
436
437
438
439
440
441
442
443
444
445
446
447
                  logger.info(
                      "\nLLM Response Summary [lang=%s, shared_key=%s, tail_key=%s, generated_chars=%s, completion_tokens=%s, prompt_tokens=%s, total_tokens=%s]",
                      target_lang,
                      shared_context_key,
                      localized_tail_key,
                      len(generated_content or ""),
                      usage.get("completion_tokens"),
                      usage.get("prompt_tokens"),
                      usage.get("total_tokens"),
                  )
                  logger.info("\nGenerated Content:\n%s", generated_content)
                  logger.info("\nMerged Markdown:\n%s", full_markdown)
6f7840cf   tangwang   refactor: rename ...
448
  
a73a751f   tangwang   enrich
449
450
                  verbose_logger.info(f"\nGenerated Content:\n{generated_content}")
                  verbose_logger.info(f"\nMerged Markdown:\n{full_markdown}")
6f7840cf   tangwang   refactor: rename ...
451
  
a73a751f   tangwang   enrich
452
                  return full_markdown, json.dumps(result, ensure_ascii=False)
6f7840cf   tangwang   refactor: rename ...
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
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
  
              except requests.exceptions.ProxyError as e:
                  logger.warning(f"Attempt {attempt + 1}/{MAX_RETRIES}: Proxy error - {str(e)}")
                  if attempt < MAX_RETRIES - 1:
                      logger.info(f"Retrying in {RETRY_DELAY} seconds...")
                      time.sleep(RETRY_DELAY)
                  else:
                      raise
  
              except requests.exceptions.RequestException as e:
                  logger.warning(f"Attempt {attempt + 1}/{MAX_RETRIES}: Request error - {str(e)}")
                  if attempt < MAX_RETRIES - 1:
                      logger.info(f"Retrying in {RETRY_DELAY} seconds...")
                      time.sleep(RETRY_DELAY)
                  else:
                      raise
  
              except Exception as e:
                  logger.error(f"Unexpected error on attempt {attempt + 1}/{MAX_RETRIES}: {str(e)}")
                  if attempt < MAX_RETRIES - 1:
                      logger.info(f"Retrying in {RETRY_DELAY} seconds...")
                      time.sleep(RETRY_DELAY)
                  else:
                      raise
  
      finally:
          session.close()
  
  
  def parse_markdown_table(markdown_content: str) -> List[Dict[str, str]]:
      """解析markdown表格内容"""
      lines = markdown_content.strip().split("\n")
      data = []
      data_started = False
  
      for line in lines:
          line = line.strip()
          if not line:
              continue
  
          # 表格行处理
          if line.startswith("|"):
              # 分隔行(---- 或 :---: 等;允许空格,如 "| ---- | ---- |")
              sep_chars = line.replace("|", "").strip().replace(" ", "")
              if sep_chars and set(sep_chars) <= {"-", ":"}:
                  data_started = True
                  continue
  
              # 首个表头行:无论语言如何,统一跳过
              if not data_started:
                  # 等待下一行数据行
                  continue
  
              # 解析数据行
              parts = [p.strip() for p in line.split("|")]
              parts = [p for p in parts if p]  # 移除空字符串
  
              if len(parts) >= 2:
                  row = {
                      "seq_no": parts[0],
                      "title": parts[1],  # 商品标题(按目标语言)
                      "category_path": parts[2] if len(parts) > 2 else "",  # 品类路径
                      "tags": parts[3] if len(parts) > 3 else "",  # 细分标签
                      "target_audience": parts[4] if len(parts) > 4 else "",  # 适用人群
                      "usage_scene": parts[5] if len(parts) > 5 else "",  # 使用场景
                      "season": parts[6] if len(parts) > 6 else "",  # 适用季节
                      "key_attributes": parts[7] if len(parts) > 7 else "",  # 关键属性
                      "material": parts[8] if len(parts) > 8 else "",  # 材质说明
                      "features": parts[9] if len(parts) > 9 else "",  # 功能特点
76e1f088   tangwang   1. 减少一列sell point...
522
                      "anchor_text": parts[10] if len(parts) > 10 else "",  # 锚文本
6f7840cf   tangwang   refactor: rename ...
523
524
525
526
527
528
                  }
                  data.append(row)
  
      return data
  
  
a73a751f   tangwang   enrich
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
  def _log_parsed_result_quality(
      batch_data: List[Dict[str, str]],
      parsed_results: List[Dict[str, str]],
      target_lang: str,
      batch_num: int,
  ) -> None:
      expected = len(batch_data)
      actual = len(parsed_results)
      if actual != expected:
          logger.warning(
              "Parsed row count mismatch for batch=%s lang=%s: expected=%s actual=%s",
              batch_num,
              target_lang,
              expected,
              actual,
          )
  
      missing_anchor = sum(1 for item in parsed_results if not str(item.get("anchor_text") or "").strip())
      missing_category = sum(1 for item in parsed_results if not str(item.get("category_path") or "").strip())
      missing_title = sum(1 for item in parsed_results if not str(item.get("title") or "").strip())
  
      logger.info(
          "Parsed Quality Summary [batch=%s, lang=%s]: rows=%s/%s, missing_title=%s, missing_category=%s, missing_anchor=%s",
          batch_num,
          target_lang,
          actual,
          expected,
          missing_title,
          missing_category,
          missing_anchor,
      )
  
  
6f7840cf   tangwang   refactor: rename ...
562
563
564
565
566
567
568
569
570
571
  def process_batch(
      batch_data: List[Dict[str, str]],
      batch_num: int,
      target_lang: str = "zh",
  ) -> List[Dict[str, str]]:
      """处理一个批次的数据"""
      logger.info(f"\n{'#' * 80}")
      logger.info(f"Processing Batch {batch_num} ({len(batch_data)} items)")
  
      # 创建提示词
a73a751f   tangwang   enrich
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
      shared_context, user_prompt, assistant_prefix = create_prompt(
          batch_data,
          target_lang=target_lang,
      )
  
      # 如果提示词创建失败(例如不支持的 target_lang),本次批次整体失败,不再继续调用 LLM
      if shared_context is None or user_prompt is None or assistant_prefix is None:
          logger.error(
              "Failed to create prompt for batch %s, target_lang=%s; "
              "marking entire batch as failed without calling LLM",
              batch_num,
              target_lang,
          )
          return [
              {
                  "id": item["id"],
                  "lang": target_lang,
                  "title_input": item.get("title", ""),
                  "title": "",
                  "category_path": "",
                  "tags": "",
                  "target_audience": "",
                  "usage_scene": "",
                  "season": "",
                  "key_attributes": "",
                  "material": "",
                  "features": "",
a73a751f   tangwang   enrich
599
600
601
602
603
                  "anchor_text": "",
                  "error": f"prompt_creation_failed: unsupported target_lang={target_lang}",
              }
              for item in batch_data
          ]
6f7840cf   tangwang   refactor: rename ...
604
605
606
  
      # 调用LLM
      try:
a73a751f   tangwang   enrich
607
608
609
610
611
612
          raw_response, full_response_json = call_llm(
              shared_context,
              user_prompt,
              assistant_prefix,
              target_lang=target_lang,
          )
6f7840cf   tangwang   refactor: rename ...
613
614
615
  
          # 解析结果
          parsed_results = parse_markdown_table(raw_response)
a73a751f   tangwang   enrich
616
          _log_parsed_result_quality(batch_data, parsed_results, target_lang, batch_num)
6f7840cf   tangwang   refactor: rename ...
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
  
          logger.info(f"\nParsed Results ({len(parsed_results)} items):")
          logger.info(json.dumps(parsed_results, ensure_ascii=False, indent=2))
  
          # 映射回原始ID
          results_with_ids = []
          for i, parsed_item in enumerate(parsed_results):
              if i < len(batch_data):
                  original_id = batch_data[i]["id"]
                  result = {
                      "id": original_id,
                      "lang": target_lang,
                      "title_input": batch_data[i]["title"],  # 原始输入标题
                      "title": parsed_item.get("title", ""),  # 模型生成的标题
                      "category_path": parsed_item.get("category_path", ""),  # 品类路径
                      "tags": parsed_item.get("tags", ""),  # 细分标签
                      "target_audience": parsed_item.get("target_audience", ""),  # 适用人群
                      "usage_scene": parsed_item.get("usage_scene", ""),  # 使用场景
                      "season": parsed_item.get("season", ""),  # 适用季节
                      "key_attributes": parsed_item.get("key_attributes", ""),  # 关键属性
                      "material": parsed_item.get("material", ""),  # 材质说明
                      "features": parsed_item.get("features", ""),  # 功能特点
6f7840cf   tangwang   refactor: rename ...
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
                      "anchor_text": parsed_item.get("anchor_text", ""),  # 锚文本
                  }
                  results_with_ids.append(result)
                  logger.info(f"Mapped: seq={parsed_item['seq_no']} -> original_id={original_id}")
  
          # 保存批次 JSON 日志到独立文件
          batch_log = {
              "batch_num": batch_num,
              "timestamp": datetime.now().isoformat(),
              "input_products": batch_data,
              "raw_response": raw_response,
              "full_response_json": full_response_json,
              "parsed_results": parsed_results,
              "final_results": results_with_ids,
          }
  
41f0b2e9   tangwang   product_enrich支持并发
655
656
657
          # 并发写 batch json 日志时,保证文件名唯一避免覆盖
          batch_call_id = uuid.uuid4().hex[:12]
          batch_log_file = LOG_DIR / f"batch_{batch_num:04d}_{timestamp}_{batch_call_id}.json"
6f7840cf   tangwang   refactor: rename ...
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
          with open(batch_log_file, "w", encoding="utf-8") as f:
              json.dump(batch_log, f, ensure_ascii=False, indent=2)
  
          logger.info(f"Batch log saved to: {batch_log_file}")
  
          return results_with_ids
  
      except Exception as e:
          logger.error(f"Error processing batch {batch_num}: {str(e)}", exc_info=True)
          # 返回空结果,保持ID映射
          return [
              {
                  "id": item["id"],
                  "lang": target_lang,
                  "title_input": item["title"],
                  "title": "",
                  "category_path": "",
                  "tags": "",
                  "target_audience": "",
                  "usage_scene": "",
                  "season": "",
                  "key_attributes": "",
                  "material": "",
                  "features": "",
6f7840cf   tangwang   refactor: rename ...
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
                  "anchor_text": "",
                  "error": str(e),
              }
              for item in batch_data
          ]
  
  
  def analyze_products(
      products: List[Dict[str, str]],
      target_lang: str = "zh",
      batch_size: Optional[int] = None,
      tenant_id: Optional[str] = None,
  ) -> List[Dict[str, Any]]:
      """
      库调用入口:根据输入+语言,返回锚文本及各维度信息。
  
      Args:
          products: [{"id": "...", "title": "..."}]
          target_lang: 输出语言
          batch_size: 批大小,默认使用全局 BATCH_SIZE
      """
      if not API_KEY:
          raise RuntimeError("DASHSCOPE_API_KEY is not set, cannot call LLM")
  
      if not products:
          return []
  
76e1f088   tangwang   1. 减少一列sell point...
709
710
711
712
713
714
715
716
717
      results_by_index: List[Optional[Dict[str, Any]]] = [None] * len(products)
      uncached_items: List[Tuple[int, Dict[str, str]]] = []
  
      for idx, product in enumerate(products):
          title = str(product.get("title") or "").strip()
          if not title:
              uncached_items.append((idx, product))
              continue
  
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
718
          cached = _get_cached_anchor_result(product, target_lang)
76e1f088   tangwang   1. 减少一列sell point...
719
720
721
          if cached:
              logger.info(
                  f"[analyze_products] Cache hit for title='{title[:50]}...', "
a47416ec   tangwang   把融合逻辑改成乘法公式,并把 ES...
722
                  f"lang={target_lang}"
76e1f088   tangwang   1. 减少一列sell point...
723
724
725
726
727
728
729
730
              )
              results_by_index[idx] = cached
              continue
  
          uncached_items.append((idx, product))
  
      if not uncached_items:
          return [item for item in results_by_index if item is not None]
6f7840cf   tangwang   refactor: rename ...
731
732
733
734
735
736
  
      # call_llm 一次处理上限固定为 BATCH_SIZE(默认 20):
      # - 尽可能攒批处理;
      # - 即便调用方传入更大的 batch_size,也会自动按上限拆批。
      req_bs = BATCH_SIZE if batch_size is None else int(batch_size)
      bs = max(1, min(req_bs, BATCH_SIZE))
76e1f088   tangwang   1. 减少一列sell point...
737
      total_batches = (len(uncached_items) + bs - 1) // bs
6f7840cf   tangwang   refactor: rename ...
738
  
41f0b2e9   tangwang   product_enrich支持并发
739
      batch_jobs: List[Tuple[int, List[Tuple[int, Dict[str, str]]], List[Dict[str, str]]]] = []
76e1f088   tangwang   1. 减少一列sell point...
740
      for i in range(0, len(uncached_items), bs):
6f7840cf   tangwang   refactor: rename ...
741
          batch_num = i // bs + 1
76e1f088   tangwang   1. 减少一列sell point...
742
743
          batch_slice = uncached_items[i : i + bs]
          batch = [item for _, item in batch_slice]
41f0b2e9   tangwang   product_enrich支持并发
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
          batch_jobs.append((batch_num, batch_slice, batch))
  
      # 只有一个批次时走串行,减少线程池创建开销与日志/日志文件的不可控交织
      if total_batches <= 1 or CONTENT_UNDERSTANDING_MAX_WORKERS <= 1:
          for batch_num, batch_slice, batch in batch_jobs:
              logger.info(
                  f"[analyze_products] Processing batch {batch_num}/{total_batches}, "
                  f"size={len(batch)}, target_lang={target_lang}"
              )
              batch_results = process_batch(batch, batch_num=batch_num, target_lang=target_lang)
  
              for (original_idx, product), item in zip(batch_slice, batch_results):
                  results_by_index[original_idx] = item
                  title_input = str(item.get("title_input") or "").strip()
                  if not title_input:
                      continue
                  if item.get("error"):
                      # 不缓存错误结果,避免放大临时故障
                      continue
                  try:
                      _set_cached_anchor_result(product, target_lang, item)
                  except Exception:
                      # 已在内部记录 warning
                      pass
      else:
          max_workers = min(CONTENT_UNDERSTANDING_MAX_WORKERS, len(batch_jobs))
6f7840cf   tangwang   refactor: rename ...
770
          logger.info(
41f0b2e9   tangwang   product_enrich支持并发
771
772
773
774
775
776
              "[analyze_products] Using ThreadPoolExecutor for uncached batches: "
              "max_workers=%s, total_batches=%s, bs=%s, target_lang=%s",
              max_workers,
              total_batches,
              bs,
              target_lang,
6f7840cf   tangwang   refactor: rename ...
777
          )
6f7840cf   tangwang   refactor: rename ...
778
  
41f0b2e9   tangwang   product_enrich支持并发
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
          # 只把“LLM 调用 + markdown 解析”放到线程里;Redis get/set 保持在主线程,避免并发写入带来额外风险。
          # 注意:线程池是模块级单例,因此这里的 max_workers 主要用于日志语义(实际并发受单例池上限约束)。
          executor = _get_content_understanding_executor()
          future_by_batch_num: Dict[int, Any] = {}
          for batch_num, _batch_slice, batch in batch_jobs:
              future_by_batch_num[batch_num] = executor.submit(
                  process_batch, batch, batch_num=batch_num, target_lang=target_lang
              )
  
          # 按 batch_num 回填,确保输出稳定(results_by_index 是按原始 input index 映射的)
          for batch_num, batch_slice, _batch in batch_jobs:
              batch_results = future_by_batch_num[batch_num].result()
              for (original_idx, product), item in zip(batch_slice, batch_results):
                  results_by_index[original_idx] = item
                  title_input = str(item.get("title_input") or "").strip()
                  if not title_input:
                      continue
                  if item.get("error"):
                      # 不缓存错误结果,避免放大临时故障
                      continue
                  try:
                      _set_cached_anchor_result(product, target_lang, item)
                  except Exception:
                      # 已在内部记录 warning
                      pass
6f7840cf   tangwang   refactor: rename ...
804
  
76e1f088   tangwang   1. 减少一列sell point...
805
      return [item for item in results_by_index if item is not None]