argo-search 2.9.8 → 2.10.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.
- package/README.en.md +48 -35
- package/README.es.md +48 -35
- package/README.ja.md +47 -34
- package/README.ko.md +47 -34
- package/README.md +50 -35
- package/SKILL.md +5 -5
- package/backends/domain_profiles.json +76 -0
- package/backends/engine_registry.yaml +161 -5
- package/backends/quota_profiles.json +122 -2
- package/bin/argo +26 -1
- package/bin/argo.js +3 -3
- package/config.yaml +180 -26
- package/docs/ARGO_INTRO.md +7 -5
- package/docs/ENGINE_CATALOG.md +64 -44
- package/docs/MCP_SETUP.md +1 -1
- package/docs/RELEASE_NOTES_v2.10.0.md +85 -0
- package/docs/RELEASE_NOTES_v2.9.8.md +1 -1
- package/docs/RELEASE_NOTES_v2.9.9.md +78 -0
- package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +9 -9
- 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 +41 -0
- package/engines/specs/sciverse.yaml +72 -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 +4 -2
- package/packages/dsh-plugin/dsh/client.js +98 -32
- package/packages/dsh-plugin/dsh/diagnostics.js +43 -0
- package/packages/dsh-plugin/dsh/index.js +23 -1
- package/packages/dsh-plugin/package.json +2 -2
- package/packages/dsh-plugin/test/client.test.js +2 -1
- package/packages/dsh-plugin/test/size-gate.test.js +113 -0
- package/scripts/adaptive.py +135 -48
- package/scripts/article.py +6 -1
- package/scripts/article_meta.py +151 -2
- package/scripts/bench_general_pool.py +145 -0
- package/scripts/bench_tail_ab.py +281 -0
- package/scripts/bounded_run.py +91 -49
- package/scripts/candidate_envelope.py +45 -4
- package/scripts/charset_decode.py +127 -0
- package/scripts/clock_bridge.py +22 -0
- package/scripts/content_security.py +119 -4
- package/scripts/crawl.py +240 -74
- package/scripts/crawl_frontier.py +217 -0
- package/scripts/crawl_policy.py +174 -0
- package/scripts/dispatch_result.py +9 -2
- package/scripts/engine_add.py +602 -0
- package/scripts/engine_dispatch.py +31 -15
- package/scripts/engine_failure.py +15 -0
- package/scripts/engine_validate.py +8 -0
- package/scripts/engines.py +10 -0
- package/scripts/engines_base.py +12 -0
- package/scripts/engines_builders.py +14 -0
- package/scripts/engines_builders_dsh.py +330 -0
- package/scripts/engines_builders_skill.py +314 -0
- package/scripts/evidence_loop.py +4 -0
- package/scripts/fetch_quality.py +13 -0
- package/scripts/fetch_v3.py +39 -7
- package/scripts/gen_engine_catalog.py +218 -2
- package/scripts/general_pool.py +162 -0
- package/scripts/http_client.py +62 -80
- package/scripts/image_ops.py +4 -0
- package/scripts/image_vision/vision_probe +0 -0
- package/scripts/install.ps1 +47 -19
- package/scripts/install.sh +45 -20
- package/scripts/matrix_search_eval.py +128 -2
- package/scripts/mcp_transport.py +1 -1
- package/scripts/ncpssd_bridge.py +123 -0
- package/scripts/net_proxy.py +27 -0
- package/scripts/paid_policy.py +109 -13
- package/scripts/pre-commit +19 -4
- package/scripts/query_signals.py +156 -3
- package/scripts/recovery.py +7 -3
- package/scripts/redskill/redskill_engine.py +29 -2
- 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 +56 -64
- package/scripts/route_domains.py +142 -13
- package/scripts/route_policy.py +6 -0
- package/scripts/safe_conn.py +52 -0
- package/scripts/search.py +9 -1
- package/scripts/search_cli.py +27 -0
- package/scripts/search_entry.py +10 -0
- package/scripts/search_output.py +29 -0
- package/scripts/search_pipeline.py +59 -3
- package/scripts/search_rank.py +7 -0
- package/scripts/serp_guard.py +23 -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/tail_completion.py +212 -0
- package/scripts/url_safety.py +126 -3
- package/scripts/usage_log.py +45 -0
- 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/scripts/adaptive.py
CHANGED
|
@@ -82,6 +82,21 @@ def quality_factor(avg_quality: float | None, sum_quality: float | int | None) -
|
|
|
82
82
|
min(QUALITY_FACTOR_MAX, 0.75 + 0.5 * avg))
|
|
83
83
|
|
|
84
84
|
|
|
85
|
+
def scenario_of(decision: dict | None) -> dict[str, str]:
|
|
86
|
+
"""从路由决策里抽 (domain, lang) 场景标签,供 record 分桶使用。
|
|
87
|
+
|
|
88
|
+
独立成函数(而非写在 search_pipeline 的 record 调用里)是为了让
|
|
89
|
+
search_pipeline 的 record 调用保持 3 行——它是祖父文件(行数上限门禁),
|
|
90
|
+
把场景抽取塞进调用点会让它超限。
|
|
91
|
+
"""
|
|
92
|
+
d = decision or {}
|
|
93
|
+
feats = d.get("features") or {}
|
|
94
|
+
return {
|
|
95
|
+
"domain": str(d.get("domain") or ""),
|
|
96
|
+
"lang": str(feats.get("primary_lang") or ""),
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
|
|
85
100
|
class AdaptiveLearner:
|
|
86
101
|
"""自适应学习引擎:追踪引擎表现并输出推荐分数。"""
|
|
87
102
|
|
|
@@ -91,7 +106,9 @@ class AdaptiveLearner:
|
|
|
91
106
|
def __init__(self):
|
|
92
107
|
self._lock = threading.Lock()
|
|
93
108
|
self._local = threading.local()
|
|
94
|
-
|
|
109
|
+
# (engine, domain, lang, purpose) -> (score, samples, expires_at)
|
|
110
|
+
self._score_cache: dict[
|
|
111
|
+
tuple[str, str, str, str], tuple[float, int, float]] = {}
|
|
95
112
|
self._session_engines: set[str] = set()
|
|
96
113
|
self._batch_depth = 0
|
|
97
114
|
self._batch_dirty = False
|
|
@@ -166,18 +183,33 @@ class AdaptiveLearner:
|
|
|
166
183
|
# 同理补列。历史行 quality=0 表示「当时没回写质量」,不是「质量为零」——
|
|
167
184
|
# 评分侧以 SUM(quality) > 0 判定有无数据,故这批行不会拉低任何引擎。
|
|
168
185
|
conn.execute("ALTER TABLE engine_perf ADD COLUMN quality REAL DEFAULT 0.0")
|
|
186
|
+
if "domain" not in cols:
|
|
187
|
+
# 场景分桶(2026-10-24):domain/lang 让学习器能表达「这个引擎在
|
|
188
|
+
# A 域强、B 域弱」。历史行留空串 = 「未分桶」,回退全局分。
|
|
189
|
+
conn.execute("ALTER TABLE engine_perf ADD COLUMN domain TEXT NOT NULL DEFAULT ''")
|
|
190
|
+
if "lang" not in cols:
|
|
191
|
+
conn.execute("ALTER TABLE engine_perf ADD COLUMN lang TEXT NOT NULL DEFAULT ''")
|
|
169
192
|
conn.execute(
|
|
170
193
|
"CREATE INDEX IF NOT EXISTS idx_perf_engine_time ON engine_perf(engine, created_at)"
|
|
171
194
|
)
|
|
195
|
+
conn.execute(
|
|
196
|
+
"CREATE INDEX IF NOT EXISTS idx_perf_engine_scenario "
|
|
197
|
+
"ON engine_perf(engine, domain, lang, created_at)"
|
|
198
|
+
)
|
|
172
199
|
cutoff = time.time() - WINDOW_DAYS * 86400
|
|
173
200
|
conn.execute("DELETE FROM engine_perf WHERE created_at < ?", (cutoff,))
|
|
174
201
|
self._prune_foreign(conn)
|
|
175
202
|
conn.commit()
|
|
176
203
|
|
|
177
204
|
def record(self, engine: str, success: bool, latency_ms: float, cost: float = 0.0,
|
|
178
|
-
empty: bool = False, quality: float | None = None
|
|
205
|
+
empty: bool = False, quality: float | None = None,
|
|
206
|
+
domain: str = "", lang: str = ""):
|
|
179
207
|
"""记录一次引擎调用结果。
|
|
180
208
|
|
|
209
|
+
``domain`` / ``lang`` 是**可选场景标签**(默认空 = 不回退旧调用方):
|
|
210
|
+
给出时按 (engine, domain, lang) 分桶学习,让「引擎在 A 域强、B 域弱」
|
|
211
|
+
可表达;不给时与旧口径完全一致(全局单桶)。见 ``get_score``。
|
|
212
|
+
|
|
181
213
|
``empty=True`` 表示「引擎正常,但这次查询它没有结果」——与「失败」是
|
|
182
214
|
两回事,见 `get_score` 的说明。默认 False 保持旧调用方行为不变。
|
|
183
215
|
|
|
@@ -187,6 +219,8 @@ class AdaptiveLearner:
|
|
|
187
219
|
`SUM(quality) > 0` 判定有无数据,故未回写的行不会拖累任何引擎。
|
|
188
220
|
"""
|
|
189
221
|
q = 0.0 if quality is None else max(0.0, min(1.0, float(quality)))
|
|
222
|
+
dom = str(domain or "")[:64]
|
|
223
|
+
lg = str(lang or "")[:16]
|
|
190
224
|
with self._lock:
|
|
191
225
|
if not hasattr(self, "_session_engines"):
|
|
192
226
|
self._session_engines = set()
|
|
@@ -194,18 +228,71 @@ class AdaptiveLearner:
|
|
|
194
228
|
conn = self._connect()
|
|
195
229
|
conn.execute(
|
|
196
230
|
"INSERT INTO engine_perf "
|
|
197
|
-
"(engine, success, latency_ms, cost, created_at, empty, quality) "
|
|
198
|
-
"VALUES (?, ?, ?, ?, ?, ?, ?)",
|
|
231
|
+
"(engine, success, latency_ms, cost, created_at, empty, quality, domain, lang) "
|
|
232
|
+
"VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
199
233
|
(engine, 1 if success else 0, latency_ms, cost, time.time(),
|
|
200
|
-
1 if empty else 0, q),
|
|
234
|
+
1 if empty else 0, q, dom, lg),
|
|
201
235
|
)
|
|
202
236
|
if getattr(self, "_batch_depth", 0) > 0:
|
|
203
237
|
self._batch_dirty = True
|
|
204
238
|
else:
|
|
205
239
|
conn.commit()
|
|
206
|
-
|
|
240
|
+
# 清掉该引擎的全部缓存键(含场景分桶键),见 get_score 的缓存口径
|
|
241
|
+
for _k in [k for k in self._score_cache if k[0] == engine]:
|
|
242
|
+
self._score_cache.pop(_k, None)
|
|
243
|
+
|
|
244
|
+
def _score_from_row(self, row, purpose: str = "daily") -> float:
|
|
245
|
+
"""把一条聚合行转成 0~1 推荐分(口径见 get_score)。
|
|
207
246
|
|
|
208
|
-
|
|
247
|
+
`purpose="research"` 把延迟悬崖从 2s 抬到 8s:2s 是**日常档的等待
|
|
248
|
+
政策**(慢源不该定义第一响应),不是质量判断。研究场景里同一台源
|
|
249
|
+
4s 交出的扎实证据值得等;沿用 2s 悬崖会让「慢而高质」的源在深研
|
|
250
|
+
排序里系统性输给「快而泛」的源——正是 2026-10-26 审查发现的偏差。
|
|
251
|
+
"""
|
|
252
|
+
total, judged, judged_ok, avg_latency, avg_cost, avg_q, sum_q, last_ts = row
|
|
253
|
+
total = int(total or 0)
|
|
254
|
+
judged = int(judged or 0)
|
|
255
|
+
if not total:
|
|
256
|
+
return 0.5
|
|
257
|
+
last_ts = float(last_ts or 0)
|
|
258
|
+
if last_ts and (time.time() - last_ts) > STALE_AFTER_SECONDS:
|
|
259
|
+
return 0.5
|
|
260
|
+
if judged == 0:
|
|
261
|
+
return 0.5
|
|
262
|
+
success_rate = (judged_ok or 0) / judged
|
|
263
|
+
latency_cap = 8000.0 if purpose == "research" else 2000.0
|
|
264
|
+
latency_factor = min(1.0, latency_cap / max(avg_latency or latency_cap, 1))
|
|
265
|
+
cost_factor = max(0.3, 1.0 - (avg_cost or 0.0) * 10)
|
|
266
|
+
return round(success_rate * latency_factor * cost_factor
|
|
267
|
+
* quality_factor(avg_q, sum_q), 4)
|
|
268
|
+
|
|
269
|
+
def _global_row(self, engine: str):
|
|
270
|
+
cutoff = time.time() - WINDOW_DAYS * 86400
|
|
271
|
+
return self._connect().execute(
|
|
272
|
+
"SELECT COUNT(*), "
|
|
273
|
+
" SUM(CASE WHEN empty = 0 THEN 1 ELSE 0 END), "
|
|
274
|
+
" SUM(CASE WHEN empty = 0 THEN success ELSE 0 END), "
|
|
275
|
+
" AVG(latency_ms), AVG(cost), "
|
|
276
|
+
" AVG(quality), SUM(quality), MAX(created_at) "
|
|
277
|
+
"FROM engine_perf WHERE engine = ? AND created_at > ?",
|
|
278
|
+
(engine, cutoff),
|
|
279
|
+
).fetchone()
|
|
280
|
+
|
|
281
|
+
def _bucket_row(self, engine: str, domain: str, lang: str):
|
|
282
|
+
cutoff = time.time() - WINDOW_DAYS * 86400
|
|
283
|
+
return self._connect().execute(
|
|
284
|
+
"SELECT COUNT(*), "
|
|
285
|
+
" SUM(CASE WHEN empty = 0 THEN 1 ELSE 0 END), "
|
|
286
|
+
" SUM(CASE WHEN empty = 0 THEN success ELSE 0 END), "
|
|
287
|
+
" AVG(latency_ms), AVG(cost), "
|
|
288
|
+
" AVG(quality), SUM(quality), MAX(created_at) "
|
|
289
|
+
"FROM engine_perf WHERE engine = ? AND created_at > ? "
|
|
290
|
+
"AND domain = ? AND lang = ?",
|
|
291
|
+
(engine, cutoff, domain, lang),
|
|
292
|
+
).fetchone()
|
|
293
|
+
|
|
294
|
+
def get_score(self, engine: str, domain: str | None = None,
|
|
295
|
+
lang: str | None = None, purpose: str = "daily") -> float:
|
|
209
296
|
"""获取引擎的综合推荐分数(0.0 ~ 1.0)。
|
|
210
297
|
|
|
211
298
|
**只按「有明确结果」的调用算成功率**(`empty=0`)。
|
|
@@ -219,51 +306,51 @@ class AdaptiveLearner:
|
|
|
219
306
|
openalex(0.29)、hackernews(0.10)、twitter(0.17)、open_library(0.17)。
|
|
220
307
|
|
|
221
308
|
延迟与成本仍按全部调用统计——空结果也是真实开销。
|
|
309
|
+
|
|
310
|
+
**场景分桶**(2026-10-24):给 `domain` / `lang` 时,按 (engine, domain,
|
|
311
|
+
lang) 聚合出「桶分」,与全局分加权融合(桶样本 <3 时权重 0.3,≥3 时 0.5)。
|
|
312
|
+
这让「引擎在 A 域强、B 域弱」可表达,新引擎也能在建议域里被更快识别。
|
|
313
|
+
桶为空时回退全局分——旧调用方(不传 domain/lang)行为逐位不变。
|
|
314
|
+
|
|
315
|
+
`purpose`:daily(默认)沿用 2s 延迟悬崖;research 抬到 8s,见
|
|
316
|
+
`_score_from_row`。默认值保证旧调用方逐位不变。
|
|
222
317
|
"""
|
|
318
|
+
return self.get_score_with_samples(
|
|
319
|
+
engine, domain, lang, purpose)[0]
|
|
320
|
+
|
|
321
|
+
def get_score_with_samples(self, engine: str, domain: str | None = None,
|
|
322
|
+
lang: str | None = None,
|
|
323
|
+
purpose: str = "daily") -> tuple[float, int]:
|
|
324
|
+
"""同 get_score,额外返回有效样本数。
|
|
325
|
+
|
|
326
|
+
选源层需要区分「0.5 分是因为没数据」与「0.5 分是因为确实平庸」:
|
|
327
|
+
对无样本的源,实测先验应当做主,而不是被自适应默认分稀释。样本数
|
|
328
|
+
取场景桶的 judged(桶为空时取全局 judged)。
|
|
329
|
+
"""
|
|
330
|
+
key = (engine, domain or "", lang or "", purpose)
|
|
223
331
|
now = time.time()
|
|
224
|
-
cached = self._score_cache.get(
|
|
225
|
-
if cached and cached[
|
|
226
|
-
return cached[0]
|
|
332
|
+
cached = self._score_cache.get(key)
|
|
333
|
+
if cached and cached[2] > now:
|
|
334
|
+
return cached[0], cached[1]
|
|
227
335
|
|
|
228
336
|
with self._lock:
|
|
229
|
-
cached = self._score_cache.get(
|
|
230
|
-
if cached and cached[
|
|
231
|
-
return cached[0]
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
if not total:
|
|
247
|
-
score = 0.5 # 无数据时中性分
|
|
248
|
-
else:
|
|
249
|
-
# 数据过时恢复:最后一次调用距今过久 → 中性分,给恢复探测机会
|
|
250
|
-
last_ts = float(last_ts or 0)
|
|
251
|
-
if last_ts and (now - last_ts) > STALE_AFTER_SECONDS:
|
|
252
|
-
score = 0.5
|
|
253
|
-
elif judged == 0:
|
|
254
|
-
# 窗口内全是空结果:没有任何可判定健康与否的调用 → 中性分。
|
|
255
|
-
# 给中性分而不是 0:否则「每次都只是没搜到」会把源打死。
|
|
256
|
-
score = 0.5
|
|
257
|
-
else:
|
|
258
|
-
success_rate = (judged_ok or 0) / judged
|
|
259
|
-
latency_factor = min(1.0, 2000.0 / max(avg_latency or 2000, 1))
|
|
260
|
-
cost_factor = max(0.3, 1.0 - (avg_cost or 0.0) * 10)
|
|
261
|
-
q_factor = quality_factor(avg_q, sum_q)
|
|
262
|
-
score = round(success_rate * latency_factor * cost_factor
|
|
263
|
-
* q_factor, 4)
|
|
264
|
-
|
|
265
|
-
self._score_cache[engine] = (score, now + self.SCORE_CACHE_TTL)
|
|
266
|
-
return score
|
|
337
|
+
cached = self._score_cache.get(key)
|
|
338
|
+
if cached and cached[2] > now:
|
|
339
|
+
return cached[0], cached[1]
|
|
340
|
+
grow = self._global_row(engine)
|
|
341
|
+
score = self._score_from_row(grow, purpose)
|
|
342
|
+
samples = int((grow[1] if grow else 0) or 0)
|
|
343
|
+
if domain or lang:
|
|
344
|
+
brow = self._bucket_row(engine, domain or "", lang or "")
|
|
345
|
+
b_judged = int(brow[1] or 0)
|
|
346
|
+
if b_judged > 0:
|
|
347
|
+
b_score = self._score_from_row(brow, purpose)
|
|
348
|
+
w = 0.5 if b_judged >= 3 else 0.3
|
|
349
|
+
score = round((1 - w) * score + w * b_score, 4)
|
|
350
|
+
samples = b_judged
|
|
351
|
+
|
|
352
|
+
self._score_cache[key] = (score, samples, now + self.SCORE_CACHE_TTL)
|
|
353
|
+
return score, samples
|
|
267
354
|
|
|
268
355
|
def get_ranking(self) -> list[tuple[str, float]]:
|
|
269
356
|
"""获取所有引擎的推荐排名(降序)。空结果的排除口径同 `get_score`。"""
|
package/scripts/article.py
CHANGED
|
@@ -29,7 +29,12 @@ def fetch(url: str, timeout: int = 30) -> str:
|
|
|
29
29
|
# (http/https scheme + 非本机/内网目标),被拒即抛错而非跟随
|
|
30
30
|
opener = urllib.request.build_opener(_SafeRedirectHandler)
|
|
31
31
|
with opener.open(req, timeout=timeout) as r:
|
|
32
|
-
|
|
32
|
+
raw = r.read()
|
|
33
|
+
try:
|
|
34
|
+
from http_client import decode_response_body
|
|
35
|
+
return decode_response_body(raw, r.headers.get("Content-Type", ""))
|
|
36
|
+
except ImportError:
|
|
37
|
+
return raw.decode("utf-8", errors="ignore")
|
|
33
38
|
|
|
34
39
|
|
|
35
40
|
class _SafeRedirectHandler(urllib.request.HTTPRedirectHandler):
|
package/scripts/article_meta.py
CHANGED
|
@@ -7,16 +7,25 @@
|
|
|
7
7
|
研究/报告场景里作者与站点名也是引用格式的必需字段。它们都在同一份 HTML 里,
|
|
8
8
|
一次解析就能拿到,不该让调用方付第二次网络往返。
|
|
9
9
|
|
|
10
|
+
2026-10-26 补 JSON-LD(对标 pagesift 的结构化数据提取):新闻站的日期与
|
|
11
|
+
作者最可靠来源是 <script type="application/ld+json"> 的 datePublished/author,
|
|
12
|
+
很多站没有 article:published_time meta 却一定有 JSON-LD。同一次解析顺手拿到,
|
|
13
|
+
零新增请求。meta 标签与 JSON-LD 同时存在时 meta 优先(既有行为不变)。
|
|
14
|
+
|
|
10
15
|
边界:
|
|
11
16
|
- 纯标准库 HTMLParser,毫秒级;不做正文判定(那是 readability 的职责)。
|
|
12
17
|
- 链接只取 <article>/<main> 内。没有语义容器时宁可不给,也不把
|
|
13
18
|
nav/header/footer 的导航链接当正文引用;相对链接按页面 URL 解析。
|
|
14
|
-
- 标题/摘要/站点名只读 meta,不从正文猜;猜错比缺失更糟。
|
|
19
|
+
- 标题/摘要/站点名只读 meta 与 JSON-LD,不从正文猜;猜错比缺失更糟。
|
|
20
|
+
- JSON-LD 日期解析不出时交空串丢弃,不透传原文(原样透传「有字段但读不出
|
|
21
|
+
日期」比缺失更糟,同 engines_builders_batch15._norm_date 的教训)。
|
|
15
22
|
- 全部字段都可能缺失,调用方按 key 是否存在判断,不返回空字符串占位。
|
|
16
23
|
"""
|
|
17
24
|
|
|
18
25
|
from __future__ import annotations
|
|
19
26
|
|
|
27
|
+
import json
|
|
28
|
+
import re
|
|
20
29
|
from html.parser import HTMLParser
|
|
21
30
|
from urllib.parse import urljoin, urlparse
|
|
22
31
|
|
|
@@ -34,6 +43,11 @@ _META_KEYS = {
|
|
|
34
43
|
"twitter:description": "excerpt",
|
|
35
44
|
"article:published_time": "published_at",
|
|
36
45
|
}
|
|
46
|
+
_LDJSON_TYPE = "application/ld+json"
|
|
47
|
+
_LD_SCRIPT_CAP = 8 # 只吃前 8 段 ld+json,防御性上限
|
|
48
|
+
_LD_SCRIPT_MAX = 262144 # 单段 256KB,防御超大内联 JSON
|
|
49
|
+
_LD_ARTICLE_HINTS = ("article", "posting", "news", "blog", "report",
|
|
50
|
+
"webpage", "itempage")
|
|
37
51
|
|
|
38
52
|
|
|
39
53
|
class _MetaParser(HTMLParser):
|
|
@@ -41,10 +55,14 @@ class _MetaParser(HTMLParser):
|
|
|
41
55
|
super().__init__(convert_charrefs=True)
|
|
42
56
|
self.meta: dict[str, str] = {}
|
|
43
57
|
self.article_links: list[dict[str, str]] = []
|
|
58
|
+
self.ld_jsons: list[str] = []
|
|
44
59
|
self._in_article = 0
|
|
45
60
|
self._skip = 0
|
|
46
61
|
self._href: str | None = None
|
|
47
62
|
self._text: list[str] = []
|
|
63
|
+
self._ld_active = False
|
|
64
|
+
self._ld_buf: list[str] = []
|
|
65
|
+
self._ld_len = 0
|
|
48
66
|
|
|
49
67
|
def handle_starttag(self, tag: str, attrs: list[tuple[str, str | None]]) -> None:
|
|
50
68
|
tag = tag.lower()
|
|
@@ -56,6 +74,11 @@ class _MetaParser(HTMLParser):
|
|
|
56
74
|
if field and value and field not in self.meta:
|
|
57
75
|
self.meta[field] = value.strip()[:MAX_TEXT]
|
|
58
76
|
return
|
|
77
|
+
if tag == "script":
|
|
78
|
+
data = {k.lower(): (v or "") for k, v in attrs if k}
|
|
79
|
+
self._ld_active = (data.get("type") or "").strip().lower() == _LDJSON_TYPE
|
|
80
|
+
self._ld_buf = []
|
|
81
|
+
self._ld_len = 0
|
|
59
82
|
if tag in _SKIP_TAGS:
|
|
60
83
|
self._skip += 1
|
|
61
84
|
return
|
|
@@ -73,6 +96,11 @@ class _MetaParser(HTMLParser):
|
|
|
73
96
|
|
|
74
97
|
def handle_endtag(self, tag: str) -> None:
|
|
75
98
|
tag = tag.lower()
|
|
99
|
+
if tag == "script":
|
|
100
|
+
if self._ld_active:
|
|
101
|
+
self._ld_active = False
|
|
102
|
+
if self._ld_buf:
|
|
103
|
+
self.ld_jsons.append("".join(self._ld_buf))
|
|
76
104
|
if tag in _SKIP_TAGS:
|
|
77
105
|
self._skip = max(0, self._skip - 1)
|
|
78
106
|
return
|
|
@@ -86,14 +114,132 @@ class _MetaParser(HTMLParser):
|
|
|
86
114
|
self._text = []
|
|
87
115
|
|
|
88
116
|
def handle_data(self, data: str) -> None:
|
|
117
|
+
if self._ld_active:
|
|
118
|
+
if self._ld_len < _LD_SCRIPT_MAX:
|
|
119
|
+
self._ld_buf.append(data)
|
|
120
|
+
self._ld_len += len(data)
|
|
121
|
+
return
|
|
89
122
|
if self._href is not None and self._skip == 0:
|
|
90
123
|
self._text.append(data)
|
|
91
124
|
|
|
92
125
|
|
|
126
|
+
# ─── JSON-LD 展开与字段提取 ─────────────────────────────────────────────────
|
|
127
|
+
|
|
128
|
+
def _iter_ld_nodes(data) -> list[dict]:
|
|
129
|
+
"""展开 ld+json 常见容器:顶层数组、@graph(含嵌套),保持文档顺序。"""
|
|
130
|
+
out: list[dict] = []
|
|
131
|
+
queue = [data]
|
|
132
|
+
while queue:
|
|
133
|
+
cur = queue.pop(0)
|
|
134
|
+
if isinstance(cur, list):
|
|
135
|
+
queue.extend(cur)
|
|
136
|
+
elif isinstance(cur, dict):
|
|
137
|
+
out.append(cur)
|
|
138
|
+
graph = cur.get("@graph")
|
|
139
|
+
if graph is not None:
|
|
140
|
+
queue.extend(graph if isinstance(graph, list) else [graph])
|
|
141
|
+
return out
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
def _ld_is_article(node: dict) -> bool:
|
|
145
|
+
t = node.get("@type")
|
|
146
|
+
if isinstance(t, list):
|
|
147
|
+
t = " ".join(str(x) for x in t)
|
|
148
|
+
t = str(t or "").lower()
|
|
149
|
+
return any(h in t for h in _LD_ARTICLE_HINTS)
|
|
150
|
+
|
|
151
|
+
|
|
152
|
+
def _ld_name(value) -> str:
|
|
153
|
+
"""author/publisher 的形态归一:str / {name} / [{name},...]。"""
|
|
154
|
+
if isinstance(value, str):
|
|
155
|
+
return value.strip()
|
|
156
|
+
if isinstance(value, dict):
|
|
157
|
+
name = value.get("name")
|
|
158
|
+
return name.strip() if isinstance(name, str) else ""
|
|
159
|
+
if isinstance(value, list):
|
|
160
|
+
parts = [n for n in (_ld_name(v) for v in value) if n]
|
|
161
|
+
return ", ".join(parts)
|
|
162
|
+
return ""
|
|
163
|
+
|
|
164
|
+
|
|
165
|
+
def _ld_date(value) -> str:
|
|
166
|
+
"""JSON-LD 日期 → ISO 前缀规整;解析不出交空串(原样透传比空更糟)。
|
|
167
|
+
|
|
168
|
+
ISO 带时区的(datePublished 主流形态)原样保留;`2026/10/1`、
|
|
169
|
+
`2026年10月1日` 规整成 `2026-10-01`;裸时间补 T。
|
|
170
|
+
"""
|
|
171
|
+
text = str(value or "").strip()
|
|
172
|
+
if not text:
|
|
173
|
+
return ""
|
|
174
|
+
m = re.match(r"(\d{4})[-/.](\d{1,2})[-/.](\d{1,2})", text)
|
|
175
|
+
if not m:
|
|
176
|
+
m = re.match(r"(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?", text)
|
|
177
|
+
if not m:
|
|
178
|
+
return ""
|
|
179
|
+
y, mo, d = (int(g) for g in m.groups())
|
|
180
|
+
if not (1 <= mo <= 12 and 1 <= d <= 31):
|
|
181
|
+
return ""
|
|
182
|
+
tail = text[m.end():].strip()
|
|
183
|
+
if tail and (tail[0].isdigit() or tail[0].isspace()):
|
|
184
|
+
tail = "T" + tail.lstrip() # `2026-10-01 08:00` → ISO 的 T 分隔
|
|
185
|
+
return f"{y:04d}-{mo:02d}-{d:02d}" + tail
|
|
186
|
+
|
|
187
|
+
|
|
188
|
+
def _ld_fields(raw_list: list[str]) -> dict:
|
|
189
|
+
"""从 ld+json 原文里提取元数据字段;文章类节点优先,缺失字段再放宽到全节点。"""
|
|
190
|
+
nodes: list[dict] = []
|
|
191
|
+
for raw in raw_list[:_LD_SCRIPT_CAP]:
|
|
192
|
+
try:
|
|
193
|
+
nodes.extend(_iter_ld_nodes(json.loads(raw)))
|
|
194
|
+
except Exception:
|
|
195
|
+
continue # 非法 JSON/非容器:跳过这一段,不影响其余
|
|
196
|
+
if not nodes:
|
|
197
|
+
return {}
|
|
198
|
+
article_nodes = [n for n in nodes if _ld_is_article(n)]
|
|
199
|
+
fields: dict[str, str] = {}
|
|
200
|
+
|
|
201
|
+
def harvest(pool: list[dict]) -> None:
|
|
202
|
+
for node in pool:
|
|
203
|
+
if "published_at" not in fields:
|
|
204
|
+
d = _ld_date(node.get("datePublished"))
|
|
205
|
+
if d:
|
|
206
|
+
fields["published_at"] = d
|
|
207
|
+
if "headline" not in fields:
|
|
208
|
+
h = node.get("headline")
|
|
209
|
+
if isinstance(h, str) and h.strip():
|
|
210
|
+
fields["headline"] = h.strip()[:MAX_TEXT]
|
|
211
|
+
if "byline" not in fields:
|
|
212
|
+
a = _ld_name(node.get("author") or node.get("creator"))
|
|
213
|
+
if a:
|
|
214
|
+
fields["byline"] = a[:MAX_TEXT]
|
|
215
|
+
if "site_name" not in fields:
|
|
216
|
+
s = _ld_name(node.get("publisher"))
|
|
217
|
+
if not s:
|
|
218
|
+
# 无 publisher 时,WebSite/Organization 的 name 即站点名;
|
|
219
|
+
# WebPage/Product 等的 name 是页面标题/商品名,不收
|
|
220
|
+
t = str(node.get("@type") or "").lower()
|
|
221
|
+
if "website" in t or "organization" in t:
|
|
222
|
+
s = _ld_name(node.get("name"))
|
|
223
|
+
if s:
|
|
224
|
+
fields["site_name"] = s[:MAX_TEXT]
|
|
225
|
+
if "excerpt" not in fields:
|
|
226
|
+
e = node.get("description")
|
|
227
|
+
if isinstance(e, str) and e.strip():
|
|
228
|
+
fields["excerpt"] = " ".join(e.split())[:MAX_TEXT]
|
|
229
|
+
|
|
230
|
+
harvest(article_nodes)
|
|
231
|
+
if len(fields) < 5 and len(article_nodes) < len(nodes):
|
|
232
|
+
rest = [n for n in nodes if n not in article_nodes]
|
|
233
|
+
harvest(rest)
|
|
234
|
+
return fields
|
|
235
|
+
|
|
236
|
+
|
|
93
237
|
def extract_article_meta(html: str, base_url: str,
|
|
94
238
|
max_links: int = MAX_LINKS) -> dict:
|
|
95
|
-
"""返回 {byline, excerpt, site_name, published_at, links},缺失的键不出现。
|
|
239
|
+
"""返回 {byline, excerpt, site_name, published_at, headline, links},缺失的键不出现。
|
|
96
240
|
|
|
241
|
+
headline 仅 JSON-LD 提供(meta 标签没有对应声明位);其余字段 meta 与
|
|
242
|
+
JSON-LD 双源,meta 优先。
|
|
97
243
|
links: [{"url": 绝对 URL, "text": 锚文本}],按出现顺序去重,最多 max_links。
|
|
98
244
|
同页锚点、javascript/mailto、非 http(s)、空文本一律丢弃。
|
|
99
245
|
"""
|
|
@@ -106,6 +252,9 @@ def extract_article_meta(html: str, base_url: str,
|
|
|
106
252
|
except Exception:
|
|
107
253
|
return {}
|
|
108
254
|
out: dict = dict(p.meta)
|
|
255
|
+
for key, value in _ld_fields(p.ld_jsons).items():
|
|
256
|
+
if value and key not in out:
|
|
257
|
+
out[key] = value # meta 已有的字段不被 JSON-LD 覆盖(缺失才补)
|
|
109
258
|
raw_links = p.article_links
|
|
110
259
|
if raw_links:
|
|
111
260
|
links: list[dict[str, str]] = []
|
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""bench_general_pool.py — 通用层选源的 static/dynamic 交错对拍。
|
|
3
|
+
|
|
4
|
+
用途:`source_selection.GENERAL_PRIORS` 的先验不是拍脑袋写的,重测/改表
|
|
5
|
+
前后用这个脚本给出同一网络时刻的两臂读数。两臂各自使用**独立的隔离状态
|
|
6
|
+
目录**,并关闭路由缓存——否则静态臂先跑会把 decision 缓存给动态臂,
|
|
7
|
+
两臂读到同一组合,A/B 变成自欺(2026-10-26 实测踩中)。
|
|
8
|
+
|
|
9
|
+
python3 scripts/bench_general_pool.py --rounds 2
|
|
10
|
+
python3 scripts/bench_general_pool.py --queries "git commit,上海 地铁 线路图" --json
|
|
11
|
+
|
|
12
|
+
输出:每条查询的墙钟、结果数、词面相关代理(query_signals.result_relevance)
|
|
13
|
+
与贡献引擎;末尾给两臂的 p50/mean/相关均值。词面相关只是代理,不等于内容
|
|
14
|
+
正确性——要看正确性得走 `--verify` 核正文。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import argparse
|
|
20
|
+
import json
|
|
21
|
+
import os
|
|
22
|
+
import subprocess
|
|
23
|
+
import sys
|
|
24
|
+
import tempfile
|
|
25
|
+
import time
|
|
26
|
+
|
|
27
|
+
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
|
28
|
+
sys.path.insert(0, os.path.join(ROOT, "scripts"))
|
|
29
|
+
|
|
30
|
+
from query_signals import result_relevance # noqa: E402
|
|
31
|
+
|
|
32
|
+
DEFAULT_QUERIES = [
|
|
33
|
+
"git commit",
|
|
34
|
+
"quiet mechanical keyboard office use review",
|
|
35
|
+
"ergonomic keyboard wrist pain 2026",
|
|
36
|
+
"best budget laptop 2026",
|
|
37
|
+
"how to clean a cast iron pan",
|
|
38
|
+
"nanjing food recommendations",
|
|
39
|
+
"Как написать скрипт",
|
|
40
|
+
"software architecture review checklist",
|
|
41
|
+
]
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _run(argo: str, query: str, static: bool, state_dir: str,
|
|
45
|
+
timeout: float) -> dict:
|
|
46
|
+
env = dict(os.environ, ARGO_USAGE_LOG="0", ARGO_ROUTE_CACHE="0",
|
|
47
|
+
ARGO_STATE_DIR=state_dir)
|
|
48
|
+
for key in ("ARGO_GENERAL_FALLBACK_STATIC", "ARGO_GENERAL_FALLBACK_LEAD",
|
|
49
|
+
"ARGO_GENERAL_FALLBACK_LEGACY"):
|
|
50
|
+
env.pop(key, None)
|
|
51
|
+
if static:
|
|
52
|
+
env["ARGO_GENERAL_FALLBACK_STATIC"] = "1"
|
|
53
|
+
started = time.perf_counter()
|
|
54
|
+
try:
|
|
55
|
+
proc = subprocess.run(
|
|
56
|
+
[argo, "search", query, "--json", "--no-cache", "-n", "8"],
|
|
57
|
+
capture_output=True, text=True, encoding="utf-8",
|
|
58
|
+
timeout=timeout, env=env)
|
|
59
|
+
elapsed = int((time.perf_counter() - started) * 1000)
|
|
60
|
+
payload = json.loads(proc.stdout) if proc.stdout.strip().startswith("{") else {}
|
|
61
|
+
results = [r for r in (payload.get("results") or [])
|
|
62
|
+
if isinstance(r, dict) and "error" not in r]
|
|
63
|
+
except Exception as exc: # 超时/非 JSON:如实记失败,不替它编读数
|
|
64
|
+
return {"ms": int((time.perf_counter() - started) * 1000),
|
|
65
|
+
"n": 0, "rel": None, "engines": [], "error": repr(exc)[:160]}
|
|
66
|
+
return {
|
|
67
|
+
"ms": elapsed,
|
|
68
|
+
"n": len(results),
|
|
69
|
+
# agent 档真实字节:与 drift 门禁同一口径(stdout 的实际大小)。
|
|
70
|
+
# 排序不读它(见 source_selection 的说明),但 A/B 必须能量出来,
|
|
71
|
+
# 否则「体积换速度」的取舍永远只能凭感觉。
|
|
72
|
+
"bytes": len(proc.stdout.encode("utf-8")),
|
|
73
|
+
"rel": result_relevance(query, results) if results else None,
|
|
74
|
+
"engines": payload.get("engines_used") or [],
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
|
|
78
|
+
def _summary(rows: list[dict]) -> dict:
|
|
79
|
+
latencies = sorted(r["ms"] for r in rows)
|
|
80
|
+
rels = [r["rel"] for r in rows if r.get("rel") is not None]
|
|
81
|
+
if not latencies:
|
|
82
|
+
return {"n": 0}
|
|
83
|
+
sizes = [r.get("bytes", 0) for r in rows if r.get("bytes")]
|
|
84
|
+
return {
|
|
85
|
+
"n": len(rows),
|
|
86
|
+
"p50_ms": latencies[len(latencies) // 2],
|
|
87
|
+
"mean_ms": round(sum(latencies) / len(latencies)),
|
|
88
|
+
"mean_bytes": round(sum(sizes) / len(sizes)) if sizes else None,
|
|
89
|
+
"rel_mean": round(sum(rels) / len(rels), 3) if rels else None,
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
|
|
93
|
+
def main() -> int:
|
|
94
|
+
parser = argparse.ArgumentParser(description="通用层选源 static/dynamic 对拍")
|
|
95
|
+
parser.add_argument("--queries", help="逗号分隔;默认 8 条混合中英查询")
|
|
96
|
+
parser.add_argument("--rounds", type=int, default=2,
|
|
97
|
+
help="每臂轮数;两轮交错臂顺序,抵消网络漂移")
|
|
98
|
+
parser.add_argument("--timeout", type=float, default=45.0)
|
|
99
|
+
parser.add_argument("--argo", default=os.path.expanduser("~/.local/bin/argo"))
|
|
100
|
+
parser.add_argument("--json", action="store_true")
|
|
101
|
+
args = parser.parse_args()
|
|
102
|
+
|
|
103
|
+
queries = ([q.strip() for q in args.queries.split(",") if q.strip()]
|
|
104
|
+
if args.queries else DEFAULT_QUERIES)
|
|
105
|
+
root = tempfile.mkdtemp(prefix="argo-bench-gp-")
|
|
106
|
+
state = {"static": os.path.join(root, "static"),
|
|
107
|
+
"dynamic": os.path.join(root, "dynamic")}
|
|
108
|
+
for path in state.values():
|
|
109
|
+
os.makedirs(path, exist_ok=True)
|
|
110
|
+
|
|
111
|
+
rows: list[dict] = []
|
|
112
|
+
for rnd in range(max(1, args.rounds)):
|
|
113
|
+
for query in queries:
|
|
114
|
+
order = [True, False] if rnd % 2 == 0 else [False, True]
|
|
115
|
+
for static in order:
|
|
116
|
+
arm = "static" if static else "dynamic"
|
|
117
|
+
reading = _run(args.argo, query, static, state[arm], args.timeout)
|
|
118
|
+
reading.update(query=query, arm=arm, round=rnd)
|
|
119
|
+
rows.append(reading)
|
|
120
|
+
if not args.json:
|
|
121
|
+
print(f"r{rnd} {query[:30]:30s} {arm:7s} "
|
|
122
|
+
f"{reading['ms']:5d}ms n={reading['n']} "
|
|
123
|
+
f"bytes={reading.get('bytes', 0)} "
|
|
124
|
+
f"rel={reading['rel']} {reading['engines']}", flush=True)
|
|
125
|
+
|
|
126
|
+
report = {
|
|
127
|
+
"state_root": root,
|
|
128
|
+
"queries": queries,
|
|
129
|
+
"rounds": max(1, args.rounds),
|
|
130
|
+
"static": _summary([r for r in rows if r["arm"] == "static"]),
|
|
131
|
+
"dynamic": _summary([r for r in rows if r["arm"] == "dynamic"]),
|
|
132
|
+
"rows": rows,
|
|
133
|
+
}
|
|
134
|
+
if args.json:
|
|
135
|
+
# 紧凑 stdout:仓库门禁禁止脚本向终端输出 pretty JSON(上下文预算)。
|
|
136
|
+
print(json.dumps(report, ensure_ascii=False))
|
|
137
|
+
else:
|
|
138
|
+
print("\n=== summary ===")
|
|
139
|
+
for arm in ("static", "dynamic"):
|
|
140
|
+
print(arm, report[arm])
|
|
141
|
+
return 0
|
|
142
|
+
|
|
143
|
+
|
|
144
|
+
if __name__ == "__main__":
|
|
145
|
+
raise SystemExit(main())
|