argo-search 2.10.1 → 2.10.2

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 (66) hide show
  1. package/README.en.md +30 -4
  2. package/README.es.md +30 -4
  3. package/README.ja.md +30 -4
  4. package/README.ko.md +30 -4
  5. package/README.md +30 -24
  6. package/SKILL.md +1 -1
  7. package/backends/concept_vectors.bin +0 -0
  8. package/backends/engine_concept_vectors.json +3104 -0
  9. package/config.yaml +82 -14
  10. package/docs/RELEASE_NOTES_v2.10.2.md +48 -0
  11. package/package.json +2 -1
  12. package/packages/dsh-plugin/dsh/diagnostics.js +8 -3
  13. package/packages/dsh-plugin/dsh/index.js +7 -7
  14. package/packages/dsh-plugin/dsh/runner.js +72 -46
  15. package/packages/dsh-plugin/package.json +1 -1
  16. package/packages/dsh-plugin/test/index.test.js +43 -0
  17. package/scripts/argo_engine_registry.py +30 -4
  18. package/scripts/argo_paths.py +7 -1
  19. package/scripts/build_concept_table.py +612 -0
  20. package/scripts/build_route_labels.py +285 -0
  21. package/scripts/caliber_dedupe.py +66 -0
  22. package/scripts/caliber_isolation.py +4 -2
  23. package/scripts/circuit_breaker.py +25 -3
  24. package/scripts/concept_lookup.py +212 -0
  25. package/scripts/engines.py +24 -7
  26. package/scripts/engines_base.py +17 -2
  27. package/scripts/engines_builders_skill.py +87 -10
  28. package/scripts/extend_route_labels.py +239 -0
  29. package/scripts/extend_route_labels_by_capability.py +344 -0
  30. package/scripts/gen_routing_snapshot.py +22 -3
  31. package/scripts/lang_detect.py +12 -3
  32. package/scripts/local_seek.py +13 -3
  33. package/scripts/mcp_transport.py +1 -1
  34. package/scripts/numeric_verify.py +330 -0
  35. package/scripts/plan.py +25 -4
  36. package/scripts/pre-commit +2 -2
  37. package/scripts/rank_signals.py +48 -4
  38. package/scripts/ranking_eval.py +23 -1
  39. package/scripts/regression_p0p1.py +7 -2
  40. package/scripts/route.py +24 -3
  41. package/scripts/route_accuracy_eval.py +191 -0
  42. package/scripts/route_combo.py +32 -1
  43. package/scripts/route_domains.py +242 -5
  44. package/scripts/route_primary.py +101 -0
  45. package/scripts/search.py +1 -0
  46. package/scripts/search_cli.py +89 -7
  47. package/scripts/search_output.py +59 -1
  48. package/scripts/search_pipeline.py +5 -0
  49. package/scripts/snippet_clean.py +60 -0
  50. package/scripts/social_engines/twitter_engine.py +127 -43
  51. package/scripts/social_engines/xiaohongshu_engine.py +11 -1
  52. package/scripts/tfidf_router.py +52 -2
  53. package/scripts/train.py +15 -0
  54. package/scripts/verify_with.py +124 -0
  55. package/sub-skills/local-search/SKILL.md +3 -2
  56. package/sub-skills/local-search/bm25.py +89 -8
  57. package/sub-skills/local-search/config.yaml +12 -0
  58. package/sub-skills/local-search/parse_maps.yaml +8 -0
  59. package/sub-skills/local-search/parsers.py +5 -2
  60. package/sub-skills/local-search/search_v3.py +87 -1
  61. package/sub-skills/local-search/smart_router.py +1 -1
  62. package/sub-skills/local-seek/SKILL.md +6 -5
  63. package/sub-skills/local-seek/scripts/eval_rank.py +1 -1
  64. package/sub-skills/local-seek/scripts/seek.py +152 -36
  65. package/sub-skills/local-seek/scripts/seek_rank.py +191 -11
  66. package/scripts/image_vision/vision_probe +0 -0
@@ -575,9 +575,10 @@ _SEMANTIC_ENGINES = frozenset({
575
575
  # 统一剥疑问前缀与属性词,保留核心实体。只作用于实体型引擎;通用 web 引擎
576
576
  # 不动(属性词对全文检索是有用信号)。
577
577
  _ENTITY_QUERY_ENGINES = frozenset({"wikidata", "thesportsdb", "local_openstreetmap"})
578
+ _ENCYCLOPEDIA_QUERY_ENGINES = frozenset({"wikipedia", "zh_wikipedia", "baidu_baike"})
578
579
  _ENTITY_Q_PREFIX_RE = re.compile(
579
580
  r"(?i)^\s*(where\s+(is|are|was|were)|where'?s|who\s+(is|are|was)|who'?s"
580
- r"|what\s+(is|are)|when\s+(was|is|did)|which\s+\w+\s+(is|was)"
581
+ r"|what\s+(is|are)|when\s+(was|is|did)|which\s+\w+\s+(is|was)|how\s+much\s+(is|are)"
581
582
  r"|哪里|在哪[里儿]?|是谁?|是什么|什么时候|哪一[个国年])\s*",
582
583
  )
583
584
  # 英文属性词带 \b(空格分词下词边界天然成立);中文属性词不进此表——
@@ -586,16 +587,27 @@ _ENTITY_Q_PREFIX_RE = re.compile(
586
587
  _ENTITY_ATTR_RE = re.compile(
587
588
  r"(?i)\b(founding year|founded|established|headquarters?|located( in)?"
588
589
  r"|population|capital|address|club|team|stadium|league|album|discography"
589
- r"|song|movie|film|director|cast)\b",
590
+ r"|song|movie|film|director|cast|price|pricing|cost|reviews?|tutorial"
591
+ r"|guide|download|official|comparison|salary|hiring"
592
+ r"|revenue|earnings|market cap|market value|net profit|lifespan"
593
+ r"|feeding|breeding|ingredients|efficacy|dosage|side effects)\b",
590
594
  )
591
595
  # 中文属性词(含繁体):只在查询尾部剥离——中文自然语序是实体名在前、
592
596
  # 属性词在后;不碰串中,「电影频道」「歌曲排行榜」这类实体名内含属性词,
593
597
  # 串中剥离会误伤。长词优先,避免「成立年份」被「成立」截断残留「年份」。
594
598
  _ENTITY_ATTR_TAILS = (
595
- "成立年份", "成立", "创立", "創立", "总部", "總部", "位置", "球队", "球隊",
596
- "俱乐部", "俱樂部", "职能", "職能", "职责", "職責", "专辑", "專輯",
597
- "歌曲", "电影", "電影", "导演", "導演", "主演",
599
+ "成立年份", "官方价格", "市场规模", "成立", "创立", "創立", "总部", "總部",
600
+ "位置", "球队", "球隊", "俱乐部", "俱樂部", "职能", "職能", "职责", "職責",
601
+ "专辑", "專輯", "歌曲", "电影", "電影", "导演", "導演", "主演",
602
+ "多少钱", "多少字", "怎么选", "怎么样", "价格", "價格", "全书", "字数",
603
+ "万字", "评测", "对比", "推荐", "官网", "官方", "下载", "教程", "指南",
604
+ "简介", "招聘", "岗位",
605
+ # 2026-11-02 补:财报/生物/医药类属性后缀(原表缺失致「贵州茅台 2025年报
606
+ # 营收」「大熊猫 寿命 怎么养」等查询剥离前后一字不差,实体源仍 0 命中)
607
+ "净利润", "营收", "市值", "年报", "季报", "财报", "寿命",
608
+ "怎么养", "饲养", "繁殖", "成分", "功效", "用法", "用量", "副作用",
598
609
  )
610
+ _TRAILING_YEAR_RE = re.compile(r"\s+(?:19\d\d|20[0-3]\d)\s*$")
599
611
 
600
612
 
601
613
  def _entity_core_query(query: str) -> str:
@@ -622,6 +634,11 @@ def _entity_core_query(query: str) -> str:
622
634
  if not changed and q.endswith("的") and len(q) > 3:
623
635
  q = q[:-1].strip()
624
636
  changed = True
637
+ if not changed:
638
+ ym = _TRAILING_YEAR_RE.search(q)
639
+ if ym and ym.start() >= 2 and not q[:ym.start()].strip().isdigit():
640
+ q = q[:ym.start()].strip()
641
+ changed = True
625
642
  q = re.sub(r"[??::,,]+", " ", q)
626
643
  q = re.sub(r"\s+", " ", q).strip()
627
644
  return q or raw
@@ -809,8 +826,8 @@ def search(query: str, engine: str, n: int = 5, timeout: float = 8, depth: str =
809
826
  # 语义型引擎不识别平台结构化语法,剥掉字段只留核心词;透传型保持原 query。
810
827
  if engine in _SEMANTIC_ENGINES:
811
828
  query = strip_structured(query)
812
- elif engine in _ENTITY_QUERY_ENGINES:
813
- # 实体型引擎:自然语言句(疑问前缀/属性词)会让实体搜索接口空结果
829
+ elif engine in _ENTITY_QUERY_ENGINES or engine in _ENCYCLOPEDIA_QUERY_ENGINES:
830
+ # 实体/百科型引擎:自然语言句(疑问前缀/属性词/价格评测后缀)会让接口空结果
814
831
  query = _entity_core_query(query)
815
832
  eff_n = bucket_n(engine, n)
816
833
 
@@ -4,6 +4,7 @@
4
4
  from __future__ import annotations
5
5
 
6
6
  import functools
7
+ import html as _htmllib
7
8
  import io
8
9
  import json
9
10
  import math
@@ -775,6 +776,13 @@ def _apply_url_kind(rows: list[dict[str, Any]], spec: dict) -> list[dict[str, An
775
776
  return rows
776
777
 
777
778
 
779
+ # 摘要标签卫生(2026-10-31 评测基线 13/64 查询摘要带裸标签):MediaWiki 类
780
+ # 源的 snippet 字段原生含 <span class="searchmatch"> 等内联高亮标签,声明式
781
+ # 映射直通输出会污染下游阅读与引用。仅当串里确实出现「像标签」的片段才剥,
782
+ # 避免误伤含裸 < 的正文(如 "a < b":`<` 后非字母不匹配)。
783
+ _TAGISH_RE = re.compile(r"</?[a-zA-Z][^>]{0,160}?>")
784
+
785
+
778
786
  def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
779
787
  output_map: dict, spec: dict) -> list[dict[str, Any]]:
780
788
  """HTTP 引擎响应体解析(GET/POST 共用)。"""
@@ -833,8 +841,15 @@ def _parse_http_payload(raw: str, fmt: str, eng: str, n: int,
833
841
  r["published_at"] = _normalize_epoch(r["published_at"])
834
842
  if _lic and r.get("image_url"):
835
843
  r.setdefault("image_license", _lic)
836
- if isinstance(r.get("snippet"), str) and len(r["snippet"]) > 300:
837
- r["snippet"] = r["snippet"][:300]
844
+ sn = r.get("snippet")
845
+ if isinstance(sn, str):
846
+ if _TAGISH_RE.search(sn):
847
+ sn = _TAGISH_RE.sub("", sn)
848
+ if "&" in sn:
849
+ sn = _htmllib.unescape(sn)
850
+ if len(sn) > 300:
851
+ sn = sn[:300]
852
+ r["snippet"] = sn
838
853
  # 图片元数据收尾(尺寸转 int / 许可归一 / 商用判据)——落在这个共同
839
854
  # 出口而不是各 parser 里:图源有三条产出路径(声明式 output_map、
840
855
  # 自定义 builder、通用兜底),只覆盖一条会让契约对一半结果生效。
@@ -15,12 +15,84 @@ Argo 已有的 skillsmp(仓库星数)、clawhub(生态下载量)是另
15
15
  from __future__ import annotations
16
16
 
17
17
  import json
18
+ import math
19
+ import re
18
20
  import urllib.parse
19
21
  import urllib.request
20
22
  from typing import Any
21
23
 
22
24
  from engines_base import safe_search, http_open, rank_score
23
25
 
26
+ # ── 面向英文技能目录(explainx/skills.sh/skillsmp/clawhub)的轻量中英概念映射 ──
27
+ _ZH_TO_EN_SKILL_TERMS: tuple[tuple[str, str], ...] = (
28
+ ("架构图", "architecture diagram"),
29
+ ("流程图", "flowchart diagram"),
30
+ ("思维导图", "mindmap"),
31
+ ("时序图", "sequence diagram"),
32
+ ("画图", "diagram"),
33
+ ("可视化", "visualization chart"),
34
+ ("图表", "chart"),
35
+ ("海报", "poster"),
36
+ ("浏览器", "browser"),
37
+ ("自动化", "automation"),
38
+ ("记忆", "memory"),
39
+ ("爬虫", "scraper crawl"),
40
+ ("抓取", "fetch scrape"),
41
+ ("网页", "web"),
42
+ ("公众号", "wechat"),
43
+ ("微信", "wechat"),
44
+ ("视频", "video"),
45
+ ("字幕", "caption subtitle"),
46
+ ("论文", "academic paper"),
47
+ ("学术", "academic"),
48
+ ("文献", "literature citation"),
49
+ ("金融", "finance stock"),
50
+ ("股票", "stock"),
51
+ ("审查", "code review"),
52
+ ("体检", "audit health"),
53
+ ("调试", "debug"),
54
+ ("测试", "testing"),
55
+ ("表格", "spreadsheet excel csv"),
56
+ ("文档", "document"),
57
+ ("技能", "skill"),
58
+ # 通用高频补充(2026-10-31:实测「渲染」查询归一后只剩 remotion,映射盲区)
59
+ ("渲染", "render"),
60
+ ("翻译", "translation translate"),
61
+ ("邮件", "email mail"),
62
+ ("摘要", "summary summarize"),
63
+ ("投资", "invest investing"),
64
+ ("图片", "image"),
65
+ ("下载", "download"),
66
+ ("剪辑", "video editing"),
67
+ )
68
+
69
+
70
+ def _normalize_en_catalog_query(query: str) -> str:
71
+ """将含中文的技能检索词对齐为英文目录可命中的英文查询词(纯英文原样返回)。"""
72
+ q = (query or "").strip()
73
+ if not q or q.isascii():
74
+ return q
75
+ en_bits: list[str] = re.findall(r"[A-Za-z0-9_+-]{2,}", q)
76
+ remaining = q
77
+ for zh, en in _ZH_TO_EN_SKILL_TERMS:
78
+ if zh in remaining:
79
+ if en not in en_bits:
80
+ en_bits.append(en)
81
+ remaining = remaining.replace(zh, " ")
82
+ return " ".join(en_bits) if en_bits else q
83
+
84
+
85
+ def _skill_rank_score(rank: int, popularity: Any = 0, is_official: bool = False) -> float:
86
+ """结合上游位次、对数饱和流行度先验 (log10(1+pop)) 与官方标记计算初始分。"""
87
+ try:
88
+ pop = max(0, int(popularity or 0))
89
+ except (TypeError, ValueError):
90
+ pop = 0
91
+ pop_bonus = min(0.14, 0.026 * math.log10(1 + pop)) if pop > 0 else 0.0
92
+ off_bonus = 0.04 if is_official else 0.0
93
+ base = min(0.92, 0.72 + pop_bonus + off_bonus)
94
+ return rank_score(base, rank)
95
+
24
96
  # ── explainx.ai(12075 条,安装量 + 分类 + 官方标记)────────────────────────
25
97
  _EXPLAINX_URL = "https://explainx.ai/api/skills"
26
98
 
@@ -79,7 +151,7 @@ def _build_explainx_engine(spec: dict[str, Any]) -> Any:
79
151
  query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
80
152
  ) -> list[dict[str, Any]]:
81
153
  to = _timeout or timeout
82
- q = (query or "").strip()
154
+ q = _normalize_en_catalog_query(query)
83
155
  if not q:
84
156
  return []
85
157
  url = f"{_EXPLAINX_URL}?q={urllib.parse.quote(q)}&limit={max(1, n)}"
@@ -99,11 +171,12 @@ def _build_explainx_engine(spec: dict[str, Any]) -> Any:
99
171
  installs = s.get("totalInstalls") or 0
100
172
  weekly = s.get("weeklyInstalls")
101
173
  category = s.get("category") or ""
174
+ is_official = bool(s.get("isOfficial"))
102
175
  # 安装量是这一源的核心价值,必须出现在摘要里(L1 做不到)
103
176
  bits = [f"安装 {installs}"]
104
177
  if weekly is not None and weekly != installs:
105
178
  bits.append(f"本周 +{weekly}")
106
- if s.get("isOfficial"):
179
+ if is_official:
107
180
  bits.append("官方")
108
181
  summary = " · ".join(bits)
109
182
  if category:
@@ -114,17 +187,18 @@ def _build_explainx_engine(spec: dict[str, Any]) -> Any:
114
187
  "url": f"https://github.com/{owner}/{repo}",
115
188
  "snippet": summary,
116
189
  "source": "explainx",
117
- "score": rank_score(0.75, rank),
190
+ "score": _skill_rank_score(rank, installs, is_official),
118
191
  # 可验证出处:owner/repo 是「装什么」的权威答案
119
192
  "upstream": f"{owner}/{repo}",
120
193
  "metadata": {
121
194
  "category": category,
122
195
  "totalInstalls": installs,
123
196
  "weeklyInstalls": weekly,
124
- "isOfficial": bool(s.get("isOfficial")),
197
+ "isOfficial": is_official,
125
198
  },
126
199
  }
127
200
  )
201
+ results.sort(key=lambda r: -r["score"])
128
202
  return results
129
203
 
130
204
  return _engine
@@ -148,7 +222,7 @@ def _build_skillsmp_engine(spec: dict[str, Any]) -> Any:
148
222
  query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
149
223
  ) -> list[dict[str, Any]]:
150
224
  to = _timeout or timeout
151
- q = (query or "").strip()
225
+ q = _normalize_en_catalog_query(query)
152
226
  if not q:
153
227
  return []
154
228
  url = (
@@ -180,7 +254,7 @@ def _build_skillsmp_engine(spec: dict[str, Any]) -> Any:
180
254
  "url": url_final,
181
255
  "snippet": summary[:400],
182
256
  "source": "skillsmp",
183
- "score": rank_score(0.75, rank),
257
+ "score": _skill_rank_score(rank, stars, False),
184
258
  "published_at": _normalize_epoch(s.get("updatedAt")),
185
259
  "upstream": github or market,
186
260
  "metadata": {
@@ -190,6 +264,7 @@ def _build_skillsmp_engine(spec: dict[str, Any]) -> Any:
190
264
  },
191
265
  }
192
266
  )
267
+ results.sort(key=lambda r: -r["score"])
193
268
  return results
194
269
 
195
270
  return _engine
@@ -211,7 +286,7 @@ def _build_clawhub_engine(spec: dict[str, Any]) -> Any:
211
286
  query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
212
287
  ) -> list[dict[str, Any]]:
213
288
  to = _timeout or timeout
214
- q = (query or "").strip()
289
+ q = _normalize_en_catalog_query(query)
215
290
  if not q:
216
291
  return []
217
292
  url = f"{_CLAWHUB_URL}?q={urllib.parse.quote(q)}&limit={max(1, n)}"
@@ -240,7 +315,7 @@ def _build_clawhub_engine(spec: dict[str, Any]) -> Any:
240
315
  "url": f"https://clawhub.ai{canonical}",
241
316
  "snippet": summary[:400],
242
317
  "source": "clawhub",
243
- "score": rank_score(0.75, rank),
318
+ "score": _skill_rank_score(rank, downloads, official),
244
319
  "published_at": _normalize_epoch(s.get("updatedAt")),
245
320
  # install.reference 是 owner/slug 形式的安装引用
246
321
  "upstream": ((s.get("install") or {}).get("reference")) or "",
@@ -253,6 +328,7 @@ def _build_clawhub_engine(spec: dict[str, Any]) -> Any:
253
328
  },
254
329
  }
255
330
  )
331
+ results.sort(key=lambda r: -r["score"])
256
332
  return results
257
333
 
258
334
  return _engine
@@ -275,7 +351,7 @@ def _build_skills_sh_engine(spec: dict[str, Any]) -> Any:
275
351
  query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
276
352
  ) -> list[dict[str, Any]]:
277
353
  to = _timeout or timeout
278
- q = (query or "").strip()
354
+ q = _normalize_en_catalog_query(query)
279
355
  if not q:
280
356
  return []
281
357
  url = f"{_SKILLS_SH_URL}?q={urllib.parse.quote(q)}&limit={max(1, n)}"
@@ -300,7 +376,7 @@ def _build_skills_sh_engine(spec: dict[str, Any]) -> Any:
300
376
  "url": f"{_SKILLS_SH_PAGE}{sid}",
301
377
  "snippet": f"安装 {installs} · {source}",
302
378
  "source": "skills_sh",
303
- "score": rank_score(0.75, rank),
379
+ "score": _skill_rank_score(rank, installs, False),
304
380
  # 可验证出处:三段式 id 指向技能本身(比市场页更精确)
305
381
  "upstream": sid,
306
382
  "metadata": {
@@ -309,6 +385,7 @@ def _build_skills_sh_engine(spec: dict[str, Any]) -> Any:
309
385
  },
310
386
  }
311
387
  )
388
+ results.sort(key=lambda r: -r["score"])
312
389
  return results
313
390
 
314
391
  return _engine
@@ -0,0 +1,239 @@
1
+ #!/usr/bin/env python3
2
+ """extend_route_labels.py — 给路由语料加意图类型标签(外部反馈驱动扩展)。
3
+
4
+ ## 为什么需要它
5
+
6
+ `build_route_labels.py` 从本机数据构建的语料只有 `expect_domain`(历史路由
7
+ 输出)。但外部反馈(GitHub Issue #34.1)暴露的是一类**意图撞车**问题:
8
+ 同一个词在不同意图下属于不同域(`PD-1` 在「市场规模」下是商业分析,在
9
+ 「蛋白结构域」下是生信)。只看 domain 标签无法覆盖这类场景——需要一层
10
+ **意图类型**标签。
11
+
12
+ ## MECE 拆解:意图类型六分类
13
+
14
+ 按「用户想要什么」正交拆分,六类互不重叠、合起来穷尽:
15
+
16
+ | 类型 | 定义 | 典型域 | 撞车场景 |
17
+ |---|---|---|---|
18
+ | `factual` | 查事实/定义/数据 | cn_encyclopedia, stock_query, macro_data | 药靶点名 vs 商业名词 |
19
+ | `content` | 找内容/攻略/教程 | chinese_general, chinese_tech_deep, english_tech | 「原理」要讲解 vs 要论文 |
20
+ | `academic` | 找文献/论文/数据集 | academic, scholar_search, dataset_search | 「论文」要文献 vs 要讲解 |
21
+ | `sentiment` | 看舆情/评论/讨论 | social | 「攻略」要内容 vs 「舆情」要监听 |
22
+ | `entity` | 查机构/公司/人物 | org_entity, company_search | 公司名 vs 产品名 |
23
+ | `navigational` | 找入口/工具/站点 | dsh_plugin_search, skill_search | 找工具 vs 找资料 |
24
+
25
+ **穷尽性检查**:六类覆盖了「事实/内容/学术/舆情/实体/导航」六个正交维度。
26
+ 不在这六类里的查询(如「天气」「股价」)归入 `factual`(它们是查事实)。
27
+
28
+ ## 与外部反馈的对应
29
+
30
+ | 外部反馈 | 撞车场景 | 标签解法 |
31
+ |---|---|---|
32
+ | Issue #34.1 | PD-1 市场规模 vs 蛋白结构域 | `factual`(商业)vs `factual`(生信)——**同类不同域**,靠域标签区分 |
33
+ | v2.10.2 路由收口 | Transformer 原理 vs 论文 | `content` vs `academic`——**跨类**,靠意图标签区分 |
34
+ | v2.10.2 路由收口 | 小红书攻略 vs 舆情 | `content` vs `sentiment`——**跨类**,靠意图标签区分 |
35
+
36
+ ## 用法
37
+
38
+ python3 scripts/extend_route_labels.py # 加标签并写回
39
+ python3 scripts/extend_route_labels.py --dry-run # 只统计不写
40
+ python3 scripts/extend_route_labels.py --report # 打印撞车场景覆盖
41
+ """
42
+
43
+ from __future__ import annotations
44
+
45
+ import argparse
46
+ import json
47
+ import re
48
+ import sys
49
+ from collections import Counter
50
+ from pathlib import Path
51
+ from typing import Any
52
+
53
+ ROOT = Path(__file__).resolve().parent.parent
54
+ SCRIPTS = ROOT / "scripts"
55
+ sys.path.insert(0, str(SCRIPTS))
56
+
57
+ LABELS = ROOT / "tests" / "golden" / "route_labeled.jsonl"
58
+
59
+ # ── 意图类型判定(规则优先,域兜底)──────────────────────────────────────────
60
+ # 判据是「查询里出现了什么意图词」,不是「路由到了哪个域」——后者是输出,
61
+ # 用它当标签等于把答案抄进题目。
62
+
63
+ _INTENT_PATTERNS: list[tuple[str, re.Pattern[str]]] = [
64
+ # academic:明确的文献意图词
65
+ ("academic", re.compile(
66
+ r"(论文|文献|综述|survey|review|arxiv|期刊|journal|doi|引用|reference|"
67
+ r"scholar|学术|科研|研究|实验|数据集|dataset|benchmark|评测)", re.I)),
68
+ # sentiment:舆情/讨论意图词
69
+ ("sentiment", re.compile(
70
+ r"(舆情|评论|讨论|网友|吐槽|口碑|评价|反馈|热议|争议|态度|"
71
+ r"sentiment|opinion|review|discussion|complaint)", re.I)),
72
+ # content:内容/教程意图词
73
+ ("content", re.compile(
74
+ r"(教程|攻略|指南|详解|原理|是什么|怎么用|如何|最佳实践|best practice|"
75
+ r"tutorial|guide|how to|example|案例|方案|步骤|方法)", re.I)),
76
+ # entity:机构/公司/人物意图词
77
+ ("entity", re.compile(
78
+ r"(公司|企业|集团|机构|组织|官网|总部|创始人|CEO|董事长|"
79
+ r"company|inc\.|corp\.|ltd\.|gmbh|organization)", re.I)),
80
+ # navigational:找入口/工具意图词
81
+ ("navigational", re.compile(
82
+ r"(插件|技能|工具|安装|下载|marketplace|plugin|skill|tool|install|"
83
+ r"下载|仓库|repo|github|npm|pypi)", re.I)),
84
+ ]
85
+
86
+
87
+ def classify_intent(query: str, domain: str | None = None) -> str:
88
+ """判定查询的意图类型。规则优先,域兜底。
89
+
90
+ 域兜底只用于规则没命中时——它是**弱信号**(域是路由输出),但比
91
+ 无标签好。兜底映射按域的语义归属,不是按域名字面。
92
+ """
93
+ for name, pat in _INTENT_PATTERNS:
94
+ if pat.search(query):
95
+ return name
96
+ # 域兜底
97
+ _DOMAIN_INTENT = {
98
+ "academic": "academic", "scholar_search": "academic",
99
+ "dataset_search": "academic",
100
+ "social": "sentiment",
101
+ "org_entity": "entity", "company_search": "entity",
102
+ "dsh_plugin_search": "navigational", "skill_search": "navigational",
103
+ "chinese_tech_deep": "content", "english_tech": "content",
104
+ "tech_deep": "content", "code_search": "content",
105
+ "cn_encyclopedia": "factual", "dictionary_search": "factual",
106
+ "stock_query": "factual", "fund_query": "factual",
107
+ "us_stock": "factual", "macro_data": "factual",
108
+ "financial_news": "factual", "weather_query": "factual",
109
+ }
110
+ if domain and domain in _DOMAIN_INTENT:
111
+ return _DOMAIN_INTENT[domain]
112
+ return "factual" # 默认:查事实
113
+
114
+
115
+ # ── 外部反馈的撞车场景(回归锚)────────────────────────────────────────────
116
+
117
+ # 来自 GitHub Issue #34.1 与 v2.10.2 路由准确率收口的实测场景。
118
+ # 每条:(查询, 期望域, 期望意图类型, 反馈来源)
119
+ COLLISION_ANCHORS: list[tuple[str, str, str, str]] = [
120
+ # Issue #34.1:药靶点撞基因名
121
+ ("PD-1 抑制剂 2026 市场规模", "chinese_general", "factual", "Issue#34.1"),
122
+ ("重组胶原蛋白 医美 市场规模", "chinese_general", "factual", "Issue#34.1"),
123
+ ("PD-1 蛋白 结构域 序列", "protein_search", "factual", "Issue#34.1"),
124
+ # v2.10.2:原理 vs 论文
125
+ ("Transformer 模型 原理", "chinese_tech_deep", "content", "v2.10.2"),
126
+ ("Transformer 原理 论文", "academic", "academic", "v2.10.2"),
127
+ ("深度学习 原理", "chinese_tech_deep", "content", "v2.10.2"),
128
+ ("Attention 机制 详解", "chinese_general", "content", "v2.10.2"),
129
+ # v2.10.2:攻略 vs 舆情
130
+ ("小红书 露营 攻略", "chinese_general", "content", "v2.10.2"),
131
+ ("小红书 露营 舆情", "social", "sentiment", "v2.10.2"),
132
+ ("小红书 露营 评论", "social", "sentiment", "v2.10.2"),
133
+ # v2.10.2:技能目录
134
+ ("小红书 技能 排行榜", "redskill_search", "navigational", "v2.10.2"),
135
+ # v2.10.2:行情 vs 财报
136
+ ("贵州茅台股价", "stock_query", "factual", "v2.10.2"),
137
+ ("宁德时代 股价", "stock_query", "factual", "v2.10.2"),
138
+ # v2.10.2:学术检索正例
139
+ ("科研数据集 开放数据 下载", "dataset_search", "academic", "v2.10.2"),
140
+ ("google scholar 学术论文 期刊", "scholar_search", "academic", "v2.10.2"),
141
+ ]
142
+
143
+
144
+ def extend(entries: list[dict[str, Any]]) -> tuple[list[dict[str, Any]], dict[str, Any]]:
145
+ """给每条语料加 `intent` 字段,并追加撞车锚。"""
146
+ out: dict[str, dict[str, Any]] = {}
147
+ for e in entries:
148
+ q = e["query"]
149
+ e2 = dict(e)
150
+ e2["intent"] = classify_intent(q, e.get("expect_domain"))
151
+ out[q] = e2
152
+
153
+ # 追加撞车锚(不在语料里的才加,避免重复)
154
+ added = 0
155
+ for q, dom, intent, src in COLLISION_ANCHORS:
156
+ if q in out:
157
+ # 已存在:核对意图标签是否一致
158
+ if out[q].get("intent") != intent:
159
+ out[q]["intent"] = intent
160
+ out[q]["intent_source"] = src
161
+ continue
162
+ out[q] = {
163
+ "query": q,
164
+ "expect_domain": dom,
165
+ "expect_family": None,
166
+ "evidence": "feedback",
167
+ "quality": {"errors": False, "recovered": False,
168
+ "count": 0, "occurrences": 1},
169
+ "source": src,
170
+ "intent": intent,
171
+ "intent_source": src,
172
+ }
173
+ added += 1
174
+
175
+ result = [out[k] for k in sorted(out)]
176
+ stats = {
177
+ "total": len(result),
178
+ "added_anchors": added,
179
+ "by_intent": dict(Counter(e.get("intent") for e in result)),
180
+ "by_evidence": dict(Counter(e.get("evidence") for e in result)),
181
+ }
182
+ return result, stats
183
+
184
+
185
+ def _report(entries: list[dict[str, Any]]) -> None:
186
+ """打印撞车场景覆盖情况。"""
187
+ from route import route_query
188
+ from config import get_domains
189
+
190
+ live = {d.get("name") for d in get_domains()}
191
+ anchors = [e for e in entries if e.get("evidence") == "feedback"]
192
+ print(f"[extend_route_labels] 撞车锚 {len(anchors)} 条,逐条核验:")
193
+ ok = 0
194
+ for e in anchors:
195
+ try:
196
+ r = route_query(e["query"], mode="auto", depth="fast")
197
+ except Exception:
198
+ continue
199
+ got = r.get("domain")
200
+ want = e["expect_domain"]
201
+ hit = got == want and want in live
202
+ ok += hit
203
+ print(f" {'OK ' if hit else 'BAD'} {e['query'][:30]!r:34} "
204
+ f"want={want:20} got={got:20} intent={e.get('intent')}")
205
+ print(f"[extend_route_labels] 撞车锚命中 {ok}/{len(anchors)}")
206
+
207
+
208
+ def main() -> int:
209
+ ap = argparse.ArgumentParser(description="给路由语料加意图类型标签")
210
+ ap.add_argument("--dry-run", action="store_true")
211
+ ap.add_argument("--report", action="store_true", help="打印撞车锚覆盖")
212
+ args = ap.parse_args()
213
+
214
+ if not LABELS.is_file():
215
+ print(f"[extend_route_labels] 语料不存在:{LABELS}", file=sys.stderr)
216
+ return 1
217
+ entries = [json.loads(l) for l in
218
+ LABELS.read_text(encoding="utf-8").splitlines() if l.strip()]
219
+
220
+ extended, stats = extend(entries)
221
+ print(f"[extend_route_labels] 语料 {len(entries)} -> {stats['total']} 条"
222
+ f"(新增撞车锚 {stats['added_anchors']})")
223
+ print(f"[extend_route_labels] 意图分布: {stats['by_intent']}")
224
+ print(f"[extend_route_labels] 证据分档: {stats['by_evidence']}")
225
+
226
+ if args.report:
227
+ _report(extended)
228
+ if args.dry_run:
229
+ return 0
230
+
231
+ with LABELS.open("w", encoding="utf-8") as f:
232
+ for e in extended:
233
+ f.write(json.dumps(e, ensure_ascii=False) + "\n")
234
+ print(f"[extend_route_labels] 已写回 {LABELS}")
235
+ return 0
236
+
237
+
238
+ if __name__ == "__main__":
239
+ raise SystemExit(main())