argo-search 2.12.0 → 2.13.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 (322) hide show
  1. package/README.en.md +23 -12
  2. package/README.es.md +23 -12
  3. package/README.ja.md +26 -13
  4. package/README.ko.md +23 -12
  5. package/README.md +57 -42
  6. package/SKILL.md +4 -4
  7. package/assets/readme/counts.json +1 -0
  8. package/assets/readme/hero.svg +1 -1
  9. package/backends/domain_profiles.json +12 -0
  10. package/backends/engine_registry.yaml +34 -7
  11. package/backends/env_passthrough.txt +73 -0
  12. package/backends/quota_profiles.json +21 -1
  13. package/config.yaml +7 -3523
  14. package/docs/ARGO_INTRO.md +4 -3
  15. package/docs/CHANGELOG.md +314 -0
  16. package/docs/ENGINE_CATALOG.md +57 -55
  17. package/docs/QUALITY_OF_SLOW_SOURCES.md +115 -0
  18. package/docs/RELEASE_NOTES_v2.13.0.md +66 -0
  19. package/docs/RELEASING.md +47 -0
  20. package/docs//344/270/272/344/273/200/344/271/210/351/200/211/346/213/251argo.md +7 -7
  21. package/engines/specs/anysearch.yaml +33 -0
  22. package/engines/specs/archive_org.yaml +31 -0
  23. package/engines/specs/arxiv.yaml +18 -0
  24. package/engines/specs/baidu_baike.yaml +16 -0
  25. package/engines/specs/baidu_hot.yaml +19 -0
  26. package/engines/specs/bilibili.yaml +33 -0
  27. package/engines/specs/bilibili_hot.yaml +19 -0
  28. package/engines/specs/bing_rss.yaml +17 -0
  29. package/engines/specs/biorxiv.yaml +2 -0
  30. package/engines/specs/bocha.yaml +26 -0
  31. package/engines/specs/bocha_ai.yaml +27 -0
  32. package/engines/specs/brave.yaml +20 -0
  33. package/engines/specs/byted.yaml +33 -0
  34. package/engines/specs/clinicaltrials.yaml +15 -0
  35. package/engines/specs/cls_telegraph.yaml +19 -0
  36. package/engines/specs/cnii.yaml +16 -0
  37. package/engines/specs/cninfo.yaml +14 -0
  38. package/engines/specs/coingecko.yaml +25 -0
  39. package/engines/specs/courtlistener.yaml +15 -0
  40. package/engines/specs/crates.yaml +30 -0
  41. package/engines/specs/crossref.yaml +27 -0
  42. package/engines/specs/csdn.yaml +18 -0
  43. package/engines/specs/dblp.yaml +29 -0
  44. package/engines/specs/devto.yaml +26 -0
  45. package/engines/specs/dnb.yaml +17 -0
  46. package/engines/specs/doaj.yaml +17 -0
  47. package/engines/specs/docker_hub.yaml +30 -0
  48. package/engines/specs/douban_book.yaml +14 -0
  49. package/engines/specs/douyin_hot.yaml +21 -0
  50. package/engines/specs/eastmoney.yaml +16 -0
  51. package/engines/specs/ecosia.yaml +18 -0
  52. package/engines/specs/electricity_maps.yaml +17 -0
  53. package/engines/specs/em_flow.yaml +14 -0
  54. package/engines/specs/em_global_news.yaml +17 -0
  55. package/engines/specs/em_miaoxiang.yaml +14 -0
  56. package/engines/specs/eu_opendata.yaml +16 -0
  57. package/engines/specs/europeana.yaml +19 -0
  58. package/engines/specs/europepmc.yaml +29 -0
  59. package/engines/specs/eurostat.yaml +14 -0
  60. package/engines/specs/exa.yaml +20 -0
  61. package/engines/specs/felo.yaml +25 -0
  62. package/engines/specs/figshare.yaml +17 -0
  63. package/engines/specs/finviz.yaml +15 -0
  64. package/engines/specs/fr_opendata.yaml +28 -0
  65. package/engines/specs/frankfurter.yaml +21 -0
  66. package/engines/specs/fred.yaml +15 -0
  67. package/engines/specs/free_dictionary.yaml +16 -0
  68. package/engines/specs/fx_rate.yaml +14 -0
  69. package/engines/specs/gbfs_nyc.yaml +3 -0
  70. package/engines/specs/gbif.yaml +15 -0
  71. package/engines/specs/github.yaml +25 -0
  72. package/engines/specs/google_patents.yaml +16 -0
  73. package/engines/specs/google_scholar.yaml +16 -0
  74. package/engines/specs/gov_policy.yaml +31 -0
  75. package/engines/specs/gutenberg.yaml +15 -0
  76. package/engines/specs/hackernews.yaml +17 -0
  77. package/engines/specs/hal.yaml +16 -0
  78. package/engines/specs/hatena_bookmark.yaml +20 -0
  79. package/engines/specs/huggingface.yaml +31 -0
  80. package/engines/specs/imdb.yaml +18 -0
  81. package/engines/specs/itotii.yaml +17 -0
  82. package/engines/specs/itunes.yaml +19 -0
  83. package/engines/specs/jin10.yaml +15 -0
  84. package/engines/specs/juejin.yaml +16 -0
  85. package/engines/specs/know_your_meme.yaml +18 -0
  86. package/engines/specs/kor_law.yaml +17 -0
  87. package/engines/specs/lieu.yaml +18 -0
  88. package/engines/specs/listenbrainz.yaml +4 -0
  89. package/engines/specs/local_arxiv.yaml +18 -0
  90. package/engines/specs/local_baidu.yaml +30 -0
  91. package/engines/specs/local_bing.yaml +16 -0
  92. package/engines/specs/local_bing_news.yaml +22 -0
  93. package/engines/specs/local_crossref.yaml +23 -0
  94. package/engines/specs/local_github.yaml +27 -0
  95. package/engines/specs/local_gitlab.yaml +23 -0
  96. package/engines/specs/local_goodreads.yaml +16 -0
  97. package/engines/specs/local_google_news.yaml +15 -0
  98. package/engines/specs/local_imdb.yaml +17 -0
  99. package/engines/specs/local_npm.yaml +25 -0
  100. package/engines/specs/local_openstreetmap.yaml +36 -0
  101. package/engines/specs/local_pubmed.yaml +21 -0
  102. package/engines/specs/local_search.yaml +22 -0
  103. package/engines/specs/local_semantic_scholar.yaml +23 -0
  104. package/engines/specs/local_sogou.yaml +15 -0
  105. package/engines/specs/local_stackoverflow.yaml +26 -0
  106. package/engines/specs/local_wikipedia.yaml +26 -0
  107. package/engines/specs/local_wikiquote.yaml +26 -0
  108. package/engines/specs/local_wiktionary.yaml +26 -0
  109. package/engines/specs/marginalia.yaml +22 -0
  110. package/engines/specs/mdn.yaml +32 -0
  111. package/engines/specs/met_museum.yaml +4 -2
  112. package/engines/specs/metaso.yaml +19 -0
  113. package/engines/specs/models_dev.yaml +16 -0
  114. package/engines/specs/moegirl.yaml +19 -0
  115. package/engines/specs/musicbrainz.yaml +31 -0
  116. package/engines/specs/nasa_cmr.yaml +15 -0
  117. package/engines/specs/nbs_stats.yaml +16 -0
  118. package/engines/specs/ndl.yaml +17 -0
  119. package/engines/specs/noaa_swpc.yaml +3 -0
  120. package/engines/specs/npm.yaml +62 -0
  121. package/engines/specs/octen.yaml +16 -0
  122. package/engines/specs/open_library.yaml +15 -0
  123. package/engines/specs/open_meteo.yaml +17 -0
  124. package/engines/specs/openalex.yaml +27 -0
  125. package/engines/specs/opencitations.yaml +4 -1
  126. package/engines/specs/opencorporates.yaml +19 -0
  127. package/engines/specs/openfda.yaml +15 -0
  128. package/engines/specs/opensky.yaml +17 -0
  129. package/engines/specs/openverse.yaml +42 -0
  130. package/engines/specs/parallel.yaml +22 -0
  131. package/engines/specs/parallel_free.yaml +20 -0
  132. package/engines/specs/polymarket.yaml +26 -0
  133. package/engines/specs/pubchem.yaml +15 -0
  134. package/engines/specs/pypi.yaml +16 -0
  135. package/engines/specs/qiita.yaml +28 -0
  136. package/engines/specs/qq_music.yaml +17 -0
  137. package/engines/specs/qwant.yaml +19 -0
  138. package/engines/specs/qweather.yaml +14 -0
  139. package/engines/specs/rcsb_pdb.yaml +15 -0
  140. package/engines/specs/reddit.yaml +28 -0
  141. package/engines/specs/redskill.yaml +24 -0
  142. package/engines/specs/rfc_editor.yaml +15 -0
  143. package/engines/specs/satnogs.yaml +5 -1
  144. package/engines/specs/searchmysite.yaml +18 -0
  145. package/engines/specs/searxng.yaml +18 -0
  146. package/engines/specs/sec_companyfacts.yaml +22 -0
  147. package/engines/specs/seeking_alpha.yaml +15 -0
  148. package/engines/specs/seltz.yaml +39 -0
  149. package/engines/specs/semantic_scholar.yaml +18 -0
  150. package/engines/specs/shenma.yaml +13 -0
  151. package/engines/specs/sina_quote.yaml +15 -0
  152. package/engines/specs/so.yaml +13 -0
  153. package/engines/specs/stackoverflow.yaml +18 -0
  154. package/engines/specs/steam.yaml +30 -0
  155. package/engines/specs/tatoeba.yaml +17 -0
  156. package/engines/specs/tavily.yaml +26 -0
  157. package/engines/specs/tencent_kline.yaml +18 -0
  158. package/engines/specs/tencent_quote.yaml +14 -0
  159. package/engines/specs/thesportsdb.yaml +18 -0
  160. package/engines/specs/ths_hot.yaml +19 -0
  161. package/engines/specs/tinyfish.yaml +36 -0
  162. package/engines/specs/tinyfish_news.yaml +34 -0
  163. package/engines/specs/tinyfish_paper.yaml +34 -0
  164. package/engines/specs/toutiao_hot.yaml +19 -0
  165. package/engines/specs/twitter.yaml +36 -0
  166. package/engines/specs/uapi.yaml +18 -0
  167. package/engines/specs/uniprot.yaml +16 -0
  168. package/engines/specs/urban_dictionary.yaml +25 -0
  169. package/engines/specs/usda.yaml +17 -0
  170. package/engines/specs/usgs.yaml +15 -0
  171. package/engines/specs/v2ex.yaml +33 -0
  172. package/engines/specs/vam.yaml +34 -0
  173. package/engines/specs/wallhaven.yaml +51 -0
  174. package/engines/specs/wallstreetcn.yaml +31 -0
  175. package/engines/specs/wayback_cdx.yaml +15 -0
  176. package/engines/specs/weather_cn.yaml +33 -0
  177. package/engines/specs/wechat_sogou.yaml +13 -0
  178. package/engines/specs/weibo.yaml +21 -0
  179. package/engines/specs/weibo_hot.yaml +21 -0
  180. package/engines/specs/wenshu.yaml +14 -0
  181. package/engines/specs/weread.yaml +14 -0
  182. package/engines/specs/wiby.yaml +18 -0
  183. package/engines/specs/wikidata.yaml +33 -0
  184. package/engines/specs/wikipedia.yaml +36 -0
  185. package/engines/specs/wolframalpha.yaml +18 -0
  186. package/engines/specs/worldbank.yaml +15 -0
  187. package/engines/specs/xiaohongshu.yaml +25 -0
  188. package/engines/specs/yahoo_finance.yaml +22 -0
  189. package/engines/specs/you.yaml +22 -0
  190. package/engines/specs/zh_wikipedia.yaml +35 -0
  191. package/engines/specs/zhihu.yaml +33 -0
  192. package/engines/specs/zhihu_global.yaml +18 -0
  193. package/engines/specs/zhihu_hot.yaml +36 -0
  194. package/engines/specs/zhihu_user.yaml +14 -0
  195. package/package.json +25 -25
  196. package/packages/dsh-plugin/README.md +11 -6
  197. package/packages/dsh-plugin/cordis.patch.yml +6 -2
  198. package/packages/dsh-plugin/dsh/client.js +64 -116
  199. package/packages/dsh-plugin/dsh/index.js +2 -2
  200. package/packages/dsh-plugin/package.json +1 -1
  201. package/packages/dsh-plugin/scripts/sync-local.sh +13 -11
  202. package/packages/dsh-plugin/test/client.test.js +16 -5
  203. package/packages/dsh-plugin/test/size-gate.test.js +2 -2
  204. package/scripts/ab_eval_p0p1.py +10 -4
  205. package/scripts/archive_run.py +4 -2
  206. package/scripts/badcase_ledger.py +3 -1
  207. package/scripts/batch_probe.py +10 -8
  208. package/scripts/build_release_assets.sh +17 -5
  209. package/scripts/cache.py +5 -5
  210. package/scripts/cache_guard.py +10 -5
  211. package/scripts/candidate_envelope.py +7 -3
  212. package/scripts/circuit_breaker.py +220 -36
  213. package/scripts/config.py +9 -10
  214. package/scripts/daemon.py +11 -2
  215. package/scripts/engine_add.py +32 -0
  216. package/scripts/engine_dispatch.py +49 -46
  217. package/scripts/engine_failure.py +14 -18
  218. package/scripts/engine_health.py +184 -0
  219. package/scripts/engine_states.py +604 -0
  220. package/scripts/engine_status.py +18 -11
  221. package/scripts/engines.py +2 -0
  222. package/scripts/engines_base.py +8 -8
  223. package/scripts/engines_builders.py +31 -19
  224. package/scripts/engines_builders_archive.py +303 -0
  225. package/scripts/engines_builders_batch11.py +63 -1
  226. package/scripts/engines_builders_batch9.py +9 -1
  227. package/scripts/engines_builders_data.py +69 -2090
  228. package/scripts/engines_builders_finance.py +354 -0
  229. package/scripts/engines_builders_intl.py +4 -1
  230. package/scripts/engines_builders_media.py +724 -0
  231. package/scripts/engines_builders_science.py +784 -0
  232. package/scripts/fetch_v3.py +16 -16
  233. package/scripts/gen_engine_catalog.py +58 -153
  234. package/scripts/gen_routing_snapshot.py +8 -6
  235. package/scripts/health_check.py +37 -4
  236. package/scripts/health_probe.py +28 -8
  237. package/scripts/install.ps1 +31 -15
  238. package/scripts/install.sh +266 -142
  239. package/scripts/job.py +8 -70
  240. package/scripts/lint_spec_contracts.py +7 -12
  241. package/scripts/mcp_launch.sh +9 -17
  242. package/scripts/mcp_transport.py +1 -1
  243. package/scripts/net_proxy.py +47 -0
  244. package/scripts/numeric_verify.py +20 -9
  245. package/scripts/output_transparency.py +21 -13
  246. package/scripts/plan.py +8 -5
  247. package/scripts/pre-commit +50 -23
  248. package/scripts/quota.py +11 -7
  249. package/scripts/redskill/redskill_engine.py +3 -9
  250. package/scripts/release.py +60 -24
  251. package/scripts/release_check.py +20 -3
  252. package/scripts/research_dossier.py +10 -5
  253. package/scripts/research_gates.py +5 -1
  254. package/scripts/retry_policy.py +8 -7
  255. package/scripts/route.py +2 -24
  256. package/scripts/route_combo.py +11 -26
  257. package/scripts/search.py +3 -10
  258. package/scripts/search_attribution.py +34 -3
  259. package/scripts/search_cli.py +12 -11
  260. package/scripts/search_entry.py +15 -3
  261. package/scripts/search_output.py +4 -2
  262. package/scripts/search_pipeline.py +14 -10
  263. package/scripts/search_rank.py +23 -62
  264. package/scripts/search_types.py +5 -0
  265. package/scripts/social_engines/bilibili_engine.py +2 -30
  266. package/scripts/social_engines/hackernews_engine.py +4 -12
  267. package/scripts/social_engines/reddit_engine.py +4 -13
  268. package/scripts/social_engines/v2ex_engine.py +3 -12
  269. package/scripts/social_engines/weibo_engine.py +2 -30
  270. package/scripts/social_engines/zhihu_engine.py +4 -5
  271. package/scripts/stats_cli.py +17 -1
  272. package/scripts/sync_backends.py +211 -8
  273. package/scripts/sync_requirements.py +159 -0
  274. package/scripts/tweet.py +3 -6
  275. package/scripts/usage_log.py +28 -9
  276. package/scripts/video_fetch.py +2 -5
  277. package/scripts/watch.py +11 -6
  278. package/scripts/wechat_article.py +6 -9
  279. package/scripts/wx.py +6 -13
  280. package/sub-skills/local-search/SKILL.md +2 -2
  281. package/sub-skills/local-search/config.yaml +2 -1
  282. package/docs/DATA_SOURCE_GAPS.md +0 -81
  283. package/docs/DESIGN_LOCAL_DATA_FUSION.md +0 -90
  284. package/docs/PLATFORM_PATHS.md +0 -111
  285. package/docs/engines/bangumi.md +0 -27
  286. package/docs/engines/biorxiv.md +0 -27
  287. package/docs/engines/clawhub.md +0 -27
  288. package/docs/engines/crt_sh.md +0 -27
  289. package/docs/engines/datacite.md +0 -27
  290. package/docs/engines/deps_dev.md +0 -27
  291. package/docs/engines/douban_movie.md +0 -27
  292. package/docs/engines/endoflife.md +0 -27
  293. package/docs/engines/flk_law.md +0 -27
  294. package/docs/engines/fxtwitter.md +0 -27
  295. package/docs/engines/google_news.md +0 -27
  296. package/docs/engines/gov_regulations.md +0 -27
  297. package/docs/engines/guqian.md +0 -27
  298. package/docs/engines/hackernews.md +0 -27
  299. package/docs/engines/iplant.md +0 -27
  300. package/docs/engines/keenable.md +0 -27
  301. package/docs/engines/met_museum.md +0 -27
  302. package/docs/engines/nasa_images.md +0 -27
  303. package/docs/engines/netease_music.md +0 -27
  304. package/docs/engines/npm.md +0 -27
  305. package/docs/engines/nvd.md +0 -27
  306. package/docs/engines/openreview.md +0 -27
  307. package/docs/engines/openstd.md +0 -27
  308. package/docs/engines/parallel_free.md +0 -27
  309. package/docs/engines/people_daily.md +0 -27
  310. package/docs/engines/pixiv.md +0 -27
  311. package/docs/engines/realtime_index.md +0 -27
  312. package/docs/engines/sec_edgar.md +0 -27
  313. package/docs/engines/seltz.md +0 -27
  314. package/docs/engines/skillsmp.md +0 -27
  315. package/docs/engines/sspai.md +0 -27
  316. package/docs/engines/std_samr.md +0 -27
  317. package/docs/engines/train.md +0 -27
  318. package/docs/engines/un_comtrade.md +0 -27
  319. package/docs/engines/wikisource.md +0 -27
  320. package/docs/engines/zdic.md +0 -27
  321. package/docs/engines/zenodo.md +0 -27
  322. package/docs/engines/zhihu_hot_app.md +0 -27
@@ -395,106 +395,6 @@ def _build_pypi_engine(spec: dict[str, Any]) -> Any:
395
395
  return _engine
396
396
 
397
397
 
398
- # ── ClinicalTrials.gov v2 ────────────────────────────────────────────────────
399
-
400
- def _build_clinicaltrials_engine(spec: dict[str, Any]) -> Any:
401
- """ClinicalTrials.gov API v2 试验检索(免认证)。"""
402
- timeout = spec.get("timeout", 12)
403
-
404
- @safe_search
405
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
406
- import urllib.parse as up
407
- q = " ".join(re.findall(r"[A-Za-z0-9][A-Za-z0-9._+-]*", query))
408
- if not re.search(r"[A-Za-z]{2,}", q):
409
- return []
410
- to = _timeout or timeout
411
- url = "https://clinicaltrials.gov/api/v2/studies?" + up.urlencode({
412
- "query.term": q, "pageSize": min(n, 20), "format": "json"})
413
- try:
414
- with http_open(urllib.request.Request(
415
- url, headers={"User-Agent": "argo-search/2.5", "Accept": "application/json"}), timeout=to, engine=spec.get("_name", "")) as resp:
416
- data = json.loads(resp.read().decode("utf-8", "replace"))
417
- except Exception as e:
418
- logger.warning(f"clinicaltrials 失败: {e}")
419
- return []
420
- results = []
421
- for _rk5, st in enumerate((data.get("studies") or [])[:n]):
422
- ps = st.get("protocolSection") or {}
423
- ident = ps.get("identificationModule") or {}
424
- desc = ps.get("descriptionModule") or {}
425
- status = (ps.get("statusModule") or {}).get("overallStatus") or ""
426
- nct = ident.get("nctId") or ""
427
- title = ident.get("briefTitle") or ident.get("officialTitle") or nct
428
- summary = desc.get("briefSummary") or status
429
- if not title and not nct:
430
- continue
431
- results.append({
432
- "title": str(title)[:200],
433
- "url": f"https://clinicaltrials.gov/study/{nct}" if nct else "",
434
- "snippet": str(summary).replace("\n", " ")[:300],
435
- "source": "clinicaltrials",
436
- "score": rank_score(0.85, _rk5),
437
- })
438
- return results
439
- return _engine
440
-
441
-
442
- # ── openFDA 药品标签 ─────────────────────────────────────────────────────────
443
-
444
- def _build_openfda_engine(spec: dict[str, Any]) -> Any:
445
- """openFDA drug label 搜索(免认证)。"""
446
- timeout = spec.get("timeout", 12)
447
-
448
- @safe_search
449
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
450
- import urllib.parse as up
451
- to = _timeout or timeout
452
- # openFDA Lucene 语法与拉丁索引守卫:提取英文药名并剥离 CJK 与问号/冒号
453
- q = re.sub(r"(?i)\b(drug|medicine|label|openfda|fda)\b", " ", query)
454
- q = " ".join(re.findall(r"[A-Za-z0-9][A-Za-z0-9._+-]*", q))
455
- if not re.search(r"[A-Za-z]{2,}", q):
456
- return []
457
- search = f'openfda.brand_name:"{q}" openfda.generic_name:"{q}"'
458
- url = "https://api.fda.gov/drug/label.json?" + up.urlencode({
459
- "search": search, "limit": min(n, 20)})
460
- try:
461
- with http_open(urllib.request.Request(
462
- url, headers={"User-Agent": "argo-search/2.5", "Accept": "application/json"}), timeout=to, engine=spec.get("_name", "")) as resp:
463
- data = json.loads(resp.read().decode("utf-8", "replace"))
464
- except Exception as e:
465
- # 回退:全文检索
466
- try:
467
- url2 = "https://api.fda.gov/drug/label.json?" + up.urlencode({
468
- "search": q, "limit": min(n, 20),
469
- })
470
- with http_open(urllib.request.Request(
471
- url2, headers={"User-Agent": "argo-search/2.5"}), timeout=to, engine=spec.get("_name", "")) as resp:
472
- data = json.loads(resp.read().decode("utf-8", "replace"))
473
- except Exception as e2:
474
- logger.warning(f"openfda 失败: {e2}")
475
- return []
476
- results = []
477
- for _rk6, item in enumerate((data.get("results") or [])[:n]):
478
- of = item.get("openfda") or {}
479
- brands = of.get("brand_name") or []
480
- generics = of.get("generic_name") or []
481
- title = (brands[0] if brands else "") or (generics[0] if generics else "") or item.get("id", "drug label")
482
- purpose = item.get("purpose") or item.get("indications_and_usage") or []
483
- if isinstance(purpose, list):
484
- purpose = purpose[0] if purpose else ""
485
- set_id = (of.get("spl_set_id") or [None])[0] if isinstance(of.get("spl_set_id"), list) else of.get("spl_set_id")
486
- url_out = f"https://dailymed.nlm.nih.gov/dailymed/drugInfo.cfm?setid={set_id}" if set_id else "https://open.fda.gov/apis/drug/label/"
487
- results.append({
488
- "title": str(title)[:200],
489
- "url": url_out,
490
- "snippet": str(purpose).replace("\n", " ")[:300],
491
- "source": "openfda",
492
- "score": rank_score(0.8, _rk6),
493
- })
494
- return results
495
- return _engine
496
-
497
-
498
398
  # ── 掘金搜索 ─────────────────────────────────────────────────────────────────
499
399
 
500
400
  def _build_juejin_engine(spec: dict[str, Any]) -> Any:
@@ -666,117 +566,6 @@ def _build_models_dev_engine(spec: dict[str, Any]) -> Any:
666
566
  return results
667
567
  return _engine
668
568
 
669
- # ── Finviz 美股筛选引擎(HTML 抓取)─────────────────────────────────────────────
670
-
671
- def _build_finviz_engine(spec: dict[str, Any]) -> Any:
672
- """Finviz 个股快照(finviz.com/stock?t=TICKER)
673
-
674
- 从 snapshot 表格提取:公司名、行业、市值、PE、价格、涨跌幅。
675
- query 视为 ticker(大写);非纯字母时取首个字母 token 作 ticker。
676
- (2026-10-28:旧地址 /quote.ashx 全站 301 到 /stock,http_open 不跟随重定向,
677
- 端点随之切换;新页 snapshot 表结构与解析器兼容,实测 AAPL 全字段命中。)
678
- """
679
- timeout = spec.get("timeout", 10)
680
-
681
- @safe_search
682
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
683
- to = _timeout or timeout
684
- m = re.search(r"[A-Za-z]{1,6}", query or "")
685
- if not m:
686
- return []
687
- ticker = m.group(0).upper()
688
- url = f"https://finviz.com/stock?t={ticker}"
689
- headers = {
690
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
691
- "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
692
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
693
- }
694
- req = urllib.request.Request(url, headers=headers)
695
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
696
- html = resp.read().decode("utf-8", errors="replace")
697
- if _detect_anti_bot(html):
698
- return []
699
-
700
- # snapshot 表格是 key-value 交替单元格
701
- cells = re.findall(r'<td[^>]*class="[^"]*snapshot-td2[^"]*"[^>]*>(.*?)</td>', html, re.DOTALL)
702
- cleaned = [re.sub(r"<[^>]+>", "", c).strip() for c in cells]
703
- kv: dict[str, str] = {}
704
- for i in range(0, len(cleaned) - 1, 2):
705
- kv[cleaned[i]] = cleaned[i + 1]
706
-
707
- # 公司名 / 行业
708
- name_m = re.search(r'<title>([^<]+)</title>', html)
709
- company = name_m.group(1).split("Stock")[0].strip() if name_m else ticker
710
-
711
- if not kv and company == ticker:
712
- return []
713
-
714
- price = kv.get("Price", "")
715
- change = kv.get("Change", "")
716
- market_cap = kv.get("Market Cap", "")
717
- pe = kv.get("P/E", "")
718
- snippet = (f"行业信息见页面 | 市值 {market_cap} | PE {pe} | "
719
- f"价格 {price} | 涨跌幅 {change}")
720
- return [{
721
- "title": f"{company} ({ticker}) 美股快照",
722
- "url": url,
723
- "snippet": snippet[:300],
724
- "source": "finviz",
725
- "score": 0.9,
726
- "facts": {"ticker": ticker, "price": price, "change": change,
727
- "market_cap": market_cap, "pe": pe},
728
- }]
729
- return _engine
730
-
731
- # ── Seeking Alpha 美股分析引擎(HTML 抓取)───────────────────────────────────────
732
-
733
- def _build_seeking_alpha_engine(spec: dict[str, Any]) -> Any:
734
- """Seeking Alpha 个股概览(seekingalpha.com/symbol/TICKER)
735
-
736
- 提取:评级 / 目标价 / 分析摘要(尽力而为,站点反爬较强,失败返回 [])。
737
- """
738
- timeout = spec.get("timeout", 12)
739
-
740
- @safe_search
741
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
742
- to = _timeout or timeout
743
- m = re.search(r"[A-Za-z]{1,6}", query or "")
744
- if not m:
745
- return []
746
- ticker = m.group(0).upper()
747
- url = f"https://seekingalpha.com/symbol/{ticker}"
748
- headers = {
749
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
750
- "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
751
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
752
- }
753
- req = urllib.request.Request(url, headers=headers)
754
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
755
- html = resp.read().decode("utf-8", errors="replace")
756
- if _detect_anti_bot(html):
757
- return []
758
-
759
- desc_m = re.search(r'<meta[^>]+name="description"[^>]+content="([^"]+)"', html)
760
- summary = desc_m.group(1).strip() if desc_m else ""
761
- rating_m = re.search(r'(Strong Buy|Buy|Hold|Sell|Strong Sell)', html)
762
- rating = rating_m.group(1) if rating_m else "N/A"
763
- target_m = re.search(r'Price Target[^0-9]{0,20}(\d+\.\d+)', html)
764
- target = target_m.group(1) if target_m else ""
765
-
766
- if not summary and rating == "N/A":
767
- return []
768
- snippet = f"评级 {rating}" + (f" | 目标价 {target}" if target else "") + \
769
- (f" | {summary}" if summary else "")
770
- return [{
771
- "title": f"{ticker} — Seeking Alpha 分析",
772
- "url": url,
773
- "snippet": snippet[:300],
774
- "source": "seeking_alpha",
775
- "score": 0.85,
776
- "facts": {"ticker": ticker, "rating": rating, "target_price": target},
777
- }]
778
- return _engine
779
-
780
569
  # ── 和风天气引擎(HTTP JSON API,需 QWEATHER_KEY)─────────────────────────────────
781
570
 
782
571
  def _build_qweather_engine(spec: dict[str, Any]) -> Any:
@@ -836,118 +625,6 @@ def _build_qweather_engine(spec: dict[str, Any]) -> Any:
836
625
  }]
837
626
  return _engine
838
627
 
839
- # ── 中国裁判文书网引擎(HTML/JSON 抓取)──────────────────────────────────────────
840
-
841
- def _build_wenshu_engine(spec: dict[str, Any]) -> Any:
842
- """中国裁判文书网(wenshu.court.gov.cn)法律文书检索。
843
-
844
- 该站有较强反爬(参数加密),此处走公开列表接口,尽力而为;
845
- 失败或被拦截时显式返回 [](不伪造结果)。
846
- 提取:案号、案由、裁判日期、法院。
847
- """
848
- timeout = spec.get("timeout", 12)
849
-
850
- @safe_search
851
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
852
- import urllib.parse as up
853
- to = _timeout or timeout
854
- # 公开检索页(列表 HTML)——政府站结构可能变化,解析失败即空
855
- url = f"https://wenshu.court.gov.cn/website/wenshu/181217BMTKHNT2W0/index.html?q={up.quote(query)}"
856
- headers = {
857
- "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
858
- "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
859
- "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
860
- "Referer": "https://wenshu.court.gov.cn/",
861
- }
862
- try:
863
- req = urllib.request.Request(url, headers=headers)
864
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
865
- html = resp.read().decode("utf-8", errors="replace")
866
- except Exception as e:
867
- logger.warning(f"裁判文书网访问失败: {e}")
868
- return []
869
- if _detect_anti_bot(html):
870
- return []
871
-
872
- results: list[dict[str, Any]] = []
873
- # 尝试解析嵌入的 JSON 数据块(站点结构变化时降级为空)
874
- blocks = re.findall(r'\{[^{}]*"caseName"[^{}]*\}', html)
875
- for b in blocks[:n]:
876
- try:
877
- item = json.loads(b)
878
- except Exception:
879
- continue
880
- results.append({
881
- "title": item.get("caseName", "")[:100],
882
- "url": "https://wenshu.court.gov.cn/",
883
- "snippet": (f"案号 {item.get('caseNo', '')} | 案由 {item.get('caseType', '')} | "
884
- f"法院 {item.get('court', '')} | 裁判日期 {item.get('judgeDate', '')}")[:300],
885
- "source": "wenshu",
886
- "facts": {"case_no": item.get("caseNo", ""), "court": item.get("court", ""),
887
- "judge_date": item.get("judgeDate", "")},
888
- })
889
- return results
890
- return _engine
891
-
892
- # ── 金十数据引擎(HTTP JSON API 财经快讯)────────────────────────────────────────
893
-
894
- def _build_jin10_engine(spec: dict[str, Any]) -> Any:
895
- """金十数据财经快讯(flash-api.jin10.com/get_flash_list)
896
-
897
- 提取:时间、标题、内容摘要;按关键词过滤(query 命中)。
898
- """
899
- timeout = spec.get("timeout", 8)
900
-
901
- @safe_search
902
- def _engine(query: str, n: int = 10, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
903
- to = _timeout or timeout
904
- url = f"https://flash-api.jin10.com/get_flash_list?channel=-8200&vip=1&t={int(time.time() * 1000)}"
905
- headers = {
906
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 "
907
- "(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36",
908
- "x-app-id": "bVBF4FyRTn5NJF5n",
909
- "x-version": "1.0.0",
910
- "Referer": "https://www.jin10.com/",
911
- }
912
- req = urllib.request.Request(url, headers=headers)
913
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
914
- data = json.loads(resp.read().decode("utf-8"))
915
- items = data.get("data") or []
916
- keywords = [k for k in (query or "").strip().split() if k]
917
- # 去掉路由触发词,避免「金十」「快讯」本身当过滤条件
918
- stop = {"金十", "jin10", "财经快讯", "市场快讯", "7x24", "快讯", "电报"}
919
- keywords = [k for k in keywords if k.lower() not in stop and k not in stop]
920
- results: list[dict[str, Any]] = []
921
- for it in items:
922
- d = it.get("data") or {}
923
- content = d.get("content", "") or d.get("pic", "") or ""
924
- title = d.get("title", "") or content[:40]
925
- text = f"{title} {content}"
926
- if keywords and not any(k.lower() in text.lower() for k in keywords):
927
- continue
928
- results.append({
929
- "title": title[:80] or "金十快讯",
930
- "url": "https://www.jin10.com/",
931
- "snippet": f"{it.get('time', '')} | {content[:150]}",
932
- "source": "jin10",
933
- })
934
- if len(results) >= n:
935
- break
936
- # 关键词未命中当前快讯池时,回退最新 N 条(金十是滚动电报,非全库检索)
937
- if not results and items:
938
- for it in items[:n]:
939
- d = it.get("data") or {}
940
- content = d.get("content", "") or d.get("pic", "") or ""
941
- title = d.get("title", "") or content[:40]
942
- results.append({
943
- "title": title[:80] or "金十快讯",
944
- "url": "https://www.jin10.com/",
945
- "snippet": f"{it.get('time', '')} | {content[:150]}",
946
- "source": "jin10",
947
- })
948
- return results
949
- return _engine
950
-
951
628
  # ── Octen AI 搜索引擎 ─────────────────────────────────────────────────────────
952
629
 
953
630
  def _build_octen_engine(spec: dict[str, Any]) -> Any:
@@ -1043,316 +720,6 @@ def _build_octen_engine(spec: dict[str, Any]) -> Any:
1043
720
  return _engine
1044
721
 
1045
722
 
1046
- # ── PubChem + ChEMBL 化学引擎(chem 域) ────────────────────────────────────
1047
-
1048
- _PUBCHEM_API = "https://pubchem.ncbi.nlm.nih.gov/rest/pug"
1049
- _CHEMBL_API = "https://www.ebi.ac.uk/chembl/api/data"
1050
- _RE_FORMULA = re.compile(r"^[A-Z][a-z]?\d*([A-Z][a-z]?\d*)*$")
1051
- # 检索噪声词:剥掉后用核心化合物名打 API(「阿司匹林分子式」→「阿司匹林」)
1052
- _CHEM_NOISE_RE = re.compile(
1053
- r"(?i)\b(?:molecular\s+weight|chemical\s+formula|cas\s*number|iupac|smiles|"
1054
- r"formula|weight|compound|molecule|mw)\b|"
1055
- r"分子式|分子量|摩尔质量|化学式|结构式|化合物|药物|CAS号?"
1056
- )
1057
- # 常用中文药名 → PubChem 英文名(中文直查常 miss,ChEMBL 会乱返回无关分子)
1058
- _CHEM_CN_ALIASES: dict[str, str] = {
1059
- "阿司匹林": "aspirin",
1060
- "乙酰水杨酸": "aspirin",
1061
- "布洛芬": "ibuprofen",
1062
- "对乙酰氨基酚": "acetaminophen",
1063
- "扑热息痛": "acetaminophen",
1064
- "咖啡因": "caffeine",
1065
- "葡萄糖": "glucose",
1066
- "乙醇": "ethanol",
1067
- "甲醇": "methanol",
1068
- "胆固醇": "cholesterol",
1069
- "青霉素": "penicillin",
1070
- "阿莫西林": "amoxicillin",
1071
- "二甲双胍": "metformin",
1072
- "奥美拉唑": "omeprazole",
1073
- "硝苯地平": "nifedipine",
1074
- "氨氯地平": "amlodipine",
1075
- "阿托伐他汀": "atorvastatin",
1076
- "氯吡格雷": "clopidogrel",
1077
- "华法林": "warfarin",
1078
- "胰岛素": "insulin",
1079
- "吗啡": "morphine",
1080
- "可待因": "codeine",
1081
- "尼古丁": "nicotine",
1082
- "维生素c": "ascorbic acid",
1083
- "维生素C": "ascorbic acid",
1084
- "抗坏血酸": "ascorbic acid",
1085
- }
1086
- _CHEM_TOKEN_NOISE = frozenset({
1087
- "分子量", "分子式", "化学", "化学式", "结构式", "化合物", "药物",
1088
- "weight", "formula", "molecular", "chemical", "compound", "molecule",
1089
- "cid", "chembl", "smiles", "iupac", "cas", "mw", "acid", "hydrochloride",
1090
- })
1091
-
1092
-
1093
- def _strip_chem_noise(query: str) -> str:
1094
- """去掉「分子式/分子量」等修饰,保留化合物核心名。"""
1095
- cleaned = _CHEM_NOISE_RE.sub(" ", query)
1096
- cleaned = re.sub(r"\s+", " ", cleaned).strip(" ,;|/")
1097
- return cleaned or query.strip()
1098
-
1099
-
1100
- def _chem_lookup_names(query: str) -> list[str]:
1101
- """生成 PubChem/ChEMBL 查询候选:核心名 + 中文别名英文化。"""
1102
- raw = query.strip()
1103
- core = _strip_chem_noise(raw)
1104
- names: list[str] = []
1105
- for candidate in (core, raw):
1106
- if candidate and candidate not in names:
1107
- names.append(candidate)
1108
- # 中文别名:核心或原文含中文药名时追加英文
1109
- hay = f"{core} {raw}"
1110
- for cn, en in _CHEM_CN_ALIASES.items():
1111
- if cn in hay and en not in names:
1112
- names.append(en)
1113
- return names
1114
-
1115
-
1116
- def _chem_tokens(text: str) -> set[str]:
1117
- """化合物相关 token:英文词 + 连续中文 + 数字。"""
1118
- if not text:
1119
- return set()
1120
- low = text.lower()
1121
- tokens = set(re.findall(r"[a-z][a-z0-9\-]{1,}", low))
1122
- tokens.update(cjk_term_grams(text))
1123
- tokens.update(re.findall(r"\d{2,}", text))
1124
- return {t for t in tokens if t not in _CHEM_TOKEN_NOISE and len(t) >= 2}
1125
-
1126
-
1127
- def _chem_result_overlaps(query: str, title: str, snippet: str = "",
1128
- pref_name: str = "") -> bool:
1129
- """结果与查询是否相关:token 交集或核心名子串命中。
1130
-
1131
- 无重叠则视为假阳性(ChEMBL 对中文常返回无关分子)。
1132
- """
1133
- q_tokens = _chem_tokens(query)
1134
- core = _strip_chem_noise(query).lower()
1135
- if core:
1136
- q_tokens |= _chem_tokens(core)
1137
- for cn, en in _CHEM_CN_ALIASES.items():
1138
- if cn in query or cn in core:
1139
- q_tokens.add(en.lower())
1140
- for part in en.lower().split():
1141
- if len(part) >= 2:
1142
- q_tokens.add(part)
1143
- doc = _chem_tokens(f"{title} {snippet} {pref_name}")
1144
- if not q_tokens:
1145
- return True # 无法判定时不误杀
1146
- if q_tokens & doc:
1147
- return True
1148
- hay = f"{title} {snippet} {pref_name}".lower()
1149
- if core and len(core) >= 2 and core in hay:
1150
- return True
1151
- # 英文别名整词
1152
- for cn, en in _CHEM_CN_ALIASES.items():
1153
- if cn in query and en.lower() in hay:
1154
- return True
1155
- return False
1156
-
1157
-
1158
- def _build_pubchem_engine(spec: dict[str, Any]) -> Any:
1159
- """化学/药学化合物检索:PubChem PUG REST 主路径 + ChEMBL 保底。
1160
-
1161
- 支持化合物名、分子式、CAS 号、IUPAC 名查询,返回分子式/分子量/IUPAC/SMILES。
1162
- 质量闸门:ChEMBL 结果须与查询 token 重叠,否则丢弃当 no-results(宁空勿假)。
1163
- """
1164
- timeout = spec.get("timeout", 10)
1165
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
1166
-
1167
- def _jget(url: str, to: float) -> dict:
1168
- req = urllib.request.Request(url, headers=_HEADERS)
1169
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
1170
- return json.loads(resp.read().decode("utf-8", "replace"))
1171
-
1172
- @safe_search
1173
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1174
- q = query.strip()
1175
- if not q:
1176
- return []
1177
- to = _timeout or timeout
1178
- results: list[dict[str, Any]] = []
1179
- lookup_names = _chem_lookup_names(q)
1180
- display_name = _strip_chem_noise(q) or q
1181
-
1182
- # 1. PubChem 主路径:多候选名 → CID → 属性(formula 端点异步,不在此轮询)
1183
- cid = ""
1184
- hit_name = display_name
1185
- for name in lookup_names:
1186
- try:
1187
- d = _jget(
1188
- f"{_PUBCHEM_API}/compound/name/{urllib.parse.quote(name)}/cids/JSON",
1189
- to,
1190
- )
1191
- cids = (d.get("IdentifierList") or {}).get("CID") or []
1192
- if cids:
1193
- cid = str(cids[0])
1194
- hit_name = name
1195
- break
1196
- except Exception:
1197
- continue
1198
- if cid:
1199
- try:
1200
- d = _jget(
1201
- f"{_PUBCHEM_API}/compound/cid/{cid}/property/"
1202
- f"MolecularFormula,MolecularWeight,IUPACName,CanonicalSMILES/JSON", to)
1203
- props = ((d.get("PropertyTable") or {}).get("Properties") or [{}])[0]
1204
- formula = props.get("MolecularFormula", "")
1205
- mw = props.get("MolecularWeight", "")
1206
- iupac = props.get("IUPACName", "") or ""
1207
- smiles = props.get("CanonicalSMILES", "") or ""
1208
- title = f"{display_name} (PubChem CID {cid})"
1209
- if hit_name.lower() != display_name.lower():
1210
- title = f"{display_name} / {hit_name} (PubChem CID {cid})"
1211
- if formula:
1212
- title += f" 分子式 {formula}"
1213
- if mw:
1214
- title += f" 分子量 {mw}"
1215
- snippet = f"CID {cid}"
1216
- if iupac:
1217
- snippet += f" | IUPAC: {iupac}"
1218
- if smiles:
1219
- snippet += f" | SMILES: {smiles}"
1220
- results.append({
1221
- "title": title,
1222
- "url": f"https://pubchem.ncbi.nlm.nih.gov/compound/{cid}",
1223
- "snippet": snippet[:400],
1224
- "source": "pubchem",
1225
- "score": 0.95,
1226
- })
1227
- except Exception as e:
1228
- logger.warning(f"PubChem 属性失败: {e}")
1229
-
1230
- # 2. ChEMBL 保底:仅保留与查询重叠的结果(无重叠 = 空,禁止交差评)
1231
- if not results:
1232
- seen_ids: set[str] = set()
1233
- for name in lookup_names:
1234
- try:
1235
- d = _jget(
1236
- f"{_CHEMBL_API}/molecule/search.json?"
1237
- f"q={urllib.parse.quote(name)}&limit={min(n, 5)}",
1238
- to,
1239
- )
1240
- except Exception as e:
1241
- logger.warning(f"ChEMBL 失败 ({name}): {e}")
1242
- continue
1243
- for m in (d.get("molecules") or [])[:n]:
1244
- props = m.get("molecule_properties") or {}
1245
- chembl_id = m.get("molecule_chembl_id", "")
1246
- if chembl_id in seen_ids:
1247
- continue
1248
- pref = (m.get("pref_name") or "") or ""
1249
- title_base = pref or chembl_id or name
1250
- title = title_base
1251
- if props.get("mw_freebase"):
1252
- title += f" 分子量 {props['mw_freebase']}"
1253
- parts = [f"ChEMBL {chembl_id}"]
1254
- if props.get("full_molformula"):
1255
- parts.append(f"分子式 {props['full_molformula']}")
1256
- if props.get("canonical_smiles"):
1257
- parts.append(f"SMILES {props['canonical_smiles'][:100]}")
1258
- snippet = " | ".join(parts)[:400]
1259
- # 质量闸门:与原查询或当前 lookup 名无重叠则丢弃
1260
- if not (
1261
- _chem_result_overlaps(q, title, snippet, pref)
1262
- or _chem_result_overlaps(name, title, snippet, pref)
1263
- ):
1264
- continue
1265
- seen_ids.add(chembl_id)
1266
- results.append({
1267
- "title": title,
1268
- "url": (f"https://www.ebi.ac.uk/chembl/explore/compound/{chembl_id}"
1269
- if chembl_id else "https://www.ebi.ac.uk/chembl/"),
1270
- "snippet": snippet,
1271
- "source": "chembl",
1272
- "score": rank_score(0.9, len(results)),
1273
- })
1274
- if results:
1275
- break
1276
- if not results:
1277
- logger.info("ChEMBL 结果与查询无重叠,返回空(宁空勿假)")
1278
- return results[: max(n, 3)]
1279
-
1280
- return _engine
1281
-
1282
-
1283
- # ── GBIF 生物多样性引擎(species 域) ────────────────────────────────────────
1284
-
1285
- _GBIF_API = "https://api.gbif.org/v1"
1286
- _GBIF_RANK_ORDER = {"SPECIES": 3, "SUBSPECIES": 2, "GENUS": 1}
1287
-
1288
-
1289
- def _build_gbif_engine(spec: dict[str, Any]) -> Any:
1290
- """GBIF 物种检索(api.gbif.org/v1/species/search,免认证)。
1291
-
1292
- 学名/俗名搜索,优先学名包含查询词的 ACCEPTED 物种条目。
1293
- """
1294
- timeout = spec.get("timeout", 12)
1295
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)"}
1296
-
1297
- def _jget(url: str, to: float) -> dict:
1298
- req = urllib.request.Request(url, headers=_HEADERS)
1299
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
1300
- return json.loads(resp.read().decode("utf-8", "replace"))
1301
-
1302
- @safe_search
1303
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1304
- q = query.strip()
1305
- if not q:
1306
- return []
1307
- # 剥离中文查询噪声词(学名/物种/俗名等);GBIF 只对拉丁学名/英文俗名可靠,
1308
- # 纯中文俗名(如「大熊猫」)搜出来的是无关属种,直接放弃
1309
- q = re.sub(r"(学名|物种|俗名|拉丁名|生物|分类|是什么|有哪些|查询|搜索)", "", q).strip()
1310
- if not re.search(r"[A-Za-z]{2,}", q):
1311
- return []
1312
- to = _timeout or timeout
1313
- ql = q.lower()
1314
- url = f"{_GBIF_API}/species/search?q={urllib.parse.quote(q)}&limit={min(n * 3, 20)}"
1315
- try:
1316
- d = _jget(url, to)
1317
- except Exception as e:
1318
- logger.warning(f"GBIF 失败: {e}")
1319
- return []
1320
-
1321
- def _key(r: dict) -> tuple:
1322
- sn = (r.get("scientificName") or "").lower()
1323
- name_hit = ql in sn # 学名包含查询词优先(俗名匹配的噪声大)
1324
- status_ok = (r.get("taxonomicStatus") or "") == "ACCEPTED"
1325
- rank = _GBIF_RANK_ORDER.get(r.get("rank"), 0)
1326
- return (name_hit, status_ok, rank)
1327
-
1328
- items = sorted((r for r in (d.get("results") or []) if r.get("scientificName")), key=_key, reverse=True)
1329
- results = []
1330
- for _rk9, r in enumerate(items[:n]):
1331
- sci = r.get("scientificName", "")
1332
- rank = r.get("rank", "")
1333
- kingdom = r.get("kingdom") or r.get("kingdomKey") or ""
1334
- status = r.get("taxonomicStatus") or ""
1335
- key = r.get("nubKey") or r.get("key")
1336
- title = f"{sci} ({rank})"
1337
- if status == "ACCEPTED":
1338
- title = f"{sci}(有效名)"
1339
- snip = f"界 {kingdom} | 分类 {rank}"
1340
- if status:
1341
- snip += f" | 状态 {status}"
1342
- if r.get("vernacularName"):
1343
- snip += f" | 俗名 {r['vernacularName']}"
1344
- results.append({
1345
- "title": title,
1346
- "url": f"https://www.gbif.org/species/{key}" if key else "https://www.gbif.org/",
1347
- "snippet": snip,
1348
- "source": "gbif",
1349
- "score": rank_score(0.92, _rk9),
1350
- })
1351
- return results[: max(n, 3)]
1352
-
1353
- return _engine
1354
-
1355
-
1356
723
  # ── RFC Editor / IETF 标准引擎(tech 域) ────────────────────────────────────
1357
724
 
1358
725
  _DATATRACKER_API = "https://datatracker.ietf.org/api/v1"
@@ -1422,1313 +789,98 @@ def _build_rfc_editor_engine(spec: dict[str, Any]) -> Any:
1422
789
 
1423
790
 
1424
791
 
1425
- # ── UniProt 蛋白质/基因组引擎 ────────────────────────────────────────────────
1426
-
1427
- _UNIPROT_API = "https://rest.uniprot.org/uniprotkb/search"
1428
-
1429
- # 高频蛋白中文名 → 英文检索词(UniProt 不索引中文)
1430
- _UNIPROT_CN = {
1431
- "胰岛素": "insulin", "血红蛋白": "hemoglobin", "肌红蛋白": "myoglobin",
1432
- "白蛋白": "albumin", "胶原蛋白": "collagen", "角蛋白": "keratin",
1433
- "胰蛋白酶": "trypsin", "溶菌酶": "lysozyme", "细胞色素c": "cytochrome c",
1434
- "细胞色素": "cytochrome", "泛素": "ubiquitin", "免疫球蛋白": "immunoglobulin",
1435
- "抗体": "antibody", "转铁蛋白": "transferrin", "纤维蛋白原": "fibrinogen",
1436
- "表皮生长因子受体": "EGFR", "生长激素": "growth hormone",
1437
- "血管内皮生长因子": "VEGF", "肿瘤坏死因子": "TNF", "白介素": "interleukin",
1438
- "干扰素": "interferon", "淀粉酶": "amylase", "胃蛋白酶": "pepsin",
1439
- "弹性蛋白": "elastin", "肌动蛋白": "actin", "肌球蛋白": "myosin",
1440
- "微管蛋白": "tubulin", "组蛋白": "histone", "核糖体蛋白": "ribosomal protein",
1441
- "谷胱甘肽过氧化物酶": "glutathione peroxidase", "超氧化物歧化酶": "superoxide dismutase",
1442
- "载脂蛋白": "apolipoprotein", "脂蛋白": "lipoprotein", "受体蛋白": "receptor protein",
1443
- "蛋白激酶": "protein kinase", "磷酸酶": "phosphatase", "转录因子": "transcription factor",
1444
- "癌基因": "oncogene", "抑癌基因": "tumor suppressor", "p53蛋白": "p53",
1445
- }
1446
-
1447
-
1448
- def _ascii_tokens(q: str) -> str:
1449
- """提取查询中的 ASCII 字母数字 token(UniProt/PDB 只索引英文)。"""
1450
- toks = re.findall(r"[A-Za-z0-9][A-Za-z0-9\-\.\*]*", q)
1451
- return " ".join(toks).strip()
1452
-
792
+ # ── GDELT 全球事件数据库 ─────────────────────────────────────────────────────
1453
793
 
1454
- def _build_uniprot_engine(spec: dict[str, Any]) -> Any:
1455
- """UniProt 蛋白质检索(rest.uniprot.org/uniprotkb/search,免认证)。
794
+ # ── Marginalia 独立索引引擎 ──────────────────────────────────────────────────
1456
795
 
1457
- 基因名/蛋白名/物种查询,返回 accession、推荐名、基因名与物种。
1458
- 中英混合查询只取 ASCII token(UniProt 不索引中文),纯中文查高频蛋白名映射表。
796
+ def _build_marginalia_engine(spec: dict[str, Any]) -> Any:
797
+ """Marginalia 独立爬虫索引搜索(old-search.marginalia.nu,免认证 HTML)。
798
+
799
+ 2026-11-08 搬家:api.marginalia.nu JSON 直出挂死(8s/25s 两轮复测 0 字节),
800
+ 主站 search.marginalia.nu 已改 SPA 空壳;old-search 服务端渲染仍活。
801
+ 上游 bot 门是文档化行为(等待页提示「wait 2 seconds」并给 sst 通行链接):
802
+ 两步流程 = 先取等待页提取 sst,睡 2.2s 后复访该链接(实测 88 外链/页;
803
+ 令牌必须新鲜,复用过期令牌会被再次门住)。非大厂代理的独立索引,
804
+ 专挖长尾非商业页面。
1459
805
  """
1460
- timeout = spec.get("timeout", 12)
1461
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
806
+ timeout = spec.get("timeout", 16)
1462
807
 
1463
808
  @safe_search
1464
809
  def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1465
- q_raw = query.strip()
1466
- if not q_raw:
1467
- return []
1468
- q = _ascii_tokens(q_raw)
1469
- if not q:
1470
- q = _UNIPROT_CN.get(q_raw, "")
1471
- if not q:
1472
- return []
810
+ import urllib.parse as up
1473
811
  to = _timeout or timeout
1474
- url = f"{_UNIPROT_API}?" + urllib.parse.urlencode({
1475
- "query": q, "format": "json", "size": min(n, 25),
1476
- })
812
+ base = "https://old-search.marginalia.nu"
813
+ url = f"{base}/search?query={up.quote(query)}"
1477
814
  try:
1478
- with http_open(urllib.request.Request(url, headers=_HEADERS), timeout=to, engine=spec.get("_name", "")) as resp:
1479
- data = json.loads(resp.read().decode("utf-8", "replace"))
815
+ with http_open(urllib.request.Request(
816
+ url, headers={"User-Agent": "argo-search/2.4 (unified-search@local)"}), timeout=to, engine=spec.get("_name", "")) as resp:
817
+ page = resp.read().decode("utf-8", "replace")
1480
818
  except Exception as e:
1481
- logger.warning(f"UniProt 失败: {e}")
819
+ logger.warning(f"Marginalia 失败: {e}")
1482
820
  return []
821
+ gate = re.search(r'href="(/search\?query=[^"]*sst=[^"]+)"', page)
822
+ if gate:
823
+ time.sleep(2.2)
824
+ try:
825
+ with http_open(urllib.request.Request(
826
+ base + gate.group(1).replace("&amp;", "&"),
827
+ headers={"User-Agent": "argo-search/2.4 (unified-search@local)"}), timeout=to, engine=spec.get("_name", "")) as resp:
828
+ page = resp.read().decode("utf-8", "replace")
829
+ except Exception as e:
830
+ logger.warning(f"Marginalia sst 复访失败: {e}")
831
+ return []
1483
832
  results = []
1484
- for _rk10, x in enumerate((data.get("results") or [])[:n]):
1485
- acc = x.get("primaryAccession", "")
1486
- pd = x.get("proteinDescription") or {}
1487
- rn = ((pd.get("recommendedName") or {}).get("fullName") or {}).get("value", "")
1488
- genes = x.get("genes") or []
1489
- gene = ""
1490
- if genes and isinstance(genes[0], dict):
1491
- gene = ((genes[0].get("geneName") or {}).get("value", ""))
1492
- org = ((x.get("organism") or {}).get("scientificName") or "")
1493
- title = rn or (f"{acc}" if acc else q)
1494
- snip = " · ".join(p for p in (org, gene) if p)
833
+ for _rk20, block in enumerate(re.split(r'<section[^>]*class="card search-result"', page)[1:]):
834
+ m = re.search(r'<h2>\s*<a[^>]*href="(https?://[^"]+)"[^>]*>(.*?)</a>', block, re.S)
835
+ if not m:
836
+ continue
837
+ title = _unescape(re.sub(r"<[^>]+>", "", m.group(2))).strip()
838
+ if not title:
839
+ continue
840
+ md = re.search(r'<p class="description">(.*?)</p>', block, re.S)
841
+ desc = _unescape(re.sub(r"<[^>]+>", "", md.group(1))).strip() if md else ""
1495
842
  results.append({
1496
- "title": f"{title} ({acc})" if acc else title,
1497
- "url": f"https://www.uniprot.org/uniprotkb/{acc}" if acc else "",
1498
- "snippet": snip[:300],
1499
- "source": "uniprot",
1500
- "score": rank_score(0.9, _rk10),
843
+ "title": title[:200],
844
+ "url": m.group(1),
845
+ "snippet": desc[:300],
846
+ "source": "marginalia",
847
+ "score": rank_score(0.7, _rk20),
1501
848
  })
849
+ if len(results) >= n:
850
+ return results
851
+ # 补足:同域折叠的 additional-results 只有标题链接(无 description)
852
+ for mu in re.finditer(r'<ul class="additional-results">(.*?)</ul>', page, re.S):
853
+ for ma in re.finditer(r'<li><a href="(https?://[^"]+)"[^>]*>(.*?)</a></li>', mu.group(1), re.S):
854
+ title = _unescape(re.sub(r"<[^>]+>", "", ma.group(2))).strip()
855
+ if not title:
856
+ continue
857
+ results.append({
858
+ "title": title[:200],
859
+ "url": ma.group(1),
860
+ "snippet": "",
861
+ "source": "marginalia",
862
+ "score": rank_score(0.55, len(results)),
863
+ })
864
+ if len(results) >= n:
865
+ break
866
+ if len(results) >= n:
867
+ break
1502
868
  return results
1503
869
  return _engine
1504
870
 
1505
871
 
1506
- # ── RCSB PDB 蛋白质结构引擎 ──────────────────────────────────────────────────
1507
-
1508
- _PDB_SEARCH_API = "https://search.rcsb.org/rcsbsearch/v2/query"
1509
-
872
+ # ── Wiby 手工网页索引引擎 ────────────────────────────────────────────────────
1510
873
 
1511
- def _build_rcsb_pdb_engine(spec: dict[str, Any]) -> Any:
1512
- """RCSB PDB 蛋白质结构检索(search.rcsb.org v2,免认证)。
874
+ def _build_wiby_engine(spec: dict[str, Any]) -> Any:
875
+ """Wiby 老式手工网页索引搜索(wiby.me/json,免认证,注意大写键)。
1513
876
 
1514
- 全文搜索返回 PDB ID 列表,链接到 rcsb.org/structure/{id}。
877
+ 专收非商业化内容的老式索引,与主流引擎互补。
1515
878
  """
1516
- timeout = spec.get("timeout", 15)
1517
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)",
1518
- "Accept": "application/json", "Content-Type": "application/json"}
879
+ timeout = spec.get("timeout", 10)
1519
880
 
1520
881
  @safe_search
1521
882
  def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1522
- q = _ascii_tokens(query)
1523
- if not q:
1524
- return []
1525
- to = _timeout or timeout
1526
- body = json.dumps({
1527
- "query": {"type": "terminal", "service": "full_text", "parameters": {"value": q}},
1528
- "return_type": "entry",
1529
- "request_options": {"return_all_hits": True},
1530
- }).encode("utf-8")
1531
- try:
1532
- req = urllib.request.Request(_PDB_SEARCH_API, data=body, headers=_HEADERS, method="POST")
1533
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
1534
- data = json.loads(resp.read().decode("utf-8", "replace"))
1535
- except Exception as e:
1536
- logger.warning(f"RCSB PDB 失败: {e}")
1537
- return []
1538
- results = []
1539
- for _rk11, x in enumerate((data.get("result_set") or [])[:n]):
1540
- pid = x.get("identifier", "")
1541
- if not pid:
1542
- continue
1543
- results.append({
1544
- "title": f"PDB 结构 {pid}({q})",
1545
- "url": f"https://www.rcsb.org/structure/{pid}",
1546
- "snippet": f"RCSB PDB 实验结构 {pid},分辨率 {x.get('score', '')}"[:300],
1547
- "source": "rcsb_pdb",
1548
- "score": rank_score(0.85, _rk11),
1549
- })
1550
- return results
1551
- return _engine
1552
-
1553
-
1554
- # ── CourtListener 美国判例引擎 ───────────────────────────────────────────────
1555
-
1556
- _COURTLISTENER_API = "https://www.courtlistener.com/api/rest/v4/search/"
1557
-
1558
-
1559
- def _build_courtlistener_engine(spec: dict[str, Any]) -> Any:
1560
- """CourtListener 美国判例检索(courtlistener.com/api/rest/v4,匿名可用)。
1561
-
1562
- 注意 2026-05 起限额骤降(免费档约 5 次/分、125 次/天),qps 已压到 1。
1563
- """
1564
- timeout = spec.get("timeout", 12)
1565
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
1566
-
1567
- @safe_search
1568
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1569
- q = query.strip()
1570
- if not q:
1571
- return []
1572
- to = _timeout or timeout
1573
- url = _COURTLISTENER_API + "?" + urllib.parse.urlencode({
1574
- "q": q, "format": "json", "page_size": min(n, 10), "order_by": "score desc",
1575
- })
1576
- try:
1577
- with http_open(urllib.request.Request(url, headers=_HEADERS), timeout=to, engine=spec.get("_name", "")) as resp:
1578
- data = json.loads(resp.read().decode("utf-8", "replace"))
1579
- except Exception as e:
1580
- logger.warning(f"CourtListener 失败: {e}")
1581
- return []
1582
- results = []
1583
- for _rk12, x in enumerate((data.get("results") or [])[:n]):
1584
- name = x.get("caseName") or q
1585
- rel = x.get("absolute_url") or ""
1586
- date = (x.get("dateFiled") or "")[:10]
1587
- snip = str(x.get("snippet") or "")[:280]
1588
- body_txt = str(x.get("plain_text") or "")[:280]
1589
- snip = snip or body_txt
1590
- parts = [p for p in (date, snip) if p]
1591
- results.append({
1592
- "title": name,
1593
- "url": f"https://www.courtlistener.com{rel}" if rel else "",
1594
- "snippet": " · ".join(parts)[:300],
1595
- "source": "courtlistener",
1596
- "score": rank_score(0.9, _rk12),
1597
- })
1598
- return results
1599
- return _engine
1600
-
1601
-
1602
- # ── Project Gutenberg 公版书引擎(Gutendex) ─────────────────────────────────
1603
-
1604
- _GUTENDEX_API = "https://gutendex.com/books"
1605
-
1606
-
1607
- def _build_gutenberg_engine(spec: dict[str, Any]) -> Any:
1608
- """Project Gutenberg 公版书检索(gutendex.com,免认证)。
1609
-
1610
- 返回书名/作者/语言与 Gutenberg 书目页链接;Gutenberg 提供结构化全文。
1611
- """
1612
- timeout = spec.get("timeout", 15)
1613
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
1614
-
1615
- @safe_search
1616
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1617
- q = query.strip()
1618
- if not q:
1619
- return []
1620
- to = _timeout or timeout
1621
- url = _GUTENDEX_API + "?" + urllib.parse.urlencode({"search": q, "page_size": min(n, 10)})
1622
- try:
1623
- with http_open(urllib.request.Request(url, headers=_HEADERS), timeout=to, engine=spec.get("_name", "")) as resp:
1624
- data = json.loads(resp.read().decode("utf-8", "replace"))
1625
- except Exception as e:
1626
- logger.warning(f"Gutendex 失败: {e}")
1627
- return []
1628
- results = []
1629
- for _rk13, x in enumerate((data.get("results") or [])[:n]):
1630
- title = x.get("title") or q
1631
- gid = x.get("id") or ""
1632
- authors = ", ".join((a.get("name") or "") for a in (x.get("authors") or [])[:2])
1633
- langs = ",".join(x.get("languages") or [])
1634
- fmt = x.get("formats") or {}
1635
- txt = fmt.get("text/plain; charset=us-ascii") or fmt.get("text/html")
1636
- snip = " · ".join(p for p in (authors, langs, "公版书全文") if p)
1637
- _row = {
1638
- "title": title,
1639
- "url": f"https://www.gutenberg.org/ebooks/{gid}" if gid else txt or "",
1640
- "snippet": snip[:300],
1641
- "source": "gutenberg",
1642
- "score": rank_score(0.85, _rk13),
1643
- }
1644
- # 源内全文直出:`/ebooks/{id}` 是下载门户页(实测首段全是 noprint
1645
- # 脚本),不是正文;gutendex 本来就把纯文本 URL 放在 formats 里,
1646
- # 此前只在缺 id 时当保底,正常路径直接丢掉。这里单独带上,供下游
1647
- # 取正文时优先使用(省掉从门户页找下载链这一步)。
1648
- if txt:
1649
- _row["full_text_url"] = txt
1650
- results.append(_row)
1651
- return results
1652
- return _engine
1653
-
1654
-
1655
- # ── Wayback CDX 已删除内容检索引擎 ───────────────────────────────────────────
1656
-
1657
- _CDX_API = "https://web.archive.org/cdx/search/cdx"
1658
-
1659
-
1660
- def _build_wayback_cdx_engine(spec: dict[str, Any]) -> Any:
1661
- """Wayback Machine CDX 快照检索(web.archive.org/cdx,免认证)。
1662
-
1663
- 输入域名/URL,返回历史快照时间戳与状态码,是查已删除页面的唯一路径。
1664
- """
1665
- timeout = spec.get("timeout", 20)
1666
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
1667
-
1668
- @safe_search
1669
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1670
- q = query.strip().lower()
1671
- if not q:
1672
- return []
1673
- # 剥离常见协议前缀,CDX 用裸域名/host 查询
1674
- q = re.sub(r"^https?://", "", q).strip()
1675
- if not q:
1676
- return []
1677
- to = _timeout or timeout
1678
- url = _CDX_API + "?" + urllib.parse.urlencode({
1679
- "url": q, "output": "json", "limit": min(n, 10),
1680
- "fl": "timestamp,original,statuscode",
1681
- })
1682
- try:
1683
- with http_open(urllib.request.Request(url, headers=_HEADERS), timeout=to, engine=spec.get("_name", "")) as resp:
1684
- data = json.loads(resp.read().decode("utf-8", "replace"))
1685
- except Exception as e:
1686
- logger.warning(f"Wayback CDX 失败: {e}")
1687
- return []
1688
- rows = data if isinstance(data, list) else []
1689
- # 带 fl 时首行是列名
1690
- if rows and rows[0] and rows[0][0] == "timestamp":
1691
- rows = rows[1:]
1692
- results = []
1693
- for _rk14, r in enumerate(rows[:n]):
1694
- if len(r) < 3:
1695
- continue
1696
- ts, orig, status = r[0], r[1], r[2]
1697
- # CDX 时间戳 YYYYMMDDHHMMSS → 标准 published_at(最早快照语义)
1698
- published_at = ""
1699
- try:
1700
- published_at = datetime.strptime(ts, "%Y%m%d%H%M%S").isoformat(timespec="seconds")
1701
- except ValueError:
1702
- pass
1703
- item = {
1704
- "title": f"快照 {orig}({ts[:8]})",
1705
- "url": f"https://web.archive.org/web/{ts}/{orig}",
1706
- "snippet": f"Wayback 快照 {ts} · HTTP {status}"[:300],
1707
- "source": "wayback_cdx",
1708
- "score": rank_score(0.8, _rk14),
1709
- }
1710
- if published_at:
1711
- item["published_at"] = published_at
1712
- results.append(item)
1713
- return results
1714
- return _engine
1715
-
1716
-
1717
- # ── USGS 地震引擎 ────────────────────────────────────────────────────────────
1718
-
1719
- _USGS_EQ_API = "https://earthquake.usgs.gov/fdsnws/event/1/query"
1720
-
1721
- # 中文地点词 → (place 匹配正则, bbox 地理框或 None)
1722
- # USGS place 是英文;美国国内震 place 用「城市, 州缩写」格式("6 km NW of Pinnacles, CA")。
1723
- # bbox 可让「台湾地震」这类查询不依赖全球 top-50,直接框选该地区全部地震。
1724
- _USGS_PLACE_CN = {
1725
- "日本": ("japan", dict(minlatitude=24, maxlatitude=47, minlongitude=122, maxlongitude=147)),
1726
- "台湾": ("taiwan", dict(minlatitude=20, maxlatitude=26, minlongitude=119, maxlongitude=124)),
1727
- "加州": (r"california|, ca\b", dict(minlatitude=32, maxlatitude=42, minlongitude=-125, maxlongitude=-114)),
1728
- "中国": ("china", None), "香港": ("hong kong", None),
1729
- "美国": (r", (ca|nv|ak|or|wa|hi|az|ut|mt|id|nm|tx|ok|ar|mo|ky|tn|sc|nc|ga)\b", None),
1730
- "阿拉斯加": ("alaska", dict(minlatitude=48, maxlatitude=72, minlongitude=-170, maxlongitude=-130)),
1731
- "夏威夷": ("hawaii", None),
1732
- "印尼": ("indonesia", None), "菲律宾": ("philippines", None), "新西兰": ("new zealand", None),
1733
- "智利": ("chile", None), "秘鲁": ("peru", None), "墨西哥": ("mexico", None), "土耳其": ("turkey", None),
1734
- "伊朗": ("iran", None), "印度": ("india", None), "尼泊尔": ("nepal", None), "意大利": ("italy", None),
1735
- "希腊": ("greece", None), "冰岛": ("iceland", None), "阿富汗": ("afghanistan", None), "缅甸": ("myanmar", None),
1736
- "巴布亚": ("papua", None), "所罗门": ("solomon", None), "汤加": ("tonga", None), "瓦努阿图": ("vanuatu", None),
1737
- "斐济": ("fiji", None), "关岛": ("guam", None), "千岛群岛": ("kuril", None),
1738
- }
1739
-
1740
-
1741
- def _build_usgs_engine(spec: dict[str, Any]) -> Any:
1742
- """USGS 地震检索(earthquake.usgs.gov FDSNWS,免认证)。
1743
-
1744
- 返回最近 30 天 M2.5+ 地震;查询含地点词(如「日本」「加州」)时客户端侧
1745
- 按 place 字段过滤,命中地点相关地震。
1746
- """
1747
- timeout = spec.get("timeout", 12)
1748
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
1749
-
1750
- @safe_search
1751
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1752
- q = query.strip()
1753
- if not q:
1754
- return []
1755
- to = _timeout or timeout
1756
- # 提取地点词:去掉「地震/earthquake/震级」等噪声
1757
- place_kw = re.sub(r"(?i)(地震|earthquake|seismic|震级|magnitude|quakes?|最近|最新)", " ", q)
1758
- place_kw = re.sub(r"\s+", " ", place_kw).strip()
1759
- params = {
1760
- "format": "geojson", "limit": 50,
1761
- "starttime": time.strftime("%Y-%m-%d", time.gmtime(time.time() - 30 * 86400)),
1762
- "minmagnitude": "2.5",
1763
- }
1764
- if place_kw:
1765
- kw = place_kw.lower()
1766
- bbox = None
1767
- # 中文地点词查映射表(正则 + 可选 bbox);英文词直接按原文匹配 place
1768
- if not re.search(r"[a-z]", kw):
1769
- entry = _USGS_PLACE_CN.get(place_kw)
1770
- if entry:
1771
- kw, bbox = entry
1772
- if bbox:
1773
- params.update(bbox)
1774
- # bbox 精确框选时无需放大样本,直接按时间取
1775
- params["limit"] = min(n * 3, 30)
1776
- else:
1777
- # 无 bbox 时按震级降序取样本,避免目标地点被全球密集地震挤出 top
1778
- params["orderby"] = "magnitude"
1779
- url = _USGS_EQ_API + "?" + urllib.parse.urlencode(params)
1780
- try:
1781
- with http_open(urllib.request.Request(url, headers=_HEADERS), timeout=to, engine=spec.get("_name", "")) as resp:
1782
- data = json.loads(resp.read().decode("utf-8", "replace"))
1783
- except Exception as e:
1784
- logger.warning(f"USGS 失败: {e}")
1785
- return []
1786
- feats = data.get("features") or []
1787
- if place_kw:
1788
- if kw:
1789
- feats = [f for f in feats if re.search(kw, str(f.get("properties", {}).get("place", "")).lower())]
1790
- results = []
1791
- for _rk15, f in enumerate(feats[:n]):
1792
- p = f.get("properties", {})
1793
- mag = p.get("mag")
1794
- place = p.get("place", "")
1795
- ts = (p.get("time") or 0) // 1000
1796
- url_ = p.get("url", "")
1797
- results.append({
1798
- "title": f"M{mag} {place}",
1799
- "url": url_ or "",
1800
- "snippet": f"USGS 地震 · {ts and time.strftime('%Y-%m-%d %H:%M UTC', time.gmtime(ts))}"[:300],
1801
- "source": "usgs",
1802
- "score": rank_score(0.85, _rk15),
1803
- })
1804
- return results
1805
- return _engine
1806
-
1807
-
1808
- # ── NASA CMR 地球科学数据目录引擎 ────────────────────────────────────────────
1809
-
1810
- _CMR_API = "https://cmr.earthdata.nasa.gov/search/collections.json"
1811
-
1812
-
1813
- def _build_nasa_cmr_engine(spec: dict[str, Any]) -> Any:
1814
- """NASA CMR 地球科学数据目录检索(cmr.earthdata.nasa.gov,免认证)。
1815
-
1816
- MODIS/卫星/遥感等关键词 → 数据集集合(含概念 ID,链接 Earthdata Search)。
1817
- """
1818
- timeout = spec.get("timeout", 12)
1819
- _HEADERS = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
1820
-
1821
- @safe_search
1822
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1823
- q = _ascii_tokens(query)
1824
- if not q:
1825
- return []
1826
- to = _timeout or timeout
1827
- url = _CMR_API + "?" + urllib.parse.urlencode({"keyword": q, "page_size": min(n, 10)})
1828
- try:
1829
- with http_open(urllib.request.Request(url, headers=_HEADERS), timeout=to, engine=spec.get("_name", "")) as resp:
1830
- data = json.loads(resp.read().decode("utf-8", "replace"))
1831
- except Exception as e:
1832
- logger.warning(f"NASA CMR 失败: {e}")
1833
- return []
1834
- results = []
1835
- for _rk16, x in enumerate(((data.get("feed") or {}).get("entry") or [])[:n]):
1836
- title = x.get("title") or q
1837
- cid = x.get("id") or ""
1838
- summary = (x.get("summary") or "")[:200]
1839
- results.append({
1840
- "title": title,
1841
- "url": f"https://search.earthdata.nasa.gov/search/granules?p={cid}" if cid else "",
1842
- "snippet": summary[:300],
1843
- "source": "nasa_cmr",
1844
- "score": rank_score(0.8, _rk16),
1845
- })
1846
- return results
1847
- return _engine
1848
-
1849
-
1850
- # ── IMDb 影视 suggestion API(免认证) ────────────────────────────────────────
1851
-
1852
- _IMDB_SUGGEST = "https://v2.sg.media-imdb.com/suggestion/{first}/{q}.json"
1853
- _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"
1854
-
1855
-
1856
- # 影视问句噪声词:整句进 suggestion 常 0 命中(如 "Interstellar film cast")
1857
- _IMDB_STOP = re.compile(
1858
- r"(?i)\b(movie|film|tv\s*show|tv\s*series|cinema|cast|starring|director|directed\s+by|"
1859
- r"screenwriter|written\s+by|actor|actress|producer|box\s*office|trailer|review|"
1860
- r"imdb|豆瓣|电影|电视剧|剧集|影视|影片|导演|主演|演员|编剧|制片|上映|首映|票房|"
1861
- r"影评|奥斯卡|金像奖|金马奖|网剧|美剧|韩剧|日剧|英剧)\b"
1862
- )
1863
-
1864
-
1865
- def _imdb_clean_query(query: str) -> str:
1866
- """去掉影视角色/事实词,保留片名/人名主体。"""
1867
- q = (query or "").strip()
1868
- if not q:
1869
- return ""
1870
- cleaned = _IMDB_STOP.sub(" ", q)
1871
- cleaned = re.sub(r"[??!!,,.。::;;]+", " ", cleaned)
1872
- cleaned = re.sub(r"\s+", " ", cleaned).strip()
1873
- # 清洗后过短则回退原 query(避免只剩空)
1874
- if len(cleaned) < 2:
1875
- return q
1876
- return cleaned
1877
-
1878
-
1879
- def _build_imdb_engine(spec: dict[str, Any]) -> Any:
1880
- """IMDb 自动补全 suggestion API(v2.sg.media-imdb.com,免认证)。
1881
-
1882
- 路径:/suggestion/{首字符}/{query}.json
1883
- 返回电影/剧集/人物,带 tt/nm ID,可拼正式 IMDb URL。
1884
- """
1885
- timeout = spec.get("timeout", 8)
1886
- source_name = spec.get("_name", "imdb")
1887
-
1888
- def _fetch_suggest(q: str, to: float) -> list[dict[str, Any]]:
1889
- if not q:
1890
- return []
1891
- first = q[0].lower()
1892
- if not (("a" <= first <= "z") or ("0" <= first <= "9")):
1893
- first = "_"
1894
- path_q = urllib.parse.quote(q[:80], safe="")
1895
- url = _IMDB_SUGGEST.format(first=first, q=path_q)
1896
- try:
1897
- req = urllib.request.Request(url, headers={"User-Agent": _IMDB_UA, "Accept": "application/json"})
1898
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
1899
- data = json.loads(resp.read().decode("utf-8", "replace"))
1900
- except Exception as e:
1901
- logger.warning(f"IMDb 失败: {e}")
1902
- return []
1903
- return [x for x in (data.get("d") or []) if isinstance(x, dict)]
1904
-
1905
- @safe_search
1906
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
1907
- raw = (query or "").strip()
1908
- if not raw:
1909
- return []
1910
- to = _timeout or timeout
1911
- cleaned = _imdb_clean_query(raw)
1912
- # 先试清洗词,空则回退原句
1913
- items = _fetch_suggest(cleaned, to)
1914
- if not items and cleaned != raw:
1915
- items = _fetch_suggest(raw, to)
1916
-
1917
- # 按标题与查询 token 重叠 + feature 优先排序
1918
- q_tokens = {t.lower() for t in re.findall(r"[A-Za-z0-9\u4e00-\u9fff]{2,}", cleaned or raw)}
1919
- ranked: list[tuple[float, dict[str, Any]]] = []
1920
- for item in items:
1921
- title = item.get("l") or ""
1922
- iid = item.get("id") or ""
1923
- if not title and not iid:
1924
- continue
1925
- t_low = title.lower()
1926
- t_tokens = {t.lower() for t in re.findall(r"[A-Za-z0-9\u4e00-\u9fff]{2,}", title)}
1927
- overlap = len(q_tokens & t_tokens) / max(len(q_tokens), 1)
1928
- # 精确/前缀加分;tt 影片优先于 nm 人名(片名查询时)
1929
- exact = 1.0 if t_low == (cleaned or raw).lower() else 0.0
1930
- prefix = 0.3 if t_low.startswith((cleaned or raw).lower()[: min(12, len(cleaned or raw))]) else 0.0
1931
- kind_bonus = 0.15 if str(iid).startswith("tt") else (0.05 if str(iid).startswith("nm") else 0.0)
1932
- year = item.get("y") or 0
1933
- try:
1934
- year_n = int(year) if year else 0
1935
- except (TypeError, ValueError):
1936
- year_n = 0
1937
- # 近年作品轻微加分(同名旧片靠后)
1938
- recency = min(max(year_n - 1980, 0), 50) / 500.0
1939
- score = 0.5 + overlap + exact + prefix + kind_bonus + recency
1940
- ranked.append((score, item))
1941
- ranked.sort(key=lambda x: -x[0])
1942
-
1943
- results = []
1944
- for score, item in ranked[: max(n, 1)]:
1945
- title = item.get("l") or ""
1946
- iid = item.get("id") or ""
1947
- year = item.get("y")
1948
- kind = item.get("q") or item.get("qid") or ""
1949
- cast = item.get("s") or ""
1950
- parts = [p for p in (str(year) if year else "", kind, cast) if p]
1951
- if str(iid).startswith("tt"):
1952
- href = f"https://www.imdb.com/title/{iid}/"
1953
- elif str(iid).startswith("nm"):
1954
- href = f"https://www.imdb.com/name/{iid}/"
1955
- else:
1956
- href = f"https://www.imdb.com/find/?q={urllib.parse.quote(title)}"
1957
- results.append({
1958
- "title": title,
1959
- "url": href,
1960
- "snippet": " · ".join(parts)[:300],
1961
- "source": source_name,
1962
- "score": min(0.95, 0.7 + score * 0.15),
1963
- })
1964
- if len(results) >= n:
1965
- break
1966
- return results
1967
- return _engine
1968
-
1969
-
1970
- # ── iTunes 媒体库(中文需 country=cn;专辑问 entity=album;播客问 entity=podcast)──
1971
-
1972
- # 媒体意图词。引擎可被 --engine 直接调用,那时拿不到路由域的上下文,
1973
- # 意图只能从查询词本身读——命中播客词即把 media 从 music 切到 podcast。
1974
- _PODCAST_HINT_RE = re.compile(r"(?i)(播客|podcast|电台|单集|一期|这期|那期|episode)")
1975
- # 单集意图:用户要的是某期节目(带时长),而非节目本体
1976
- _PODCAST_EPISODE_RE = re.compile(r"(?i)(单集|一期|这期|那期|episode|第\s*\d+\s*集|#\s*\d+)")
1977
- _ALBUM_HINT_RE = re.compile(r"(?i)(专辑|album|discography|唱片)")
1978
- # 意图词只用于定实体,须从检索词里剥掉,否则「播客」这类词会污染 term
1979
- _MEDIA_INTENT_WORD_RE = re.compile(
1980
- r"(?i)(专辑|新专辑|唱片|音乐|歌曲|单曲|播客|电台|单集|一期|这期|那期|"
1981
- r"album|discography|music|song|songs|single|podcast|podcasts|episode)"
1982
- )
1983
- # 节目级时长必须二跳取样(见下方 docstring),逐条补会让请求数随结果数膨胀。
1984
- # 只补首条:播客名查询通常只有一个正解(实测「张小珺 商业访谈录」Apple 只回 1 条)。
1985
- _ITUNES_SHOW_ENRICH_MAX = 1
1986
- # 文字稿/feed 拉取的字节上限:预览只需几百字,2MB 足够防超大文件吃内存
1987
- _TRANSCRIPT_MAX_BYTES = 2 * 1024 * 1024
1988
-
1989
-
1990
- def _itunes_date(raw: Any) -> str:
1991
- """Apple 的 releaseDate 形如 2026-09-03T00:00:00Z,裁到日期部分供展示。"""
1992
- s = str(raw or "").strip()
1993
- return s[:10] if len(s) >= 10 else ""
1994
-
1995
-
1996
- def _transcript_to_text(raw: str, ctype: str) -> str:
1997
- """文字稿原文 → 纯文本。VTT/SRT 去时间轴与样式行,HTML 去 tag。
1998
-
1999
- Podcasting 2.0 文字稿的 type 值不统一(text/vtt、application/srt、
2000
- 裸 text/plain 都见过),按字符串包含判断而非全等。
2001
- """
2002
- if "html" in ctype:
2003
- text = re.sub(r"<[^>]+>", " ", raw)
2004
- text = _unescape(text)
2005
- elif "vtt" in ctype or "srt" in ctype or "plain" in ctype:
2006
- lines: list[str] = []
2007
- for ln in raw.splitlines():
2008
- s = ln.strip()
2009
- if (not s or s == "WEBVTT"
2010
- or s.startswith(("NOTE", "STYLE", "REGION"))
2011
- or "-->" in s or s.isdigit()):
2012
- continue
2013
- s = re.sub(r"<[^>]+>", "", s) # <c> 高亮、<v 说话人> 内联标签
2014
- if s:
2015
- lines.append(s)
2016
- text = " ".join(lines)
2017
- else:
2018
- text = raw
2019
- return re.sub(r"\s+", " ", text).strip()
2020
-
2021
-
2022
- def _build_itunes_engine(spec: dict[str, Any]) -> Any:
2023
- """iTunes Search API:按语言与意图调 country / media / entity。
2024
-
2025
- 三种媒体形态(播客为 2026-09-15 补入):
2026
- - 播客节目 media=podcast&entity=podcast → 集数(trackCount)、更新日期、类型
2027
- - 播客单集 media=podcast&entity=podcastEpisode → 时长(trackTimeMillis)、发布日期
2028
- - 音乐 media=music(专辑问 entity=album)
2029
-
2030
- 播客时长只能取自单集:**节目对象上的 trackTimeMillis 不是时长**。实测 12 档
2031
- 节目只有 6 档等于最新单集的秒数,另 6 档明显偏小(忽左忽右 3491 而最新单集
2032
- 5739),单位与含义上游都未文档化——取信它会静默给出错值。所以节目级的
2033
- 「每期多长」走二跳单集取样,见 _recent_episode_duration。
2034
- """
2035
- timeout = spec.get("timeout", 8)
2036
- source_name = spec.get("_name", "itunes")
2037
- engine_tag = spec.get("_name", "")
2038
- base = spec.get("url") or "https://itunes.apple.com/search"
2039
- lookup_base = (base.replace("/search", "/lookup") if "/search" in base
2040
- else "https://itunes.apple.com/lookup")
2041
- ua_headers = {"User-Agent": "argo-search/2.6 (itunes)", "Accept": "application/json"}
2042
-
2043
- def _get_json(url: str, to: float) -> dict[str, Any]:
2044
- req = urllib.request.Request(url, headers=ua_headers)
2045
- with http_open(req, timeout=to, engine=engine_tag) as resp:
2046
- return json.loads(resp.read().decode("utf-8", "replace"))
2047
-
2048
- def _recent_episode_duration(collection_id: Any, country: str, to: float) -> tuple[int | None, int]:
2049
- """节目近 5 期单集时长的中位数 → (中位分钟, 样本数)。
2050
-
2051
- 取中位数而非最新一期:访谈类单集长度波动大,一期 4 小时长访谈代表不了
2052
- 整个节目。任何失败一律退回 (None, 0),节目本体照常返回——时长是补充
2053
- 信息,不该让整条结果缺失。
2054
- """
2055
- import statistics
2056
- if not collection_id:
2057
- return None, 0
2058
- params = {"id": str(collection_id), "entity": "podcastEpisode", "limit": "5"}
2059
- if country:
2060
- params["country"] = country
2061
- try:
2062
- data = _get_json(f"{lookup_base}?{urllib.parse.urlencode(params)}", to)
2063
- except Exception as e:
2064
- logger.debug(f"iTunes 单集取样失败: {e}")
2065
- return None, 0
2066
- mins = []
2067
- for it in data.get("results") or []:
2068
- if not isinstance(it, dict):
2069
- continue
2070
- if str(it.get("wrapperType") or "").lower() != "podcastepisode":
2071
- continue
2072
- ms = it.get("trackTimeMillis")
2073
- if isinstance(ms, (int, float)) and ms > 0:
2074
- mins.append(ms / 60000.0)
2075
- if not mins:
2076
- return None, 0
2077
- return int(round(statistics.median(mins))), len(mins)
2078
-
2079
- def _show_transcript(feed_url: str, to: float) -> tuple[str, str]:
2080
- """节目官方文字稿(Podcasting 2.0):feed 里 <podcast:transcript> 标签
2081
- 指向创作者自己挂的全文,不是 ASR 猜的——这是播客转录里唯一免费且
2082
- 准确的通道(英文生态采纳率高,中文节目普遍没挂)。
2083
-
2084
- 取 feed 中第一份可解析格式的文字稿(最新一期):搜索对象是「节目」,
2085
- 最新一期代表当前内容;历史各期的文字稿同挂在 feed,下游拿着
2086
- transcript_url 可回读全文。任何失败一律 ("", ""),节目本体照常返回。
2087
- application/json(Podcasting 2.0 的机器格式)本版不解析,静默跳过。
2088
- """
2089
- if not feed_url:
2090
- return "", ""
2091
- feed_url = str(feed_url).strip()
2092
- if not feed_url.lower().startswith(("https://", "http://")):
2093
- return "", ""
2094
- try:
2095
- req = urllib.request.Request(feed_url, headers=ua_headers)
2096
- with http_open(req, timeout=to, engine=engine_tag) as resp:
2097
- feed_xml = resp.read(_TRANSCRIPT_MAX_BYTES).decode("utf-8", "replace")
2098
- except Exception as e:
2099
- logger.debug(f"iTunes 文字稿 feed 拉取失败: {e}")
2100
- return "", ""
2101
- ok_types = ("text/vtt", "text/srt", "text/plain", "text/html")
2102
- ok_exts = ("vtt", "srt", "txt", "html", "htm")
2103
- for m in re.finditer(r"<podcast:transcript\b[^>]*>", feed_xml):
2104
- tag = m.group(0)
2105
- # 属性可能是单引号或双引号;type 可能带 ;charset= 参数
2106
- url_m = re.search(r"""\burl=("([^"]+)"|'([^']+)')""", tag)
2107
- if not url_m:
2108
- continue
2109
- raw_url = url_m.group(2) or url_m.group(3)
2110
- type_m = re.search(r"""\btype=("([^"]+)"|'([^']+)')""", tag)
2111
- ctype = (type_m.group(2) or type_m.group(3) if type_m else "").lower()
2112
- ctype = ctype.split(";", 1)[0].strip()
2113
- try:
2114
- parsed = urllib.parse.urlsplit(raw_url)
2115
- if parsed.scheme == "":
2116
- parsed = urllib.parse.urlsplit(urllib.parse.urljoin(feed_url, raw_url))
2117
- # 文字稿 URL 来自第三方 feed 内容:仅接受 https,防 file://
2118
- # 读本地文件、防内网地址(SSRF);urlsplit 对畸形输入抛
2119
- # ValueError,一并拦下
2120
- if parsed.scheme != "https" or not parsed.hostname:
2121
- continue
2122
- t_url = urllib.parse.urlunsplit(parsed)
2123
- except ValueError:
2124
- continue
2125
- if not ctype:
2126
- ext = parsed.path.rsplit(".", 1)[-1].lower() if "." in parsed.path.rsplit("?", 1)[0] else ""
2127
- if ext in ok_exts:
2128
- ctype = "text/plain" if ext in ("txt", "srt") else f"text/{ext}"
2129
- if ctype not in ok_types:
2130
- continue
2131
- try:
2132
- req = urllib.request.Request(t_url, headers=ua_headers)
2133
- with http_open(req, timeout=to, engine=engine_tag) as resp:
2134
- raw = resp.read(_TRANSCRIPT_MAX_BYTES).decode("utf-8", "replace")
2135
- except Exception as e:
2136
- logger.debug(f"iTunes 文字稿下载失败: {e}")
2137
- continue # 这份坏了不放弃整条节目,试下一份候选
2138
- text = _transcript_to_text(raw, ctype)
2139
- if text:
2140
- return t_url, text
2141
- return "", ""
2142
-
2143
- @safe_search
2144
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
2145
- q = (query or "").strip()
2146
- if not q:
2147
- return []
2148
- to = _timeout or timeout
2149
- want_podcast = bool(_PODCAST_HINT_RE.search(q))
2150
- want_episode = want_podcast and bool(_PODCAST_EPISODE_RE.search(q))
2151
- want_album = bool(_ALBUM_HINT_RE.search(q)) and not want_podcast
2152
- # 去掉意图词,保留实体名
2153
- term = _MEDIA_INTENT_WORD_RE.sub(" ", q)
2154
- term = re.sub(r"\s+", " ", term).strip() or q
2155
- has_zh = bool(re.search(r"[\u4e00-\u9fff]", term))
2156
- country = "cn" if has_zh else ""
2157
- params: dict[str, str] = {
2158
- "term": term,
2159
- "limit": str(min(max(n, 1), 25)),
2160
- }
2161
- if want_podcast:
2162
- params["media"] = "podcast"
2163
- params["entity"] = "podcastEpisode" if want_episode else "podcast"
2164
- else:
2165
- params["media"] = "music"
2166
- if want_album:
2167
- params["entity"] = "album"
2168
- if country:
2169
- params["country"] = country
2170
- params["lang"] = "zh_cn"
2171
- try:
2172
- data = _get_json(f"{base}?{urllib.parse.urlencode(params)}", to)
2173
- except Exception as e:
2174
- logger.warning(f"iTunes 失败: {e}")
2175
- return []
2176
- items = data.get("results") or []
2177
- # 相关度:实体名与 term 重叠。播客单集的标题里不含节目名,故比对
2178
- # 「标题 + 摘要」——摘要首段就是《节目名》,否则搜节目名拿单集会全被滤掉。
2179
- t_keys = {t.lower() for t in re.findall(r"[A-Za-z0-9\u4e00-\u9fff]{2,}", term)}
2180
- base_score = 0.88 if want_album else 0.85
2181
- out: list[dict[str, Any]] = []
2182
- for it in items:
2183
- if not isinstance(it, dict):
2184
- continue
2185
- is_episode = want_podcast and (
2186
- str(it.get("wrapperType") or "").lower() == "podcastepisode"
2187
- or (not it.get("wrapperType") and it.get("episodeUrl"))
2188
- )
2189
- if want_podcast and not is_episode:
2190
- title = str(it.get("collectionName") or it.get("trackName") or "").strip()
2191
- href = it.get("collectionViewUrl") or it.get("feedUrl") or ""
2192
- count = it.get("trackCount")
2193
- bits = ["播客"]
2194
- if isinstance(count, int) and count > 0:
2195
- bits.append(f"{count} 集")
2196
- genre = str(it.get("primaryGenreName") or "").strip()
2197
- if genre:
2198
- bits.append(genre)
2199
- updated = _itunes_date(it.get("releaseDate"))
2200
- if updated:
2201
- bits.append(f"更新 {updated}")
2202
- row: dict[str, Any] = {
2203
- "title": title,
2204
- "url": str(href or "").strip(),
2205
- "snippet": " · ".join(bits)[:300],
2206
- "source": source_name,
2207
- }
2208
- if isinstance(count, int) and count > 0:
2209
- row["episode_count"] = count
2210
- # published_at 是既有的一等字段(--fields agent 与 --sort 都认它)。
2211
- # 只给播客挂:音乐的 releaseDate 不在本次范围内,而挂上会改变
2212
- # 音乐查询在 --sort newest 下的重排行为(releaseDate≠引擎相关序)。
2213
- _published = str(it.get("releaseDate") or "").strip()
2214
- if _published:
2215
- row["published_at"] = _published[:64]
2216
- elif is_episode:
2217
- title = str(it.get("trackName") or "").strip()
2218
- show = str(it.get("collectionName") or "").strip()
2219
- bits = [f"《{show}》"] if show else []
2220
- ms = it.get("trackTimeMillis")
2221
- row = {
2222
- "title": title,
2223
- "url": str(it.get("trackViewUrl") or it.get("episodeUrl") or "").strip(),
2224
- "snippet": "",
2225
- "source": source_name,
2226
- }
2227
- if isinstance(ms, (int, float)) and ms > 0:
2228
- mins = int(round(ms / 60000.0))
2229
- row["duration_minutes"] = mins
2230
- bits.append(f"时长 {mins} 分")
2231
- pub_date = _itunes_date(it.get("releaseDate"))
2232
- if pub_date:
2233
- bits.append(pub_date)
2234
- _published = str(it.get("releaseDate") or "").strip()
2235
- if _published:
2236
- row["published_at"] = _published[:64]
2237
- row["snippet"] = " · ".join(bits)[:300]
2238
- else:
2239
- if want_album:
2240
- title = str(it.get("collectionName") or it.get("trackName") or "").strip()
2241
- href = it.get("collectionViewUrl") or it.get("trackViewUrl") or ""
2242
- else:
2243
- title = str(it.get("trackName") or it.get("collectionName") or "").strip()
2244
- href = it.get("trackViewUrl") or it.get("collectionViewUrl") or ""
2245
- row = {
2246
- "title": title,
2247
- "url": str(href or "").strip(),
2248
- "snippet": str(it.get("artistName") or "").strip()[:300],
2249
- "source": source_name,
2250
- }
2251
- if not row["title"] or not row["url"]:
2252
- continue
2253
- blob = f"{row['title']} {row['snippet']}".lower()
2254
- if t_keys and not any(k in blob for k in t_keys):
2255
- continue
2256
- row["score"] = rank_score(base_score, len(out))
2257
- out.append(row)
2258
- if len(out) >= n:
2259
- break
2260
- # 节目级时长补在筛选之后:被滤掉的结果不该付二跳的代价
2261
- if want_podcast and not want_episode:
2262
- enriched = 0
2263
- for it in items:
2264
- if enriched >= _ITUNES_SHOW_ENRICH_MAX:
2265
- break
2266
- if not isinstance(it, dict):
2267
- continue
2268
- name = str(it.get("collectionName") or "").strip()
2269
- target = next((r for r in out if r["title"] == name), None)
2270
- if target is None or "duration_minutes" in target:
2271
- continue
2272
- mid, samples = _recent_episode_duration(it.get("collectionId"), country, to)
2273
- if mid is not None:
2274
- target["duration_minutes"] = mid
2275
- target["snippet"] = f"{target['snippet']} · 近 {samples} 期中位 {mid} 分"
2276
- enriched += 1
2277
- # 文字稿与时长共用 enrich 配额(前 1 条节目):官方全文预览的
2278
- # 信息密度远高于「N 集 · 类型」元数据行,有文字稿时 snippet
2279
- # 拼接全文开头,episode_count/published_at 等结构字段不动
2280
- feed_url = str(it.get("feedUrl") or "").strip()
2281
- if feed_url:
2282
- t_url, t_prev = _show_transcript(feed_url, to)
2283
- if t_url:
2284
- target["transcript_url"] = t_url
2285
- if t_prev:
2286
- target["snippet"] = f"{target['snippet']} | {t_prev}"[:300]
2287
- enriched += 1
2288
- return out
2289
- return _engine
2290
-
2291
-
2292
- # ── TheSportsDB 体育(免认证 test key=3) ────────────────────────────────────
2293
-
2294
- _SPORTSDB_BASE = "https://www.thesportsdb.com/api/v1/json/3"
2295
- _SPORTSDB_UA = "argo-search/2.6 (unified-search@local)"
2296
-
2297
- # 高频中文球员/球队 → TheSportsDB 英文检索名(公开 API 基本只认拉丁文)
2298
- _SPORTS_ZH_ALIASES: dict[str, str] = {
2299
- "梅西": "Messi",
2300
- "C罗": "Ronaldo",
2301
- "C羅": "Ronaldo",
2302
- "罗纳尔多": "Ronaldo",
2303
- "Cristiano": "Ronaldo",
2304
- "内马尔": "Neymar",
2305
- "姆巴佩": "Mbappe",
2306
- "哈兰德": "Haaland",
2307
- # 单姓 Curry 会命中 Eddy Curry;中文「库里」默认指 Stephen Curry
2308
- "库里": "Stephen Curry",
2309
- "斯蒂芬库里": "Stephen Curry",
2310
- "史蒂芬库里": "Stephen Curry",
2311
- "詹姆斯": "LeBron James",
2312
- "勒布朗": "LeBron",
2313
- "杜兰特": "Durant",
2314
- "科比": "Kobe",
2315
- "乔丹": "Jordan",
2316
- "姚明": "Yao Ming",
2317
- "易建联": "Yi Jianlian",
2318
- "皇马": "Real Madrid",
2319
- "巴萨": "Barcelona",
2320
- "曼联": "Manchester United",
2321
- "曼城": "Manchester City",
2322
- "湖人": "Lakers",
2323
- "勇士": "Warriors",
2324
- "凯尔特人": "Celtics",
2325
- }
2326
-
2327
-
2328
- def _sports_expand_aliases(query: str) -> list[str]:
2329
- """中文别名展开为英文检索变体。"""
2330
- out: list[str] = []
2331
- for zh, en in _SPORTS_ZH_ALIASES.items():
2332
- if zh in query:
2333
- if en not in out:
2334
- out.append(en)
2335
- return out
2336
-
2337
-
2338
- def _build_thesportsdb_engine(spec: dict[str, Any]) -> Any:
2339
- """TheSportsDB 球员/球队/赛事搜索(api key=3 公开测试钥,免认证)。
2340
-
2341
- 并行查 searchplayers / searchteams / searchevents,合并去重。
2342
- """
2343
- timeout = spec.get("timeout", 10)
2344
- source_name = spec.get("_name", "thesportsdb")
2345
-
2346
- def _fetch(path: str, params: dict[str, str], to: float) -> Any:
2347
- url = f"{_SPORTSDB_BASE}/{path}?" + urllib.parse.urlencode(params)
2348
- req = urllib.request.Request(
2349
- url, headers={"User-Agent": _SPORTSDB_UA, "Accept": "application/json"},
2350
- )
2351
- with http_open(req, timeout=to, engine=spec.get("_name", "")) as resp:
2352
- return json.loads(resp.read().decode("utf-8", "replace"))
2353
-
2354
- @safe_search
2355
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
2356
- q = (query or "").strip()
2357
- if not q:
2358
- return []
2359
- to = _timeout or timeout
2360
- # 多词查询(如 "NBA finals MVP 2024")整句常 0 命中 → 短语 + token 变体
2361
- stop = {
2362
- "finals", "final", "mvp", "vs", "the", "and", "of", "in", "for", "a", "an",
2363
- "winner", "winners", "who", "won", "what", "which", "year", "years",
2364
- "team", "club", "player", "coach", "manager", "roster", "squad",
2365
- "决赛", "半决赛", "总冠军", "联赛", "球员", "俱乐部", "进球", "冠军",
2366
- "球队", "球星", "效力", "夺冠", "卫冕", "助攻", "得分王",
2367
- }
2368
- tokens = re.findall(r"[A-Za-z\u4e00-\u9fff]{2,}", q)
2369
- # 纯数字年号单独收集,用于 event 年份保持一致,不当主检索词
2370
- # 注意:必须整年捕获;r"(19|20)\d{2}" 的 findall 只会返回 "20",
2371
- # 导致 "20" in "2016-11-24" 恒真、年份过滤失效。
2372
- years = re.findall(r"\b((?:19|20)\d{2})\b", q)
2373
- meaningful = [t for t in tokens if t.lower() not in stop and not re.fullmatch(r"\d{4}", t)]
2374
-
2375
- variants: list[str] = []
2376
- # 中文别名优先(梅西→Messi)
2377
- for alias in _sports_expand_aliases(q):
2378
- if alias not in variants:
2379
- variants.append(alias)
2380
- # 双词短语优先(World Cup / LeBron James)
2381
- for i in range(len(meaningful) - 1):
2382
- phrase = f"{meaningful[i]} {meaningful[i + 1]}"
2383
- if phrase not in variants:
2384
- variants.append(phrase)
2385
- # 整句(短查询,非纯中文)
2386
- if len(q) <= 40 and q not in variants and re.search(r"[A-Za-z]", q):
2387
- variants.insert(0, q)
2388
- for t in meaningful:
2389
- # 纯中文 token 对英文 API 无效,跳过(已由别名覆盖)
2390
- if re.fullmatch(r"[\u4e00-\u9fff]+", t):
2391
- continue
2392
- if t not in variants:
2393
- variants.append(t)
2394
- if len(variants) >= 5:
2395
- break
2396
- if not variants:
2397
- variants = [q]
2398
-
2399
- # 意图:club/team/球队 → 优先 team/player;event 词 → 保留 event
2400
- q_low = q.lower()
2401
- prefer_entity = bool(re.search(
2402
- r"(?i)(team|club|player|coach|球队|球星|俱乐部|效力|球员|roster|squad)", q,
2403
- ))
2404
- prefer_event = bool(re.search(
2405
- r"(?i)(finals?|mvp|cup|championship|winner|won|决赛|总冠军|世界杯|欧冠|季后赛)", q,
2406
- )) and not prefer_entity
2407
-
2408
- bucket: list[dict[str, Any]] = []
2409
- seen: set[str] = set()
2410
-
2411
- endpoints = (
2412
- ("searchplayers.php", "p", "player", "strPlayer", "idPlayer",
2413
- lambda x: " · ".join(p for p in (
2414
- x.get("strTeam") or "",
2415
- x.get("strSport") or "",
2416
- x.get("strPosition") or "",
2417
- x.get("strNationality") or "",
2418
- ) if p)),
2419
- ("searchteams.php", "t", "team", "strTeam", "idTeam",
2420
- lambda x: " · ".join(p for p in (
2421
- x.get("strSport") or "",
2422
- x.get("strLeague") or "",
2423
- x.get("strCountry") or "",
2424
- ) if p)),
2425
- ("searchevents.php", "e", "event", "strEvent", "idEvent",
2426
- lambda x: " · ".join(p for p in (
2427
- x.get("strLeague") or "",
2428
- x.get("strSport") or "",
2429
- x.get("dateEvent") or x.get("strTimestamp") or "",
2430
- ) if p)),
2431
- )
2432
- list_keys = {
2433
- "searchplayers.php": "player",
2434
- "searchteams.php": "teams",
2435
- "searchevents.php": "event",
2436
- }
2437
- url_tpl = {
2438
- "player": "https://www.thesportsdb.com/player/{id}",
2439
- "team": "https://www.thesportsdb.com/team/{id}",
2440
- "event": "https://www.thesportsdb.com/event/{id}",
2441
- }
2442
- score_of = {"player": 0.86, "team": 0.84, "event": 0.82}
2443
- # 实体问优先 player/team;赛事问放宽 event
2444
- if prefer_entity:
2445
- endpoints = endpoints[:2] + endpoints[2:] # 顺序已是 p,t,e
2446
- elif prefer_event:
2447
- endpoints = (endpoints[2], endpoints[0], endpoints[1])
2448
-
2449
- q_token_set = {t.lower() for t in meaningful}
2450
-
2451
- for v in variants:
2452
- for path, param_k, kind, title_k, id_k, snip_fn in endpoints:
2453
- try:
2454
- data = _fetch(path, {param_k: v}, to)
2455
- except Exception as e:
2456
- logger.warning(f"TheSportsDB {path} 失败: {e}")
2457
- continue
2458
- items = data.get(list_keys[path]) if isinstance(data, dict) else None
2459
- if not items:
2460
- continue
2461
- for x in items[: max(n, 5)]:
2462
- if not isinstance(x, dict):
2463
- continue
2464
- title = x.get(title_k) or ""
2465
- iid = str(x.get(id_k) or "")
2466
- key = f"{kind}:{iid or title}"
2467
- if not title or key in seen:
2468
- continue
2469
- # 相关度:标题/摘要 token 与查询重叠;event 尤其严格
2470
- snip = snip_fn(x) or ""
2471
- sport = str(x.get("strSport") or "")
2472
- league = str(x.get("strLeague") or "")
2473
- blob = f"{title} {snip} {sport} {league}".lower()
2474
- t_tokens = set(re.findall(r"[a-z0-9\u4e00-\u9fff]{2,}", blob))
2475
- overlap = len(q_token_set & t_tokens) if q_token_set else 1
2476
- # 「世界杯/World Cup」默认足球;公开 API 常塞高尔夫/篮网等噪声 → 非足球一律丢
2477
- world_cup_q = bool(re.search(r"(?i)world\s*cup|世界杯|fifa", q))
2478
- if world_cup_q:
2479
- if not re.search(r"(?i)soccer|football|fifa", f"{title} {sport} {league} {snip}"):
2480
- continue
2481
- if kind == "event":
2482
- # 无实质重叠 → 丢弃噪声 event(如 World Cup → World Sand Greens)
2483
- if q_token_set and overlap == 0:
2484
- continue
2485
- # 有年份且 API 给了日期:年份不对直接丢(避免 2022 问到 2016 Golf)
2486
- date_s = str(x.get("dateEvent") or x.get("strTimestamp") or "")
2487
- if years and date_s and not any(y in date_s for y in years):
2488
- continue
2489
- # 双词短语(如 World Cup)若在标题中,要求更高相关;单 token 过宽
2490
- phrase_hit = any(
2491
- len(p.split()) >= 2 and p.lower() in title.lower()
2492
- for p in variants[:3]
2493
- )
2494
- if q_token_set and overlap < 2 and not phrase_hit:
2495
- continue
2496
- rel = 0.35 + 0.15 * overlap + (0.2 if phrase_hit else 0)
2497
- if years and date_s and any(y in date_s for y in years):
2498
- rel += 0.2
2499
- if world_cup_q and re.search(r"(?i)soccer|football|fifa", blob):
2500
- rel += 0.25
2501
- else:
2502
- # 赛事问勿用弱 token 沾上球员(Metta World Peace)
2503
- if prefer_event and overlap < 2 and v.lower() not in title.lower():
2504
- continue
2505
- if world_cup_q and kind == "player" and not re.search(
2506
- r"(?i)soccer|football", f"{sport} {snip}",
2507
- ):
2508
- continue
2509
- # player/team:变体本身已是名,重叠可放宽
2510
- rel = 0.35 + 0.25 * overlap
2511
- if v.lower() in title.lower():
2512
- rel += 0.25
2513
- # 全名变体(Stephen Curry)精确命中加权
2514
- if " " in v and v.lower() == title.lower():
2515
- rel += 0.3
2516
- seen.add(key)
2517
- href = url_tpl[kind].format(id=iid) if iid else ""
2518
- base = score_of.get(kind, 0.8)
2519
- bucket.append({
2520
- "title": f"[{kind}] {title}",
2521
- "url": href,
2522
- "snippet": (snip_fn(x) or kind)[:300],
2523
- "source": source_name,
2524
- "score": min(0.95, base * 0.5 + rel),
2525
- "_kind": kind,
2526
- "_rel": rel,
2527
- })
2528
- # 已有高相关实体则早停
2529
- if sum(1 for r in bucket if r.get("_rel", 0) >= 0.5) >= n:
2530
- break
2531
-
2532
- kind_rank = {"player": 0, "team": 1, "event": 2}
2533
- if prefer_entity:
2534
- kind_rank = {"player": 0, "team": 0, "event": 3}
2535
- elif prefer_event:
2536
- kind_rank = {"event": 0, "player": 1, "team": 2}
2537
-
2538
- bucket.sort(key=lambda r: (
2539
- kind_rank.get(r.get("_kind", ""), 9),
2540
- -float(r.get("_rel", 0)),
2541
- -float(r.get("score", 0)),
2542
- ))
2543
- out = []
2544
- for r in bucket[:n]:
2545
- r.pop("_kind", None)
2546
- r.pop("_rel", None)
2547
- out.append(r)
2548
- return out
2549
- return _engine
2550
-
2551
-
2552
- # ── GDELT 全球事件数据库 ─────────────────────────────────────────────────────
2553
-
2554
- # ── OpenCorporates 全球公司注册 ──────────────────────────────────────────────
2555
-
2556
- def _build_opencorporates_engine(spec: dict[str, Any]) -> Any:
2557
- """OpenCorporates 全球公司注册(api.opencorporates.com/v0.4/companies/search)。
2558
-
2559
- 公司尽调/反欺诈:公司名、注册号、司法辖区、成立日期、状态。
2560
- argo 现有引擎无公司注册数据源,这是尽调类查询的核心空白。
2561
- (2026-10-28:匿名请求已被上游全面拒 401,API 需 api_token;直连实测确认。
2562
- 支持 ARGO_OPENCORPORATES_API_TOKEN / OPENCORPORATES_API_TOKEN 双别名,
2563
- spec required_env 已声明,无 token 时被 env 门自动跳过而非报错。)
2564
- """
2565
- timeout = spec.get("timeout", 10)
2566
- _token = get_env(["ARGO_OPENCORPORATES_API_TOKEN", "OPENCORPORATES_API_TOKEN"]) or ""
2567
-
2568
- @safe_search
2569
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
2570
- to = _timeout or timeout
2571
- q = query.strip()
2572
- # 去常见修饰语,取核心公司名
2573
- q2 = re.sub(r"(?i)\b(company|corporation|inc|limited|ltd|llc|公司|集团|有限|注册|查一下|查询)\b", " ", q)
2574
- q2 = re.sub(r"\s+", " ", q2).strip() or q
2575
- url = (
2576
- "https://api.opencorporates.com/v0.4/companies/search"
2577
- f"?q={urllib.parse.quote(q2)}&per_page={min(n, 10)}"
2578
- + (f"&api_token={urllib.parse.quote(_token)}" if _token else "")
2579
- )
2580
- headers = {"User-Agent": "argo-search/2.6 (unified-search@local)", "Accept": "application/json"}
2581
- try:
2582
- with http_open(urllib.request.Request(url, headers=headers), timeout=to, engine=spec.get("_name", "")) as resp:
2583
- data = json.loads(resp.read().decode("utf-8", "replace"))
2584
- except Exception:
2585
- return []
2586
- companies = ((data.get("results") or {}).get("companies")) or []
2587
- results: list[dict[str, Any]] = []
2588
- for _rk19, c in enumerate(companies[:n]):
2589
- comp = c.get("company") or {}
2590
- name = comp.get("name") or ""
2591
- if not name:
2592
- continue
2593
- num = comp.get("company_number") or ""
2594
- juris = comp.get("jurisdiction_code") or ""
2595
- inc_date = (comp.get("incorporation_date") or "")[:10]
2596
- status = comp.get("current_status") or ""
2597
- cc = (comp.get("registered_address") or {}).get("country") or ""
2598
- results.append({
2599
- "title": name[:200],
2600
- "url": comp.get("opencorporates_url") or f"https://opencorporates.com/companies/{juris}/{num}",
2601
- "snippet": (
2602
- f"{juris}{'/'+num if num else ''}"
2603
- f"{' · 成立 '+inc_date if inc_date else ''}"
2604
- f"{' · 状态 '+status if status else ''}"
2605
- f"{' · '+cc if cc else ''}"
2606
- )[:300],
2607
- "source": "opencorporates",
2608
- "score": rank_score(0.8, _rk19),
2609
- "company_number": num,
2610
- "jurisdiction": juris,
2611
- "incorporation_date": inc_date,
2612
- "status": status,
2613
- })
2614
- return results
2615
- return _engine
2616
-
2617
-
2618
- # ── Google Patents 专利搜索 ──────────────────────────────────────────────────
2619
-
2620
- def _build_google_patents_engine(spec: dict[str, Any]) -> Any:
2621
- """Google Patents 专利搜索(patents.google.com/xhr/query,免认证)。
2622
-
2623
- 技术尽调/竞品分析:专利标题、公开号、公开日期、申请人。
2624
- 用 patents.google.com 的公开 XHR 接口,免 key、返回 JSON。
2625
- argo 现有引擎无专利数据源,这是技术尽调的核心空白。
2626
- """
2627
- timeout = spec.get("timeout", 10)
2628
-
2629
- @safe_search
2630
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
2631
- to = _timeout or timeout
2632
- q = query.strip()
2633
- # 去常见修饰语
2634
- q2 = re.sub(r"(?i)\b(patent|专利|查询|搜索|检索)\b", " ", q)
2635
- q2 = re.sub(r"\s+", " ", q2).strip() or q
2636
- url = "https://patents.google.com/xhr/query"
2637
- params = {
2638
- "url": f"q={urllib.parse.quote(q2)}",
2639
- "exp": "",
2640
- }
2641
- full_url = url + "?" + urllib.parse.urlencode(params)
2642
- headers = {
2643
- "User-Agent": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Safari/537.36",
2644
- "Accept": "application/json",
2645
- }
2646
- try:
2647
- with http_open(urllib.request.Request(full_url, headers=headers), timeout=to, engine=spec.get("_name", "")) as resp:
2648
- data = json.loads(resp.read().decode("utf-8", "replace"))
2649
- except Exception:
2650
- return []
2651
- results: list[dict[str, Any]] = []
2652
- try:
2653
- cluster = (data.get("results") or {}).get("cluster") or []
2654
- for c in cluster:
2655
- for r in (c.get("result") or []):
2656
- if len(results) >= n:
2657
- break
2658
- pat = r.get("patent") or {}
2659
- title = pat.get("title") or ""
2660
- if not title:
2661
- continue
2662
- pub_date = pat.get("publication_date") or ""
2663
- pub_num = pat.get("publication_number") or ""
2664
- assignee = (pat.get("assignee") or [{}])[0].get("name") if isinstance(pat.get("assignee"), list) else ""
2665
- pub_id = pat.get("publication_number") or pub_num or ""
2666
- results.append({
2667
- "title": title[:200],
2668
- "url": f"https://patents.google.com/patent/{pub_id}" if pub_id else "",
2669
- "snippet": (r.get("snippet") or "")[:300],
2670
- "source": "google_patents",
2671
- "score": rank_score(0.8, len(results)),
2672
- "publication_date": pub_date,
2673
- "publication_number": pub_num,
2674
- "assignee": assignee,
2675
- })
2676
- except Exception:
2677
- pass
2678
- return results
2679
- return _engine
2680
-
2681
-
2682
- # ── Marginalia 独立索引引擎 ──────────────────────────────────────────────────
2683
-
2684
- def _build_marginalia_engine(spec: dict[str, Any]) -> Any:
2685
- """Marginalia 独立爬虫索引搜索(api.marginalia.nu,免认证 JSON)。
2686
-
2687
- 非大厂代理的独立索引,专挖长尾非商业页面;JSON 直出。
2688
- """
2689
- timeout = spec.get("timeout", 10)
2690
-
2691
- @safe_search
2692
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
2693
- import urllib.parse as up
2694
- to = _timeout or timeout
2695
- url = f"https://api.marginalia.nu/public/search/{up.quote(query)}?count={min(n, 10)}"
2696
- try:
2697
- with http_open(urllib.request.Request(
2698
- url, headers={"User-Agent": "argo-search/2.4 (unified-search@local)"}), timeout=to, engine=spec.get("_name", "")) as resp:
2699
- data = json.loads(resp.read().decode("utf-8", "replace"))
2700
- except Exception as e:
2701
- logger.warning(f"Marginalia 失败: {e}")
2702
- return []
2703
- results = []
2704
- for _rk20, r in enumerate((data.get("results") or [])[:n]):
2705
- title = r.get("title", "")
2706
- url_ = r.get("url", "")
2707
- if not title and not url_:
2708
- continue
2709
- results.append({
2710
- "title": title,
2711
- "url": url_,
2712
- "snippet": r.get("description", "")[:300],
2713
- "source": "marginalia",
2714
- "score": rank_score(0.7, _rk20),
2715
- })
2716
- return results
2717
- return _engine
2718
-
2719
-
2720
- # ── Wiby 手工网页索引引擎 ────────────────────────────────────────────────────
2721
-
2722
- def _build_wiby_engine(spec: dict[str, Any]) -> Any:
2723
- """Wiby 老式手工网页索引搜索(wiby.me/json,免认证,注意大写键)。
2724
-
2725
- 专收非商业化内容的老式索引,与主流引擎互补。
2726
- """
2727
- timeout = spec.get("timeout", 10)
2728
-
2729
- @safe_search
2730
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
2731
- import urllib.parse as up
883
+ import urllib.parse as up
2732
884
  to = _timeout or timeout
2733
885
  url = f"https://wiby.me/json/?q={up.quote(query)}"
2734
886
  try:
@@ -2755,176 +907,3 @@ def _build_wiby_engine(spec: dict[str, Any]) -> Any:
2755
907
  })
2756
908
  return results
2757
909
  return _engine
2758
-
2759
-
2760
- # ── bioRxiv / medRxiv 预印本引擎 ─────────────────────────────────────────────
2761
-
2762
- # DOI 提取:10. 开头的标准 DOI(bioRxiv DOI 形态 10.1101/2024.01.02.123456)
2763
- _PREPRINT_DOI_RE = re.compile(r"10\.\d{4,9}/[^\s\"',。;)((]+", re.I)
2764
-
2765
-
2766
- def _build_biorxiv_engine(spec: dict[str, Any]) -> Any:
2767
- """bioRxiv / medRxiv 预印本引擎(API 免认证)。
2768
-
2769
- bioRxiv API 没有关键词搜索端点——只有两种查询语义是诚实的:
2770
- ① DOI(10.xxxx/… 或 bioRxiv/medRxiv 链接)→ 取单篇详情(标题/作者/摘要)
2771
- ② 「最新 / recent」或空 → 最近 3 天全量列表
2772
- 关键词查询诚实返回空(不伪造结果);关键词发现交给 openalex /
2773
- semantic_scholar,本引擎负责预印本原文入口与时效性列表。
2774
- medRxiv 按 DOI 自动路由到 medrxiv 子库。
2775
- """
2776
- timeout = spec.get("timeout", 12)
2777
-
2778
- @safe_search
2779
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
2780
- from datetime import date, timedelta
2781
- to = _timeout or timeout
2782
- from engines_base import _http_get_raw
2783
- q = (query or "").strip()
2784
- m = _PREPRINT_DOI_RE.search(q)
2785
- headers = {"Accept": "application/json"}
2786
- if m:
2787
- doi = m.group(0).rstrip(".")
2788
- server = "medrxiv" if ("medrxiv" in q.lower()) else "biorxiv"
2789
- url = f"https://api.biorxiv.org/details/{server}/{doi}"
2790
- raw = _http_get_raw(url, headers, to, engine="biorxiv")
2791
- if not raw:
2792
- return []
2793
- try:
2794
- data = json.loads(raw)
2795
- except json.JSONDecodeError:
2796
- return []
2797
- coll = data.get("collection") or []
2798
- items = coll
2799
- else:
2800
- # 时效模式:最近 3 天(含「最新/recent」触发词;关键词一律走时效模式
2801
- # 的如实空列表——API 无搜索端点,不伪造)
2802
- end = date.today()
2803
- start = end - timedelta(days=3)
2804
- url = (f"https://api.biorxiv.org/details/biorxiv/"
2805
- f"{start.isoformat()}/{end.isoformat()}/0")
2806
- raw = _http_get_raw(url, headers, to, engine="biorxiv")
2807
- if not raw:
2808
- return []
2809
- try:
2810
- data = json.loads(raw)
2811
- except json.JSONDecodeError:
2812
- return []
2813
- coll = data.get("collection") or []
2814
- # 时效模式下按查询词做本地相关过滤;纯触发词(最新/recent)放行
2815
- kws = [w for w in q.lower().split() if w not in ("最新", "recent", "预印本")]
2816
- if kws:
2817
- coll = [c for c in coll
2818
- if any(kw in (str(c.get("title") or "") + str(c.get("abstract") or "")).lower()
2819
- for kw in kws)]
2820
- items = coll[:n]
2821
-
2822
- results = []
2823
- for c in items:
2824
- doi = str(c.get("doi") or "")
2825
- results.append({
2826
- "title": str(c.get("title") or "")[:120],
2827
- "url": f"https://doi.org/{doi}" if doi else "https://www.biorxiv.org/",
2828
- "snippet": f"{str(c.get('authors') or '')[:80]} | {str(c.get('abstract') or '')[:220]}",
2829
- "source": "biorxiv",
2830
- "score": 0.9 if m else 0.75,
2831
- "published_at": str(c.get("date") or "")[:10],
2832
- })
2833
- return results
2834
- return _engine
2835
-
2836
-
2837
- # ── UN Comtrade 双边贸易引擎 ─────────────────────────────────────────────────
2838
-
2839
- # 报告国词表:查询里的国家名 → Comtrade reporterCode。
2840
- # 取主要经济体 30+;未收录国家诚实返回空(代码表不硬猜)。
2841
- _COMTRADE_REPORTERS = {
2842
- "中国": 156, "美国": 842, "日本": 392, "德国": 276, "韩国": 410,
2843
- "印度": 699, "英国": 826, "法国": 251, "意大利": 380, "荷兰": 528,
2844
- "俄罗斯": 643, "巴西": 76, "澳大利亚": 36, "加拿大": 124, "墨西哥": 484,
2845
- "印尼": 360, "印度尼西亚": 360, "泰国": 764, "越南": 704, "马来西亚": 458,
2846
- "新加坡": 702, "土耳其": 792, "西班牙": 724, "波兰": 616, "瑞士": 756,
2847
- "瑞典": 752, "阿联酋": 784, "沙特": 682, "南非": 710, "阿根廷": 32,
2848
- "智利": 152, "菲律宾": 608, "香港": 344, "挪威": 578, "丹麦": 208,
2849
- }
2850
-
2851
-
2852
- def _build_un_comtrade_engine(spec: dict[str, Any]) -> Any:
2853
- """UN Comtrade 双边商品贸易引擎(preview 端点免 key)。
2854
-
2855
- 查询形态:「<国家> <HS 码> [年份] [出口]」,如「中国 8541」「美国 8542
2856
- 2024 出口」。未提供国家或 HS 码时诚实返回空——参数解析不做猜测。
2857
- preview 端点返回代码与数值,不含描述字典(reporter/partner/cmd 的
2858
- Desc 字段为 null),故标题用查询词原文回显、金额取 primaryValue。
2859
- 每条结果附 comtradeplus 网页链接可核验同一数据。
2860
- """
2861
- timeout = spec.get("timeout", 15)
2862
-
2863
- @safe_search
2864
- def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
2865
- import urllib.parse as up
2866
- to = _timeout or timeout
2867
- q = (query or "").strip()
2868
- reporter = None
2869
- reporter_name = ""
2870
- for name, code in _COMTRADE_REPORTERS.items():
2871
- if name in q:
2872
- reporter, reporter_name = code, name
2873
- break
2874
- if reporter is None:
2875
- return []
2876
- year_m = re.search(r"\b(20[0-2]\d)\b", q)
2877
- period = year_m.group(1) if year_m else "2023"
2878
- flow = "X" if ("出口" in q or "export" in q.lower()) else "M"
2879
- flow_name = "出口" if flow == "X" else "进口"
2880
- cmd = ""
2881
- for tok in re.findall(r"\d{4,6}", q):
2882
- if tok == period:
2883
- continue
2884
- cmd = tok
2885
- break
2886
- if not cmd:
2887
- return []
2888
- params = {
2889
- "reporterCode": reporter,
2890
- "period": period,
2891
- "cmdCode": cmd,
2892
- "flowCode": flow,
2893
- }
2894
- url = ("https://comtradeapi.un.org/public/v1/preview/C/A/HS?"
2895
- + up.urlencode(params))
2896
- from engines_base import _http_get_raw
2897
- raw = _http_get_raw(url, {"Accept": "application/json"}, to,
2898
- engine="un_comtrade")
2899
- if not raw:
2900
- return []
2901
- try:
2902
- data = json.loads(raw)
2903
- except json.JSONDecodeError:
2904
- return []
2905
- rows = data.get("data") or []
2906
- if not rows:
2907
- return []
2908
- rows.sort(key=lambda r: float(r.get("primaryValue") or 0), reverse=True)
2909
- results = []
2910
- for r in rows[:n]:
2911
- partner = r.get("partnerCode")
2912
- value = r.get("primaryValue")
2913
- value_str = f"{float(value):,.0f} USD" if value else "金额未披露"
2914
- # title/url 均带伙伴维度:融合层按 title+url 去重,同一伙伴维度
2915
- # 才算重复;URL 带 PartnerAreas 使每条结果可独立核验
2916
- partner_url = (
2917
- "https://comtradeplus.un.org/TradeFlow?Frequency=A&Classification=HS"
2918
- f"&Commodities={cmd}&Flow={flow}&Reporters={reporter}"
2919
- f"&PartnerAreas={partner}&Period={period}")
2920
- label = "全球合计" if partner in (0, 1) else f"伙伴 {partner}"
2921
- results.append({
2922
- "title": f"{reporter_name} {flow_name} HS{cmd} {period} → {label}",
2923
- "url": partner_url,
2924
- "snippet": value_str + (f" | 净重 {r.get('netWgt')}" if r.get('netWgt') else ""),
2925
- "source": "un_comtrade",
2926
- "score": 0.95 if partner in (0, 1) else 0.75,
2927
- "published_at": f"{period}-12-31",
2928
- })
2929
- return results
2930
- return _engine