argo-search 2.12.0 → 2.14.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.
Files changed (371) hide show
  1. package/AGENTS.md +93 -0
  2. package/README.en.md +35 -12
  3. package/README.es.md +35 -12
  4. package/README.ja.md +38 -13
  5. package/README.ko.md +35 -12
  6. package/README.md +69 -42
  7. package/SKILL.md +4 -4
  8. package/assets/readme/counts.json +1 -0
  9. package/assets/readme/hero.svg +1 -1
  10. package/backends/domain_profiles.json +78 -6
  11. package/backends/engine_registry.yaml +188 -22
  12. package/backends/env_passthrough.txt +75 -0
  13. package/backends/quota_profiles.json +132 -12
  14. package/bin/argo +3 -0
  15. package/config.yaml +34 -3524
  16. package/docs/ARGO_INTRO.md +4 -3
  17. package/docs/CHANGELOG.md +337 -0
  18. package/docs/COMMIT_STANDARD.md +98 -0
  19. package/docs/ENGINE_CATALOG.md +65 -48
  20. package/docs/QUALITY_OF_SLOW_SOURCES.md +115 -0
  21. package/docs/RELEASE_NOTES_v2.13.0.md +66 -0
  22. package/docs/RELEASE_NOTES_v2.14.0.md +77 -0
  23. package/docs/RELEASING.md +47 -0
  24. package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +7 -7
  25. package/engines/specs/anysearch.yaml +33 -0
  26. package/engines/specs/archive_org.yaml +31 -0
  27. package/engines/specs/arxiv.yaml +18 -0
  28. package/engines/specs/baidu_baike.yaml +16 -0
  29. package/engines/specs/baidu_hot.yaml +19 -0
  30. package/engines/specs/bilibili.yaml +33 -0
  31. package/engines/specs/bilibili_hot.yaml +19 -0
  32. package/engines/specs/bing_rss.yaml +17 -0
  33. package/engines/specs/biorxiv.yaml +2 -0
  34. package/engines/specs/bocha.yaml +26 -0
  35. package/engines/specs/bocha_ai.yaml +27 -0
  36. package/engines/specs/brave.yaml +20 -0
  37. package/engines/specs/byted.yaml +33 -0
  38. package/engines/specs/clinicaltrials.yaml +23 -0
  39. package/engines/specs/cls_telegraph.yaml +19 -0
  40. package/engines/specs/cnii.yaml +21 -0
  41. package/engines/specs/cninfo.yaml +14 -0
  42. package/engines/specs/coingecko.yaml +33 -0
  43. package/engines/specs/courtlistener.yaml +15 -0
  44. package/engines/specs/crates.yaml +30 -0
  45. package/engines/specs/crossref.yaml +27 -0
  46. package/engines/specs/csdn.yaml +18 -0
  47. package/engines/specs/dblp.yaml +29 -0
  48. package/engines/specs/dbpedia.yaml +32 -0
  49. package/engines/specs/devto.yaml +26 -0
  50. package/engines/specs/dnb.yaml +17 -0
  51. package/engines/specs/doaj.yaml +17 -0
  52. package/engines/specs/docker_hub.yaml +30 -0
  53. package/engines/specs/douban_book.yaml +14 -0
  54. package/engines/specs/douyin_hot.yaml +21 -0
  55. package/engines/specs/eastmoney.yaml +16 -0
  56. package/engines/specs/ecosia.yaml +18 -0
  57. package/engines/specs/electricity_maps.yaml +17 -0
  58. package/engines/specs/em_flow.yaml +14 -0
  59. package/engines/specs/em_global_news.yaml +17 -0
  60. package/engines/specs/em_miaoxiang.yaml +14 -0
  61. package/engines/specs/eu_opendata.yaml +16 -0
  62. package/engines/specs/europeana.yaml +19 -0
  63. package/engines/specs/europepmc.yaml +29 -0
  64. package/engines/specs/eurostat.yaml +14 -0
  65. package/engines/specs/exa.yaml +20 -0
  66. package/engines/specs/felo.yaml +25 -0
  67. package/engines/specs/figshare.yaml +17 -0
  68. package/engines/specs/finviz.yaml +15 -0
  69. package/engines/specs/fourget.yaml +23 -0
  70. package/engines/specs/fr_opendata.yaml +28 -0
  71. package/engines/specs/frankfurter.yaml +21 -0
  72. package/engines/specs/fred.yaml +15 -0
  73. package/engines/specs/free_dictionary.yaml +16 -0
  74. package/engines/specs/fx_rate.yaml +14 -0
  75. package/engines/specs/gbfs_nyc.yaml +3 -0
  76. package/engines/specs/gbif.yaml +15 -0
  77. package/engines/specs/github.yaml +25 -0
  78. package/engines/specs/google_patents.yaml +16 -0
  79. package/engines/specs/google_scholar.yaml +16 -0
  80. package/engines/specs/gov_policy.yaml +31 -0
  81. package/engines/specs/grep_app.yaml +19 -0
  82. package/engines/specs/gutenberg.yaml +15 -0
  83. package/engines/specs/hackernews.yaml +18 -0
  84. package/engines/specs/hal.yaml +16 -0
  85. package/engines/specs/hatena_bookmark.yaml +20 -0
  86. package/engines/specs/hf_papers.yaml +26 -0
  87. package/engines/specs/huggingface.yaml +31 -0
  88. package/engines/specs/imdb.yaml +18 -0
  89. package/engines/specs/itotii.yaml +17 -0
  90. package/engines/specs/itunes.yaml +19 -0
  91. package/engines/specs/jin10.yaml +15 -0
  92. package/engines/specs/juejin.yaml +16 -0
  93. package/engines/specs/kaggle.yaml +44 -0
  94. package/engines/specs/know_your_meme.yaml +18 -0
  95. package/engines/specs/kor_law.yaml +17 -0
  96. package/engines/specs/lieu.yaml +18 -0
  97. package/engines/specs/listenbrainz.yaml +4 -0
  98. package/engines/specs/local_arxiv.yaml +18 -0
  99. package/engines/specs/local_baidu.yaml +35 -0
  100. package/engines/specs/local_bing.yaml +16 -0
  101. package/engines/specs/local_bing_news.yaml +22 -0
  102. package/engines/specs/local_crossref.yaml +23 -0
  103. package/engines/specs/local_github.yaml +27 -0
  104. package/engines/specs/local_gitlab.yaml +23 -0
  105. package/engines/specs/local_goodreads.yaml +16 -0
  106. package/engines/specs/local_google_news.yaml +15 -0
  107. package/engines/specs/local_imdb.yaml +17 -0
  108. package/engines/specs/local_npm.yaml +25 -0
  109. package/engines/specs/local_openstreetmap.yaml +36 -0
  110. package/engines/specs/local_pubmed.yaml +21 -0
  111. package/engines/specs/local_search.yaml +22 -0
  112. package/engines/specs/local_seek.yaml +34 -0
  113. package/engines/specs/local_semantic_scholar.yaml +23 -0
  114. package/engines/specs/local_sogou.yaml +15 -0
  115. package/engines/specs/local_stackoverflow.yaml +26 -0
  116. package/engines/specs/local_wikipedia.yaml +26 -0
  117. package/engines/specs/local_wikiquote.yaml +26 -0
  118. package/engines/specs/local_wiktionary.yaml +26 -0
  119. package/engines/specs/local_yandex.yaml +37 -0
  120. package/engines/specs/marginalia.yaml +22 -0
  121. package/engines/specs/mdn.yaml +32 -0
  122. package/engines/specs/met_museum.yaml +4 -2
  123. package/engines/specs/metaso.yaml +19 -0
  124. package/engines/specs/models_dev.yaml +16 -0
  125. package/engines/specs/moegirl.yaml +19 -0
  126. package/engines/specs/mojeek.yaml +31 -0
  127. package/engines/specs/musicbrainz.yaml +31 -0
  128. package/engines/specs/mwmbl.yaml +39 -0
  129. package/engines/specs/nasa_cmr.yaml +15 -0
  130. package/engines/specs/nbs_stats.yaml +16 -0
  131. package/engines/specs/ndl.yaml +17 -0
  132. package/engines/specs/noaa_swpc.yaml +3 -0
  133. package/engines/specs/npm.yaml +62 -0
  134. package/engines/specs/octen.yaml +16 -0
  135. package/engines/specs/open_library.yaml +15 -0
  136. package/engines/specs/open_meteo.yaml +17 -0
  137. package/engines/specs/openaire.yaml +34 -0
  138. package/engines/specs/openalex.yaml +27 -0
  139. package/engines/specs/opencitations.yaml +4 -1
  140. package/engines/specs/opencorporates.yaml +19 -0
  141. package/engines/specs/openfda.yaml +15 -0
  142. package/engines/specs/opensky.yaml +17 -0
  143. package/engines/specs/openverse.yaml +42 -0
  144. package/engines/specs/parallel.yaml +22 -0
  145. package/engines/specs/parallel_free.yaml +20 -0
  146. package/engines/specs/polymarket.yaml +26 -0
  147. package/engines/specs/pubchem.yaml +15 -0
  148. package/engines/specs/pypi.yaml +16 -0
  149. package/engines/specs/qiita.yaml +28 -0
  150. package/engines/specs/qq_music.yaml +17 -0
  151. package/engines/specs/qwant.yaml +19 -0
  152. package/engines/specs/qweather.yaml +14 -0
  153. package/engines/specs/rcsb_pdb.yaml +15 -0
  154. package/engines/specs/reddit.yaml +28 -0
  155. package/engines/specs/redskill.yaml +24 -0
  156. package/engines/specs/repology.yaml +18 -0
  157. package/engines/specs/rfc_editor.yaml +15 -0
  158. package/engines/specs/satnogs.yaml +5 -1
  159. package/engines/specs/searchmysite.yaml +18 -0
  160. package/engines/specs/searxng.yaml +18 -0
  161. package/engines/specs/sec_companyfacts.yaml +22 -0
  162. package/engines/specs/seeking_alpha.yaml +15 -0
  163. package/engines/specs/seltz.yaml +39 -0
  164. package/engines/specs/semantic_scholar.yaml +18 -0
  165. package/engines/specs/shenma.yaml +13 -0
  166. package/engines/specs/sina_quote.yaml +15 -0
  167. package/engines/specs/so.yaml +13 -0
  168. package/engines/specs/stackoverflow.yaml +18 -0
  169. package/engines/specs/steam.yaml +30 -0
  170. package/engines/specs/tatoeba.yaml +17 -0
  171. package/engines/specs/tavily.yaml +26 -0
  172. package/engines/specs/tencent_kline.yaml +18 -0
  173. package/engines/specs/tencent_quote.yaml +14 -0
  174. package/engines/specs/thesportsdb.yaml +18 -0
  175. package/engines/specs/ths_hot.yaml +19 -0
  176. package/engines/specs/tinyfish.yaml +36 -0
  177. package/engines/specs/tinyfish_news.yaml +34 -0
  178. package/engines/specs/tinyfish_paper.yaml +34 -0
  179. package/engines/specs/toutiao_hot.yaml +19 -0
  180. package/engines/specs/twitter.yaml +36 -0
  181. package/engines/specs/uapi.yaml +18 -0
  182. package/engines/specs/uniprot.yaml +16 -0
  183. package/engines/specs/urban_dictionary.yaml +25 -0
  184. package/engines/specs/usda.yaml +17 -0
  185. package/engines/specs/usgs.yaml +15 -0
  186. package/engines/specs/v2ex.yaml +33 -0
  187. package/engines/specs/vam.yaml +34 -0
  188. package/engines/specs/wallhaven.yaml +51 -0
  189. package/engines/specs/wallstreetcn.yaml +31 -0
  190. package/engines/specs/wayback_cdx.yaml +15 -0
  191. package/engines/specs/weather_cn.yaml +33 -0
  192. package/engines/specs/wechat_sogou.yaml +13 -0
  193. package/engines/specs/weibo.yaml +21 -0
  194. package/engines/specs/weibo_hot.yaml +21 -0
  195. package/engines/specs/wenshu.yaml +14 -0
  196. package/engines/specs/weread.yaml +14 -0
  197. package/engines/specs/wiby.yaml +18 -0
  198. package/engines/specs/wikidata.yaml +33 -0
  199. package/engines/specs/wikipedia.yaml +36 -0
  200. package/engines/specs/wolframalpha.yaml +18 -0
  201. package/engines/specs/worldbank.yaml +15 -0
  202. package/engines/specs/xiaohongshu.yaml +25 -0
  203. package/engines/specs/yahoo_finance.yaml +22 -0
  204. package/engines/specs/you.yaml +22 -0
  205. package/engines/specs/zh_wikipedia.yaml +35 -0
  206. package/engines/specs/zhihu.yaml +33 -0
  207. package/engines/specs/zhihu_global.yaml +18 -0
  208. package/engines/specs/zhihu_hot.yaml +36 -0
  209. package/engines/specs/zhihu_user.yaml +14 -0
  210. package/package.json +25 -22
  211. package/packages/dsh-plugin/README.md +11 -6
  212. package/packages/dsh-plugin/cordis.patch.yml +6 -2
  213. package/packages/dsh-plugin/dsh/client.js +65 -116
  214. package/packages/dsh-plugin/dsh/index.js +2 -2
  215. package/packages/dsh-plugin/dsh/native-tools.mjs +24 -3
  216. package/packages/dsh-plugin/dsh/runner.js +35 -1
  217. package/packages/dsh-plugin/dsh/specs.js +3 -1
  218. package/packages/dsh-plugin/dsh/wide-research.js +4 -2
  219. package/packages/dsh-plugin/package.json +1 -1
  220. package/packages/dsh-plugin/scripts/sync-local.sh +13 -11
  221. package/packages/dsh-plugin/test/client.test.js +22 -5
  222. package/packages/dsh-plugin/test/config.test.js +5 -1
  223. package/packages/dsh-plugin/test/index.test.js +3 -1
  224. package/packages/dsh-plugin/test/size-gate.test.js +2 -2
  225. package/scripts/ab_eval_p0p1.py +10 -4
  226. package/scripts/archive_run.py +4 -2
  227. package/scripts/badcase_causes.py +81 -0
  228. package/scripts/badcase_ledger.py +290 -15
  229. package/scripts/batch_probe.py +10 -8
  230. package/scripts/build_release_assets.sh +17 -5
  231. package/scripts/cache.py +8 -8
  232. package/scripts/cache_guard.py +10 -5
  233. package/scripts/candidate_envelope.py +7 -3
  234. package/scripts/check_commit_report.py +168 -0
  235. package/scripts/circuit_breaker.py +220 -36
  236. package/scripts/config.py +9 -10
  237. package/scripts/daemon.py +11 -2
  238. package/scripts/engine_add.py +32 -0
  239. package/scripts/engine_admission.py +9 -5
  240. package/scripts/engine_dispatch.py +49 -46
  241. package/scripts/engine_failure.py +14 -18
  242. package/scripts/engine_families.py +13 -2
  243. package/scripts/engine_health.py +184 -0
  244. package/scripts/engine_policy.py +1 -1
  245. package/scripts/engine_states.py +989 -0
  246. package/scripts/engine_status.py +49 -11
  247. package/scripts/engine_validate.py +47 -39
  248. package/scripts/engines.py +8 -0
  249. package/scripts/engines_base.py +34 -88
  250. package/scripts/engines_builders.py +36 -19
  251. package/scripts/engines_builders_archive.py +303 -0
  252. package/scripts/engines_builders_batch11.py +63 -1
  253. package/scripts/engines_builders_batch12.py +168 -0
  254. package/scripts/engines_builders_batch16.py +186 -0
  255. package/scripts/engines_builders_batch9.py +9 -1
  256. package/scripts/engines_builders_data.py +69 -2090
  257. package/scripts/engines_builders_finance.py +354 -0
  258. package/scripts/engines_builders_intl.py +4 -1
  259. package/scripts/engines_builders_media.py +724 -0
  260. package/scripts/engines_builders_science.py +784 -0
  261. package/scripts/engines_parsers.py +399 -0
  262. package/scripts/fetch_browser.py +4 -2
  263. package/scripts/fetch_jsrun.py +2 -1
  264. package/scripts/fetch_v3.py +38 -38
  265. package/scripts/gen_engine_catalog.py +58 -153
  266. package/scripts/gen_native_tools.py +44 -17
  267. package/scripts/gen_routing_snapshot.py +8 -6
  268. package/scripts/health_check.py +37 -4
  269. package/scripts/health_probe.py +28 -8
  270. package/scripts/install.ps1 +31 -15
  271. package/scripts/install.sh +266 -142
  272. package/scripts/job.py +8 -70
  273. package/scripts/lint_spec_contracts.py +7 -12
  274. package/scripts/local_intent.py +139 -0
  275. package/scripts/local_seek.py +223 -91
  276. package/scripts/local_seek_adapter.py +87 -0
  277. package/scripts/mcp_launch.sh +9 -17
  278. package/scripts/mcp_transport.py +1 -1
  279. package/scripts/net_proxy.py +47 -0
  280. package/scripts/numeric_verify.py +20 -9
  281. package/scripts/output_transparency.py +21 -13
  282. package/scripts/plan.py +8 -5
  283. package/scripts/pre-commit +93 -23
  284. package/scripts/quota.py +11 -7
  285. package/scripts/recovery.py +14 -5
  286. package/scripts/recovery_l0.py +5 -3
  287. package/scripts/redskill/redskill_engine.py +3 -9
  288. package/scripts/release.py +60 -24
  289. package/scripts/release_check.py +20 -3
  290. package/scripts/research.py +1 -1
  291. package/scripts/research_dossier.py +10 -5
  292. package/scripts/research_gates.py +8 -4
  293. package/scripts/retry_policy.py +8 -7
  294. package/scripts/route.py +2 -24
  295. package/scripts/route_combo.py +11 -26
  296. package/scripts/route_lang.py +6 -1
  297. package/scripts/route_policy.py +21 -14
  298. package/scripts/search.py +36 -35
  299. package/scripts/search_attribution.py +34 -3
  300. package/scripts/search_cli.py +22 -12
  301. package/scripts/search_entry.py +15 -3
  302. package/scripts/search_output.py +87 -18
  303. package/scripts/search_pipeline.py +14 -10
  304. package/scripts/search_rank.py +23 -62
  305. package/scripts/search_types.py +5 -0
  306. package/scripts/social_engines/bilibili_engine.py +2 -30
  307. package/scripts/social_engines/hackernews_engine.py +4 -12
  308. package/scripts/social_engines/reddit_engine.py +4 -13
  309. package/scripts/social_engines/v2ex_engine.py +3 -12
  310. package/scripts/social_engines/weibo_engine.py +2 -30
  311. package/scripts/social_engines/zhihu_engine.py +4 -5
  312. package/scripts/source_audit.py +331 -0
  313. package/scripts/stats_cli.py +17 -1
  314. package/scripts/sync_backends.py +241 -8
  315. package/scripts/sync_requirements.py +159 -0
  316. package/scripts/tweet.py +3 -6
  317. package/scripts/usage_log.py +28 -9
  318. package/scripts/video_fetch.py +2 -5
  319. package/scripts/watch.py +11 -6
  320. package/scripts/wechat_article.py +11 -12
  321. package/scripts/wide_research.py +4 -1
  322. package/scripts/wx.py +6 -13
  323. package/scripts/x_article_fetch.py +2 -1
  324. package/sub-skills/local-search/SKILL.md +2 -2
  325. package/sub-skills/local-search/config.yaml +2 -1
  326. package/sub-skills/local-search/parsers.py +6 -1
  327. package/sub-skills/local-seek/scripts/seek.py +390 -24
  328. package/sub-skills/local-seek/scripts/seek_fts.py +20 -9
  329. package/sub-skills/local-seek/scripts/seek_rank.py +64 -1
  330. package/docs/DATA_SOURCE_GAPS.md +0 -81
  331. package/docs/DESIGN_LOCAL_DATA_FUSION.md +0 -90
  332. package/docs/PLATFORM_PATHS.md +0 -111
  333. package/docs/engines/bangumi.md +0 -27
  334. package/docs/engines/biorxiv.md +0 -27
  335. package/docs/engines/clawhub.md +0 -27
  336. package/docs/engines/crt_sh.md +0 -27
  337. package/docs/engines/datacite.md +0 -27
  338. package/docs/engines/deps_dev.md +0 -27
  339. package/docs/engines/douban_movie.md +0 -27
  340. package/docs/engines/endoflife.md +0 -27
  341. package/docs/engines/flk_law.md +0 -27
  342. package/docs/engines/fxtwitter.md +0 -27
  343. package/docs/engines/google_news.md +0 -27
  344. package/docs/engines/gov_regulations.md +0 -27
  345. package/docs/engines/guqian.md +0 -27
  346. package/docs/engines/hackernews.md +0 -27
  347. package/docs/engines/iplant.md +0 -27
  348. package/docs/engines/keenable.md +0 -27
  349. package/docs/engines/met_museum.md +0 -27
  350. package/docs/engines/nasa_images.md +0 -27
  351. package/docs/engines/netease_music.md +0 -27
  352. package/docs/engines/npm.md +0 -27
  353. package/docs/engines/nvd.md +0 -27
  354. package/docs/engines/openreview.md +0 -27
  355. package/docs/engines/openstd.md +0 -27
  356. package/docs/engines/parallel_free.md +0 -27
  357. package/docs/engines/people_daily.md +0 -27
  358. package/docs/engines/pixiv.md +0 -27
  359. package/docs/engines/realtime_index.md +0 -27
  360. package/docs/engines/sec_edgar.md +0 -27
  361. package/docs/engines/seltz.md +0 -27
  362. package/docs/engines/skillsmp.md +0 -27
  363. package/docs/engines/sspai.md +0 -27
  364. package/docs/engines/std_samr.md +0 -27
  365. package/docs/engines/train.md +0 -27
  366. package/docs/engines/un_comtrade.md +0 -27
  367. package/docs/engines/wikisource.md +0 -27
  368. package/docs/engines/zdic.md +0 -27
  369. package/docs/engines/zenodo.md +0 -27
  370. package/docs/engines/zhihu_hot_app.md +0 -27
  371. package/engines/specs/cinii.yaml +0 -44
@@ -0,0 +1,724 @@
1
+ #!/usr/bin/env python3
2
+ """专用构建器:影视、音乐播客与体育(IMDb / iTunes / TheSportsDB)
3
+
4
+ 自 engines_builders_data.py 按主题拆出(2026-11-08)。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ import json
10
+ import logging
11
+ import re
12
+ import urllib.error
13
+ import urllib.parse
14
+ import urllib.request
15
+ from html import unescape as _unescape
16
+ from typing import Any
17
+
18
+ from engines_base import (
19
+ rank_score,
20
+ safe_search, http_open,
21
+ )
22
+
23
+ logger = logging.getLogger("unified_search.engines")
24
+
25
+ # ── IMDb 影视 suggestion API(免认证) ────────────────────────────────────────
26
+
27
+ _IMDB_SUGGEST = "https://v2.sg.media-imdb.com/suggestion/{first}/{q}.json"
28
+ _IMDB_UA = "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/126.0 Safari/537.36"
29
+
30
+
31
+ # 影视问句噪声词:整句进 suggestion 常 0 命中(如 "Interstellar film cast")
32
+ _IMDB_STOP = re.compile(
33
+ r"(?i)\b(movie|film|tv\s*show|tv\s*series|cinema|cast|starring|director|directed\s+by|"
34
+ r"screenwriter|written\s+by|actor|actress|producer|box\s*office|trailer|review|"
35
+ r"imdb|豆瓣|电影|电视剧|剧集|影视|影片|导演|主演|演员|编剧|制片|上映|首映|票房|"
36
+ r"影评|奥斯卡|金像奖|金马奖|网剧|美剧|韩剧|日剧|英剧)\b"
37
+ )
38
+
39
+
40
+ def _imdb_clean_query(query: str) -> str:
41
+ """去掉影视角色/事实词,保留片名/人名主体。"""
42
+ q = (query or "").strip()
43
+ if not q:
44
+ return ""
45
+ cleaned = _IMDB_STOP.sub(" ", q)
46
+ cleaned = re.sub(r"[??!!,,.。::;;]+", " ", cleaned)
47
+ cleaned = re.sub(r"\s+", " ", cleaned).strip()
48
+ # 清洗后过短则回退原 query(避免只剩空)
49
+ if len(cleaned) < 2:
50
+ return q
51
+ return cleaned
52
+
53
+
54
+ def _build_imdb_engine(spec: dict[str, Any]) -> Any:
55
+ """IMDb 自动补全 suggestion API(v2.sg.media-imdb.com,免认证)。
56
+
57
+ 路径:/suggestion/{首字符}/{query}.json
58
+ 返回电影/剧集/人物,带 tt/nm ID,可拼正式 IMDb URL。
59
+ """
60
+ timeout = spec.get("timeout", 8)
61
+ source_name = spec.get("_name", "imdb")
62
+
63
+ def _fetch_suggest(q: str, to: float) -> list[dict[str, Any]]:
64
+ if not q:
65
+ return []
66
+ first = q[0].lower()
67
+ if not (("a" <= first <= "z") or ("0" <= first <= "9")):
68
+ first = "_"
69
+ path_q = urllib.parse.quote(q[:80], safe="")
70
+ url = _IMDB_SUGGEST.format(first=first, q=path_q)
71
+ try:
72
+ req = urllib.request.Request(url, headers={"User-Agent": _IMDB_UA, "Accept": "application/json"})
73
+ with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
74
+ data = json.loads(resp.read().decode("utf-8", "replace"))
75
+ except Exception as e:
76
+ logger.warning(f"IMDb 失败: {e}")
77
+ return []
78
+ return [x for x in (data.get("d") or []) if isinstance(x, dict)]
79
+
80
+ @safe_search
81
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
82
+ raw = (query or "").strip()
83
+ if not raw:
84
+ return []
85
+ to = _timeout or timeout
86
+ cleaned = _imdb_clean_query(raw)
87
+ # 先试清洗词,空则回退原句
88
+ items = _fetch_suggest(cleaned, to)
89
+ if not items and cleaned != raw:
90
+ items = _fetch_suggest(raw, to)
91
+
92
+ # 按标题与查询 token 重叠 + feature 优先排序
93
+ q_tokens = {t.lower() for t in re.findall(r"[A-Za-z0-9\u4e00-\u9fff]{2,}", cleaned or raw)}
94
+ ranked: list[tuple[float, dict[str, Any]]] = []
95
+ for item in items:
96
+ title = item.get("l") or ""
97
+ iid = item.get("id") or ""
98
+ if not title and not iid:
99
+ continue
100
+ t_low = title.lower()
101
+ t_tokens = {t.lower() for t in re.findall(r"[A-Za-z0-9\u4e00-\u9fff]{2,}", title)}
102
+ overlap = len(q_tokens & t_tokens) / max(len(q_tokens), 1)
103
+ # 精确/前缀加分;tt 影片优先于 nm 人名(片名查询时)
104
+ exact = 1.0 if t_low == (cleaned or raw).lower() else 0.0
105
+ prefix = 0.3 if t_low.startswith((cleaned or raw).lower()[: min(12, len(cleaned or raw))]) else 0.0
106
+ kind_bonus = 0.15 if str(iid).startswith("tt") else (0.05 if str(iid).startswith("nm") else 0.0)
107
+ year = item.get("y") or 0
108
+ try:
109
+ year_n = int(year) if year else 0
110
+ except (TypeError, ValueError):
111
+ year_n = 0
112
+ # 近年作品轻微加分(同名旧片靠后)
113
+ recency = min(max(year_n - 1980, 0), 50) / 500.0
114
+ score = 0.5 + overlap + exact + prefix + kind_bonus + recency
115
+ ranked.append((score, item))
116
+ ranked.sort(key=lambda x: -x[0])
117
+
118
+ results = []
119
+ for score, item in ranked[: max(n, 1)]:
120
+ title = item.get("l") or ""
121
+ iid = item.get("id") or ""
122
+ year = item.get("y")
123
+ kind = item.get("q") or item.get("qid") or ""
124
+ cast = item.get("s") or ""
125
+ parts = [p for p in (str(year) if year else "", kind, cast) if p]
126
+ if str(iid).startswith("tt"):
127
+ href = f"https://www.imdb.com/title/{iid}/"
128
+ elif str(iid).startswith("nm"):
129
+ href = f"https://www.imdb.com/name/{iid}/"
130
+ else:
131
+ href = f"https://www.imdb.com/find/?q={urllib.parse.quote(title)}"
132
+ results.append({
133
+ "title": title,
134
+ "url": href,
135
+ "snippet": " · ".join(parts)[:300],
136
+ "source": source_name,
137
+ "score": min(0.95, 0.7 + score * 0.15),
138
+ })
139
+ if len(results) >= n:
140
+ break
141
+ return results
142
+ return _engine
143
+
144
+
145
+ # ── iTunes 媒体库(中文需 country=cn;专辑问 entity=album;播客问 entity=podcast)──
146
+
147
+ # 媒体意图词。引擎可被 --engine 直接调用,那时拿不到路由域的上下文,
148
+ # 意图只能从查询词本身读——命中播客词即把 media 从 music 切到 podcast。
149
+ _PODCAST_HINT_RE = re.compile(r"(?i)(播客|podcast|电台|单集|一期|这期|那期|episode)")
150
+ # 单集意图:用户要的是某期节目(带时长),而非节目本体
151
+ _PODCAST_EPISODE_RE = re.compile(r"(?i)(单集|一期|这期|那期|episode|第\s*\d+\s*集|#\s*\d+)")
152
+ _ALBUM_HINT_RE = re.compile(r"(?i)(专辑|album|discography|唱片)")
153
+ # 意图词只用于定实体,须从检索词里剥掉,否则「播客」这类词会污染 term
154
+ _MEDIA_INTENT_WORD_RE = re.compile(
155
+ r"(?i)(专辑|新专辑|唱片|音乐|歌曲|单曲|播客|电台|单集|一期|这期|那期|"
156
+ r"album|discography|music|song|songs|single|podcast|podcasts|episode)"
157
+ )
158
+ # 节目级时长必须二跳取样(见下方 docstring),逐条补会让请求数随结果数膨胀。
159
+ # 只补首条:播客名查询通常只有一个正解(实测「张小珺 商业访谈录」Apple 只回 1 条)。
160
+ _ITUNES_SHOW_ENRICH_MAX = 1
161
+ # 文字稿/feed 拉取的字节上限:预览只需几百字,2MB 足够防超大文件吃内存
162
+ _TRANSCRIPT_MAX_BYTES = 2 * 1024 * 1024
163
+
164
+
165
+ def _itunes_date(raw: Any) -> str:
166
+ """Apple 的 releaseDate 形如 2026-09-03T00:00:00Z,裁到日期部分供展示。"""
167
+ s = str(raw or "").strip()
168
+ return s[:10] if len(s) >= 10 else ""
169
+
170
+
171
+ def _transcript_to_text(raw: str, ctype: str) -> str:
172
+ """文字稿原文 → 纯文本。VTT/SRT 去时间轴与样式行,HTML 去 tag。
173
+
174
+ Podcasting 2.0 文字稿的 type 值不统一(text/vtt、application/srt、
175
+ 裸 text/plain 都见过),按字符串包含判断而非全等。
176
+ """
177
+ if "html" in ctype:
178
+ text = re.sub(r"<[^>]+>", " ", raw)
179
+ text = _unescape(text)
180
+ elif "vtt" in ctype or "srt" in ctype or "plain" in ctype:
181
+ lines: list[str] = []
182
+ for ln in raw.splitlines():
183
+ s = ln.strip()
184
+ if (not s or s == "WEBVTT"
185
+ or s.startswith(("NOTE", "STYLE", "REGION"))
186
+ or "-->" in s or s.isdigit()):
187
+ continue
188
+ s = re.sub(r"<[^>]+>", "", s) # <c> 高亮、<v 说话人> 内联标签
189
+ if s:
190
+ lines.append(s)
191
+ text = " ".join(lines)
192
+ else:
193
+ text = raw
194
+ return re.sub(r"\s+", " ", text).strip()
195
+
196
+
197
+ def _build_itunes_engine(spec: dict[str, Any]) -> Any:
198
+ """iTunes Search API:按语言与意图调 country / media / entity。
199
+
200
+ 三种媒体形态(播客为 2026-09-15 补入):
201
+ - 播客节目 media=podcast&entity=podcast → 集数(trackCount)、更新日期、类型
202
+ - 播客单集 media=podcast&entity=podcastEpisode → 时长(trackTimeMillis)、发布日期
203
+ - 音乐 media=music(专辑问 entity=album)
204
+
205
+ 播客时长只能取自单集:**节目对象上的 trackTimeMillis 不是时长**。实测 12 档
206
+ 节目只有 6 档等于最新单集的秒数,另 6 档明显偏小(忽左忽右 3491 而最新单集
207
+ 5739),单位与含义上游都未文档化——取信它会静默给出错值。所以节目级的
208
+ 「每期多长」走二跳单集取样,见 _recent_episode_duration。
209
+ """
210
+ timeout = spec.get("timeout", 8)
211
+ source_name = spec.get("_name", "itunes")
212
+ engine_tag = spec.get("_name", "")
213
+ base = spec.get("url") or "https://itunes.apple.com/search"
214
+ lookup_base = (base.replace("/search", "/lookup") if "/search" in base
215
+ else "https://itunes.apple.com/lookup")
216
+ ua_headers = {"User-Agent": "argo-search/2.6 (itunes)", "Accept": "application/json"}
217
+
218
+ def _get_json(url: str, to: float) -> dict[str, Any]:
219
+ req = urllib.request.Request(url, headers=ua_headers)
220
+ with http_open(req, timeout=to, engine=engine_tag) as resp:
221
+ return json.loads(resp.read().decode("utf-8", "replace"))
222
+
223
+ def _recent_episode_duration(collection_id: Any, country: str, to: float) -> tuple[int | None, int]:
224
+ """节目近 5 期单集时长的中位数 → (中位分钟, 样本数)。
225
+
226
+ 取中位数而非最新一期:访谈类单集长度波动大,一期 4 小时长访谈代表不了
227
+ 整个节目。任何失败一律退回 (None, 0),节目本体照常返回——时长是补充
228
+ 信息,不该让整条结果缺失。
229
+ """
230
+ import statistics
231
+ if not collection_id:
232
+ return None, 0
233
+ params = {"id": str(collection_id), "entity": "podcastEpisode", "limit": "5"}
234
+ if country:
235
+ params["country"] = country
236
+ try:
237
+ data = _get_json(f"{lookup_base}?{urllib.parse.urlencode(params)}", to)
238
+ except Exception as e:
239
+ logger.debug(f"iTunes 单集取样失败: {e}")
240
+ return None, 0
241
+ mins = []
242
+ for it in data.get("results") or []:
243
+ if not isinstance(it, dict):
244
+ continue
245
+ if str(it.get("wrapperType") or "").lower() != "podcastepisode":
246
+ continue
247
+ ms = it.get("trackTimeMillis")
248
+ if isinstance(ms, (int, float)) and ms > 0:
249
+ mins.append(ms / 60000.0)
250
+ if not mins:
251
+ return None, 0
252
+ return int(round(statistics.median(mins))), len(mins)
253
+
254
+ def _show_transcript(feed_url: str, to: float) -> tuple[str, str]:
255
+ """节目官方文字稿(Podcasting 2.0):feed 里 <podcast:transcript> 标签
256
+ 指向创作者自己挂的全文,不是 ASR 猜的——这是播客转录里唯一免费且
257
+ 准确的通道(英文生态采纳率高,中文节目普遍没挂)。
258
+
259
+ 取 feed 中第一份可解析格式的文字稿(最新一期):搜索对象是「节目」,
260
+ 最新一期代表当前内容;历史各期的文字稿同挂在 feed,下游拿着
261
+ transcript_url 可回读全文。任何失败一律 ("", ""),节目本体照常返回。
262
+ application/json(Podcasting 2.0 的机器格式)本版不解析,静默跳过。
263
+ """
264
+ if not feed_url:
265
+ return "", ""
266
+ feed_url = str(feed_url).strip()
267
+ if not feed_url.lower().startswith(("https://", "http://")):
268
+ return "", ""
269
+ try:
270
+ req = urllib.request.Request(feed_url, headers=ua_headers)
271
+ with http_open(req, timeout=to, engine=engine_tag) as resp:
272
+ feed_xml = resp.read(_TRANSCRIPT_MAX_BYTES).decode("utf-8", "replace")
273
+ except Exception as e:
274
+ logger.debug(f"iTunes 文字稿 feed 拉取失败: {e}")
275
+ return "", ""
276
+ ok_types = ("text/vtt", "text/srt", "text/plain", "text/html")
277
+ ok_exts = ("vtt", "srt", "txt", "html", "htm")
278
+ for m in re.finditer(r"<podcast:transcript\b[^>]*>", feed_xml):
279
+ tag = m.group(0)
280
+ # 属性可能是单引号或双引号;type 可能带 ;charset= 参数
281
+ url_m = re.search(r"""\burl=("([^"]+)"|'([^']+)')""", tag)
282
+ if not url_m:
283
+ continue
284
+ raw_url = url_m.group(2) or url_m.group(3)
285
+ type_m = re.search(r"""\btype=("([^"]+)"|'([^']+)')""", tag)
286
+ ctype = (type_m.group(2) or type_m.group(3) if type_m else "").lower()
287
+ ctype = ctype.split(";", 1)[0].strip()
288
+ try:
289
+ parsed = urllib.parse.urlsplit(raw_url)
290
+ if parsed.scheme == "":
291
+ parsed = urllib.parse.urlsplit(urllib.parse.urljoin(feed_url, raw_url))
292
+ # 文字稿 URL 来自第三方 feed 内容:仅接受 https,防 file://
293
+ # 读本地文件、防内网地址(SSRF);urlsplit 对畸形输入抛
294
+ # ValueError,一并拦下
295
+ if parsed.scheme != "https" or not parsed.hostname:
296
+ continue
297
+ t_url = urllib.parse.urlunsplit(parsed)
298
+ except ValueError:
299
+ continue
300
+ if not ctype:
301
+ ext = parsed.path.rsplit(".", 1)[-1].lower() if "." in parsed.path.rsplit("?", 1)[0] else ""
302
+ if ext in ok_exts:
303
+ ctype = "text/plain" if ext in ("txt", "srt") else f"text/{ext}"
304
+ if ctype not in ok_types:
305
+ continue
306
+ try:
307
+ req = urllib.request.Request(t_url, headers=ua_headers)
308
+ with http_open(req, timeout=to, engine=engine_tag) as resp:
309
+ raw = resp.read(_TRANSCRIPT_MAX_BYTES).decode("utf-8", "replace")
310
+ except Exception as e:
311
+ logger.debug(f"iTunes 文字稿下载失败: {e}")
312
+ continue # 这份坏了不放弃整条节目,试下一份候选
313
+ text = _transcript_to_text(raw, ctype)
314
+ if text:
315
+ return t_url, text
316
+ return "", ""
317
+
318
+ @safe_search
319
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
320
+ q = (query or "").strip()
321
+ if not q:
322
+ return []
323
+ to = _timeout or timeout
324
+ want_podcast = bool(_PODCAST_HINT_RE.search(q))
325
+ want_episode = want_podcast and bool(_PODCAST_EPISODE_RE.search(q))
326
+ want_album = bool(_ALBUM_HINT_RE.search(q)) and not want_podcast
327
+ # 去掉意图词,保留实体名
328
+ term = _MEDIA_INTENT_WORD_RE.sub(" ", q)
329
+ term = re.sub(r"\s+", " ", term).strip() or q
330
+ has_zh = bool(re.search(r"[\u4e00-\u9fff]", term))
331
+ country = "cn" if has_zh else ""
332
+ params: dict[str, str] = {
333
+ "term": term,
334
+ "limit": str(min(max(n, 1), 25)),
335
+ }
336
+ if want_podcast:
337
+ params["media"] = "podcast"
338
+ params["entity"] = "podcastEpisode" if want_episode else "podcast"
339
+ else:
340
+ params["media"] = "music"
341
+ if want_album:
342
+ params["entity"] = "album"
343
+ if country:
344
+ params["country"] = country
345
+ params["lang"] = "zh_cn"
346
+ try:
347
+ data = _get_json(f"{base}?{urllib.parse.urlencode(params)}", to)
348
+ except Exception as e:
349
+ logger.warning(f"iTunes 失败: {e}")
350
+ return []
351
+ items = data.get("results") or []
352
+ # 相关度:实体名与 term 重叠。播客单集的标题里不含节目名,故比对
353
+ # 「标题 + 摘要」——摘要首段就是《节目名》,否则搜节目名拿单集会全被滤掉。
354
+ t_keys = {t.lower() for t in re.findall(r"[A-Za-z0-9\u4e00-\u9fff]{2,}", term)}
355
+ base_score = 0.88 if want_album else 0.85
356
+ out: list[dict[str, Any]] = []
357
+ for it in items:
358
+ if not isinstance(it, dict):
359
+ continue
360
+ is_episode = want_podcast and (
361
+ str(it.get("wrapperType") or "").lower() == "podcastepisode"
362
+ or (not it.get("wrapperType") and it.get("episodeUrl"))
363
+ )
364
+ if want_podcast and not is_episode:
365
+ title = str(it.get("collectionName") or it.get("trackName") or "").strip()
366
+ href = it.get("collectionViewUrl") or it.get("feedUrl") or ""
367
+ count = it.get("trackCount")
368
+ bits = ["播客"]
369
+ if isinstance(count, int) and count > 0:
370
+ bits.append(f"{count} 集")
371
+ genre = str(it.get("primaryGenreName") or "").strip()
372
+ if genre:
373
+ bits.append(genre)
374
+ updated = _itunes_date(it.get("releaseDate"))
375
+ if updated:
376
+ bits.append(f"更新 {updated}")
377
+ row: dict[str, Any] = {
378
+ "title": title,
379
+ "url": str(href or "").strip(),
380
+ "snippet": " · ".join(bits)[:300],
381
+ "source": source_name,
382
+ }
383
+ if isinstance(count, int) and count > 0:
384
+ row["episode_count"] = count
385
+ # published_at 是既有的一等字段(--fields agent 与 --sort 都认它)。
386
+ # 只给播客挂:音乐的 releaseDate 不在本次范围内,而挂上会改变
387
+ # 音乐查询在 --sort newest 下的重排行为(releaseDate≠引擎相关序)。
388
+ _published = str(it.get("releaseDate") or "").strip()
389
+ if _published:
390
+ row["published_at"] = _published[:64]
391
+ elif is_episode:
392
+ title = str(it.get("trackName") or "").strip()
393
+ show = str(it.get("collectionName") or "").strip()
394
+ bits = [f"《{show}》"] if show else []
395
+ ms = it.get("trackTimeMillis")
396
+ row = {
397
+ "title": title,
398
+ "url": str(it.get("trackViewUrl") or it.get("episodeUrl") or "").strip(),
399
+ "snippet": "",
400
+ "source": source_name,
401
+ }
402
+ if isinstance(ms, (int, float)) and ms > 0:
403
+ mins = int(round(ms / 60000.0))
404
+ row["duration_minutes"] = mins
405
+ bits.append(f"时长 {mins} 分")
406
+ pub_date = _itunes_date(it.get("releaseDate"))
407
+ if pub_date:
408
+ bits.append(pub_date)
409
+ _published = str(it.get("releaseDate") or "").strip()
410
+ if _published:
411
+ row["published_at"] = _published[:64]
412
+ row["snippet"] = " · ".join(bits)[:300]
413
+ else:
414
+ if want_album:
415
+ title = str(it.get("collectionName") or it.get("trackName") or "").strip()
416
+ href = it.get("collectionViewUrl") or it.get("trackViewUrl") or ""
417
+ else:
418
+ title = str(it.get("trackName") or it.get("collectionName") or "").strip()
419
+ href = it.get("trackViewUrl") or it.get("collectionViewUrl") or ""
420
+ row = {
421
+ "title": title,
422
+ "url": str(href or "").strip(),
423
+ "snippet": str(it.get("artistName") or "").strip()[:300],
424
+ "source": source_name,
425
+ }
426
+ if not row["title"] or not row["url"]:
427
+ continue
428
+ blob = f"{row['title']} {row['snippet']}".lower()
429
+ if t_keys and not any(k in blob for k in t_keys):
430
+ continue
431
+ row["score"] = rank_score(base_score, len(out))
432
+ out.append(row)
433
+ if len(out) >= n:
434
+ break
435
+ # 节目级时长补在筛选之后:被滤掉的结果不该付二跳的代价
436
+ if want_podcast and not want_episode:
437
+ enriched = 0
438
+ for it in items:
439
+ if enriched >= _ITUNES_SHOW_ENRICH_MAX:
440
+ break
441
+ if not isinstance(it, dict):
442
+ continue
443
+ name = str(it.get("collectionName") or "").strip()
444
+ target = next((r for r in out if r["title"] == name), None)
445
+ if target is None or "duration_minutes" in target:
446
+ continue
447
+ mid, samples = _recent_episode_duration(it.get("collectionId"), country, to)
448
+ if mid is not None:
449
+ target["duration_minutes"] = mid
450
+ target["snippet"] = f"{target['snippet']} · 近 {samples} 期中位 {mid} 分"
451
+ enriched += 1
452
+ # 文字稿与时长共用 enrich 配额(前 1 条节目):官方全文预览的
453
+ # 信息密度远高于「N 集 · 类型」元数据行,有文字稿时 snippet
454
+ # 拼接全文开头,episode_count/published_at 等结构字段不动
455
+ feed_url = str(it.get("feedUrl") or "").strip()
456
+ if feed_url:
457
+ t_url, t_prev = _show_transcript(feed_url, to)
458
+ if t_url:
459
+ target["transcript_url"] = t_url
460
+ if t_prev:
461
+ target["snippet"] = f"{target['snippet']} | {t_prev}"[:300]
462
+ enriched += 1
463
+ return out
464
+ return _engine
465
+
466
+
467
+ # ── TheSportsDB 体育(免认证 test key=3) ────────────────────────────────────
468
+
469
+ _SPORTSDB_BASE = "https://www.thesportsdb.com/api/v1/json/3"
470
+ _SPORTSDB_UA = "argo-search/2.6 (unified-search@local)"
471
+
472
+ # 高频中文球员/球队 → TheSportsDB 英文检索名(公开 API 基本只认拉丁文)
473
+ _SPORTS_ZH_ALIASES: dict[str, str] = {
474
+ "梅西": "Messi",
475
+ "C罗": "Ronaldo",
476
+ "C羅": "Ronaldo",
477
+ "罗纳尔多": "Ronaldo",
478
+ "Cristiano": "Ronaldo",
479
+ "内马尔": "Neymar",
480
+ "姆巴佩": "Mbappe",
481
+ "哈兰德": "Haaland",
482
+ # 单姓 Curry 会命中 Eddy Curry;中文「库里」默认指 Stephen Curry
483
+ "库里": "Stephen Curry",
484
+ "斯蒂芬库里": "Stephen Curry",
485
+ "史蒂芬库里": "Stephen Curry",
486
+ "詹姆斯": "LeBron James",
487
+ "勒布朗": "LeBron",
488
+ "杜兰特": "Durant",
489
+ "科比": "Kobe",
490
+ "乔丹": "Jordan",
491
+ "姚明": "Yao Ming",
492
+ "易建联": "Yi Jianlian",
493
+ "皇马": "Real Madrid",
494
+ "巴萨": "Barcelona",
495
+ "曼联": "Manchester United",
496
+ "曼城": "Manchester City",
497
+ "湖人": "Lakers",
498
+ "勇士": "Warriors",
499
+ "凯尔特人": "Celtics",
500
+ }
501
+
502
+
503
+ def _sports_expand_aliases(query: str) -> list[str]:
504
+ """中文别名展开为英文检索变体。"""
505
+ out: list[str] = []
506
+ for zh, en in _SPORTS_ZH_ALIASES.items():
507
+ if zh in query:
508
+ if en not in out:
509
+ out.append(en)
510
+ return out
511
+
512
+
513
+ def _build_thesportsdb_engine(spec: dict[str, Any]) -> Any:
514
+ """TheSportsDB 球员/球队/赛事搜索(api key=3 公开测试钥,免认证)。
515
+
516
+ 并行查 searchplayers / searchteams / searchevents,合并去重。
517
+ """
518
+ timeout = spec.get("timeout", 10)
519
+ source_name = spec.get("_name", "thesportsdb")
520
+
521
+ def _fetch(path: str, params: dict[str, str], to: float) -> Any:
522
+ url = f"{_SPORTSDB_BASE}/{path}?" + urllib.parse.urlencode(params)
523
+ req = urllib.request.Request(
524
+ url, headers={"User-Agent": _SPORTSDB_UA, "Accept": "application/json"},
525
+ )
526
+ with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
527
+ return json.loads(resp.read().decode("utf-8", "replace"))
528
+
529
+ @safe_search
530
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
531
+ q = (query or "").strip()
532
+ if not q:
533
+ return []
534
+ to = _timeout or timeout
535
+ # 多词查询(如 "NBA finals MVP 2024")整句常 0 命中 → 短语 + token 变体
536
+ stop = {
537
+ "finals", "final", "mvp", "vs", "the", "and", "of", "in", "for", "a", "an",
538
+ "winner", "winners", "who", "won", "what", "which", "year", "years",
539
+ "team", "club", "player", "coach", "manager", "roster", "squad",
540
+ "决赛", "半决赛", "总冠军", "联赛", "球员", "俱乐部", "进球", "冠军",
541
+ "球队", "球星", "效力", "夺冠", "卫冕", "助攻", "得分王",
542
+ }
543
+ tokens = re.findall(r"[A-Za-z\u4e00-\u9fff]{2,}", q)
544
+ # 纯数字年号单独收集,用于 event 年份保持一致,不当主检索词
545
+ # 注意:必须整年捕获;r"(19|20)\d{2}" 的 findall 只会返回 "20",
546
+ # 导致 "20" in "2016-11-24" 恒真、年份过滤失效。
547
+ years = re.findall(r"\b((?:19|20)\d{2})\b", q)
548
+ meaningful = [t for t in tokens if t.lower() not in stop and not re.fullmatch(r"\d{4}", t)]
549
+
550
+ variants: list[str] = []
551
+ # 中文别名优先(梅西→Messi)
552
+ for alias in _sports_expand_aliases(q):
553
+ if alias not in variants:
554
+ variants.append(alias)
555
+ # 双词短语优先(World Cup / LeBron James)
556
+ for i in range(len(meaningful) - 1):
557
+ phrase = f"{meaningful[i]} {meaningful[i + 1]}"
558
+ if phrase not in variants:
559
+ variants.append(phrase)
560
+ # 整句(短查询,非纯中文)
561
+ if len(q) <= 40 and q not in variants and re.search(r"[A-Za-z]", q):
562
+ variants.insert(0, q)
563
+ for t in meaningful:
564
+ # 纯中文 token 对英文 API 无效,跳过(已由别名覆盖)
565
+ if re.fullmatch(r"[\u4e00-\u9fff]+", t):
566
+ continue
567
+ if t not in variants:
568
+ variants.append(t)
569
+ if len(variants) >= 5:
570
+ break
571
+ if not variants:
572
+ variants = [q]
573
+
574
+ # 意图:club/team/球队 → 优先 team/player;event 词 → 保留 event
575
+ q_low = q.lower()
576
+ prefer_entity = bool(re.search(
577
+ r"(?i)(team|club|player|coach|球队|球星|俱乐部|效力|球员|roster|squad)", q,
578
+ ))
579
+ prefer_event = bool(re.search(
580
+ r"(?i)(finals?|mvp|cup|championship|winner|won|决赛|总冠军|世界杯|欧冠|季后赛)", q,
581
+ )) and not prefer_entity
582
+
583
+ bucket: list[dict[str, Any]] = []
584
+ seen: set[str] = set()
585
+
586
+ endpoints = (
587
+ ("searchplayers.php", "p", "player", "strPlayer", "idPlayer",
588
+ lambda x: " · ".join(p for p in (
589
+ x.get("strTeam") or "",
590
+ x.get("strSport") or "",
591
+ x.get("strPosition") or "",
592
+ x.get("strNationality") or "",
593
+ ) if p)),
594
+ ("searchteams.php", "t", "team", "strTeam", "idTeam",
595
+ lambda x: " · ".join(p for p in (
596
+ x.get("strSport") or "",
597
+ x.get("strLeague") or "",
598
+ x.get("strCountry") or "",
599
+ ) if p)),
600
+ ("searchevents.php", "e", "event", "strEvent", "idEvent",
601
+ lambda x: " · ".join(p for p in (
602
+ x.get("strLeague") or "",
603
+ x.get("strSport") or "",
604
+ x.get("dateEvent") or x.get("strTimestamp") or "",
605
+ ) if p)),
606
+ )
607
+ list_keys = {
608
+ "searchplayers.php": "player",
609
+ "searchteams.php": "teams",
610
+ "searchevents.php": "event",
611
+ }
612
+ url_tpl = {
613
+ "player": "https://www.thesportsdb.com/player/{id}",
614
+ "team": "https://www.thesportsdb.com/team/{id}",
615
+ "event": "https://www.thesportsdb.com/event/{id}",
616
+ }
617
+ score_of = {"player": 0.86, "team": 0.84, "event": 0.82}
618
+ # 实体问优先 player/team;赛事问放宽 event
619
+ if prefer_entity:
620
+ endpoints = endpoints[:2] + endpoints[2:] # 顺序已是 p,t,e
621
+ elif prefer_event:
622
+ endpoints = (endpoints[2], endpoints[0], endpoints[1])
623
+
624
+ q_token_set = {t.lower() for t in meaningful}
625
+
626
+ for v in variants:
627
+ for path, param_k, kind, title_k, id_k, snip_fn in endpoints:
628
+ try:
629
+ data = _fetch(path, {param_k: v}, to)
630
+ except Exception as e:
631
+ logger.warning(f"TheSportsDB {path} 失败: {e}")
632
+ continue
633
+ items = data.get(list_keys[path]) if isinstance(data, dict) else None
634
+ if not items:
635
+ continue
636
+ for x in items[: max(n, 5)]:
637
+ if not isinstance(x, dict):
638
+ continue
639
+ title = x.get(title_k) or ""
640
+ iid = str(x.get(id_k) or "")
641
+ key = f"{kind}:{iid or title}"
642
+ if not title or key in seen:
643
+ continue
644
+ # 相关度:标题/摘要 token 与查询重叠;event 尤其严格
645
+ snip = snip_fn(x) or ""
646
+ sport = str(x.get("strSport") or "")
647
+ league = str(x.get("strLeague") or "")
648
+ blob = f"{title} {snip} {sport} {league}".lower()
649
+ t_tokens = set(re.findall(r"[a-z0-9\u4e00-\u9fff]{2,}", blob))
650
+ overlap = len(q_token_set & t_tokens) if q_token_set else 1
651
+ # 「世界杯/World Cup」默认足球;公开 API 常塞高尔夫/篮网等噪声 → 非足球一律丢
652
+ world_cup_q = bool(re.search(r"(?i)world\s*cup|世界杯|fifa", q))
653
+ if world_cup_q:
654
+ if not re.search(r"(?i)soccer|football|fifa", f"{title} {sport} {league} {snip}"):
655
+ continue
656
+ if kind == "event":
657
+ # 无实质重叠 → 丢弃噪声 event(如 World Cup → World Sand Greens)
658
+ if q_token_set and overlap == 0:
659
+ continue
660
+ # 有年份且 API 给了日期:年份不对直接丢(避免 2022 问到 2016 Golf)
661
+ date_s = str(x.get("dateEvent") or x.get("strTimestamp") or "")
662
+ if years and date_s and not any(y in date_s for y in years):
663
+ continue
664
+ # 双词短语(如 World Cup)若在标题中,要求更高相关;单 token 过宽
665
+ phrase_hit = any(
666
+ len(p.split()) >= 2 and p.lower() in title.lower()
667
+ for p in variants[:3]
668
+ )
669
+ if q_token_set and overlap < 2 and not phrase_hit:
670
+ continue
671
+ rel = 0.35 + 0.15 * overlap + (0.2 if phrase_hit else 0)
672
+ if years and date_s and any(y in date_s for y in years):
673
+ rel += 0.2
674
+ if world_cup_q and re.search(r"(?i)soccer|football|fifa", blob):
675
+ rel += 0.25
676
+ else:
677
+ # 赛事问勿用弱 token 沾上球员(Metta World Peace)
678
+ if prefer_event and overlap < 2 and v.lower() not in title.lower():
679
+ continue
680
+ if world_cup_q and kind == "player" and not re.search(
681
+ r"(?i)soccer|football", f"{sport} {snip}",
682
+ ):
683
+ continue
684
+ # player/team:变体本身已是名,重叠可放宽
685
+ rel = 0.35 + 0.25 * overlap
686
+ if v.lower() in title.lower():
687
+ rel += 0.25
688
+ # 全名变体(Stephen Curry)精确命中加权
689
+ if " " in v and v.lower() == title.lower():
690
+ rel += 0.3
691
+ seen.add(key)
692
+ href = url_tpl[kind].format(id=iid) if iid else ""
693
+ base = score_of.get(kind, 0.8)
694
+ bucket.append({
695
+ "title": f"[{kind}] {title}",
696
+ "url": href,
697
+ "snippet": (snip_fn(x) or kind)[:300],
698
+ "source": source_name,
699
+ "score": min(0.95, base * 0.5 + rel),
700
+ "_kind": kind,
701
+ "_rel": rel,
702
+ })
703
+ # 已有高相关实体则早停
704
+ if sum(1 for r in bucket if r.get("_rel", 0) >= 0.5) >= n:
705
+ break
706
+
707
+ kind_rank = {"player": 0, "team": 1, "event": 2}
708
+ if prefer_entity:
709
+ kind_rank = {"player": 0, "team": 0, "event": 3}
710
+ elif prefer_event:
711
+ kind_rank = {"event": 0, "player": 1, "team": 2}
712
+
713
+ bucket.sort(key=lambda r: (
714
+ kind_rank.get(r.get("_kind", ""), 9),
715
+ -float(r.get("_rel", 0)),
716
+ -float(r.get("score", 0)),
717
+ ))
718
+ out = []
719
+ for r in bucket[:n]:
720
+ r.pop("_kind", None)
721
+ r.pop("_rel", None)
722
+ out.append(r)
723
+ return out
724
+ return _engine