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,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
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""video_meta.py — 视频来源识别与时长归一(零依赖纯函数)。
|
|
3
|
+
|
|
4
|
+
搜索链路里「视频」此前只体现为平台名:B 站引擎抓到了时长/播放量,但
|
|
5
|
+
CLI 解析层不透传 social_meta,envelope 又把所有带 social_meta 的结果写成
|
|
6
|
+
social_post。本模块只做三件可单独测试的事:
|
|
7
|
+
|
|
8
|
+
- URL → 平台/是否视频页(区分 B 站 /video/ 与 /read/ 图文);
|
|
9
|
+
- 各种时长写法 → 秒(B 站 "8:27"、API 数字、文本 "5分钟");
|
|
10
|
+
- 结果集 → 视频过滤/时长过滤(供 --video 与 --min-duration 使用)。
|
|
11
|
+
|
|
12
|
+
判据刻意按「页面是不是视频」而不是「域名是不是视频站」:B 站专栏与动态
|
|
13
|
+
(/read/、/opus/)不是视频,抖音用户主页也不是单条视频。按域名一刀切会
|
|
14
|
+
把图文当视频放进来,--video 的结果就不再可信。
|
|
15
|
+
"""
|
|
16
|
+
|
|
17
|
+
from __future__ import annotations
|
|
18
|
+
|
|
19
|
+
import re
|
|
20
|
+
from typing import Any
|
|
21
|
+
from urllib.parse import urlparse
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
# 域名 → 平台名。匹配按后缀(www./m. 等子域自动命中),路径规则在
|
|
25
|
+
# video_platform 里逐平台收紧。
|
|
26
|
+
_VIDEO_HOSTS: dict[str, str] = {
|
|
27
|
+
"youtube.com": "youtube",
|
|
28
|
+
"youtu.be": "youtube",
|
|
29
|
+
"bilibili.com": "bilibili",
|
|
30
|
+
"b23.tv": "bilibili",
|
|
31
|
+
"douyin.com": "douyin",
|
|
32
|
+
"iesdouyin.com": "douyin",
|
|
33
|
+
"kuaishou.com": "kuaishou",
|
|
34
|
+
"vimeo.com": "vimeo",
|
|
35
|
+
"v.qq.com": "tencent_video",
|
|
36
|
+
"youku.com": "youku",
|
|
37
|
+
"iqiyi.com": "iqiyi",
|
|
38
|
+
"ixigua.com": "xigua",
|
|
39
|
+
"xigua.com": "xigua",
|
|
40
|
+
"ted.com": "ted",
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
# envelope 里算「视频」的平台名(与 _platform_of 的返回值对齐)。
|
|
44
|
+
VIDEO_PLATFORMS = frozenset({
|
|
45
|
+
"youtube", "bilibili", "douyin", "kuaishou", "vimeo",
|
|
46
|
+
"tencent_video", "youku", "iqiyi", "xigua", "ted",
|
|
47
|
+
})
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
def _host_of(url: str) -> str:
|
|
51
|
+
try:
|
|
52
|
+
host = (urlparse(url).netloc or "").lower().split("@")[-1]
|
|
53
|
+
except (ValueError, AttributeError):
|
|
54
|
+
return ""
|
|
55
|
+
# 去端口(IPv6 不在视频站范围,按常见 host:port 处理即可)
|
|
56
|
+
return host.split(":")[0]
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def video_platform(url: str) -> str | None:
|
|
60
|
+
"""URL → 视频平台名;不是单条视频页返回 None。
|
|
61
|
+
|
|
62
|
+
路径判据比域名严格,原因见模块头:B 站 /read/ 与抖音用户主页不是视频。
|
|
63
|
+
"""
|
|
64
|
+
if not url:
|
|
65
|
+
return None
|
|
66
|
+
host = _host_of(url)
|
|
67
|
+
if not host:
|
|
68
|
+
return None
|
|
69
|
+
platform = None
|
|
70
|
+
for domain, name in _VIDEO_HOSTS.items():
|
|
71
|
+
if host == domain or host.endswith("." + domain):
|
|
72
|
+
platform = name
|
|
73
|
+
break
|
|
74
|
+
if platform is None:
|
|
75
|
+
return None
|
|
76
|
+
|
|
77
|
+
try:
|
|
78
|
+
path = urlparse(url).path or ""
|
|
79
|
+
except (ValueError, AttributeError):
|
|
80
|
+
path = ""
|
|
81
|
+
|
|
82
|
+
if platform == "bilibili":
|
|
83
|
+
# 短链 b23.tv 任何路径都视为视频;主站只认 /video/ 与 /bangumi/
|
|
84
|
+
if host == "b23.tv" or host.endswith(".b23.tv"):
|
|
85
|
+
return platform
|
|
86
|
+
if path.startswith("/video/") or path.startswith("/bangumi/"):
|
|
87
|
+
return platform
|
|
88
|
+
return None
|
|
89
|
+
if platform == "youtube":
|
|
90
|
+
if host == "youtu.be" or host.endswith(".youtu.be"):
|
|
91
|
+
return platform
|
|
92
|
+
if any(path.startswith(p) for p in
|
|
93
|
+
("/watch", "/shorts/", "/embed/", "/live/")):
|
|
94
|
+
return platform
|
|
95
|
+
return None
|
|
96
|
+
if platform == "douyin":
|
|
97
|
+
if host.startswith("v.") or host.startswith("v-"):
|
|
98
|
+
return platform
|
|
99
|
+
return platform if "/video/" in path else None
|
|
100
|
+
if platform == "kuaishou":
|
|
101
|
+
return platform if ("/short-video/" in path or "/fw/photo/" in path) else None
|
|
102
|
+
if platform == "vimeo":
|
|
103
|
+
return platform if re.search(r"/\d+", path) else None
|
|
104
|
+
if platform == "tencent_video":
|
|
105
|
+
return platform if ("/x/page/" in path or "/x/cover/" in path) else None
|
|
106
|
+
if platform == "youku":
|
|
107
|
+
return platform if "/v_show/" in path else None
|
|
108
|
+
if platform == "iqiyi":
|
|
109
|
+
return platform if "/v_" in path else None
|
|
110
|
+
if platform == "xigua":
|
|
111
|
+
return platform if "/video/" in path else None
|
|
112
|
+
if platform == "ted":
|
|
113
|
+
return platform if "/talks/" in path else None
|
|
114
|
+
return platform
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def is_video_url(url: str) -> bool:
|
|
118
|
+
"""是否单条视频页(视频平台 + 视频路径)。"""
|
|
119
|
+
return video_platform(url) is not None
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
def parse_duration_seconds(value: Any) -> int | None:
|
|
123
|
+
"""把视频时长归一成秒。
|
|
124
|
+
|
|
125
|
+
支持:整数/浮点秒、"8:27"、"1:02:03"、"5分钟"、"90秒"、"1小时2分"。
|
|
126
|
+
解析不了返回 None(而不是 0):0 会被下游当成「零时长视频」误过滤。
|
|
127
|
+
"""
|
|
128
|
+
if value is None or isinstance(value, bool):
|
|
129
|
+
return None
|
|
130
|
+
if isinstance(value, (int, float)):
|
|
131
|
+
return int(value) if value >= 0 else None
|
|
132
|
+
text = str(value).strip()
|
|
133
|
+
if not text:
|
|
134
|
+
return None
|
|
135
|
+
|
|
136
|
+
# 纯数字秒
|
|
137
|
+
if re.fullmatch(r"\d+(?:\.\d+)?", text):
|
|
138
|
+
return int(float(text))
|
|
139
|
+
|
|
140
|
+
# mm:ss / hh:mm:ss(B 站搜索结果里 "1:0" 表示 1 分 0 秒)
|
|
141
|
+
if re.fullmatch(r"\d+(?::\d+){1,2}", text):
|
|
142
|
+
total = 0
|
|
143
|
+
for part in text.split(":"):
|
|
144
|
+
total = total * 60 + int(part)
|
|
145
|
+
return total
|
|
146
|
+
|
|
147
|
+
# 中文时长("5分钟"、"1小时2分"、"90秒")
|
|
148
|
+
m = re.search(
|
|
149
|
+
r"(?:(\d+)\s*(?:小时|时))?\s*(?:(\d+)\s*(?:分钟|分))?\s*(?:(\d+)\s*秒)?",
|
|
150
|
+
text,
|
|
151
|
+
)
|
|
152
|
+
if m and any(m.groups()):
|
|
153
|
+
hours = int(m.group(1) or 0)
|
|
154
|
+
minutes = int(m.group(2) or 0)
|
|
155
|
+
seconds = int(m.group(3) or 0)
|
|
156
|
+
return hours * 3600 + minutes * 60 + seconds
|
|
157
|
+
return None
|
|
158
|
+
|
|
159
|
+
|
|
160
|
+
def result_duration_seconds(item: dict[str, Any]) -> int | None:
|
|
161
|
+
"""从一条搜索结果里取时长(social_meta 优先,其次顶层与 metrics)。"""
|
|
162
|
+
if not isinstance(item, dict):
|
|
163
|
+
return None
|
|
164
|
+
for container in (item.get("social_meta"), item, item.get("metrics")):
|
|
165
|
+
if not isinstance(container, dict):
|
|
166
|
+
continue
|
|
167
|
+
for key in ("duration_seconds", "duration"):
|
|
168
|
+
seconds = parse_duration_seconds(container.get(key))
|
|
169
|
+
if seconds is not None:
|
|
170
|
+
return seconds
|
|
171
|
+
return None
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
def is_video_result(item: dict[str, Any]) -> bool:
|
|
175
|
+
"""一条结果是否是视频(引擎声明的 content_type 优先,其次 URL 判据)。"""
|
|
176
|
+
if not isinstance(item, dict):
|
|
177
|
+
return False
|
|
178
|
+
social = item.get("social_meta")
|
|
179
|
+
if isinstance(social, dict) and social.get("content_type") == "video":
|
|
180
|
+
return True
|
|
181
|
+
return is_video_url(item.get("url") or "")
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def filter_video_results(
|
|
185
|
+
results: list[dict[str, Any]],
|
|
186
|
+
) -> tuple[list[dict[str, Any]], int]:
|
|
187
|
+
"""只保留视频结果,返回 (保留, 剔除数)。"""
|
|
188
|
+
kept: list[dict[str, Any]] = []
|
|
189
|
+
dropped = 0
|
|
190
|
+
for item in results:
|
|
191
|
+
if is_video_result(item):
|
|
192
|
+
kept.append(item)
|
|
193
|
+
else:
|
|
194
|
+
dropped += 1
|
|
195
|
+
return kept, dropped
|
|
196
|
+
|
|
197
|
+
|
|
198
|
+
def filter_duration(
|
|
199
|
+
results: list[dict[str, Any]],
|
|
200
|
+
min_seconds: int | None = None,
|
|
201
|
+
max_seconds: int | None = None,
|
|
202
|
+
) -> tuple[list[dict[str, Any]], int, int]:
|
|
203
|
+
"""按时长过滤,返回 (保留, 剔除数, 时长未知且保留数)。
|
|
204
|
+
|
|
205
|
+
时长未知的条目保留:除 B 站外的引擎大多没有时长字段,硬删会把
|
|
206
|
+
anysearch 的 YouTube 结果全部清空。调用方据第三个数判断这次过滤的
|
|
207
|
+
实际覆盖率,不要把它当成「已严格过滤」。
|
|
208
|
+
"""
|
|
209
|
+
kept: list[dict[str, Any]] = []
|
|
210
|
+
filtered = 0
|
|
211
|
+
unknown = 0
|
|
212
|
+
for item in results:
|
|
213
|
+
seconds = result_duration_seconds(item)
|
|
214
|
+
if seconds is None:
|
|
215
|
+
unknown += 1
|
|
216
|
+
kept.append(item)
|
|
217
|
+
continue
|
|
218
|
+
if min_seconds is not None and seconds < min_seconds:
|
|
219
|
+
filtered += 1
|
|
220
|
+
continue
|
|
221
|
+
if max_seconds is not None and seconds > max_seconds:
|
|
222
|
+
filtered += 1
|
|
223
|
+
continue
|
|
224
|
+
kept.append(item)
|
|
225
|
+
return kept, filtered, unknown
|
|
@@ -0,0 +1,65 @@
|
|
|
1
|
+
#!/usr/bin/env python3
|
|
2
|
+
"""video_route.py — `--video` 的强制路由决策。
|
|
3
|
+
|
|
4
|
+
为什么单独成模块:route.py 已登记模块体积上限,而这段逻辑只服务一个显式
|
|
5
|
+
开关,不需要挤进主路由。决策形状必须与 route_query 的返回一致(prepare
|
|
6
|
+
直接读 engines_combo / parallel / engine_request),否则 --video 会在
|
|
7
|
+
执行层退化成空 combo。
|
|
8
|
+
|
|
9
|
+
与自然语言路由的分工:
|
|
10
|
+
- 查询里出现「视频教程 / B站 / 视频(结尾)」等显式意图 → config 的 video
|
|
11
|
+
域自然命中,不需要本模块;
|
|
12
|
+
- 用户敲 `--video` → 不看查询词,直接锁定视频 combo,并由 pipeline 的
|
|
13
|
+
video_only 过滤器保证结果里没有网页。
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
from __future__ import annotations
|
|
17
|
+
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
# config 缺 video 域时的兜底:B 站是当前唯一稳定免费的视频搜索源,
|
|
21
|
+
# anysearch 负责带出 YouTube 等海外视频(无独立 YouTube 引擎时)。
|
|
22
|
+
_FALLBACK = ("bilibili", "anysearch")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
def _video_domain() -> dict[str, Any]:
|
|
26
|
+
try:
|
|
27
|
+
from config import get_domains
|
|
28
|
+
for domain in get_domains() or []:
|
|
29
|
+
if isinstance(domain, dict) and domain.get("name") == "video":
|
|
30
|
+
return domain
|
|
31
|
+
except Exception:
|
|
32
|
+
pass
|
|
33
|
+
return {}
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def video_decision(min_duration: int | None = None,
|
|
37
|
+
max_duration: int | None = None) -> dict[str, Any]:
|
|
38
|
+
"""构造 `--video` 的路由决策(形状对齐 route_query 的返回值)。"""
|
|
39
|
+
domain = _video_domain()
|
|
40
|
+
combo = [str(e) for e in (domain.get("engines_combo") or _FALLBACK) if e]
|
|
41
|
+
try:
|
|
42
|
+
from config import get_engines
|
|
43
|
+
specs = get_engines() or {}
|
|
44
|
+
combo = [e for e in combo if (specs.get(e) or {}).get("enabled", True)]
|
|
45
|
+
except Exception:
|
|
46
|
+
pass
|
|
47
|
+
combo = combo or list(_FALLBACK)
|
|
48
|
+
primary = domain.get("primary")
|
|
49
|
+
if primary not in combo:
|
|
50
|
+
primary = combo[0]
|
|
51
|
+
return {
|
|
52
|
+
"engine": primary,
|
|
53
|
+
"engines": list(combo),
|
|
54
|
+
"engines_combo": list(combo),
|
|
55
|
+
"domain": "video",
|
|
56
|
+
"parallel": True,
|
|
57
|
+
"no_early_stop": True,
|
|
58
|
+
"reason": "用户指定 --video:视频源优先(B站 + anysearch),只保留视频结果",
|
|
59
|
+
"confidence": 1.0,
|
|
60
|
+
# 请求身份进缓存键:--video 的结果不能与同 query 的 auto 结果互串。
|
|
61
|
+
"engine_request": "--video",
|
|
62
|
+
"video_only": True,
|
|
63
|
+
"min_duration": min_duration,
|
|
64
|
+
"max_duration": max_duration,
|
|
65
|
+
}
|