argo-search 2.10.2 → 2.12.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/README.en.md +36 -21
  2. package/README.es.md +35 -20
  3. package/README.ja.md +36 -21
  4. package/README.ko.md +35 -20
  5. package/README.md +41 -22
  6. package/SKILL.md +19 -18
  7. package/backends/domain_profiles.json +30 -6
  8. package/backends/engine_registry.yaml +63 -13
  9. package/backends/quota_profiles.json +50 -10
  10. package/bin/argo +13 -0
  11. package/config.yaml +34 -20
  12. package/docs/ENGINE_CATALOG.md +14 -9
  13. package/docs/MCP_SETUP.md +16 -4
  14. package/docs/RELEASE_NOTES_v2.11.2.md +166 -0
  15. package/docs/RELEASE_NOTES_v2.12.0.md +65 -0
  16. package/docs/engines/pixiv.md +27 -0
  17. package/engines/specs/animetrace.yaml +35 -0
  18. package/engines/specs/google_lens.yaml +50 -0
  19. package/engines/specs/pixiv.yaml +52 -0
  20. package/engines/specs/saucenao.yaml +45 -0
  21. package/engines/specs/tracemoe.yaml +33 -0
  22. package/package.json +4 -2
  23. package/packages/dsh-plugin/README.md +20 -11
  24. package/packages/dsh-plugin/dsh/client.js +3 -3
  25. package/packages/dsh-plugin/dsh/index.js +27 -176
  26. package/packages/dsh-plugin/dsh/runner.js +19 -3
  27. package/packages/dsh-plugin/dsh/specs.js +133 -0
  28. package/packages/dsh-plugin/package.json +10 -2
  29. package/packages/dsh-plugin/test/client.test.js +4 -4
  30. package/packages/dsh-plugin/test/diagnostics.test.js +1 -1
  31. package/packages/dsh-plugin/test/index.test.js +49 -2
  32. package/scripts/adaptive.py +101 -27
  33. package/scripts/budget.py +13 -3
  34. package/scripts/build_route_labels.py +122 -169
  35. package/scripts/caliber_dedupe.py +4 -4
  36. package/scripts/caliber_isolation.py +17 -17
  37. package/scripts/concept_lookup.py +14 -1
  38. package/scripts/config.py +21 -3
  39. package/scripts/engine_admission.py +35 -17
  40. package/scripts/engine_dispatch.py +18 -17
  41. package/scripts/engine_env.py +4 -0
  42. package/scripts/engine_families.py +10 -4
  43. package/scripts/engines.py +15 -2
  44. package/scripts/engines_base.py +1 -1
  45. package/scripts/engines_builders.py +0 -1
  46. package/scripts/engines_builders_data.py +10 -10
  47. package/scripts/engines_builders_intl.py +4 -4
  48. package/scripts/engines_builders_pixiv.py +633 -0
  49. package/scripts/engines_builders_reverse_image.py +958 -0
  50. package/scripts/engines_builders_tech.py +0 -78
  51. package/scripts/env_store.py +216 -0
  52. package/scripts/extend_route_labels_by_capability.py +4 -4
  53. package/scripts/extend_route_labels_by_language.py +306 -0
  54. package/scripts/extend_route_labels_full_coverage.py +329 -0
  55. package/scripts/fetch_v3.py +74 -5
  56. package/scripts/image_vision/vision_probe +0 -0
  57. package/scripts/job.py +33 -7
  58. package/scripts/lint_spec_contracts.py +110 -0
  59. package/scripts/lint_stub_targets.py +130 -0
  60. package/scripts/local_image.py +25 -11
  61. package/scripts/mcp_compact.py +13 -0
  62. package/scripts/mcp_launch.sh +1 -1
  63. package/scripts/mcp_setup.py +85 -1
  64. package/scripts/mcp_transport.py +1 -1
  65. package/scripts/net_proxy.py +47 -0
  66. package/scripts/plan.py +11 -0
  67. package/scripts/pre-commit +24 -13
  68. package/scripts/query_signals.py +35 -20
  69. package/scripts/quota.py +116 -12
  70. package/scripts/recovery.py +38 -13
  71. package/scripts/redskill/redskill_engine.py +33 -10
  72. package/scripts/route.py +2 -2
  73. package/scripts/route_accuracy_eval.py +2 -2
  74. package/scripts/route_combo.py +22 -3
  75. package/scripts/route_domains.py +182 -50
  76. package/scripts/search.py +13 -14
  77. package/scripts/search_entry.py +38 -42
  78. package/scripts/search_output.py +3 -0
  79. package/scripts/search_pipeline.py +18 -23
  80. package/scripts/search_rank.py +22 -7
  81. package/scripts/serp_guard.py +7 -16
  82. package/scripts/settings_page.py +486 -0
  83. package/scripts/social_engines/twitter_engine.py +35 -2
  84. package/scripts/social_engines/xiaohongshu_engine.py +25 -0
  85. package/scripts/straggler_policy.py +8 -4
  86. package/scripts/tfidf_router.py +82 -24
package/scripts/quota.py CHANGED
@@ -145,11 +145,71 @@ def _at_or_over_budget(cost_used: float, budget: float) -> bool:
145
145
  return round(float(cost_used), 6) >= round(float(budget), 6)
146
146
 
147
147
 
148
+ # 远端配额报错的默认冷却(秒):不依赖 profile 的 period 字段(那是本地记账
149
+ # 周期)。远端配额报错分两类,“多久能好”取决于归因类别,而不取决于“这条限制
150
+ # 是按天还是按月”:
151
+ # - 预充值余额不足(HTTP 402 insufficient balance / “not enough money”):
152
+ # 账户余额问题,充值或换 Key 立即恢复,绝不会到月底自动恢复。锁 30 天是
153
+ # 最坏组合(#42 实测:充值后每次调用 55ms 返回 skipped,自愈日期写着下月)。
154
+ # 默认 1h——够覆盖一次误充/换 Key 的操作窗口,又不至于让用户干等。
155
+ # - 免费额度耗尽(10406 Free quota exhausted 等):多数按下月重置,沿用既有
156
+ # period 口径(默认 24h 兜底,避免 second/minute 的限频周期被误当配额周期)。
157
+ # 换 Key 自愈(key_fp 对比)对两类都生效,见 _mark_expired。
158
+ _BALANCE_QUOTA_COOLDOWN_S = 3600
159
+ _DEFAULT_QUOTA_COOLDOWN_S = 86400
160
+
161
+
162
+ def _quota_cooldown_seconds(category: str | None, reason: str,
163
+ period: str | None) -> int:
164
+ """远端配额耗尽的冷却秒数(单一计算点,mark 与文案都读它)。
165
+
166
+ 余额不足类固定短冷却、与 period 解耦;其余按 period 映射,过短按 24h 兜底。
167
+ 坏值一律回落默认,不让一次异常把某种引擎永久锁死。
168
+ """
169
+ if category == "quota_exhausted" and _looks_like_balance_error(reason):
170
+ return _BALANCE_QUOTA_COOLDOWN_S
171
+ seconds = {"hour": 3600, "day": 86400, "month": 30 * 86400}.get(
172
+ str(period or "day"), _DEFAULT_QUOTA_COOLDOWN_S)
173
+ return seconds if seconds >= 3600 else _DEFAULT_QUOTA_COOLDOWN_S
174
+
175
+
176
+ def _looks_like_balance_error(reason: str) -> bool:
177
+ """错误文本是否是「账户余额不足」(预充值用尽,充值即恢复)。"""
178
+ m = str(reason or "").lower()
179
+ return any(k in m for k in ("insufficient balance", "insufficient funds",
180
+ "not enough money", "余额不足", "402"))
181
+
182
+
183
+ def _required_candidates(engine: str, spec: dict[str, Any]) -> list[str]:
184
+ """引擎 key 的候选环境变量名(含 ARGO_ 变体与占位符别名展开)。
185
+
186
+ 与 engine_env.missing_env_for 的候选构造同源;这里只是把「候选」摊平成
187
+ 一条可读的名单,供取指纹用。无 required_env 时返回空(由调用方回退)。
188
+ """
189
+ from engine_env import PLACEHOLDER_ALIASES
190
+ explicit = spec.get("required_env")
191
+ if not explicit:
192
+ return []
193
+ out: list[str] = []
194
+ for item in explicit:
195
+ if isinstance(item, list):
196
+ out.extend(str(x) for x in item if x)
197
+ elif isinstance(item, str) and item:
198
+ if item in PLACEHOLDER_ALIASES:
199
+ out.extend(PLACEHOLDER_ALIASES[item])
200
+ elif item.startswith("ARGO_"):
201
+ out.extend([item, item[len("ARGO_"):]])
202
+ else:
203
+ out.extend([f"ARGO_{item}", item])
204
+ return out
205
+
206
+
148
207
  class QuotaManager:
149
208
  """配额追踪与消耗速率计算(v2)。"""
150
209
 
151
- # 远端配额周期候选;本地 period=second/minute 只是限频计算方式,不代表远端
152
- # 配额周期(火山免费额度按日),过短一律按 24h 保守处理
210
+
211
+ # 远端配额周期候选(模块级 _quota_cooldown_seconds 是唯一计算点;本地
212
+ # period=second/minute 只是限频口径,不代表远端配额周期,过短按 24h 兜底)
153
213
  _PERIOD_SECONDS = {"hour": 3600, "day": 86400, "month": 30 * 86400}
154
214
 
155
215
  def __init__(self):
@@ -405,12 +465,48 @@ class QuotaManager:
405
465
 
406
466
  @staticmethod
407
467
  def _engine_key_fp(engine: str) -> str:
408
- """当前引擎生效密钥的短指纹(8 hex);无密钥或读取失败返回空串。"""
468
+ """当前引擎生效密钥的短指纹(8 hex);无密钥或读取失败返回空串。
469
+
470
+ **必须与实际取 key 的地方同源**(issue #42):指纹的用途是「换 Key 就
471
+ 自愈」,所以它算的必须是引擎运行时真正读的那个环境变量。此前用
472
+ resolve_env_name 按 `<ENGINE>_API_KEY` 拼名,与 spec.required_env 对不上
473
+ 的 13 个引擎(deepseek_search 读 DEEPSEEK_API_KEY、metaso_* 读
474
+ ARGO_METASO_API_KEY、you 读 YDC_API_KEY 等)指纹恒为空串,于是
475
+ `_mark_expired` 的换 Key 分支永远不触发,换新 Key 也解不了熔断。
476
+ 改为与 search._missing_env_for 同一条链:先取 spec,用
477
+ required_env_for/missing_env_for 的候选解析逻辑取值,无 spec 再回退
478
+ resolve_env_name。任一候选有值即算命中——与「路由认为它可用」同口径。
479
+ """
409
480
  try:
410
481
  import hashlib
411
- from engine_env import get_env, resolve_env_name
412
- val = get_env(resolve_env_name(engine))
413
- return hashlib.sha256(val.encode("utf-8")).hexdigest()[:8] if val else ""
482
+ from engine_env import get_env, missing_env_for, resolve_env_name
483
+ spec = None
484
+ try:
485
+ from config import get_engines
486
+ spec = get_engines().get(engine)
487
+ except Exception:
488
+ spec = None
489
+ val = ""
490
+ if spec is not None:
491
+ # required_env 声明的是「主名」,但候选链(PLACEHOLDER_ALIASES /
492
+ # ARGO_ 变体)里任一有值都算配置了 key——与 missing_env_for 同源。
493
+ missing = missing_env_for(engine, spec)
494
+ if not missing:
495
+ # 有声明且都齐了:取主名的实际值算指纹
496
+ from engine_env import required_env_for
497
+ for name in required_env_for(engine, spec):
498
+ cand = [name] if name.startswith("ARGO_") else [f"ARGO_{name}", name]
499
+ got = get_env(cand)
500
+ if got:
501
+ val = got
502
+ break
503
+ else:
504
+ # 声明了但缺:仍尝试按声明候选读(可能只有可选键齐)
505
+ val = get_env(_required_candidates(engine, spec))
506
+ if not val:
507
+ val = get_env(resolve_env_name(engine))
508
+ return (hashlib.sha256(val.encode("utf-8")).hexdigest()[:8]
509
+ if val else "")
414
510
  except Exception:
415
511
  return ""
416
512
 
@@ -419,21 +515,31 @@ class QuotaManager:
419
515
  """远端耗尽标记是否已失效(周期到期、数据损坏、或已更换新 API Key)。"""
420
516
  if not isinstance(mark, dict) or now >= float(mark.get("until") or 0):
421
517
  return True
518
+ marked_at = float(mark.get("marked_at") or 0)
519
+ if marked_at > 0 and _looks_like_balance_error(str(mark.get("reason") or "")):
520
+ if now >= marked_at + _BALANCE_QUOTA_COOLDOWN_S:
521
+ return True
422
522
  saved_fp = mark.get("key_fp")
423
523
  if saved_fp:
424
- cur_fp = cls._engine_key_fp(engine)
425
- if cur_fp != saved_fp:
524
+ if cls._engine_key_fp(engine) != saved_fp:
426
525
  return True
526
+ elif "key_fp" in mark and cls._engine_key_fp(engine):
527
+ return True
427
528
  return False
428
529
 
429
530
  def mark_remote_exhausted(self, engine: str, reason: str = "",
430
- period: str | None = None) -> None:
531
+ period: str | None = None,
532
+ category: str | None = None) -> None:
431
533
  """远端明示「配额耗尽」(如火山 10406 Free quota exhausted)时调用。
432
534
 
433
535
  设计目标:配额问题不需要人工改配置——标记后路由组合层全模式排除
434
536
  该引擎,备用源自然接管;到下一周期边界或更换新 Key 时惰性自愈(is_available /
435
537
  is_hard_down 检查时清除),恢复后引擎自动回归。提前恢复(如原 Key 充值)
436
538
  可执行 `python3 scripts/quota.py reset <engine>`。
539
+
540
+ `category`(如 "quota_exhausted")与 `reason` 一起决定冷却时长:余额不足
541
+ 类(402 insufficient balance)与月度预算周期解耦、固定短冷却,避免一次
542
+ 欠费把引擎锁死 30 天(issue #42)。
437
543
  """
438
544
  key_fp = self._engine_key_fp(engine)
439
545
  with self._lock:
@@ -444,9 +550,7 @@ class QuotaManager:
444
550
  })
445
551
  profile = self._profiles.get(engine, {})
446
552
  p = period or profile.get("period") or "day"
447
- seconds = self._PERIOD_SECONDS.get(p, 86400)
448
- if seconds < 3600:
449
- seconds = 86400
553
+ seconds = _quota_cooldown_seconds(category, reason, p)
450
554
  st["remote_exhausted"] = {
451
555
  "until": time.time() + seconds,
452
556
  "reason": (reason or "")[:200],
@@ -46,12 +46,29 @@ _STOPWORDS_CN = {
46
46
  _STOPWORDS_EN = {"the", "a", "an", "of", "for", "to", "please", "how", "what"}
47
47
 
48
48
  # 常见「过长尾修饰」:地点/时间/程度等,去掉后主体更聚焦
49
+ # 年份只认「独立的四位数」:前后不能贴着数字、点、横线或斜杠。旧写法
50
+ # `\b\d{4}` 只要求左边界,会把「GB/T 15834」的 1583 当年份切掉、剩下孤立
51
+ # 的「4」(2026-11-07 实测 L1/L3 恢复都在用被改坏的查询)。
49
52
  _TAIL_MODIFIERS = re.compile(
50
- r"(?:\b\d{4}年?(?:度)?|\b\d{1,2}月|"
51
- r"最新|最全|详细|完整|全面|2020|2021|2022|2023|2024|2025|2026|"
53
+ r"(?:(?<![\w.\-/])\d{4}(?![\d.\-])年?(?:度)?|\b\d{1,2}月|"
54
+ r"最新|最全|详细|完整|全面|(?<!\d)(?:2020|2021|2022|2023|2024|2025|2026)(?!\d)|"
52
55
  r"知乎|贴吧|论坛|大全|汇总|排行榜|一览|数据|报告|统计|分析|趋势)"
53
56
  )
54
57
 
58
+ # 标识符原子:放宽与切词时整体保留,不拆、不删。切词正则只认字母数字,
59
+ # 「GB/T 15834-2011」会变成「GB T 15834 2011」,DOI、版本号同理被拆碎,
60
+ # 这类精确标识一旦拆开,引擎就按散词召回。顺序即优先级(DOI 先于版本号)。
61
+ _ATOM_RE = re.compile(
62
+ r"\b10\.\d{4,9}/[^\s\"'“”「」]+" # DOI
63
+ r"|\bCVE-\d{4}-\d{4,}\b" # CVE 编号
64
+ # 标准号:带斜杠前缀(GB/T、ISO/IEC)或已知标准组织前缀。不放开成任意
65
+ # 大写词加数字,否则「AI 2026」会被当成标准号、年份删不掉。
66
+ r"|\b(?:[A-Z]{2,6}/[A-Z]{1,3}|RFC|ISO|IEC|IEEE|GB|GJB|JIS|DIN|ASTM|ANSI|PEP|ECMA)"
67
+ r"[ \t]?\d{2,6}(?:[.:\-]\d+)*"
68
+ r"|\bv?\d+(?:\.\d+){1,3}\b" # 版本号、章节号
69
+ r"|(?<!\d)\d{5,}(?!\d)" # 长数字代码(股票代码等)
70
+ )
71
+
55
72
  _QUOTE_CHARS = re.compile(r'["\'“”‘’「」『』]')
56
73
  _TOKEN_RE = re.compile(r"[\u4e00-\u9fff]|[a-zA-Z0-9]+")
57
74
  _EN_WORD = re.compile(r"\b[a-zA-Z]{3,}\b")
@@ -120,19 +137,27 @@ def _load_synonyms() -> dict[str, Any]:
120
137
 
121
138
  # ── L1 放宽 ────────────────────────────────────────────────────────────────────
122
139
 
140
+ def _relax_plain(segment: str) -> list[str]:
141
+ """对不含标识符原子的片段去尾修饰、孤立年月与停用词,返回保留词。"""
142
+ seg = _TAIL_MODIFIERS.sub(" ", segment)
143
+ seg = re.sub(r"(?<=\s)[年月](?=\s|$)|^([年月]\s+)", " ", seg)
144
+ return [t for t in re.findall(r"[\u4e00-\u9fffA-Za-z0-9]+", seg)
145
+ if t.lower() not in _STOPWORDS_EN and t not in _STOPWORDS_CN]
146
+
147
+
123
148
  def relax_query(query: str) -> str:
124
- """L1:去引号 / 去停用词 / 去过长尾修饰与孤立年份时间词。"""
149
+ """L1:去引号 / 去停用词 / 去过长尾修饰与孤立年份时间词。
150
+
151
+ 标识符原子(标准号、DOI、CVE、版本号、长数字代码)原样保留,见 `_ATOM_RE`。
152
+ """
125
153
  q = _QUOTE_CHARS.sub(" ", query)
126
- q = _TAIL_MODIFIERS.sub(" ", q)
127
- # 清理孤立残留的年月单字
128
- q = re.sub(r"(?<=\s)[年月](?=\s|$)|^([年月]\s+)", " ", q)
129
- # 去停用词(按 token)
130
- tokens = re.findall(r"[\u4e00-\u9fffA-Za-z0-9]+", q)
131
- kept = []
132
- for t in tokens:
133
- if t.lower() in _STOPWORDS_EN or t in _STOPWORDS_CN:
134
- continue
135
- kept.append(t)
154
+ kept: list[str] = []
155
+ pos = 0
156
+ for m in _ATOM_RE.finditer(q):
157
+ kept.extend(_relax_plain(q[pos:m.start()]))
158
+ kept.append(m.group(0))
159
+ pos = m.end()
160
+ kept.extend(_relax_plain(q[pos:]))
136
161
  relaxed = " ".join(kept).strip()
137
162
  # 保底:去停用词后不能为空
138
163
  return relaxed or re.sub(r"\s+", " ", q).strip() or query
@@ -45,9 +45,30 @@ PAGE_URL = "https://cowork.xiaohongshu.com/s/redskill-rank/"
45
45
  EXPLORE_URL = "https://www.xiaohongshu.com/explore/{}"
46
46
  SEARCH_URL = "https://www.xiaohongshu.com/search_result?keyword={}"
47
47
  PROFILE_URL = "https://www.xiaohongshu.com/user/profile/{}"
48
- CACHE_DIR = Path(os.environ.get("ARGO_REDSKILL_CACHE")
49
- or (argo_paths.platform_cache_default() / "argo-redskill"))
50
- CACHE_FILE = CACHE_DIR / "data.json"
48
+ def _cache_dir() -> Path:
49
+ """缓存根:模块属性(测试 patch 的真名)优先,否则按当前 env 解析。"""
50
+ patched = globals().get("CACHE_DIR")
51
+ if patched is not None:
52
+ return patched
53
+ return Path(os.environ.get("ARGO_REDSKILL_CACHE")
54
+ or (argo_paths.platform_cache_default() / "argo-redskill"))
55
+
56
+
57
+ def _cache_file() -> Path:
58
+ return _cache_dir() / "data.json"
59
+
60
+
61
+ def __getattr__(name: str):
62
+ """`CACHE_DIR`/`CACHE_FILE` 按当前 ARGO_REDSKILL_CACHE 解析(PEP 562,290d3d8 同口径)。
63
+
64
+ 模块内裸名查找不触发本函数(LOAD_GLOBAL 语义),函数体一律走
65
+ _cache_dir()/_cache_file();这里只维持外部属性访问契约。
66
+ """
67
+ if name == "CACHE_DIR":
68
+ return _cache_dir()
69
+ if name == "CACHE_FILE":
70
+ return _cache_file()
71
+ raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
51
72
  USER_AGENT = "argo-search/1.0 (+https://github.com/taxueseek/argo; redskill)"
52
73
  DOWNLOAD_TIMEOUT = 120 # 14.6MB 全量,首次下载需要更长时间
53
74
 
@@ -114,8 +135,9 @@ def _is_fresh(data_date: str) -> bool:
114
135
 
115
136
  def _read_cache() -> dict[str, Any] | None:
116
137
  try:
117
- if CACHE_FILE.exists() and CACHE_FILE.stat().st_size > 0:
118
- with open(CACHE_FILE, encoding="utf-8") as f:
138
+ cf = _cache_file()
139
+ if cf.exists() and cf.stat().st_size > 0:
140
+ with open(cf, encoding="utf-8") as f:
119
141
  return json.load(f)
120
142
  except Exception as e:
121
143
  _log(f"缓存读取失败: {e}")
@@ -123,7 +145,8 @@ def _read_cache() -> dict[str, Any] | None:
123
145
 
124
146
 
125
147
  def _download(force: bool = False) -> dict[str, Any]:
126
- CACHE_DIR.mkdir(parents=True, exist_ok=True)
148
+ cache_file = _cache_file()
149
+ _cache_dir().mkdir(parents=True, exist_ok=True)
127
150
  raw = _http_get(DATA_URL)
128
151
  data = json.loads(raw.decode("utf-8"))
129
152
  if "allSkills" not in data:
@@ -131,9 +154,9 @@ def _download(force: bool = False) -> dict[str, Any]:
131
154
  # 原子写走 argo_paths 唯一来源(唯一 tmp 名);旧实现固定 `.tmp` 名,
132
155
  # 并发刷新(手动 update 撞上搜索自动刷新)会互相搬走临时文件而写失败。
133
156
  # 14.6MB 缓存用 indent=None 省掉格式化的时间与体积。
134
- argo_paths.atomic_write_json(CACHE_FILE, data, indent=None)
157
+ argo_paths.atomic_write_json(cache_file, data, indent=None)
135
158
  if force:
136
- _log(f"已强制刷新缓存: {CACHE_FILE} ({CACHE_FILE.stat().st_size / 1e6:.1f}MB, dataDate={data.get('dataDate')})")
159
+ _log(f"已强制刷新缓存: {cache_file} ({cache_file.stat().st_size / 1e6:.1f}MB, dataDate={data.get('dataDate')})")
137
160
  return data
138
161
 
139
162
 
@@ -295,8 +318,8 @@ def _stats(data: dict[str, Any]) -> dict[str, Any]:
295
318
  "authorList": len(data.get("authorList", [])),
296
319
  "allSkills": len(data.get("allSkills", [])),
297
320
  },
298
- "cache_file": str(CACHE_FILE),
299
- "cache_mb": round(CACHE_FILE.stat().st_size / 1e6, 1) if CACHE_FILE.exists() else 0,
321
+ "cache_file": str((cf := _cache_file())),
322
+ "cache_mb": round(cf.stat().st_size / 1e6, 1) if cf.exists() else 0,
300
323
  }
301
324
 
302
325
 
package/scripts/route.py CHANGED
@@ -381,11 +381,11 @@ def _route_by_domain(ctx: _RouteCtx, domain: dict[str, Any], secondary: list[dic
381
381
  _specs_snapshot()))
382
382
  _filtered = [e for e in engines_combo if e not in _drop]
383
383
  engines_combo = _filtered or [e for e in ["anysearch"] if e in enabled] or engines_combo
384
- # 🔑 中文查询 + 学术类域 → 剔除英文论文源(openalex/europepmc 对中文查询噪声大)
384
+ # 🔑 中文查询 + 学术类域 → 剔除纯英文论文源(ENGINE_LANGS 声明 langs=["en"])
385
385
  if (domain.get("name") in ("tech_deep", "academic")
386
386
  and any("\u4e00" <= ch <= "\u9fff" for ch in query)):
387
387
  engines_combo = [e for e in engines_combo
388
- if e not in ("openalex", "europepmc")]
388
+ if engine_langs(e, _specs_snapshot().get(e)) != {"en"}]
389
389
  if not engines_combo:
390
390
  engines_combo = [e for e in ["arxiv", "anysearch", "local_search"]
391
391
  if e in enabled]
@@ -31,7 +31,7 @@
31
31
  ## 用法
32
32
 
33
33
  python3 scripts/route_accuracy_eval.py # 全量
34
- python3 scripts/route_accuracy_eval.py --evidence badcase
34
+ python3 scripts/route_accuracy_eval.py --evidence capability
35
35
  python3 scripts/route_accuracy_eval.py --json
36
36
  python3 scripts/route_accuracy_eval.py --show-miss 20 # 打印失配样例
37
37
  """
@@ -171,7 +171,7 @@ def _print_text(r: dict[str, Any]) -> None:
171
171
  def main() -> int:
172
172
  ap = argparse.ArgumentParser(description="路由准确率评测(离线)")
173
173
  ap.add_argument("--evidence", default=None,
174
- choices=["badcase", "usage_error", "usage_ok"])
174
+ choices=["capability", "language", "feedback"])
175
175
  ap.add_argument("--json", action="store_true", dest="json_output")
176
176
  ap.add_argument("--show-miss", type=int, default=0)
177
177
  args = ap.parse_args()
@@ -517,13 +517,32 @@ def _get_engines_combo(domain: dict[str, Any], enabled: set[str], mode: str = "a
517
517
  # 只是多了一个维度——「引擎在 A 域强、B 域弱」现在可被路由区分。
518
518
  _dom_name = str(domain.get("name") or "")
519
519
  _q_lang = str((features or {}).get("primary_lang") or "")
520
+ _score_memo: dict[str, float] = {}
520
521
 
521
522
  def _score_of(e: str) -> float:
523
+ cached_s = _score_memo.get(e)
524
+ if cached_s is not None:
525
+ return cached_s
522
526
  try:
523
- return _adaptive_learner.get_score(e, _dom_name, _q_lang)
527
+ s = float(_adaptive_learner.get_score(e, _dom_name, _q_lang))
524
528
  except TypeError:
525
529
  # 旧版 adaptive(无 domain/lang 形参)回退全局分
526
- return _adaptive_learner.get_score(e)
530
+ s = float(_adaptive_learner.get_score(e))
531
+ _score_memo[e] = s
532
+ return s
533
+
534
+ def _ucb_of(e: str) -> float:
535
+ s = _score_of(e)
536
+ if s < _VERTICAL_FLOOR or s >= 0.3:
537
+ return s
538
+ try:
539
+ _, n = _adaptive_learner.get_score_with_samples(e, _dom_name, _q_lang)
540
+ if isinstance(n, int):
541
+ from adaptive import AdaptiveLearner
542
+ return AdaptiveLearner.heb_ucb_score(s, n, floor=_VERTICAL_FLOOR)
543
+ except Exception:
544
+ pass
545
+ return s
527
546
 
528
547
  combo = domain.get("engines_combo", [])
529
548
  primary = domain.get("primary", "anysearch")
@@ -638,7 +657,7 @@ def _get_engines_combo(domain: dict[str, Any], enabled: set[str], mode: str = "a
638
657
  if e in protect
639
658
  or (e == primary
640
659
  and _score_of(e) >= _VERTICAL_FLOOR)
641
- or _score_of(e) >= 0.3
660
+ or _ucb_of(e) >= 0.3
642
661
  ]
643
662
  if not filtered:
644
663
  filtered = original