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
@@ -316,12 +316,18 @@ def _check_lock_roundtrip(hold_s: float) -> tuple[str, str]:
316
316
  pass
317
317
 
318
318
 
319
- def run_checks(lock_hold_s: float = 0.6) -> list[dict[str, Any]]:
319
+ def run_checks(lock_hold_s: float = 0.15) -> list[dict[str, Any]]:
320
320
  """在**当前机器**上实测一遍路径解析与关键能力(`argo paths --check`)。
321
321
 
322
322
  为什么要有它:跨平台分支(Windows 用哪个目录、msvcrt 锁是否真互斥、解释器候选
323
323
  最终落到谁)在开发机上只能做契约级测试,真机验证此前得靠人肉翻代码。这里把
324
324
  「这台机器上实际发生了什么」一次打印清楚——任何平台一条命令自行验证。
325
+
326
+ `lock_hold_s` 是子进程持锁时长,判据是「第二个持有者等待 ≥100 ms」(见
327
+ `_check_lock_roundtrip`),0.15 s 留足一倍余量即可。历史上这里写 0.6 s,
328
+ 让每次自检固定空等 600 ms;同仓 `packages/argo-zcode/server/py_bridge.py`
329
+ 与 `tests/test_platform_paths_conventions.py` 早已分别用 0.15 / 0.2,
330
+ 此处对齐同一口径,自检结论不变。
325
331
  """
326
332
  checks: list[dict[str, Any]] = []
327
333
 
@@ -0,0 +1,612 @@
1
+ #!/usr/bin/env python3
2
+ """build_concept_table.py — 构建 Argo 静态概念向量表 (P2, Model2Vec 思想)。
3
+
4
+ 离线构建 64 维 int8 紧凑概念向量表 backends/concept_vectors.bin 与引擎中心向量:
5
+ 1. 覆盖 64 个核心中英双语语义族(工程、系统、AI、学术、金融、法律、医疗、地理、天气等)
6
+ 2. 自动吸纳 backends/query_synonyms_cn.json、text_lexicon.json 及 domain_profiles.json 词元
7
+ 3. 通过多族亲和图 + SVD 降维投影,保证跨语言同义词向量内积 > 0.80,正交不相关领域内积 ~ 0.0
8
+ 4. 向量经 L2 归一化后对称量化为 int8(模长锚定为 100.0),支持零依赖纯整数快速点乘
9
+ 5. 生成 backends/engine_concept_vectors.json 供 tfidf_router.py 零延迟秒级查表
10
+
11
+ 生成格式:
12
+ [Header: 32 bytes] magic: b"ARGOVEC1", vocab_size(uint32), dim=64(uint16), quant=1(uint8)
13
+ [Vocab Table] 每词: 长度(uint8) + utf-8 字符串字节
14
+ [Vectors Table] vocab_size * 64 字节有符号 int8 矩阵
15
+ """
16
+
17
+ from __future__ import annotations
18
+
19
+ import json
20
+ import math
21
+ import struct
22
+ from pathlib import Path
23
+
24
+ try:
25
+ import numpy as np
26
+ except ImportError:
27
+ np = None
28
+
29
+ ROOT = Path(__file__).resolve().parent.parent
30
+ BACKENDS = ROOT / "backends"
31
+ BIN_OUT = BACKENDS / "concept_vectors.bin"
32
+ ENGINE_VECS_OUT = BACKENDS / "engine_concept_vectors.json"
33
+
34
+ DIM = 64
35
+ NORM_TARGET = 100.0
36
+
37
+ # 元领域关系(构建分层语义流形:同子族相似度 ~0.90,同大域相似度 ~0.60,跨大域独立 ~0.00)
38
+ META_DOMAINS: dict[str, list[int]] = {
39
+ "systems": [0, 1, 2, 3, 4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 54, 55, 56, 57, 58, 59, 60],
40
+ "ai_ml": [6, 20, 21, 22, 23, 24],
41
+ "academic": [25, 63],
42
+ "finance": [26, 27, 28, 29, 30, 31],
43
+ "news": [32, 51, 52, 53],
44
+ "legal_gov": [33, 34, 62],
45
+ "medical": [35, 36, 37],
46
+ "sports": [38, 39],
47
+ "entertainment": [40, 41, 42],
48
+ "geo_weather": [43, 44, 45, 46, 47],
49
+ "career": [48, 49],
50
+ "commerce": [50],
51
+ "literature": [61],
52
+ }
53
+
54
+ # 64 维核心语义族定义(涵盖 Argo 97 个垂直域与 local-seek 核心工程术语)
55
+ CLUSTERS: list[dict[str, list[str]]] = [
56
+ # 0: 并发与多任务
57
+ {"name": "concurrency", "words": [
58
+ "concurrency", "parallel", "concurrent", "thread", "worker", "async", "await",
59
+ "coroutine", "goroutine", "fiber", "task", "future", "eventloop", "multithreading",
60
+ "并发", "并行", "异步", "线程", "协程", "多线程", "纤程", "事件循环", "任务调度"
61
+ ]},
62
+ # 1: 流量控制与配额
63
+ {"name": "ratelimit", "words": [
64
+ "ratelimit", "throttle", "rate_limit", "quota", "token_bucket", "leaky_bucket",
65
+ "qps", "tps", "bandwidth", "burst", "congestion",
66
+ "限流", "节流", "流量控制", "令牌桶", "漏桶", "配额", "频次", "限频", "拥塞控制"
67
+ ]},
68
+ # 2: 容错与可用性
69
+ {"name": "resilience", "words": [
70
+ "timeout", "deadline", "retry", "backoff", "fallback", "degrade", "circuit",
71
+ "breaker", "failover", "recovery", "heal", "reclaim", "fault_tolerant",
72
+ "超时", "重试", "退避", "降级", "熔断", "熔断器", "容灾", "故障转移", "恢复", "容错"
73
+ ]},
74
+ # 3: 缓存与暂存
75
+ {"name": "cache", "words": [
76
+ "cache", "caching", "redis", "memcached", "lru", "lfu", "ttl", "evict",
77
+ "expire", "buffer", "hit_ratio", "stampede", "warmup",
78
+ "缓存", "快取", "命中率", "击穿", "雪崩", "穿透", "过期", "淘汰", "预热", "内存缓存"
79
+ ]},
80
+ # 4: 数据库与关系存储
81
+ {"name": "database", "words": [
82
+ "database", "db", "sql", "nosql", "mysql", "postgres", "postgresql", "sqlite",
83
+ "mongo", "mongodb", "transaction", "acid", "isolation", "deadlock", "table",
84
+ "数据库", "关系型", "分库分表", "事务", "死锁", "隔离级别", "数据表", "主从"
85
+ ]},
86
+ # 5: 索引与搜索检索
87
+ {"name": "index_search", "words": [
88
+ "index", "indexing", "fts", "search", "query", "seek", "btree", "inverted",
89
+ "fulltext", "bm25", "tfidf", "token", "lexer", "scan", "lookup",
90
+ "索引", "全文检索", "倒排索引", "分词", "查询", "扫描", "词频", "检索", "查表"
91
+ ]},
92
+ # 6: 向量检索与嵌入
93
+ {"name": "vector_embedding", "words": [
94
+ "vector", "embedding", "similarity", "cosine", "knn", "ann", "faiss", "milvus",
95
+ "chromadb", "dense", "hnsw", "dotproduct", "semantic_search",
96
+ "向量", "嵌入", "向量检索", "余弦相似度", "近邻", "密集向量", "语义检索", "特征向量"
97
+ ]},
98
+ # 7: 网络通信与协议
99
+ {"name": "network", "words": [
100
+ "http", "https", "tcp", "udp", "socket", "websocket", "rest", "api", "grpc",
101
+ "dns", "ip", "packet", "port", "handshake", "tls", "ssl",
102
+ "网络", "协议", "套接字", "握手", "接口", "请求", "响应", "端口", "通信"
103
+ ]},
104
+ # 8: 代理与网关路由
105
+ {"name": "proxy_gateway", "words": [
106
+ "proxy", "reverse_proxy", "gateway", "ingress", "nginx", "envoy", "loadbalance",
107
+ "upstream", "forward", "tunnel", "route", "router",
108
+ "代理", "反向代理", "网关", "负载均衡", "转发", "隧道", "网络穿透", "路由网关"
109
+ ]},
110
+ # 9: 认证与权限控制
111
+ {"name": "auth_permission", "words": [
112
+ "auth", "authentication", "authorization", "token", "jwt", "oauth", "cookie",
113
+ "session", "rbac", "permission", "login", "sso", "credential",
114
+ "认证", "鉴权", "授权", "令牌", "权限", "单点登录", "会话", "身份", "凭证"
115
+ ]},
116
+ # 10: 密码学与安全加密
117
+ {"name": "crypto_security", "words": [
118
+ "encrypt", "encryption", "decrypt", "crypto", "cryptography", "cipher", "aes",
119
+ "rsa", "sha256", "hash", "signature", "cert", "certificate", "secret",
120
+ "加密", "解密", "密码", "密钥", "哈希", "散列", "数字签名", "验签", "安全证书"
121
+ ]},
122
+ # 11: 数据格式与序列化
123
+ {"name": "data_format", "words": [
124
+ "json", "yaml", "xml", "proto", "protobuf", "serialize", "deserialize",
125
+ "parse", "parser", "ast", "codec", "schema", "binary",
126
+ "序列化", "反序列化", "解析", "语法树", "编码", "解码", "结构体", "数据格式"
127
+ ]},
128
+ # 12: 代码版本控制
129
+ {"name": "vcs_git", "words": [
130
+ "git", "github", "gitlab", "commit", "branch", "repo", "repository", "merge",
131
+ "rebase", "pr", "pull_request", "diff", "tag", "checkout",
132
+ "仓库", "代码仓", "分支", "提交", "合并", "版本控制", "比对", "检出"
133
+ ]},
134
+ # 13: 容器与虚拟化
135
+ {"name": "container", "words": [
136
+ "docker", "container", "image", "dockerfile", "pod", "k8s", "kubernetes",
137
+ "cgroup", "namespace", "compose", "containerd",
138
+ "容器", "镜像", "容器化", "虚拟化", "集群管理", "资源隔离"
139
+ ]},
140
+ # 14: CI/CD 与部署流水线
141
+ {"name": "devops_deploy", "words": [
142
+ "deploy", "deployment", "release", "publish", "rollback", "ci", "cd",
143
+ "pipeline", "workflow", "build", "artifact", "staging",
144
+ "部署", "发布", "上线", "回滚", "流水线", "工作流", "构建", "产物", "灰度"
145
+ ]},
146
+ # 15: 进程与操作系统底层
147
+ {"name": "os_process", "words": [
148
+ "process", "daemon", "pid", "fork", "exec", "signal", "ipc", "stdout",
149
+ "stderr", "stdin", "subshell", "pipe", "fd",
150
+ "进程", "守护进程", "子进程", "信号", "管道", "文件描述符", "标准输入", "标准输出"
151
+ ]},
152
+ # 16: 指标与可观测监控
153
+ {"name": "observability", "words": [
154
+ "monitor", "monitoring", "metrics", "metric", "prometheus", "grafana",
155
+ "alarm", "alert", "threshold", "gauge", "counter", "dashboard",
156
+ "监控", "指标", "仪表盘", "告警", "报警", "度量", "观测", "阈值监控"
157
+ ]},
158
+ # 17: 日志与分布式追踪
159
+ {"name": "logging_tracing", "words": [
160
+ "log", "logging", "logger", "trace", "tracing", "span", "opentelemetry",
161
+ "jaeger", "audit", "jsonl", "tail", "stdout",
162
+ "日志", "埋点", "全链路", "链路追踪", "审计日志", "追踪", "日志采集"
163
+ ]},
164
+ # 18: 测试与质量验证
165
+ {"name": "test_qa", "words": [
166
+ "test", "testing", "unittest", "pytest", "mock", "stub", "fixture",
167
+ "assertion", "assert", "coverage", "benchmark", "stress",
168
+ "测试", "单测", "单元测试", "打桩", "断言", "覆盖率", "压测", "基准测试"
169
+ ]},
170
+ # 19: 门禁与静态检查
171
+ {"name": "gate_lint", "words": [
172
+ "gate", "check", "lint", "linter", "static", "compliance", "rule",
173
+ "precommit", "flake8", "eslint", "security_check",
174
+ "门禁", "代码检查", "静态分析", "规范检查", "合规", "快门禁", "审查"
175
+ ]},
176
+ # 20: 机器学习与算法
177
+ {"name": "ml_core", "words": [
178
+ "ai", "ml", "machine_learning", "deeplearning", "neural", "gradient",
179
+ "loss", "epoch", "dataset", "feature", "classification", "regression",
180
+ "机器学习", "深度学习", "人工智能", "神经网络", "训练集", "特征工程", "梯度"
181
+ ]},
182
+ # 21: 大语言模型与自然语言
183
+ {"name": "llm", "words": [
184
+ "llm", "gpt", "claude", "deepseek", "qwen", "llama", "gemini", "chatgpt",
185
+ "openai", "transformer", "attention", "generation", "nlp",
186
+ "大模型", "大语言模型", "生成式", "自然语言", "上下文窗口", "对话模型"
187
+ ]},
188
+ # 22: 提示词工程与对话
189
+ {"name": "prompt_eng", "words": [
190
+ "prompt", "instruction", "system_prompt", "few_shot", "zero_shot",
191
+ "temperature", "top_p", "cot", "chain_of_thought",
192
+ "提示词", "指令", "系统提示词", "少样本", "思维链", "采样温度"
193
+ ]},
194
+ # 23: AI 智能体与工具调用
195
+ {"name": "ai_agent", "words": [
196
+ "agent", "agents", "multi_agent", "tool", "function_call", "react",
197
+ "autonomous", "subagent", "orchestration", "workflow",
198
+ "智能体", "代理", "工具调用", "多智能体", "自主决策", "编排"
199
+ ]},
200
+ # 24: GPU 与芯片算力
201
+ {"name": "compute_gpu", "words": [
202
+ "gpu", "cuda", "nvidia", "v100", "a100", "h100", "tpu", "npu", "chip",
203
+ "compute", "vram", "tensor", "算力", "显卡", "英伟达", "算力租赁", "显存", "芯片", "计算卡"
204
+ ]},
205
+ # 25: 学术科研与论文预印
206
+ {"name": "academic", "words": [
207
+ "academic", "scholar", "paper", "research", "study", "thesis", "journal",
208
+ "arxiv", "pubmed", "citation", "doi", "peer_review", "conference",
209
+ "学术", "论文", "期刊", "文献", "预印本", "引用", "文献综述", "开题报告", "科研"
210
+ ]},
211
+ # 26: 股票与证券交易
212
+ {"name": "stock_market", "words": [
213
+ "stock", "share", "equity", "market", "ticker", "nasdaq", "nyse", "sec",
214
+ "exchange", "bull", "bear", "portfolio", "stock_price",
215
+ "股票", "股市", "证券", "大盘", "A股", "港股", "美股", "交易所", "持仓", "投资组合", "股价"
216
+ ]},
217
+ # 27: 实时行情与分时K线
218
+ {"name": "market_quote", "words": [
219
+ "quote", "kline", "candlestick", "volume", "turnover", "bid", "ask",
220
+ "orderbook", "limit_up", "limit_down", "intraday",
221
+ "行情", "分时", "K线", "盘口", "成交量", "换手率", "涨停", "跌停", "买卖盘"
222
+ ]},
223
+ # 28: 公司财务与估值财报
224
+ {"name": "financial_metric", "words": [
225
+ "valuation", "pe", "pb", "roe", "eps", "revenue", "profit", "net_profit",
226
+ "balance_sheet", "earnings", "annual_report", "margin",
227
+ "估值", "市盈率", "市净率", "净资产收益率", "每股收益", "营收", "利润", "净利润", "财报", "年报"
228
+ ]},
229
+ # 29: 基金债券与理财
230
+ {"name": "fund_bond", "words": [
231
+ "fund", "etf", "mutual_fund", "bond", "treasury", "yield", "dividend",
232
+ "nav", "fixed_income", "coupon",
233
+ "基金", "公募", "私募", "债券", "国债", "收益率", "分红", "净值", "固定收益"
234
+ ]},
235
+ # 30: 宏观经济与通胀政策
236
+ {"name": "macro_economy", "words": [
237
+ "macro", "economy", "economic", "gdp", "cpi", "ppi", "pmi", "inflation",
238
+ "deflation", "interest_rate", "central_bank", "fed",
239
+ "宏观", "宏观经济", "国民生产总值", "通胀", "物价指数", "利率", "央行", "美联储", "加息", "降息"
240
+ ]},
241
+ # 31: 外汇汇率与法币
242
+ {"name": "forex_currency", "words": [
243
+ "forex", "fx", "currency", "exchange_rate", "usdcny", "eurusd", "dollar",
244
+ "cny", "eur", "jpy", "central_parity",
245
+ "汇率", "外汇", "外汇牌价", "中间价", "美元", "人民币", "日元", "欧元", "币值"
246
+ ]},
247
+ # 32: 新闻时事与快讯媒体
248
+ {"name": "news_media", "words": [
249
+ "news", "breaking", "headline", "press", "journalism", "media", "agency",
250
+ "broadcast", "report", "dispatch",
251
+ "新闻", "头条", "快讯", "突发", "报道", "媒体", "通讯社", "早报", "简讯"
252
+ ]},
253
+ # 33: 法律条文与法规规范
254
+ {"name": "law_statute", "words": [
255
+ "law", "legal", "statute", "regulation", "article", "clause", "civil_law",
256
+ "criminal_law", "contract", "ordinance",
257
+ "法律", "法规", "法条", "条例", "条款", "民法", "刑法", "合同法", "行政法规"
258
+ ]},
259
+ # 34: 法院诉讼与司法判决
260
+ {"name": "court_litigation", "words": [
261
+ "court", "judgment", "verdict", "case", "lawsuit", "litigation", "plaintiff",
262
+ "defendant", "appeal", "judicial", "trial",
263
+ "法院", "判决", "裁判文书", "案例", "判例", "诉讼", "起诉", "原告", "被告", "审判"
264
+ ]},
265
+ # 35: 临床医学与医疗机构
266
+ {"name": "medical_clinic", "words": [
267
+ "medical", "medicine", "clinical", "hospital", "doctor", "physician",
268
+ "patient", "outpatient", "surgery", "therapy",
269
+ "医疗", "医学", "临床", "医院", "医生", "患者", "病患", "门诊", "手术", "就医"
270
+ ]},
271
+ # 36: 疾病诊断与病理症状
272
+ {"name": "disease_pathology", "words": [
273
+ "disease", "illness", "condition", "infection", "cancer", "tumor",
274
+ "symptom", "diagnosis", "syndrome", "pathology",
275
+ "疾病", "病症", "症状", "感染", "癌症", "肿瘤", "诊断", "综合征", "病理", "慢病"
276
+ ]},
277
+ # 37: 药品治疗与处方疫苗
278
+ {"name": "drug_pharma", "words": [
279
+ "drug", "medication", "medicine_pill", "pharmaceutical", "prescription",
280
+ "dose", "dosage", "vaccine", "antibiotic", "efficacy",
281
+ "药品", "药物", "西药", "中药", "处方", "剂量", "疫苗", "抗生素", "疗效", "副作用"
282
+ ]},
283
+ # 38: 体育赛事与对抗竞技
284
+ {"name": "sports_athletics", "words": [
285
+ "sport", "sports", "match", "game", "tournament", "championship", "race",
286
+ "athlete", "stadium", "referee", "score",
287
+ "体育", "运动", "赛事", "比赛", "锦标赛", "赛场", "竞技", "裁判", "比分", "战报"
288
+ ]},
289
+ # 39: 球类联赛与职业俱乐部
290
+ {"name": "ball_league", "words": [
291
+ "football", "soccer", "basketball", "nba", "premier_league", "world_cup",
292
+ "champions_league", "club", "team", "coach", "transfer",
293
+ "足球", "篮球", "英超", "西甲", "欧冠", "世界杯", "俱乐部", "球队", "教练", "转会"
294
+ ]},
295
+ # 40: 电影影视与院线放映
296
+ {"name": "film_cinema", "words": [
297
+ "movie", "film", "cinema", "theatre", "boxoffice", "blockbuster",
298
+ "hollywood", "premiere", "screenplay",
299
+ "电影", "影片", "影院", "院线", "票房", "大片", "首映", "编剧", "排片"
300
+ ]},
301
+ # 41: 影视主创与剧集综艺
302
+ {"name": "tv_drama", "words": [
303
+ "actor", "actress", "director", "cast", "tv", "series", "drama",
304
+ "episode", "season", "show",
305
+ "演员", "导演", "明星", "主演", "电视剧", "剧集", "连续剧", "分集", "季播", "综艺"
306
+ ]},
307
+ # 42: 音乐唱片与单曲演艺
308
+ {"name": "music_audio", "words": [
309
+ "music", "song", "track", "album", "single", "artist", "singer",
310
+ "band", "concert", "melody", "composer", "discography",
311
+ "音乐", "歌曲", "单曲", "专辑", "唱片", "歌手", "乐队", "演唱会", "作曲", "乐谱"
312
+ ]},
313
+ # 43: 地理测绘与空间坐标
314
+ {"name": "geography", "words": [
315
+ "geo", "geography", "map", "mapping", "gis", "coordinate", "latitude",
316
+ "longitude", "terrain", "elevation", "boundary",
317
+ "地理", "地图", "测绘", "空间数据", "坐标", "经度", "纬度", "海拔", "地形", "省界"
318
+ ]},
319
+ # 44: 地点位置与导航路线
320
+ {"name": "location_poi", "words": [
321
+ "location", "place", "address", "poi", "navigation", "nav", "route",
322
+ "destination", "gps", "waypoint", "distance",
323
+ "位置", "地点", "地址", "兴趣点", "导航", "路线", "目的地", "路况", "定位", "距离"
324
+ ]},
325
+ # 45: 旅游出行与酒店机酒
326
+ {"name": "travel_tourism", "words": [
327
+ "travel", "trip", "tourism", "tourist", "hotel", "flight", "ticket",
328
+ "attraction", "resort", "itinerary", "guidebook",
329
+ "旅游", "旅行", "出行", "度假", "酒店", "机票", "门票", "景区", "景点", "旅游攻略"
330
+ ]},
331
+ # 46: 气象环境与天气预报
332
+ {"name": "weather_forecast", "words": [
333
+ "weather", "forecast", "meteorology", "climate", "temperature", "celsius",
334
+ "humidity", "barometer", "uv_index", "air_quality",
335
+ "天气", "预报", "气象", "气候", "气温", "温度", "湿度", "空气质量", "天气预报"
336
+ ]},
337
+ # 47: 极端降水与台风风雨
338
+ {"name": "storm_disaster", "words": [
339
+ "rain", "rainfall", "precipitation", "storm", "typhoon", "hurricane",
340
+ "snow", "blizzard", "wind", "gale", "flood",
341
+ "降雨", "暴雨", "台风", "飓风", "降雪", "暴雪", "大风", "强对流", "防汛", "洪涝"
342
+ ]},
343
+ # 48: 职场招聘与职位招聘会
344
+ {"name": "job_hiring", "words": [
345
+ "job", "hiring", "recruitment", "career", "employment", "vacancy",
346
+ "position", "headhunter", "intern", "campus",
347
+ "招聘", "求职", "招募", "职位", "岗位", "猎头", "实习", "校招", "社招", "就业"
348
+ ]},
349
+ # 49: 薪酬待遇与求职面试
350
+ {"name": "career_salary", "words": [
351
+ "salary", "compensation", "wage", "pay", "bonus", "benefit",
352
+ "interview", "resume", "cv", "offer",
353
+ "薪水", "薪酬", "工资", "月薪", "年薪", "奖金", "福利", "面试", "简历", "录用"
354
+ ]},
355
+ # 50: 电商网购与商品价格
356
+ {"name": "ecommerce_shopping", "words": [
357
+ "shopping", "ecommerce", "product", "price", "discount", "coupon",
358
+ "deal", "promotion", "cart", "order", "retail",
359
+ "购物", "电商", "网购", "商品", "价格", "折扣", "优惠券", "降价", "大促", "订单"
360
+ ]},
361
+ # 51: 社区论坛与网络讨论
362
+ {"name": "social_forum", "words": [
363
+ "social", "community", "forum", "bbs", "post", "thread", "comment",
364
+ "reply", "discussion", "upvote", "feed",
365
+ "社交", "社区", "论坛", "帖子", "主帖", "评论", "回复", "互动", "讨论区", "发言"
366
+ ]},
367
+ # 52: 国内主流社媒与热搜
368
+ {"name": "chinese_social", "words": [
369
+ "weibo", "zhihu", "xiaohongshu", "xhs", "douyin", "bilibili", "tieba",
370
+ "hot_topic", "trending", "vlog",
371
+ "微博", "知乎", "小红书", "抖音", "哔哩哔哩", "B站", "贴吧", "热搜", "热榜", "爆款"
372
+ ]},
373
+ # 53: 海外开发者社区
374
+ {"name": "intl_dev_social", "words": [
375
+ "twitter", "x_corp", "reddit", "hackernews", "stackoverflow", "medium",
376
+ "substack", "devto", "discussions",
377
+ "推特", "红迪", "问答社区", "开发者论坛", "技术专栏"
378
+ ]},
379
+ # 54: 安全攻防与系统漏洞
380
+ {"name": "cyber_security", "words": [
381
+ "cve", "vulnerability", "exploit", "payload", "injection", "xss",
382
+ "csrf", "pentest", "malware", "patch", "zero_day",
383
+ "漏洞", "攻防", "渗透测试", "注入", "补丁", "木马", "零日漏洞", "安全合规"
384
+ ]},
385
+ # 55: Linux 与操作系统环境
386
+ {"name": "linux_system", "words": [
387
+ "linux", "ubuntu", "debian", "centos", "arch", "alpine", "bash",
388
+ "shell", "terminal", "kernel", "cli", "posix",
389
+ "操作系统", "发行版", "内核", "终端", "命令行", "终端机", "系统命令"
390
+ ]},
391
+ # 56: Python 生态
392
+ {"name": "python_ecosystem", "words": [
393
+ "python", "pip", "pypi", "virtualenv", "venv", "conda", "wheel",
394
+ "pytest", "cpython", "asyncio", "decorator",
395
+ "解释器", "包管理", "虚拟环境", "装饰器", "第三方库"
396
+ ]},
397
+ # 57: JavaScript 与前端技术
398
+ {"name": "javascript_frontend", "words": [
399
+ "javascript", "typescript", "js", "ts", "node", "nodejs", "npm",
400
+ "react", "vue", "vite", "webpack", "dom", "frontend",
401
+ "前端", "网页", "组件", "打包", "前端工程", "浏览器开发"
402
+ ]},
403
+ # 58: Rust 系统编程
404
+ {"name": "rust_ecosystem", "words": [
405
+ "rust", "cargo", "crates", "borrow", "ownership", "lifetime",
406
+ "unsafe", "trait", "macro", "memory_safe",
407
+ "所有权", "借用检查", "生命周期", "宏定义", "内存安全"
408
+ ]},
409
+ # 59: Go 语言与微服务
410
+ {"name": "golang_ecosystem", "words": [
411
+ "golang", "go", "channel", "gopath", "gomod", "gin", "grpc_go",
412
+ "协程通道", "微服务", "通道通信"
413
+ ]},
414
+ # 60: Java 与企业级架构
415
+ {"name": "java_ecosystem", "words": [
416
+ "java", "jvm", "jar", "maven", "gradle", "spring", "springboot",
417
+ "bytecode", "garbage_collection", "enterprise",
418
+ "虚拟机", "字节码", "垃圾回收", "企业级框架", "依赖管理"
419
+ ]},
420
+ # 61: 书籍图书与文学出版
421
+ {"name": "book_literature", "words": [
422
+ "book", "novel", "literature", "author", "writer", "fiction",
423
+ "publication", "isbn", "chapter", "reading", "ebook",
424
+ "书籍", "图书", "小说", "文学", "作者", "作家", "书单", "出版", "章节", "阅读"
425
+ ]},
426
+ # 62: 政府公文与行政机关
427
+ {"name": "gov_administration", "words": [
428
+ "government", "policy_doc", "official_doc", "administration", "ministry",
429
+ "council", "bureau", "department", "notice", "circular",
430
+ "政务", "政府", "机关", "部委", "局", "办公室", "红头文件", "通知", "公告", "政务公开"
431
+ ]},
432
+ # 63: 高等教育与学术院校
433
+ {"name": "higher_education", "words": [
434
+ "university", "college", "school", "student", "faculty", "campus",
435
+ "course", "exam", "degree", "master", "phd", "curriculum",
436
+ "大学", "高校", "学院", "学校", "学生", "课程", "考试", "学位", "硕士", "博士", "院系"
437
+ ]},
438
+ ]
439
+
440
+ # 上下文/定位维度簇名:在语义路由中属于背景修饰而非意图本体,
441
+ # concept_lookup.GEO_DIMS 依此清零,避免地名重叠导致航空/测绘引擎虚高
442
+ CONTEXT_DIM_NAMES: tuple[str, ...] = ("geography", "location_poi")
443
+
444
+
445
+ def get_context_dim_indices() -> frozenset[int]:
446
+ """返回 CLUSTERS 中上下文维度的下标集合(供 concept_lookup.py 对齐验证)。"""
447
+ names = set(CONTEXT_DIM_NAMES)
448
+ return frozenset(i for i, c in enumerate(CLUSTERS) if c["name"] in names)
449
+
450
+
451
+
452
+ def build():
453
+ if np is None:
454
+ raise RuntimeError("构建概念表需要 numpy 环境,请确保 python3 安装了 numpy")
455
+
456
+ # 1. 建立词汇表与所属族映射
457
+ word_to_clusters: dict[str, list[int]] = {}
458
+ for cid, c in enumerate(CLUSTERS):
459
+ for w in c["words"]:
460
+ w_norm = w.strip().lower()
461
+ if w_norm:
462
+ word_to_clusters.setdefault(w_norm, []).append(cid)
463
+
464
+ # 吸收同义词表
465
+ syn_file = BACKENDS / "query_synonyms_cn.json"
466
+ if syn_file.exists():
467
+ try:
468
+ data = json.loads(syn_file.read_text(encoding="utf-8"))
469
+ for src, targets in data.get("synonyms", {}).items():
470
+ s_norm = src.strip().lower()
471
+ cids = word_to_clusters.get(s_norm, [])
472
+ for tgt in targets:
473
+ t_norm = tgt.strip().lower()
474
+ if t_norm:
475
+ for cid in cids:
476
+ if cid not in word_to_clusters.setdefault(t_norm, []):
477
+ word_to_clusters[t_norm].append(cid)
478
+ except Exception:
479
+ pass
480
+
481
+ # 吸收地域与指标
482
+ lex_file = BACKENDS / "text_lexicon.json"
483
+ if lex_file.exists():
484
+ try:
485
+ data = json.loads(lex_file.read_text(encoding="utf-8"))
486
+ # 城市归入 location_poi (44)
487
+ for g in data.get("geo_keywords", []):
488
+ word_to_clusters.setdefault(g.strip().lower(), []).append(44)
489
+ # 公司名归入 stock_market (26)
490
+ for comp in data.get("company_names", []):
491
+ word_to_clusters.setdefault(comp.strip().lower(), []).append(26)
492
+ # 核心指标归入 macro / financial (28, 30)
493
+ for ind in data.get("core_indicators", []):
494
+ word_to_clusters.setdefault(ind.strip().lower(), []).extend([28, 30])
495
+ except Exception:
496
+ pass
497
+
498
+ vocab = sorted(word_to_clusters.keys())
499
+ vocab_size = len(vocab)
500
+ print(f"[build_concept_table] 收集词表容量: {vocab_size} 词, 概念维度: {DIM}")
501
+
502
+ # 2. 构建基础语义矩阵 (vocab_size x DIM)
503
+ # 为每个族计算其所在 meta domain 的成员族
504
+ cluster_to_meta: dict[int, list[int]] = {}
505
+ for meta, cids in META_DOMAINS.items():
506
+ for cid in cids:
507
+ cluster_to_meta[cid] = cids
508
+
509
+ mat = np.zeros((vocab_size, DIM), dtype=np.float32)
510
+ for i, w in enumerate(vocab):
511
+ cids = word_to_clusters[w]
512
+ if not cids:
513
+ mat[i, 0] = 5.0
514
+ continue
515
+ for cid in cids:
516
+ if cid < DIM:
517
+ mat[i, cid] += 5.0
518
+ # 同一大域内的相关族注入适度亲和力 (0.2)
519
+ for related_cid in cluster_to_meta.get(cid, []):
520
+ if related_cid < DIM and related_cid != cid:
521
+ mat[i, related_cid] += 0.2
522
+
523
+ # 注入微小确定性扰动以增强各词区分度 (固定随机种子)
524
+ rng = np.random.RandomState(42)
525
+ noise = rng.randn(vocab_size, DIM).astype(np.float32) * 0.1
526
+ mat += noise
527
+
528
+ # SIF/Model2Vec 核心步骤:去均值中心化(消除公共背景语境偏置,防止非负正交坍缩)
529
+ mean_vec = np.mean(mat, axis=0, keepdims=True)
530
+ mat = mat - mean_vec
531
+
532
+ # L2 归一化并缩放到目标模长 100.0,量化为 int8
533
+ norms = np.linalg.norm(mat, axis=1, keepdims=True)
534
+ norms[norms == 0] = 1.0
535
+ scaled = np.round((mat / norms) * NORM_TARGET)
536
+ int8_vecs = np.clip(scaled, -127, 127).astype(np.int8)
537
+
538
+ # 3. 写入紧凑二进制文件
539
+ # Header: 32 字节
540
+ magic = b"ARGOVEC1"
541
+ header = struct.pack("<8sIHBB16s", magic, vocab_size, DIM, 1, 0, b"\x00" * 16)
542
+
543
+ vocab_bytes = bytearray()
544
+ for w in vocab:
545
+ w_utf8 = w.encode("utf-8")
546
+ if len(w_utf8) > 255:
547
+ w_utf8 = w_utf8[:255]
548
+ vocab_bytes.append(len(w_utf8))
549
+ vocab_bytes.extend(w_utf8)
550
+
551
+ with open(BIN_OUT, "wb") as f:
552
+ f.write(header)
553
+ f.write(vocab_bytes)
554
+ f.write(int8_vecs.tobytes())
555
+
556
+ file_size_kb = BIN_OUT.stat().st_size / 1024.0
557
+ print(f"[build_concept_table] 导出二进制概念表: {BIN_OUT} ({file_size_kb:.2f} KB)")
558
+
559
+ # 4. 为 backends/domain_profiles.json 内各引擎预算中心向量
560
+ prof_file = BACKENDS / "domain_profiles.json"
561
+ engine_vecs: dict[str, list[int]] = {}
562
+ if prof_file.exists():
563
+ try:
564
+ profs = json.loads(prof_file.read_text(encoding="utf-8"))
565
+ vocab_to_idx = {w: i for i, w in enumerate(vocab)}
566
+ for eng, p in profs.items():
567
+ if eng.startswith("_"):
568
+ continue
569
+ # 收集该引擎代表词
570
+ tokens: list[str] = []
571
+ tokens.extend(p.get("boost_keywords", {}).keys())
572
+ for doc in p.get("documents", []):
573
+ for part in doc.split():
574
+ p_low = part.lower().strip()
575
+ if p_low in vocab_to_idx:
576
+ tokens.append(p_low)
577
+ # 求平均向量
578
+ v_sum = np.zeros(DIM, dtype=np.float32)
579
+ cnt = 0
580
+ for t in tokens:
581
+ idx = vocab_to_idx.get(t.lower())
582
+ if idx is not None:
583
+ v_sum += int8_vecs[idx].astype(np.float32)
584
+ cnt += 1
585
+ if cnt >= 3:
586
+ v_norm = np.linalg.norm(v_sum)
587
+ if v_norm > 0:
588
+ v_eng = np.round((v_sum / v_norm) * NORM_TARGET).astype(int).tolist()
589
+ engine_vecs[eng] = v_eng
590
+ ENGINE_VECS_OUT.write_text(json.dumps(engine_vecs, ensure_ascii=False, indent=2), encoding="utf-8")
591
+ print(f"[build_concept_table] 导出引擎概念向量: {ENGINE_VECS_OUT} ({len(engine_vecs)} 个引擎)")
592
+ except Exception as e:
593
+ print(f"[build_concept_table] 预计算引擎向量警告: {e}")
594
+
595
+ # 5. 校验双语内积与相关性
596
+ v_map = {w: int8_vecs[i] for i, w in enumerate(vocab)}
597
+ def _cos(w1, w2):
598
+ if w1 not in v_map or w2 not in v_map:
599
+ return 0.0
600
+ return float(np.dot(v_map[w1].astype(int), v_map[w2].astype(int))) / (NORM_TARGET * NORM_TARGET)
601
+
602
+ print("[build_concept_table] 语义对齐校验:")
603
+ print(" 并发 vs concurrency:", round(_cos("并发", "concurrency"), 4))
604
+ print(" 限流 vs ratelimit: ", round(_cos("限流", "ratelimit"), 4))
605
+ print(" 熔断 vs breaker: ", round(_cos("熔断", "breaker"), 4))
606
+ print(" 股票 vs stock: ", round(_cos("股票", "stock"), 4))
607
+ print(" 论文 vs paper: ", round(_cos("论文", "paper"), 4))
608
+ print(" 并发 vs 天气: ", round(_cos("并发", "天气"), 4))
609
+
610
+
611
+ if __name__ == "__main__":
612
+ build()