argo-search 2.9.9 → 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 +24 -21
- package/README.es.md +24 -21
- package/README.ja.md +23 -20
- package/README.ko.md +23 -20
- package/README.md +26 -21
- 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 +22 -1
- package/bin/argo.js +3 -3
- package/config.yaml +128 -21
- package/docs/ARGO_INTRO.md +4 -4
- 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//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 +3 -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/crawl.py +240 -74
- package/scripts/crawl_frontier.py +217 -0
- package/scripts/crawl_policy.py +174 -0
- package/scripts/engine_dispatch.py +22 -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/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/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_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 +4 -1
- package/scripts/route_policy.py +6 -0
- package/scripts/search.py +9 -1
- package/scripts/search_cli.py +27 -0
- package/scripts/search_entry.py +9 -0
- package/scripts/search_output.py +29 -0
- package/scripts/search_pipeline.py +39 -1
- package/scripts/search_rank.py +1 -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/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/local_engines.py +0 -321
|
@@ -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())
|
|
@@ -22,13 +22,23 @@ from datetime import datetime, timezone, timedelta
|
|
|
22
22
|
from typing import Any
|
|
23
23
|
from urllib.parse import urlparse
|
|
24
24
|
|
|
25
|
+
from video_meta import VIDEO_PLATFORMS, parse_duration_seconds
|
|
26
|
+
|
|
25
27
|
_TZ_CN = timezone(timedelta(hours=8))
|
|
26
28
|
|
|
27
29
|
# 技能目录源(engines/specs/*.yaml 里声明 `coverage: skill` 的那些,加上走
|
|
28
30
|
# 自定义引擎的 redskill)。这里用常量而非运行时读 spec:本函数在输出路径上,
|
|
29
31
|
# config.yaml 有 130KB+,为一句局限声明去解析它是拿延迟换措辞。
|
|
30
32
|
# 与 spec 的一致性由 tests/test_skill_registry_contract.py 断言,不靠人记。
|
|
31
|
-
|
|
33
|
+
# DSH 插件三源(dshopen / deepseek1024 / dsh_hub)同属此列:它们都是「可安装
|
|
34
|
+
# 扩展的目录」,命中时带 SKILL_REGISTRY_LIMITATION 提示(市场列表不等于已验证
|
|
35
|
+
# 包,装前看上游引用)。与 spec 的 coverage: skill 声明对账,由
|
|
36
|
+
# tests/test_skill_registry_contract.py 把守。
|
|
37
|
+
SKILL_REGISTRY_ENGINES = frozenset({
|
|
38
|
+
"redskill", "skillsmp", "clawhub",
|
|
39
|
+
"explainx", "skills_sh",
|
|
40
|
+
"dshopen", "deepseek1024", "dsh_hub",
|
|
41
|
+
})
|
|
32
42
|
|
|
33
43
|
SKILL_REGISTRY_LIMITATION = (
|
|
34
44
|
"Skill directory hits are marketplace listings, not verified packages; "
|
|
@@ -71,6 +81,20 @@ def _platform_of(url: str, source: str) -> str:
|
|
|
71
81
|
return "weibo"
|
|
72
82
|
if "youtube.com" in host or "youtu.be" in host:
|
|
73
83
|
return "youtube"
|
|
84
|
+
if "douyin.com" in host:
|
|
85
|
+
return "douyin"
|
|
86
|
+
if "kuaishou.com" in host:
|
|
87
|
+
return "kuaishou"
|
|
88
|
+
if "vimeo.com" in host:
|
|
89
|
+
return "vimeo"
|
|
90
|
+
if "v.qq.com" in host:
|
|
91
|
+
return "tencent_video"
|
|
92
|
+
if "youku.com" in host:
|
|
93
|
+
return "youku"
|
|
94
|
+
if "iqiyi.com" in host:
|
|
95
|
+
return "iqiyi"
|
|
96
|
+
if "ixigua.com" in host or "xigua.com" in host:
|
|
97
|
+
return "xigua"
|
|
74
98
|
if host in {"x.com", "twitter.com"} or host.endswith(".x.com"):
|
|
75
99
|
return "x"
|
|
76
100
|
if "mp.weixin.qq.com" in host:
|
|
@@ -142,12 +166,28 @@ def result_to_candidate(
|
|
|
142
166
|
platform = _platform_of(url, source)
|
|
143
167
|
canon = canonicalize_url(url) or url
|
|
144
168
|
social = item.get("social_meta") if isinstance(item.get("social_meta"), dict) else {}
|
|
169
|
+
duration_seconds = parse_duration_seconds(social.get("duration")) if social else None
|
|
170
|
+
if duration_seconds is None:
|
|
171
|
+
duration_seconds = parse_duration_seconds(item.get("duration"))
|
|
172
|
+
if social.get("content_type") == "video" or platform in VIDEO_PLATFORMS:
|
|
173
|
+
content_type = "video"
|
|
174
|
+
elif social:
|
|
175
|
+
content_type = "social_post"
|
|
176
|
+
else:
|
|
177
|
+
content_type = "web_page"
|
|
145
178
|
metrics = {
|
|
146
|
-
"likes":
|
|
179
|
+
"likes": next(
|
|
180
|
+
(social[k] for k in ("likes", "like_count") if social.get(k) is not None),
|
|
181
|
+
None),
|
|
147
182
|
"comments": social.get("comments") if social else None,
|
|
148
183
|
"collects": social.get("collects") if social else None,
|
|
149
184
|
"shares": social.get("shares") or social.get("retweets"),
|
|
150
|
-
|
|
185
|
+
# B 站引擎的字段名是 play_count;旧写法只认 views/play,实测播放量
|
|
186
|
+
# 恒为 null,与「统一 engagement 口径」的目标相反。
|
|
187
|
+
"views": next(
|
|
188
|
+
(social[k] for k in ("views", "play", "play_count")
|
|
189
|
+
if social.get(k) is not None),
|
|
190
|
+
None),
|
|
151
191
|
}
|
|
152
192
|
# 明确后端给了 0 才保留 0;否则 null
|
|
153
193
|
for k, v in list(metrics.items()):
|
|
@@ -173,7 +213,8 @@ def result_to_candidate(
|
|
|
173
213
|
"snippet": (item.get("snippet") or "")[:300],
|
|
174
214
|
"author": social.get("author") if social else None,
|
|
175
215
|
"published_at": item.get("published_at") or social.get("published_at"),
|
|
176
|
-
"content_type":
|
|
216
|
+
"content_type": content_type,
|
|
217
|
+
"duration_seconds": duration_seconds,
|
|
177
218
|
"language": None,
|
|
178
219
|
"metrics": metrics,
|
|
179
220
|
"access": {
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""charset_decode.py — 响应体解码:响应头声明 > HTML meta 嗅探 > 严格猜测链。
|
|
3
|
+
|
|
4
|
+
为什么独立成模块(2026-10-26,对标 pagesift 的字符集检测):HTTP 头缺失
|
|
5
|
+
charset 是常态(老站尤甚),此前 http_client 对这些响应一律 utf-8 replace,
|
|
6
|
+
GBK/GB2312 页面解出满屏 U+FFFD(实测 zol/4399/pconline 三站各 1.6 万~5 万个)。
|
|
7
|
+
解码层是纯函数、无网络依赖,拆出既让 http_client 体积门禁随动下调,也让
|
|
8
|
+
fetch_v3/article.py 的 urllib 兜底车道能直接复用(它们在 http_client 不可
|
|
9
|
+
导入时同样要能正确解码)。
|
|
10
|
+
|
|
11
|
+
解码顺序:
|
|
12
|
+
1. 响应头显式声明且 codec 已注册 → 信任头(与浏览器一致),即使解出替换符
|
|
13
|
+
也不回退猜测——显式声明的二进制残余不许被误猜成别的编码;
|
|
14
|
+
2. 头缺失/不可识别 → 按 WHATWG prescan 语义嗅探 HTML 前 2KB 的 <meta>
|
|
15
|
+
声明(content-type meta 的 content 值优先于 charset 属性;带 content 的
|
|
16
|
+
其他 meta 跳过——description 正文里的「charset=」是数据不是声明);
|
|
17
|
+
3. 仍无果 → 严格猜测链:utf-8 严格成功即原样;失败且高字节占比达标
|
|
18
|
+
(西文页零星弯引号 <2%,GBK 中文页即便混排标记也 >10%)时依次试
|
|
19
|
+
gb18030/big5(严格);全败 utf-8 replace 兜底,任何失败不丢 body。
|
|
20
|
+
|
|
21
|
+
gb18030 是 GBK/GB2312 的超集,一个 codec 覆盖中文生态,无需 chardet 依赖。
|
|
22
|
+
纯标准库,零 pip 依赖。
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from __future__ import annotations
|
|
26
|
+
|
|
27
|
+
import re
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
def _header_charset(content_type: str) -> str | None:
|
|
31
|
+
"""Content-Type 头里可用(codec 已注册)的 charset;缺失或不可识别返回 None。
|
|
32
|
+
|
|
33
|
+
None 与显式 "utf-8" 语义不同:前者允许进入嗅探/猜测链,后者必须信任头。
|
|
34
|
+
未知编码必须先判定再解码:`bytes.decode("x-unknown-8bit")` 会抛 LookupError,
|
|
35
|
+
而 LookupError 不是 OSError 子类,会被 HttpClient.get 的 `except Exception`
|
|
36
|
+
吞掉并返回 status=0——一个正常的 200 响应被静默降级成「连接失败」,
|
|
37
|
+
还被归因为 network。运维现实里 `charset=x-unknown-8bit`、
|
|
38
|
+
`charset=gb2312;` 这类脏头并不罕见。
|
|
39
|
+
"""
|
|
40
|
+
import codecs
|
|
41
|
+
if "charset=" in content_type:
|
|
42
|
+
charset = content_type.split("charset=")[-1].strip().split(";")[0].strip().strip('"\'')
|
|
43
|
+
try:
|
|
44
|
+
codecs.lookup(charset)
|
|
45
|
+
return charset
|
|
46
|
+
except (LookupError, ValueError):
|
|
47
|
+
pass
|
|
48
|
+
return None
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _charset_of(content_type: str) -> str:
|
|
52
|
+
"""从 Content-Type 解析 charset;缺失或无法识别时回落 utf-8。"""
|
|
53
|
+
return _header_charset(content_type) or "utf-8"
|
|
54
|
+
|
|
55
|
+
|
|
56
|
+
# ─── HTML 字符集嗅探(对标 pagesift 的 mojibake 防线)────────────────────────
|
|
57
|
+
|
|
58
|
+
_PRESCAN_WINDOW = 2048
|
|
59
|
+
_HIGH_BYTE_SAMPLE = 65536
|
|
60
|
+
_HIGH_BYTE_RATIO = 0.1 # 西文页零星弯引号 <2%,GBK 中文页即便混排标记也 >10%
|
|
61
|
+
_META_TAG_RE = re.compile(rb"<meta\b[^>]*>", re.I)
|
|
62
|
+
_META_CHARSET_ATTR_RE = re.compile(
|
|
63
|
+
rb"""[\s"']charset\s*=\s*["']?\s*([a-zA-Z0-9._\-]+)""", re.I)
|
|
64
|
+
_CONTENT_TYPE_META_RE = re.compile(
|
|
65
|
+
rb"""(?:http-equiv|name)\s*=\s*["']?content-type["']?""", re.I)
|
|
66
|
+
_CONTENT_ATTR_RE = re.compile(
|
|
67
|
+
rb"""content\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s>]+))""", re.I)
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
def _sniff_meta_charset(raw_body: bytes) -> str:
|
|
71
|
+
"""从 HTML 前 2KB 嗅探 <meta> 声明的字符集;无声明或 codec 不存在返回空。
|
|
72
|
+
|
|
73
|
+
按 WHATWG prescan 语义:content-type meta(http-equiv/name 均收,现实里
|
|
74
|
+
两种写法都有)的 content 值优先,其次 charset 属性。只做字节层正则,
|
|
75
|
+
不建 DOM,毫秒级;声明不可信的残留 damage 由 errors="replace" 兜住。
|
|
76
|
+
"""
|
|
77
|
+
window = raw_body[:_PRESCAN_WINDOW]
|
|
78
|
+
if b"<meta" not in window.lower():
|
|
79
|
+
return ""
|
|
80
|
+
candidates: list[str] = []
|
|
81
|
+
for tag in _META_TAG_RE.finditer(window):
|
|
82
|
+
tag_bytes = tag.group(0)
|
|
83
|
+
if _CONTENT_TYPE_META_RE.search(tag_bytes):
|
|
84
|
+
m = _CONTENT_ATTR_RE.search(tag_bytes)
|
|
85
|
+
if m:
|
|
86
|
+
value = next(g for g in m.groups() if g is not None)
|
|
87
|
+
text = value.decode("ascii", "ignore")
|
|
88
|
+
idx = text.lower().find("charset=")
|
|
89
|
+
if idx >= 0:
|
|
90
|
+
name = text[idx + 8:].split(";")[0].strip().strip("\"'")
|
|
91
|
+
candidates.append(name)
|
|
92
|
+
continue
|
|
93
|
+
if _CONTENT_ATTR_RE.search(tag_bytes):
|
|
94
|
+
continue
|
|
95
|
+
m = _META_CHARSET_ATTR_RE.search(b" " + tag_bytes)
|
|
96
|
+
if m:
|
|
97
|
+
candidates.append(m.group(1).decode("ascii", "ignore"))
|
|
98
|
+
import codecs
|
|
99
|
+
for name in candidates:
|
|
100
|
+
try:
|
|
101
|
+
codecs.lookup(name)
|
|
102
|
+
return name
|
|
103
|
+
except (LookupError, ValueError):
|
|
104
|
+
continue
|
|
105
|
+
return ""
|
|
106
|
+
|
|
107
|
+
|
|
108
|
+
def decode_response_body(raw_body: bytes, content_type: str) -> str:
|
|
109
|
+
"""按「响应头声明 > HTML meta 嗅探 > 严格解码链」解出文本,任何失败都不丢 body。"""
|
|
110
|
+
declared = _header_charset(content_type)
|
|
111
|
+
if declared is not None:
|
|
112
|
+
return raw_body.decode(declared, errors="replace")
|
|
113
|
+
sniffed = _sniff_meta_charset(raw_body)
|
|
114
|
+
if sniffed and sniffed.lower() not in ("utf-8", "utf8", "ascii", "us-ascii"):
|
|
115
|
+
return raw_body.decode(sniffed, errors="replace")
|
|
116
|
+
try:
|
|
117
|
+
return raw_body.decode("utf-8", errors="strict")
|
|
118
|
+
except UnicodeDecodeError:
|
|
119
|
+
pass
|
|
120
|
+
sample = raw_body[:_HIGH_BYTE_SAMPLE]
|
|
121
|
+
if sample and sum(1 for b in sample if b >= 0x80) / len(sample) >= _HIGH_BYTE_RATIO:
|
|
122
|
+
for enc in ("gb18030", "big5"):
|
|
123
|
+
try:
|
|
124
|
+
return raw_body.decode(enc, errors="strict")
|
|
125
|
+
except (UnicodeDecodeError, ValueError):
|
|
126
|
+
continue
|
|
127
|
+
return raw_body.decode("utf-8", errors="replace")
|