argo-search 2.9.9 → 2.10.1
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.
- package/README.en.md +39 -22
- package/README.es.md +39 -22
- package/README.ja.md +38 -21
- package/README.ko.md +38 -21
- package/README.md +41 -22
- package/SKILL.md +13 -12
- package/backends/domain_profiles.json +76 -0
- package/backends/engine_registry.yaml +163 -7
- package/backends/quota_profiles.json +122 -2
- package/backends/source_types_cn.json +9 -0
- package/bin/argo +22 -1
- package/bin/argo.js +3 -3
- package/config.yaml +150 -30
- package/docs/ARGO_INTRO.md +4 -4
- package/docs/ENGINE_CATALOG.md +68 -48
- package/docs/MCP_SETUP.md +1 -1
- package/docs/RELEASE_NOTES_v2.10.0.md +85 -0
- package/docs/RELEASE_NOTES_v2.10.1.md +57 -0
- package/docs/RELEASE_NOTES_v2.9.8.md +1 -1
- package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +9 -9
- package/engines/_template_http.yaml +2 -0
- package/engines/specs/clawhub.yaml +16 -15
- package/engines/specs/deepseek1024.yaml +46 -0
- package/engines/specs/dsh_hub.yaml +44 -0
- package/engines/specs/dshopen.yaml +32 -0
- package/engines/specs/explainx.yaml +32 -0
- package/engines/specs/gbfs_nyc.yaml +6 -1
- package/engines/specs/metaso_doc.yaml +49 -0
- package/engines/specs/metaso_image.yaml +65 -0
- package/engines/specs/metaso_podcast.yaml +60 -0
- package/engines/specs/metaso_scholar.yaml +57 -0
- package/engines/specs/metaso_video.yaml +62 -0
- package/engines/specs/ncpssd.yaml +44 -0
- package/engines/specs/sciverse.yaml +73 -0
- package/engines/specs/skills_sh.yaml +32 -0
- package/engines/specs/skillsmp.yaml +18 -16
- package/package.json +4 -2
- package/packages/dsh-plugin/README.md +3 -2
- package/packages/dsh-plugin/package.json +1 -1
- package/packages/dsh-plugin/test/size-gate.test.js +113 -0
- package/scripts/adaptive.py +41 -14
- package/scripts/article.py +6 -1
- package/scripts/article_meta.py +151 -2
- package/scripts/bench_general_pool.py +145 -0
- package/scripts/candidate_envelope.py +45 -4
- package/scripts/charset_decode.py +127 -0
- package/scripts/ci_drift_gate.py +47 -24
- package/scripts/crawl.py +240 -74
- package/scripts/crawl_frontier.py +217 -0
- package/scripts/crawl_policy.py +174 -0
- package/scripts/engine_dispatch.py +23 -18
- package/scripts/engine_failure.py +15 -0
- package/scripts/engine_status.py +12 -5
- package/scripts/engine_validate.py +8 -0
- package/scripts/engines.py +15 -0
- package/scripts/engines_base.py +43 -15
- package/scripts/engines_builders.py +14 -0
- package/scripts/engines_builders_data.py +10 -3
- package/scripts/engines_builders_dsh.py +330 -0
- package/scripts/engines_builders_skill.py +314 -0
- package/scripts/evidence.py +26 -5
- package/scripts/fetch_v3.py +37 -5
- package/scripts/gen_engine_catalog.py +218 -2
- package/scripts/general_pool.py +162 -0
- package/scripts/http_client.py +38 -42
- package/scripts/image_ops.py +4 -0
- package/scripts/install.ps1 +47 -19
- package/scripts/install.sh +45 -20
- package/scripts/local_seek.py +53 -11
- package/scripts/matrix_search_eval.py +17 -1
- package/scripts/mcp_transport.py +1 -1
- package/scripts/ncpssd_bridge.py +123 -0
- package/scripts/paid_policy.py +109 -13
- package/scripts/pre-commit +19 -4
- package/scripts/query_signals.py +156 -3
- package/scripts/redskill/redskill_engine.py +29 -2
- package/scripts/release.py +398 -0
- package/scripts/release_check.py +209 -0
- package/scripts/retry_policy.py +22 -1
- package/scripts/robots_guard.py +26 -0
- package/scripts/route.py +11 -8
- package/scripts/route_cache.py +6 -0
- package/scripts/route_combo.py +37 -59
- package/scripts/route_domains.py +22 -3
- package/scripts/route_policy.py +6 -0
- package/scripts/search.py +13 -3
- package/scripts/search_cli.py +49 -0
- package/scripts/search_entry.py +9 -0
- package/scripts/search_output.py +43 -0
- package/scripts/search_pipeline.py +43 -3
- package/scripts/search_rank.py +4 -1
- package/scripts/serp_guard.py +11 -0
- package/scripts/social_engines/bilibili_engine.py +163 -26
- package/scripts/social_engines/reddit_engine.py +52 -51
- package/scripts/source_selection.py +302 -0
- package/scripts/url_canon.py +2 -1
- package/scripts/video_fetch.py +303 -0
- package/scripts/video_meta.py +225 -0
- package/scripts/video_route.py +65 -0
- package/scripts/watch.py +123 -0
- package/sub-skills/local-seek/scripts/seek.py +19 -4
- package/engines/specs/_cisa_kev.yaml +0 -54
- package/engines/specs/_osv.yaml +0 -63
- package/scripts/local_engines.py +0 -321
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""source_selection.py — 通用层候选源的统一排序。
|
|
3
|
+
|
|
4
|
+
## 为什么(2026-10-26)
|
|
5
|
+
|
|
6
|
+
通用 fallback 此前是 `engine_policy.GENERAL_FREE_FALLBACK` 的静态元组,
|
|
7
|
+
再由 `filter_combo_by_policy` 按**位置**截断到前 2 位。实测后果:
|
|
8
|
+
|
|
9
|
+
· 第一、二位是 octen(余额不足,403)与 anysearch(p50 1.7s),
|
|
10
|
+
3015 条真实查询里 44.5% 最终由 anysearch 参与交付;
|
|
11
|
+
· 实测 0.8–1.3s、词面质量更高的 tavily_free / parallel_free / firecrawl
|
|
12
|
+
排在第 6–8 位,日常预算截断后**永远不可达**;
|
|
13
|
+
· 学习器算了 engine×domain×lang 的分,但通用路径不读它,
|
|
14
|
+
「这个源在我这里已经坏了」进不了选源。
|
|
15
|
+
|
|
16
|
+
本模块只做**排序**,不做过滤(quota/熔断/语言仍由既有层处理)。过滤放在
|
|
17
|
+
这里会让「为什么这个源没出现」多一个隐藏分支;排序只回答「同样可用时
|
|
18
|
+
先试谁」。
|
|
19
|
+
|
|
20
|
+
## 先验的来源
|
|
21
|
+
|
|
22
|
+
`GENERAL_PRIORS` 是 2026-10-26 单机实测的固定先验(4–6 条真实查询 ×
|
|
23
|
+
单引擎单跑;复跑入口 `python3 scripts/bench_general_pool.py`,脚本会用
|
|
24
|
+
隔离状态目录交错跑 static/dynamic 两臂)。它是**冷启动种子**,不是长期
|
|
25
|
+
真值:源一旦有 ≥3 条自适应样本,自适应分占 6 成、先验占 4 成。重测后用
|
|
26
|
+
新数据更新此表,不要按印象调。
|
|
27
|
+
|
|
28
|
+
## 覆盖地板与语言门(2026-10-27,issue #23)
|
|
29
|
+
|
|
30
|
+
只按「快 + 词面」排序会选出交付很薄的源,或与查询语言错配的源(英文
|
|
31
|
+
查询由中文语料源领跑,5 条结果全是中文长摘要,体积翻倍且相关性不对)。
|
|
32
|
+
现在排序先分层、层内再比分数:
|
|
33
|
+
|
|
34
|
+
0 合格:覆盖率 ≥ COVERAGE_FLOOR(3 条)且语言适配;
|
|
35
|
+
1 语言错配:声明了 chinese 却拿来跑英文查询(或反之);
|
|
36
|
+
2 交付太薄:实测平均交付 < 3 条(如 tavily_free 的匿名通道常态 2 条)。
|
|
37
|
+
|
|
38
|
+
层级是**先验数据**决定的硬约束,不参与自适应混合——自适应分学习的是
|
|
39
|
+
「这个源好不好」,回答不了「它能不能交够数」。非中英脚本不参与分层
|
|
40
|
+
(语言覆盖源本身就是唯一召回,见 _NON_LATIN_LANG_BOOST)。
|
|
41
|
+
"""
|
|
42
|
+
|
|
43
|
+
from __future__ import annotations
|
|
44
|
+
|
|
45
|
+
from typing import Callable
|
|
46
|
+
|
|
47
|
+
# 先验 = 实测延迟 + 词面相关 + 稳定性的人工压缩(0–1)。只列通用候选;
|
|
48
|
+
# 未列出的源给 DEFAULT_PRIOR,不会凭名字占便宜。
|
|
49
|
+
GENERAL_PRIORS: dict[str, float] = {
|
|
50
|
+
# 0.6s / 0.76(6 条),中文硬新闻弱于 anysearch
|
|
51
|
+
"yuanbao": 1.00,
|
|
52
|
+
# 1.0s / 0.92(4 条),免 key 匿名通道
|
|
53
|
+
"tavily_free": 0.98,
|
|
54
|
+
# 1.1s / 0.92(4 条)
|
|
55
|
+
"parallel_free": 0.96,
|
|
56
|
+
# 1.3s / 0.88(4 条),1000 credits/月,配额层会限
|
|
57
|
+
"firecrawl": 0.90,
|
|
58
|
+
# 2.7s / 0.78(6 条),中文新闻与长尾覆盖最强,慢
|
|
59
|
+
"anysearch": 0.86,
|
|
60
|
+
# 0.4s,英文技术/国际新闻强,中文通用弱;官方 API 带 authority/date。
|
|
61
|
+
# 付费,预算内才进池,fast/budget 永不进(见 _paid_candidate_allowed)。
|
|
62
|
+
"deepseek_search": 0.84,
|
|
63
|
+
# 2.3s / 0.89(4 条),慢但内容扎实,研究档应提权
|
|
64
|
+
"uapi": 0.72,
|
|
65
|
+
# 2.5s / 0.60(5 条),语义泛化,作最后备选
|
|
66
|
+
"local_bing": 0.62,
|
|
67
|
+
# 实测 4/4 零结果或不是通用搜索源:留在池里只作解释,排序垫底
|
|
68
|
+
"local_baidu": 0.10,
|
|
69
|
+
"wikipedia": 0.10,
|
|
70
|
+
"octen": 0.10,
|
|
71
|
+
}
|
|
72
|
+
DEFAULT_PRIOR = 0.50
|
|
73
|
+
|
|
74
|
+
# 允许进入通用池的付费候选。与 paid_policy 的域级对冲是两条不同的路:
|
|
75
|
+
# 域级对冲只在 english_tech / intl_news_flash 的第二位;这里是通用池的
|
|
76
|
+
# 第 3+ 候选(日常预算截断到 2 时通常轮不到,研究档不截断才参与)。
|
|
77
|
+
# fast/budget 永不进;ARGO_PAID_SEARCH=off 或预算耗尽也不进。
|
|
78
|
+
PAID_GENERAL_CANDIDATES = frozenset({"deepseek_search"})
|
|
79
|
+
|
|
80
|
+
# ─── 交付覆盖(2026-10-27 单引擎单跑实测)──────────────────────────────────
|
|
81
|
+
#
|
|
82
|
+
# 排序只看「快 + 词面」会选出交付很薄的源:2026-10-27 nightly(issue #23)
|
|
83
|
+
# 里无 key 环境的领队 tavily_free 对 Alan Turing 只交 2 条(基线 5 条)。
|
|
84
|
+
# 覆盖地板让这种源顺延给交付够数的源,而不是靠早停后才发现「怎么只有两条」。
|
|
85
|
+
#
|
|
86
|
+
# 数据来源:同一条查询 `Alan Turing` 单引擎单跑(--no-cache,agent 档)。
|
|
87
|
+
# 未列出的源给 COVERAGE_FLOOR 中性值——缺数据不惩罚,交给自适应分兜底。
|
|
88
|
+
GENERAL_COVERAGE: dict[str, float] = {
|
|
89
|
+
"yuanbao": 5.0, # 5 条,但全是中文长摘要(见 GENERAL_BYTES 与语言门)
|
|
90
|
+
"tavily_free": 2.0, # 2 条:匿名通道交付薄,不能当领队
|
|
91
|
+
"parallel_free": 5.0,
|
|
92
|
+
"anysearch": 5.0,
|
|
93
|
+
"deepseek_search": 5.0,
|
|
94
|
+
"local_bing": 2.0, # 单点实测 0 条,历史口径也不高;给保守值
|
|
95
|
+
}
|
|
96
|
+
COVERAGE_FLOOR = 3.0
|
|
97
|
+
|
|
98
|
+
# agent 档 5 条结果的平均字节(同日实测)。**不参与排序**,只做监控报表与
|
|
99
|
+
# bench 对照:把它折进分数需要凭空定一个「每 KB 折多少毫秒」的系数,而中文
|
|
100
|
+
# 查询的长摘要(yuanbao 12.5KB)恰恰是分析场景要的上下文——体积该由 drift
|
|
101
|
+
# 门禁守,不该让排序替用户做取舍。英文查询的体积问题由语言门解决。
|
|
102
|
+
GENERAL_BYTES: dict[str, int] = {
|
|
103
|
+
"yuanbao": 12508,
|
|
104
|
+
"tavily_free": 3993,
|
|
105
|
+
"parallel_free": 6790,
|
|
106
|
+
"anysearch": 5859,
|
|
107
|
+
"deepseek_search": 7064,
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
# 语言与源声明的适配:只对中文/英文查询生效。zh 查询不让「只声明 english」
|
|
111
|
+
# 的源领跑,en 查询不让「只声明 chinese」的源领跑;没声明语言的源(anysearch
|
|
112
|
+
# 的 general/tech)保持中性。声明真源是 config 引擎字典(sync_backends 从
|
|
113
|
+
# spec 派生),读不到时不判(fail-open)——缺数据不等于不适配。
|
|
114
|
+
_LANG_PAIR = {"zh": ("chinese", "english"), "en": ("english", "chinese")}
|
|
115
|
+
_COVERAGE_CACHE: dict[str, tuple[str, ...]] | None = None
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def _coverage_of(engine: str) -> tuple[str, ...]:
|
|
119
|
+
global _COVERAGE_CACHE
|
|
120
|
+
if _COVERAGE_CACHE is None:
|
|
121
|
+
try:
|
|
122
|
+
from config import load_config
|
|
123
|
+
engines = load_config().get("engines") or {}
|
|
124
|
+
_COVERAGE_CACHE = {
|
|
125
|
+
str(name): tuple((meta or {}).get("coverage") or ())
|
|
126
|
+
for name, meta in engines.items() if isinstance(meta, dict)}
|
|
127
|
+
except Exception:
|
|
128
|
+
_COVERAGE_CACHE = {}
|
|
129
|
+
return _COVERAGE_CACHE.get(engine, ())
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _lang_misfit(engine: str, lang: str) -> bool:
|
|
133
|
+
"""查询语言与源声明语言错配(只认 chinese/english 两种标记)。"""
|
|
134
|
+
pair = _LANG_PAIR.get(lang)
|
|
135
|
+
if not pair:
|
|
136
|
+
return False
|
|
137
|
+
own, other = pair
|
|
138
|
+
cov = {str(c).lower() for c in _coverage_of(engine)}
|
|
139
|
+
return other in cov and own not in cov
|
|
140
|
+
|
|
141
|
+
|
|
142
|
+
# 非中英脚本(西里尔/阿拉伯/日韩…)不参与覆盖地板与语言门:那些语言下
|
|
143
|
+
# anysearch/local_bing 这类语言覆盖源本就是唯一召回,交给既有 boost 处理。
|
|
144
|
+
_TIERED_LANGS = frozenset({"zh", "en", "mixed", "other", ""})
|
|
145
|
+
|
|
146
|
+
|
|
147
|
+
def _tier(engine: str, lang: str) -> int:
|
|
148
|
+
"""排序层级:0 合格(覆盖够 + 语言适配)/ 1 语言错配 / 2 交付太薄。"""
|
|
149
|
+
if lang not in _TIERED_LANGS:
|
|
150
|
+
return 0
|
|
151
|
+
if GENERAL_COVERAGE.get(engine, COVERAGE_FLOOR) < COVERAGE_FLOOR:
|
|
152
|
+
return 2
|
|
153
|
+
return 1 if _lang_misfit(engine, lang) else 0
|
|
154
|
+
|
|
155
|
+
# 非中英查询的语言覆盖加成。先验表是在中英查询上测的;西里尔/阿拉伯/
|
|
156
|
+
# 日韩等脚本下,语言无关的覆盖源(anysearch/local_bing 带动态 setlang)
|
|
157
|
+
# 比英文快源更有召回价值。2026-10-26 全量测试的 cyrillic 用例暴露:
|
|
158
|
+
# 不做这层加成,top-2 会全被 tavily/parallel 占掉,语言源被预算截断。
|
|
159
|
+
_NON_LATIN_LANG_BOOST: dict[str, float] = {
|
|
160
|
+
"anysearch": 0.35,
|
|
161
|
+
"local_bing": 0.40,
|
|
162
|
+
}
|
|
163
|
+
_LATIN_OR_CN_LANGS = frozenset({"zh", "en", "mixed", "other", ""})
|
|
164
|
+
|
|
165
|
+
# 有 ≥3 条自适应样本时,先验与自适应分各占一半;否则先验做主。
|
|
166
|
+
_ADAPTIVE_BLEND_SAMPLES = 3
|
|
167
|
+
|
|
168
|
+
|
|
169
|
+
def _prior_for(engine: str, lang: str) -> float:
|
|
170
|
+
prior = GENERAL_PRIORS.get(engine, DEFAULT_PRIOR)
|
|
171
|
+
if lang not in _LATIN_OR_CN_LANGS:
|
|
172
|
+
prior += _NON_LATIN_LANG_BOOST.get(engine, 0.0)
|
|
173
|
+
return prior
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _is_research(mode: str, depth: str, context: str) -> bool:
|
|
177
|
+
try:
|
|
178
|
+
from engine_policy import is_research_context
|
|
179
|
+
return is_research_context(mode=mode, depth=depth, context=context)
|
|
180
|
+
except Exception:
|
|
181
|
+
return mode == "deep" or depth == "deep" or context == "research"
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _usable(candidates: list[str], *, mode: str) -> list[str]:
|
|
185
|
+
"""硬性不可用(远端配额耗尽 / fast 档付费源)不参与排序。
|
|
186
|
+
|
|
187
|
+
fail-open:quota 模块不可用时保留原列表,由执行层暴露真实失败。
|
|
188
|
+
"""
|
|
189
|
+
out = list(candidates)
|
|
190
|
+
try:
|
|
191
|
+
from quota import get_quota_manager
|
|
192
|
+
qm = get_quota_manager()
|
|
193
|
+
try:
|
|
194
|
+
exhausted = qm.remote_exhausted_marks()
|
|
195
|
+
out = [e for e in out if e not in exhausted]
|
|
196
|
+
except Exception:
|
|
197
|
+
pass
|
|
198
|
+
if mode in ("fast", "budget"):
|
|
199
|
+
out = [e for e in out if qm.is_available(e, mode=mode)]
|
|
200
|
+
except Exception:
|
|
201
|
+
pass
|
|
202
|
+
return out
|
|
203
|
+
|
|
204
|
+
|
|
205
|
+
def _paid_search_enabled() -> bool:
|
|
206
|
+
try:
|
|
207
|
+
from engine_env import get_env
|
|
208
|
+
raw = str(get_env("ARGO_PAID_SEARCH", "auto") or "auto")
|
|
209
|
+
except Exception:
|
|
210
|
+
import os
|
|
211
|
+
raw = os.environ.get("ARGO_PAID_SEARCH", "auto")
|
|
212
|
+
return raw.strip().lower() not in ("off", "0", "false", "no")
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _paid_candidate_allowed(engine: str, mode: str) -> bool:
|
|
216
|
+
"""付费候选的准入:白名单 + 非 fast/budget + 开关开 + 预算未耗尽。
|
|
217
|
+
|
|
218
|
+
与 paid_policy 的 `_paid_hedge_ready` 同一套门槛,只是位置不同:这里
|
|
219
|
+
进通用池,那里插域 combo 第二位。花钱的事一律 fail-closed。
|
|
220
|
+
"""
|
|
221
|
+
if engine not in PAID_GENERAL_CANDIDATES or mode in ("fast", "budget"):
|
|
222
|
+
return False
|
|
223
|
+
if not _paid_search_enabled():
|
|
224
|
+
return False
|
|
225
|
+
try:
|
|
226
|
+
from engine_env import is_engine_allowed_by_env
|
|
227
|
+
if not is_engine_allowed_by_env(engine):
|
|
228
|
+
return False
|
|
229
|
+
except Exception:
|
|
230
|
+
pass
|
|
231
|
+
try:
|
|
232
|
+
from engine_admission import is_blocked
|
|
233
|
+
if is_blocked(engine):
|
|
234
|
+
return False
|
|
235
|
+
except Exception:
|
|
236
|
+
pass
|
|
237
|
+
try:
|
|
238
|
+
from quota import get_quota_manager
|
|
239
|
+
return not get_quota_manager().is_hard_down(engine)
|
|
240
|
+
except Exception:
|
|
241
|
+
return False
|
|
242
|
+
|
|
243
|
+
|
|
244
|
+
def candidate_allowed(engine: str, enabled: set[str], mode: str) -> bool:
|
|
245
|
+
"""通用候选是否允许参与:enabled 成员,或预算内的白名单付费源。
|
|
246
|
+
|
|
247
|
+
两条通用路径都要用这一处判据:`rank_general_candidates` 的池过滤,
|
|
248
|
+
以及 `tfidf_lead_combo` 的最终 `out` 过滤。后者的 `if e in enabled`
|
|
249
|
+
曾把 paid 候选单独丢掉——池排序里有它,组合装配时又被剔掉。
|
|
250
|
+
"""
|
|
251
|
+
return engine in enabled or _paid_candidate_allowed(engine, mode)
|
|
252
|
+
|
|
253
|
+
|
|
254
|
+
def rank_general_candidates(
|
|
255
|
+
candidates: list[str],
|
|
256
|
+
*,
|
|
257
|
+
enabled: set[str],
|
|
258
|
+
mode: str = "auto",
|
|
259
|
+
depth: str = "fast",
|
|
260
|
+
context: str = "search",
|
|
261
|
+
lang: str = "",
|
|
262
|
+
score_fn: Callable[[str, str, str, str], tuple[float, int]] | None = None,
|
|
263
|
+
) -> list[str]:
|
|
264
|
+
"""按「先验 × 自适应 × 用途」排序通用候选源。
|
|
265
|
+
|
|
266
|
+
`score_fn(engine, domain, lang, purpose) -> (score, samples)` 可注入,
|
|
267
|
+
测试用假学习器即可确定性断言,不依赖本机 adaptive.db 的时点数据。
|
|
268
|
+
"""
|
|
269
|
+
pool = _usable(candidates, mode=mode)
|
|
270
|
+
pool = [e for e in pool if candidate_allowed(e, enabled, mode)]
|
|
271
|
+
if not pool:
|
|
272
|
+
return []
|
|
273
|
+
|
|
274
|
+
purpose = "research" if _is_research(mode, depth, context) else "daily"
|
|
275
|
+
if score_fn is None:
|
|
276
|
+
def score_fn(engine: str, domain: str, q_lang: str,
|
|
277
|
+
use: str) -> tuple[float, int]:
|
|
278
|
+
from adaptive import get_learner
|
|
279
|
+
return get_learner().get_score_with_samples(
|
|
280
|
+
engine, domain, q_lang, use)
|
|
281
|
+
|
|
282
|
+
ranked: list[tuple[int, float, int, str]] = []
|
|
283
|
+
for idx, engine in enumerate(pool):
|
|
284
|
+
prior = _prior_for(engine, lang)
|
|
285
|
+
try:
|
|
286
|
+
adaptive_score, samples = score_fn(
|
|
287
|
+
engine, "general_search", lang, purpose)
|
|
288
|
+
except Exception:
|
|
289
|
+
adaptive_score, samples = 0.5, 0
|
|
290
|
+
if samples >= _ADAPTIVE_BLEND_SAMPLES:
|
|
291
|
+
# 有样本时自适应占 6 成:先验是冷启动种子,不能让「高先验但已
|
|
292
|
+
# 证实失败」的源靠乘法永远压住健康源(实测反例:先验 1.0、
|
|
293
|
+
# 自适应 0 的源乘出来 0.5,仍高于先验 0.5、自适应 0.5 的健康源)。
|
|
294
|
+
weight = 0.4 * prior + 0.6 * min(1.0, float(adaptive_score))
|
|
295
|
+
else:
|
|
296
|
+
weight = prior
|
|
297
|
+
# 层级先于分数:覆盖太薄 / 语言错配的源,即便更快更高分也排到
|
|
298
|
+
# 合格源之后(分数在层内仍然说了算)。idx 取负:同分保持候选池
|
|
299
|
+
# 原顺序(稳定排序,便于 A/B 复现)。
|
|
300
|
+
ranked.append((_tier(engine, lang), -weight, idx, engine))
|
|
301
|
+
ranked.sort()
|
|
302
|
+
return [engine for _t, _w, _i, engine in ranked]
|
package/scripts/url_canon.py
CHANGED
|
@@ -47,11 +47,12 @@ TRACKING_PARAMS: frozenset[str] = frozenset({
|
|
|
47
47
|
"from_source", "from_spmid", "from_spmid2", "vd_source", "unique_k",
|
|
48
48
|
"buvid", "buvid3", "buvid4", "up_id", "seid", "spmid", "timestamp",
|
|
49
49
|
"wxshare", "weibo_id", "share_referer", "share_object_id",
|
|
50
|
-
#
|
|
50
|
+
# 通用归因与平台语言/分享变体(YouTube vl/si 会把同一视频拆成多条重复 URL)
|
|
51
51
|
"ref", "ref_src", "ref_url", "refer", "referer", "referrer",
|
|
52
52
|
"source", "from", "src", "cmp", "camp", "srsltid",
|
|
53
53
|
"clickid", "click_id", "clicktime", "scid", "scene", "sessionid",
|
|
54
54
|
"trace", "trace_id", "track", "tracking_id", "trk", "trkcampaign",
|
|
55
|
+
"si", "vl",
|
|
55
56
|
})
|
|
56
57
|
|
|
57
58
|
# 移动站/AMP 子域前缀(fold_mobile)与 www 前缀(fold_www)分开——
|
|
@@ -0,0 +1,303 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""video_fetch.py — 视频页正文/元数据提取(B 站优先,YouTube 次之)。
|
|
3
|
+
|
|
4
|
+
为什么单独成模块:通用 fetch_v3 的降级链是「HTML → 正文提取」,而视频页的
|
|
5
|
+
正文不在 HTML 里。实测 B 站视频页只抓到 225 字相关推荐标题,YouTube 只有
|
|
6
|
+
134 字页脚——能搜到视频,但读不了,evidence/verify 拿到的是垃圾。
|
|
7
|
+
|
|
8
|
+
本模块走平台 API,不抓播放器页面:
|
|
9
|
+
- B 站:view 接口取标题/简介/时长/UP 主/统计/cid;player/v2 取字幕
|
|
10
|
+
(有字幕才有,没有则留空);可选 ARGO_VIDEO_ASR_CMD 兜底转写。
|
|
11
|
+
- YouTube:oEmbed 取标题/作者;timedtext 取字幕(多数视频为空)。
|
|
12
|
+
- 抖音等其它平台不接管:返回 None,让通用抓取链继续(移动 UA 对
|
|
13
|
+
share/video 页仍可能有效,不能在这里判死)。
|
|
14
|
+
|
|
15
|
+
返回 dict 与 fetch_v3._make_result 的字段对齐;调用方(fetch_v3)再跑一次
|
|
16
|
+
质量评估并覆盖 page_type=video。不支持的平台返回 None,让通用抓取链继续。
|
|
17
|
+
"""
|
|
18
|
+
|
|
19
|
+
from __future__ import annotations
|
|
20
|
+
|
|
21
|
+
import html
|
|
22
|
+
import json
|
|
23
|
+
import os
|
|
24
|
+
import re
|
|
25
|
+
import shlex
|
|
26
|
+
import subprocess
|
|
27
|
+
import urllib.parse
|
|
28
|
+
import urllib.request
|
|
29
|
+
from datetime import datetime, timedelta, timezone
|
|
30
|
+
|
|
31
|
+
from net_proxy import open_url
|
|
32
|
+
from video_meta import parse_duration_seconds, video_platform
|
|
33
|
+
|
|
34
|
+
_TZ_CN = timezone(timedelta(hours=8))
|
|
35
|
+
_UA = ("Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) "
|
|
36
|
+
"AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124 Safari/537.36")
|
|
37
|
+
|
|
38
|
+
|
|
39
|
+
def _get(url: str, timeout: float) -> bytes:
|
|
40
|
+
req = urllib.request.Request(url, headers={"User-Agent": _UA})
|
|
41
|
+
with open_url(req, timeout=timeout) as resp:
|
|
42
|
+
return resp.read()
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _get_json(url: str, timeout: float) -> dict:
|
|
46
|
+
return json.loads(_get(url, timeout).decode("utf-8", "replace"))
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
def _iso(ts) -> str:
|
|
50
|
+
try:
|
|
51
|
+
return datetime.fromtimestamp(int(ts), tz=_TZ_CN).isoformat()
|
|
52
|
+
except (TypeError, ValueError, OSError):
|
|
53
|
+
return ""
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
def _bvid_of(url: str) -> str:
|
|
57
|
+
m = re.search(r"(BV[0-9A-Za-z]+)", url or "")
|
|
58
|
+
return m.group(1) if m else ""
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
def _youtube_id(url: str) -> str:
|
|
62
|
+
try:
|
|
63
|
+
parsed = urllib.parse.urlparse(url)
|
|
64
|
+
except ValueError:
|
|
65
|
+
return ""
|
|
66
|
+
if parsed.netloc.endswith("youtu.be"):
|
|
67
|
+
return parsed.path.strip("/").split("/")[0]
|
|
68
|
+
query = urllib.parse.parse_qs(parsed.query)
|
|
69
|
+
if query.get("v"):
|
|
70
|
+
return query["v"][0]
|
|
71
|
+
m = re.search(r"/(?:shorts|embed|live)/([0-9A-Za-z_-]{6,})", parsed.path or "")
|
|
72
|
+
return m.group(1) if m else ""
|
|
73
|
+
|
|
74
|
+
|
|
75
|
+
def _limit(text: str, max_chars: int) -> tuple[str, bool, int]:
|
|
76
|
+
full = text or ""
|
|
77
|
+
if max_chars and max_chars > 0 and len(full) > max_chars:
|
|
78
|
+
return full[:max_chars], True, len(full)
|
|
79
|
+
return full, False, len(full)
|
|
80
|
+
|
|
81
|
+
|
|
82
|
+
def _result(url: str, title: str, content: str, method: str, *,
|
|
83
|
+
max_chars: int = 8000, success: bool = True,
|
|
84
|
+
error: str | None = None, content_ok: bool | None = None,
|
|
85
|
+
video_meta: dict | None = None) -> dict:
|
|
86
|
+
delivered, truncated, full_length = _limit(content, max_chars)
|
|
87
|
+
if content_ok is None:
|
|
88
|
+
content_ok = len(delivered.strip()) >= 40
|
|
89
|
+
return {
|
|
90
|
+
"url": url,
|
|
91
|
+
"title": title or "",
|
|
92
|
+
"content": delivered,
|
|
93
|
+
"html": "",
|
|
94
|
+
"length": len(delivered),
|
|
95
|
+
"full_length": full_length,
|
|
96
|
+
"truncated": truncated,
|
|
97
|
+
"success": success,
|
|
98
|
+
"error": error,
|
|
99
|
+
"fetch_method": method,
|
|
100
|
+
"content_ok": content_ok,
|
|
101
|
+
"page_type": "video",
|
|
102
|
+
"source_type": "video",
|
|
103
|
+
"is_official": False,
|
|
104
|
+
"video_meta": video_meta or {},
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def _bilibili_subtitle(bvid: str, cid, timeout: float) -> str:
|
|
109
|
+
"""取 B 站字幕文本;没有字幕(或接口要求登录)返回空串,不报错。"""
|
|
110
|
+
if not bvid or not cid:
|
|
111
|
+
return ""
|
|
112
|
+
try:
|
|
113
|
+
player = _get_json(
|
|
114
|
+
"https://api.bilibili.com/x/player/v2?"
|
|
115
|
+
+ urllib.parse.urlencode({"bvid": bvid, "cid": cid}),
|
|
116
|
+
timeout,
|
|
117
|
+
)
|
|
118
|
+
except Exception:
|
|
119
|
+
return ""
|
|
120
|
+
subtitles = ((player.get("data") or {}).get("subtitle") or {}).get("subtitles") or []
|
|
121
|
+
for item in subtitles:
|
|
122
|
+
sub_url = item.get("subtitle_url") or ""
|
|
123
|
+
if not sub_url:
|
|
124
|
+
continue
|
|
125
|
+
if sub_url.startswith("//"):
|
|
126
|
+
sub_url = "https:" + sub_url
|
|
127
|
+
try:
|
|
128
|
+
body = _get_json(sub_url, timeout)
|
|
129
|
+
except Exception:
|
|
130
|
+
continue
|
|
131
|
+
lines = [str(x.get("content") or "").strip()
|
|
132
|
+
for x in (body.get("body") or []) if isinstance(x, dict)]
|
|
133
|
+
text = "\n".join(x for x in lines if x)
|
|
134
|
+
if text:
|
|
135
|
+
return text
|
|
136
|
+
return ""
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _run_asr(url: str, timeout: float) -> str:
|
|
140
|
+
"""可选 ASR 兜底:ARGO_VIDEO_ASR_CMD 是外部命令模板(含 {url} 或自动追加)。
|
|
141
|
+
|
|
142
|
+
不内置 whisper/yt-dlp:两者都不是本仓依赖,装不装由使用者决定。命令用
|
|
143
|
+
shlex.split 执行、不走 shell,避免 URL 里的特殊字符被解释。
|
|
144
|
+
"""
|
|
145
|
+
template = os.environ.get("ARGO_VIDEO_ASR_CMD", "").strip()
|
|
146
|
+
if not template:
|
|
147
|
+
return ""
|
|
148
|
+
parts = shlex.split(template)
|
|
149
|
+
if any("{url}" in p for p in parts):
|
|
150
|
+
parts = [p.replace("{url}", url) for p in parts]
|
|
151
|
+
else:
|
|
152
|
+
parts.append(url)
|
|
153
|
+
try:
|
|
154
|
+
proc = subprocess.run(
|
|
155
|
+
parts, capture_output=True, text=True,
|
|
156
|
+
encoding="utf-8", errors="replace",
|
|
157
|
+
# 抓取超时通常是 8s,ASR 转一条几分钟的视频不够;转写是显式
|
|
158
|
+
# opt-in,给到 30s 下限,超时由外部命令自己负责长视频队列。
|
|
159
|
+
timeout=max(timeout, 30.0))
|
|
160
|
+
except (OSError, subprocess.SubprocessError):
|
|
161
|
+
return ""
|
|
162
|
+
return proc.stdout.strip() if proc.returncode == 0 else ""
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _fetch_bilibili(url: str, max_chars: int, timeout: float) -> dict | None:
|
|
166
|
+
bvid = _bvid_of(url)
|
|
167
|
+
if not bvid:
|
|
168
|
+
return None
|
|
169
|
+
try:
|
|
170
|
+
payload = _get_json(
|
|
171
|
+
"https://api.bilibili.com/x/web-interface/view?"
|
|
172
|
+
+ urllib.parse.urlencode({"bvid": bvid}),
|
|
173
|
+
timeout,
|
|
174
|
+
)
|
|
175
|
+
except Exception as e:
|
|
176
|
+
return _result(url, "", "", "bilibili_api", max_chars=max_chars,
|
|
177
|
+
success=False, error=f"B站详情接口失败: {type(e).__name__}: {e}")
|
|
178
|
+
if payload.get("code") != 0 or not isinstance(payload.get("data"), dict):
|
|
179
|
+
return _result(url, "", "", "bilibili_api", max_chars=max_chars,
|
|
180
|
+
success=False,
|
|
181
|
+
error=f"B站详情接口返回 code={payload.get('code')}")
|
|
182
|
+
data = payload["data"]
|
|
183
|
+
pages = data.get("pages") or []
|
|
184
|
+
cid = (pages[0] or {}).get("cid") if pages else None
|
|
185
|
+
transcript = _bilibili_subtitle(bvid, cid, timeout)
|
|
186
|
+
if not transcript:
|
|
187
|
+
transcript = _run_asr(url, timeout)
|
|
188
|
+
|
|
189
|
+
title = html.unescape(str(data.get("title") or ""))
|
|
190
|
+
desc = html.unescape(str(data.get("desc") or "")).strip()
|
|
191
|
+
duration = parse_duration_seconds(data.get("duration"))
|
|
192
|
+
owner = (data.get("owner") or {}).get("name") or ""
|
|
193
|
+
stat = data.get("stat") or {}
|
|
194
|
+
published = _iso(data.get("pubdate"))
|
|
195
|
+
parts = [f"标题:{title}"]
|
|
196
|
+
if owner:
|
|
197
|
+
parts.append(f"UP主:{owner}")
|
|
198
|
+
if duration is not None:
|
|
199
|
+
minutes, seconds = divmod(duration, 60)
|
|
200
|
+
parts.append(f"时长:{minutes}:{seconds:02d}")
|
|
201
|
+
if published:
|
|
202
|
+
parts.append(f"发布:{published}")
|
|
203
|
+
if stat.get("view") is not None:
|
|
204
|
+
parts.append(f"播放:{stat.get('view')}")
|
|
205
|
+
if desc:
|
|
206
|
+
parts.append("简介:\n" + desc)
|
|
207
|
+
if transcript:
|
|
208
|
+
parts.append("字幕/转写:\n" + transcript)
|
|
209
|
+
else:
|
|
210
|
+
parts.append("(该视频没有可用字幕;只提取到标题、简介与元数据,"
|
|
211
|
+
"需要正文请配置 ARGO_VIDEO_ASR_CMD)")
|
|
212
|
+
content = "\n\n".join(parts)
|
|
213
|
+
return _result(
|
|
214
|
+
url, title, content, "bilibili_api", max_chars=max_chars,
|
|
215
|
+
content_ok=bool(desc or transcript),
|
|
216
|
+
video_meta={
|
|
217
|
+
"platform": "bilibili",
|
|
218
|
+
"bvid": bvid,
|
|
219
|
+
"duration_seconds": duration,
|
|
220
|
+
"author": owner,
|
|
221
|
+
"published_at": published,
|
|
222
|
+
"view_count": stat.get("view"),
|
|
223
|
+
"danmaku_count": stat.get("danmaku"),
|
|
224
|
+
"like_count": stat.get("like"),
|
|
225
|
+
"favorite_count": stat.get("favorite"),
|
|
226
|
+
"transcript_available": bool(transcript),
|
|
227
|
+
},
|
|
228
|
+
)
|
|
229
|
+
|
|
230
|
+
|
|
231
|
+
def _youtube_captions(video_id: str, timeout: float) -> str:
|
|
232
|
+
"""取 YouTube 字幕;无字幕/被墙返回空串。"""
|
|
233
|
+
if not video_id:
|
|
234
|
+
return ""
|
|
235
|
+
for lang in ("zh-Hans", "zh-CN", "en"):
|
|
236
|
+
url = ("https://www.youtube.com/api/timedtext?"
|
|
237
|
+
+ urllib.parse.urlencode({"v": video_id, "lang": lang}))
|
|
238
|
+
try:
|
|
239
|
+
raw = _get(url, timeout).decode("utf-8", "replace")
|
|
240
|
+
except Exception:
|
|
241
|
+
continue
|
|
242
|
+
if "<text" not in raw:
|
|
243
|
+
continue
|
|
244
|
+
lines = [html.unescape(re.sub(r"<[^>]+>", "", x)).strip()
|
|
245
|
+
for x in re.findall(r"<text[^>]*>(.*?)</text>", raw, re.S)]
|
|
246
|
+
text = "\n".join(x for x in lines if x)
|
|
247
|
+
if text:
|
|
248
|
+
return text
|
|
249
|
+
return ""
|
|
250
|
+
|
|
251
|
+
|
|
252
|
+
def _fetch_youtube(url: str, max_chars: int, timeout: float) -> dict | None:
|
|
253
|
+
video_id = _youtube_id(url)
|
|
254
|
+
if not video_id:
|
|
255
|
+
return None
|
|
256
|
+
try:
|
|
257
|
+
oembed = _get_json(
|
|
258
|
+
"https://www.youtube.com/oembed?"
|
|
259
|
+
+ urllib.parse.urlencode({"url": url, "format": "json"}),
|
|
260
|
+
timeout,
|
|
261
|
+
)
|
|
262
|
+
except Exception as e:
|
|
263
|
+
return _result(url, "", "", "youtube_oembed", max_chars=max_chars,
|
|
264
|
+
success=False,
|
|
265
|
+
error=f"YouTube oEmbed 失败: {type(e).__name__}: {e}")
|
|
266
|
+
title = str(oembed.get("title") or "")
|
|
267
|
+
author = str(oembed.get("author_name") or "")
|
|
268
|
+
transcript = _youtube_captions(video_id, timeout)
|
|
269
|
+
parts = [f"标题:{title}"]
|
|
270
|
+
if author:
|
|
271
|
+
parts.append(f"频道:{author}")
|
|
272
|
+
if transcript:
|
|
273
|
+
parts.append("字幕/转写:\n" + transcript)
|
|
274
|
+
else:
|
|
275
|
+
parts.append("(YouTube 未返回可用字幕;当前网络下播放页要求登录,"
|
|
276
|
+
"只提取到标题与频道)")
|
|
277
|
+
content = "\n\n".join(parts)
|
|
278
|
+
return _result(
|
|
279
|
+
url, title, content, "youtube_oembed", max_chars=max_chars,
|
|
280
|
+
content_ok=bool(transcript),
|
|
281
|
+
video_meta={
|
|
282
|
+
"platform": "youtube",
|
|
283
|
+
"video_id": video_id,
|
|
284
|
+
"author": author,
|
|
285
|
+
"transcript_available": bool(transcript),
|
|
286
|
+
},
|
|
287
|
+
)
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
def fetch_video(url: str, max_chars: int = 8000,
|
|
291
|
+
timeout: float = 8.0) -> dict | None:
|
|
292
|
+
"""视频页提取入口。
|
|
293
|
+
|
|
294
|
+
只接管「API 一定比 HTML 好」的两个平台:B 站与 YouTube。抖音等平台
|
|
295
|
+
返回 None,让通用抓取链继续——实测抖音 share/video 页在移动 UA 下仍能
|
|
296
|
+
提取,直接判「不支持」会打断既有降级链(而且会把可读页面说成不可读)。
|
|
297
|
+
"""
|
|
298
|
+
platform = video_platform(url)
|
|
299
|
+
if platform == "bilibili":
|
|
300
|
+
return _fetch_bilibili(url, max_chars, timeout)
|
|
301
|
+
if platform == "youtube":
|
|
302
|
+
return _fetch_youtube(url, max_chars, timeout)
|
|
303
|
+
return None
|