argo-search 2.10.1 → 2.11.2

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 (89) hide show
  1. package/README.en.md +48 -11
  2. package/README.es.md +48 -11
  3. package/README.ja.md +48 -11
  4. package/README.ko.md +47 -10
  5. package/README.md +48 -31
  6. package/SKILL.md +16 -15
  7. package/backends/concept_vectors.bin +0 -0
  8. package/backends/domain_profiles.json +18 -6
  9. package/backends/engine_concept_vectors.json +3104 -0
  10. package/backends/engine_registry.yaml +38 -13
  11. package/backends/quota_profiles.json +30 -10
  12. package/bin/argo +6 -0
  13. package/config.yaml +98 -31
  14. package/docs/ENGINE_CATALOG.md +11 -8
  15. package/docs/RELEASE_NOTES_v2.10.2.md +48 -0
  16. package/docs/RELEASE_NOTES_v2.11.2.md +50 -0
  17. package/engines/specs/animetrace.yaml +35 -0
  18. package/engines/specs/google_lens.yaml +50 -0
  19. package/engines/specs/saucenao.yaml +45 -0
  20. package/package.json +4 -2
  21. package/packages/dsh-plugin/dsh/diagnostics.js +8 -3
  22. package/packages/dsh-plugin/dsh/index.js +12 -7
  23. package/packages/dsh-plugin/dsh/runner.js +79 -47
  24. package/packages/dsh-plugin/package.json +1 -1
  25. package/packages/dsh-plugin/test/index.test.js +64 -0
  26. package/scripts/argo_engine_registry.py +30 -4
  27. package/scripts/argo_paths.py +7 -1
  28. package/scripts/budget.py +13 -3
  29. package/scripts/build_concept_table.py +612 -0
  30. package/scripts/build_route_labels.py +285 -0
  31. package/scripts/caliber_dedupe.py +66 -0
  32. package/scripts/caliber_isolation.py +4 -2
  33. package/scripts/circuit_breaker.py +25 -3
  34. package/scripts/concept_lookup.py +212 -0
  35. package/scripts/engine_dispatch.py +2 -1
  36. package/scripts/engine_families.py +7 -3
  37. package/scripts/engines.py +34 -9
  38. package/scripts/engines_base.py +17 -2
  39. package/scripts/engines_builders.py +0 -1
  40. package/scripts/engines_builders_intl.py +4 -4
  41. package/scripts/engines_builders_reverse_image.py +783 -0
  42. package/scripts/engines_builders_skill.py +87 -10
  43. package/scripts/engines_builders_tech.py +0 -78
  44. package/scripts/extend_route_labels.py +239 -0
  45. package/scripts/extend_route_labels_by_capability.py +344 -0
  46. package/scripts/extend_route_labels_by_language.py +306 -0
  47. package/scripts/gen_routing_snapshot.py +22 -3
  48. package/scripts/job.py +2 -1
  49. package/scripts/lang_detect.py +12 -3
  50. package/scripts/lint_spec_contracts.py +110 -0
  51. package/scripts/lint_stub_targets.py +130 -0
  52. package/scripts/local_image.py +3 -3
  53. package/scripts/local_seek.py +13 -3
  54. package/scripts/mcp_compact.py +5 -0
  55. package/scripts/mcp_transport.py +1 -1
  56. package/scripts/net_proxy.py +47 -0
  57. package/scripts/numeric_verify.py +330 -0
  58. package/scripts/plan.py +36 -4
  59. package/scripts/pre-commit +21 -13
  60. package/scripts/quota.py +109 -10
  61. package/scripts/rank_signals.py +48 -4
  62. package/scripts/ranking_eval.py +23 -1
  63. package/scripts/regression_p0p1.py +7 -2
  64. package/scripts/route.py +24 -3
  65. package/scripts/route_accuracy_eval.py +191 -0
  66. package/scripts/route_combo.py +32 -1
  67. package/scripts/route_domains.py +242 -5
  68. package/scripts/route_primary.py +101 -0
  69. package/scripts/search.py +14 -12
  70. package/scripts/search_cli.py +89 -7
  71. package/scripts/search_output.py +59 -1
  72. package/scripts/search_pipeline.py +20 -15
  73. package/scripts/snippet_clean.py +60 -0
  74. package/scripts/social_engines/twitter_engine.py +159 -42
  75. package/scripts/social_engines/xiaohongshu_engine.py +36 -1
  76. package/scripts/tfidf_router.py +52 -2
  77. package/scripts/train.py +15 -0
  78. package/scripts/verify_with.py +124 -0
  79. package/sub-skills/local-search/SKILL.md +3 -2
  80. package/sub-skills/local-search/bm25.py +89 -8
  81. package/sub-skills/local-search/config.yaml +12 -0
  82. package/sub-skills/local-search/parse_maps.yaml +8 -0
  83. package/sub-skills/local-search/parsers.py +5 -2
  84. package/sub-skills/local-search/search_v3.py +87 -1
  85. package/sub-skills/local-search/smart_router.py +1 -1
  86. package/sub-skills/local-seek/SKILL.md +6 -5
  87. package/sub-skills/local-seek/scripts/eval_rank.py +1 -1
  88. package/sub-skills/local-seek/scripts/seek.py +152 -36
  89. package/sub-skills/local-seek/scripts/seek_rank.py +191 -11
@@ -0,0 +1,783 @@
1
+ #!/usr/bin/env python3
2
+ """专用构建器:反向图片搜索(SauceNAO / AnimeTrace / Google Lens)
3
+
4
+ 以图搜图与其他引擎的根本差别在输入:query 不是关键词,而是**一张图**——
5
+ 引擎把这串图交给上游做图片指纹比对,回答「这张图出自哪里」,输出的是
6
+ 原图/出处页,而不是「讲述了这张图的网页」。因此:
7
+
8
+ - 输入有两种形态:公网图片 URL,或本地图片(`file://` / 盘符路径 / UNC)。
9
+ 本地图由 SauceNAO 走 multipart 上传、AnimeTrace 走 base64;Google Lens
10
+ 先经 SerpAPI Image API 上传换 `image_id` 再检索(只收 JPEG/PNG/WebP、
11
+ 单张 ≤500KB,`image_id` 10 分钟内有效);
12
+ - 关键词在入口直接返回可读的 error 条目(静默返回 [] 会让调用方误以为
13
+ 「查了但没找到」);
14
+ - 只做显式调用(spec 里 explicit_only),不进自动路由候选池——没有图片
15
+ 的普通查询落进来必然是空结果;
16
+ - known-url 输入不应被离线 handoff 拦截:显式指定引擎时按 URL 取数,
17
+ 见 `search.py` 的 URL 输入引擎豁免。
18
+
19
+ 两条实测约束(2026-11-04):
20
+
21
+ 1. SauceNAO 匿名档已关闭 API 调用:不带 api_key 时返回
22
+ `{"header":{"status":-1,"message":"The anonymous account type does not permit
23
+ API usage."}}`。站点在 Cloudflare 之后(urllib 直连拿到 `Cf-Mitigated:
24
+ challenge` 的 403 页),取数须走 TLS 指纹伪造(curl_cffi impersonate),
25
+ 故 `_http_get_raw` 传 `tls_profiles`,multipart 上传由 curl_cffi 直接发。
26
+ 2. AnimeTrace 免 key 但按出口 IP 限频:超限返回 HTTP 429 + `code:17737`,
27
+ 配额用尽是 `code:17728`。两者都映射成 error 条目而不是空结果——调用方
28
+ 需要分清「这张图认不出」与「这次没资格查」。
29
+ """
30
+
31
+ from __future__ import annotations
32
+
33
+ import base64
34
+ import io
35
+ import json
36
+ import os
37
+ import re
38
+ import stat
39
+ import urllib.error
40
+ import urllib.parse
41
+ import urllib.request
42
+ from typing import Any
43
+
44
+ from engines_base import _http_get_raw, http_open, rank_score, safe_search
45
+ from engine_env import get_env
46
+
47
+ # 公网图片地址;裸关键词在入口挡下并说明原因。
48
+ _IMAGE_URL_RE = re.compile(r"(?i)^https?://[^\s]+$")
49
+ # 本地图片来源:file://、盘符绝对路径(C:\ 或 C:/)、UNC 路径。
50
+ _LOCAL_REF_RE = re.compile(r"(?i)^(file:|[a-z]:[\\/]|\\\\)")
51
+ _MAX_LOCAL_BYTES = 20 * 1024 * 1024
52
+ # 只认图片魔数:路径可能指向任意本地文件,按扩展名放行等于把整个磁盘
53
+ # 交给一条「上传到第三方」的通路。
54
+ _IMAGE_MAGIC: tuple[tuple[bytes, str], ...] = (
55
+ (b"\xff\xd8\xff", "image/jpeg"),
56
+ (b"\x89PNG\r\n\x1a\n", "image/png"),
57
+ (b"GIF8", "image/gif"),
58
+ (b"RIFF", "image/webp"),
59
+ (b"BM", "image/bmp"),
60
+ )
61
+
62
+
63
+ def _image_input_error(engine: str, query: str) -> list[dict[str, Any]]:
64
+ """输入既不是图片 URL 也不是可读本地图片时的可读错误。"""
65
+ return [{
66
+ "error": "反搜图引擎要喂公网图片 URL 或本地图片路径作为查询,"
67
+ f"收到的是「{(query or '')[:50]}」",
68
+ "source": engine,
69
+ }]
70
+
71
+
72
+ def _local_image_path(query: str) -> str | None:
73
+ """把 file:// 或本地绝对路径还原成文件系统路径;不是本地引用则返回 None。"""
74
+ q = (query or "").strip()
75
+ if not _LOCAL_REF_RE.match(q):
76
+ return None
77
+ if q.lower().startswith("file:"):
78
+ try:
79
+ path = urllib.request.url2pathname(urllib.parse.urlparse(q).path)
80
+ except ValueError:
81
+ return None
82
+ # file:///D:/x.jpg 的 path 是 /D:/x.jpg;盘符前那个斜杠要去掉。
83
+ if re.match(r"^/[A-Za-z]:", path):
84
+ path = path[1:]
85
+ return path
86
+ return q
87
+
88
+
89
+ def _local_roots() -> list[str]:
90
+ """`ARGO_IMAGE_LOCAL_ROOTS` 允许的目录(os.pathsep 分隔)。
91
+
92
+ 未设置时不限目录(本机 CLI 由人直接调用,路径就是人给的);MCP 宿主
93
+ 里把它设成收图目录,模型便只能把落盘的那几张图送去反搜,而不是任意
94
+ 本地文件(群消息可注入「反搜一下 C:\\...\\id_rsa」这种指令)。
95
+ """
96
+ raw = os.environ.get("ARGO_IMAGE_LOCAL_ROOTS", "")
97
+ return [os.path.realpath(p) for p in raw.split(os.pathsep) if p.strip()]
98
+
99
+
100
+ def _sniff_mime(data: bytes) -> str:
101
+ for magic, mime in _IMAGE_MAGIC:
102
+ if data.startswith(magic):
103
+ if magic == b"RIFF" and data[8:12] != b"WEBP":
104
+ continue
105
+ return mime
106
+ return ""
107
+
108
+
109
+ def _load_local_image(query: str) -> tuple[bytes, str, str] | dict[str, Any]:
110
+ """读本地图片:返回 (bytes, 文件名, mime);失败返回可读 error 条目。"""
111
+ path = _local_image_path(query)
112
+ if not path:
113
+ return {"error": "无法解析本地图片路径", "source": "reverse_image"}
114
+ engine = "reverse_image"
115
+ try:
116
+ st = os.stat(path)
117
+ except OSError as e:
118
+ return {"error": f"读不到本地图片 {path}({type(e).__name__})",
119
+ "source": engine}
120
+ if not stat.S_ISREG(st.st_mode):
121
+ return {"error": f"{path} 不是普通文件", "source": engine}
122
+ if st.st_size > _MAX_LOCAL_BYTES:
123
+ return {"error": f"本地图片 {st.st_size // (1024 * 1024)}MB 超过上限 "
124
+ f"{_MAX_LOCAL_BYTES // (1024 * 1024)}MB", "source": engine}
125
+ roots = _local_roots()
126
+ if roots:
127
+ real = os.path.realpath(path)
128
+ if not any(real == r or real.startswith(r + os.sep) for r in roots):
129
+ return {"error": "本地图片只允许读取已配置的收图目录"
130
+ "(ARGO_IMAGE_LOCAL_ROOTS)", "source": engine}
131
+ try:
132
+ with open(path, "rb") as f:
133
+ data = f.read()
134
+ except OSError as e:
135
+ return {"error": f"读本地图片失败({type(e).__name__})", "source": engine}
136
+ mime = _sniff_mime(data)
137
+ if not mime:
138
+ return {"error": f"{os.path.basename(path)} 不是可识别的图片"
139
+ "(只支持 JPEG/PNG/GIF/WebP/BMP)", "source": engine}
140
+ return data, os.path.basename(path), mime
141
+
142
+
143
+ # ── SauceNAO(二次元图源索引,需免费 API key)───────────────────────────────
144
+
145
+ _SAUCENAO_ENDPOINT = "https://saucenao.com/search.php"
146
+
147
+ # 上游 header.status 的语义(见 saucenao.com 文档);负值都是「没查成」,
148
+ # 不能当「没找到」,否则缺 key 的实例会显得一切正常。
149
+ _SAUCENAO_STATUS_HINT = {
150
+ -1: "匿名档已不允许 API 调用,请在 saucenao.com 注册免费账号并配 ARGO_SAUCENAO_API_KEY",
151
+ -2: "API key 无效或已失效",
152
+ -3: "API 用量超出限制(免费档 150 次/日)",
153
+ -4: "单次请求参数超出限制",
154
+ -5: "上游内部错误,稍后重试",
155
+ }
156
+
157
+
158
+ def _saucenao_source_url(data: dict[str, Any]) -> str:
159
+ """按来源站 ID 还原出处页;SauceNAO 只给 ID,不给页面 URL。"""
160
+ if data.get("pixiv_id"):
161
+ return f"https://www.pixiv.net/artworks/{data['pixiv_id']}"
162
+ if data.get("pawoo_id"):
163
+ return f"https://pawoo.net/@{data.get('pawoo_user_acct', '')}/{data['pawoo_id']}"
164
+ if data.get("getchu_id"):
165
+ return f"https://www.getchu.com/soft.phtml?id={data['getchu_id']}"
166
+ ext = data.get("ext_urls") or []
167
+ if isinstance(ext, list) and ext and isinstance(ext[0], str):
168
+ return ext[0]
169
+ return ""
170
+
171
+
172
+ def _saucenao_author(data: dict[str, Any]) -> str:
173
+ """作者名:不同数据库的字段名不一致,按优先级取第一个非空。"""
174
+ for key in ("author", "member_name", "creator", "twitter_user_handle",
175
+ "pawoo_user_display_name", "author_name", "user_name",
176
+ "artist", "company"):
177
+ val = data.get(key)
178
+ if isinstance(val, list) and val:
179
+ return ", ".join(str(v) for v in val)
180
+ if isinstance(val, str) and val:
181
+ return val
182
+ return ""
183
+
184
+
185
+ def _saucenao_title(data: dict[str, Any], index_name: str) -> str:
186
+ for key in ("title", "material", "jp_name", "eng_name", "source", "created_at"):
187
+ val = data.get(key)
188
+ if isinstance(val, str) and val:
189
+ return val
190
+ return index_name or "SauceNAO 匹配"
191
+
192
+
193
+ def _saucenao_post_file(params: list[tuple[str, str]], data: bytes, filename: str,
194
+ mime: str, timeout: float, engine: str) -> tuple[str | None, str]:
195
+ """multipart 上传本地图片,返回 (响应文本, 错误说明)。
196
+
197
+ SauceNAO 在 Cloudflare 之后,带文件的 POST 也须走 TLS 指纹伪造;`HttpClient`
198
+ 只支持 JSON / urlencode 的 body,multipart 由 curl_cffi 直接发。
199
+ """
200
+ try:
201
+ from curl_cffi import requests as cr
202
+ except ImportError:
203
+ return None, "本地图片需要 curl_cffi(SauceNAO 走 Cloudflare,需指纹伪造)"
204
+ # 0.17 起 curl_cffi 只认 multipart=CurlMime(files= 会抛 NotImplementedError)。
205
+ try:
206
+ from curl_cffi import CurlMime
207
+ mime_body = CurlMime()
208
+ mime_body.addpart("file", filename=filename, content_type=mime, data=data)
209
+ except (ImportError, AttributeError):
210
+ mime_body = None
211
+ proxies = None
212
+ try:
213
+ from net_proxy import resolve_proxy
214
+ p = resolve_proxy(_SAUCENAO_ENDPOINT)
215
+ if p:
216
+ proxies = {"https": p}
217
+ except Exception:
218
+ proxies = None
219
+ last: Exception | None = None
220
+ for fp in ("chrome", "safari"):
221
+ try:
222
+ if mime_body is not None:
223
+ resp = cr.post(_SAUCENAO_ENDPOINT, params=params,
224
+ multipart=mime_body,
225
+ headers={"Accept": "application/json",
226
+ "Referer": "https://saucenao.com/"},
227
+ timeout=timeout, impersonate=fp, proxies=proxies)
228
+ else:
229
+ resp = cr.post(_SAUCENAO_ENDPOINT, params=params,
230
+ files={"file": (filename, data, mime)},
231
+ headers={"Accept": "application/json",
232
+ "Referer": "https://saucenao.com/"},
233
+ timeout=timeout, impersonate=fp, proxies=proxies)
234
+ except Exception as e:
235
+ last = e
236
+ continue
237
+ if resp.status_code == 200:
238
+ return resp.text, ""
239
+ last = RuntimeError(f"HTTP {resp.status_code} · {resp.text[:120]}")
240
+ return None, f"上传失败({type(last).__name__}: {last})"
241
+
242
+
243
+ def _build_saucenao_engine(spec: dict[str, Any]) -> Any:
244
+ """SauceNAO 以图搜图(POST/GET 同一端点,需 API key,走 TLS 指纹伪造过 CF)。"""
245
+ timeout = spec.get("timeout", 20)
246
+ res_cap = int(spec.get("num_results", 5) or 5)
247
+ min_sim = int(spec.get("min_similarity", 30) or 30)
248
+ # hide:0 全显示 / 1 隐藏露骨 / 2 再隐藏疑似 / 3 只留安全内容。群聊默认 1。
249
+ try:
250
+ hide = min(max(int(spec.get("hide", 1)), 0), 3)
251
+ except (TypeError, ValueError):
252
+ hide = 1
253
+ # dedupe:0 不去重 / 1 按条目去重 / 2 连系列一起并(SauceNAO 默认 2)。
254
+ try:
255
+ dedupe = min(max(int(spec.get("dedupe", 2)), 0), 2)
256
+ except (TypeError, ValueError):
257
+ dedupe = 2
258
+
259
+ @safe_search
260
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
261
+ q = (query or "").strip()
262
+ is_local = _local_image_path(q) is not None
263
+ if not is_local and not _IMAGE_URL_RE.match(q):
264
+ return _image_input_error("saucenao", q)
265
+ key = get_env(["ARGO_SAUCENAO_API_KEY", "SAUCENAO_API_KEY"])
266
+ if not key:
267
+ return [{"error": "缺 ARGO_SAUCENAO_API_KEY"
268
+ "(匿名档已不允许 API 调用;saucenao.com 免费注册 150 次/日)",
269
+ "source": "saucenao"}]
270
+ # 用 (键, 值) 列表而不是 dict:dbs[] 是重复键,且 curl_cffi 的 multipart
271
+ # POST 与 urllib 的 GET 都能直接吃列表。
272
+ params: list[tuple[str, str]] = [
273
+ ("testmode", "0"),
274
+ ("numres", str(min(max(int(n), 1), res_cap))),
275
+ ("output_type", "2"),
276
+ ("hide", str(hide)),
277
+ ("dedupe", str(dedupe)),
278
+ ("minsim", str(min_sim)),
279
+ ("api_key", key),
280
+ ]
281
+ dbs = spec.get("dbs")
282
+ if isinstance(dbs, (list, tuple)) and dbs:
283
+ params.extend(("dbs[]", str(i)) for i in dbs)
284
+ else:
285
+ params.append(("db", str(spec.get("db", 999) or 999)))
286
+ if is_local:
287
+ loaded = _load_local_image(q)
288
+ if isinstance(loaded, dict):
289
+ return [loaded]
290
+ data, filename, mime = loaded
291
+ # 原图直传在慢链路上会顶满 20s 引擎超时(实测 2.9 MB 走代理偶发
292
+ # 20s 无响应),缩到 1024px 后相似度不变(95.55 → 95.50)而上传
293
+ # 体积降一个量级。
294
+ shrunk = _shrink_image_bytes(data)
295
+ if shrunk:
296
+ data = shrunk
297
+ mime = "image/jpeg"
298
+ filename = f"{os.path.splitext(filename)[0]}.jpg"
299
+ raw, post_err = _saucenao_post_file(
300
+ params, data, filename, mime, float(_timeout or timeout),
301
+ spec.get("_name", ""),
302
+ )
303
+ if post_err:
304
+ return [{"error": post_err, "source": "saucenao"}]
305
+ else:
306
+ params.append(("url", q))
307
+ url = f"{_SAUCENAO_ENDPOINT}?{urllib.parse.urlencode(params)}"
308
+ raw = _http_get_raw(url, {"Accept": "application/json",
309
+ "Referer": "https://saucenao.com/"},
310
+ _timeout or timeout, engine=spec.get("_name", ""),
311
+ tls_profiles=["chrome", "safari"])
312
+ if not raw:
313
+ return []
314
+ try:
315
+ payload = json.loads(raw)
316
+ except (json.JSONDecodeError, ValueError):
317
+ return []
318
+ if not isinstance(payload, dict):
319
+ return []
320
+ header = payload.get("header")
321
+ status = 0
322
+ if isinstance(header, dict):
323
+ try:
324
+ status = int(header.get("status") or 0)
325
+ except (TypeError, ValueError):
326
+ status = 0
327
+ if status:
328
+ msg = str(header.get("message") or "").strip()
329
+ hint = _SAUCENAO_STATUS_HINT.get(status, "")
330
+ detail = " · ".join(b for b in (f"status {status}", msg, hint) if b)
331
+ return [{"error": detail, "source": "saucenao"}]
332
+ results: list[dict[str, Any]] = []
333
+ seen: set[str] = set()
334
+ for item in payload.get("results") or []:
335
+ if len(results) >= max(1, int(n)):
336
+ break
337
+ if not isinstance(item, dict):
338
+ continue
339
+ item_header = item.get("header") if isinstance(item.get("header"), dict) else {}
340
+ item_data = item.get("data") if isinstance(item.get("data"), dict) else {}
341
+ page_url = _saucenao_source_url(item_data)
342
+ if not page_url or page_url in seen:
343
+ continue
344
+ seen.add(page_url)
345
+ try:
346
+ sim = float(item_header.get("similarity"))
347
+ except (TypeError, ValueError):
348
+ sim = 0.0
349
+ index_name = str(item_header.get("index_name") or "").strip()
350
+ author = _saucenao_author(item_data)
351
+ thumb = str(item_header.get("thumbnail") or "").strip()
352
+ bits = [b for b in (
353
+ f"相似度 {sim:g}%" if sim > 0 else "",
354
+ f"库 {index_name}" if index_name else "",
355
+ f"作者 {author}" if author else "",
356
+ f"素材 {item_data.get('material')}" if item_data.get("material") else "",
357
+ ) if b]
358
+ results.append({
359
+ "title": _saucenao_title(item_data, index_name)[:200],
360
+ "url": page_url,
361
+ "snippet": " · ".join(bits)[:300],
362
+ "source": spec.get("_name") or "saucenao",
363
+ "score": rank_score(min(sim / 100.0, 1.0) if sim > 0 else 0.6, len(results)),
364
+ "metadata": {
365
+ "similarity": sim,
366
+ "index_name": index_name,
367
+ "author": author,
368
+ "thumbnail": thumb,
369
+ "pixiv_id": item_data.get("pixiv_id"),
370
+ "ext_urls": item_data.get("ext_urls") or [],
371
+ },
372
+ **({"image_url": thumb} if thumb else {}),
373
+ })
374
+ return results
375
+ return _engine
376
+
377
+
378
+ # ── Google Lens(SerpAPI 托管,付费档)─────────────────────────────────────
379
+
380
+ _SERPAPI_ENDPOINT = "https://serpapi.com/search.json"
381
+ # Image API:本地图上传换 image_id 的入口(google_lens 的 image_id 参数只认
382
+ # 这个通道发出的 id,10 分钟内有效)。上限 500KB,格式只收 JPEG/PNG/WebP。
383
+ _SERPAPI_IMAGE_ENDPOINT = "https://serpapi.com/image"
384
+ _SERPAPI_IMAGE_MAX_BYTES = 500 * 1024
385
+ _SERPAPI_IMAGE_MIMES = frozenset({"image/jpeg", "image/png", "image/webp"})
386
+
387
+ # 抓取顺序即相关度顺序:先「同一张图」(exact),再「长得像的图」(visual),
388
+ # 最后才是「讲到这张图的网页」(organic)。三者混在一列里必须各自带标,
389
+ # 否则调用方会把「视觉相似的另一张图」当成这张图的出处。
390
+ _GOOGLE_LENS_BUCKETS: tuple[tuple[str, str, float], ...] = (
391
+ ("exact_matches", "精确匹配", 0.95),
392
+ ("visual_matches", "视觉相似", 0.78),
393
+ ("organic_results", "相关网页", 0.6),
394
+ )
395
+
396
+
397
+ def _google_lens_error(status: int, payload_text: str) -> dict[str, Any]:
398
+ """SerpAPI 的错误统一走 `error` 字段(无效 key、额度用尽、上游失败)。"""
399
+ msg = ""
400
+ try:
401
+ obj = json.loads(payload_text)
402
+ except (json.JSONDecodeError, ValueError):
403
+ obj = None
404
+ if isinstance(obj, dict):
405
+ msg = str(obj.get("error") or "").strip()
406
+ if not msg:
407
+ msg = (payload_text or "").strip()[:120]
408
+ detail = " · ".join(b for b in (f"HTTP {status}" if status else "", msg) if b)
409
+ return {"error": detail or "请求失败", "source": "google_lens"}
410
+
411
+
412
+ def _serpapi_upload_image(data: bytes, filename: str, mime: str, key: str,
413
+ timeout: float, engine: str) -> tuple[str, dict[str, Any] | None]:
414
+ """上传本地图到 SerpAPI Image API,返回 (image_id, error)。
415
+
416
+ multipart 由标准库拼装:SerpAPI 不在 Cloudflare 后,不需要 TLS 指纹伪造,
417
+ 走 `http_open` 即可复用全仓的代理与失败归因。
418
+ """
419
+ safe_name = (os.path.basename(filename).replace('"', "")
420
+ .replace("\r", "").replace("\n", ""))
421
+ boundary = f"----argo{os.urandom(12).hex()}"
422
+ head = [
423
+ (f"--{boundary}\r\nContent-Disposition: form-data; "
424
+ f"name=\"api_key\"\r\n\r\n{key}\r\n").encode("utf-8"),
425
+ (f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; "
426
+ f"filename=\"{safe_name}\"\r\nContent-Type: {mime}\r\n\r\n").encode("utf-8"),
427
+ ]
428
+ body = b"".join(head) + data + f"\r\n--{boundary}--\r\n".encode("utf-8")
429
+ req = urllib.request.Request(
430
+ _SERPAPI_IMAGE_ENDPOINT, data=body, method="POST",
431
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}",
432
+ "Accept": "application/json"},
433
+ )
434
+ try:
435
+ with http_open(req, timeout=timeout, engine=engine) as resp:
436
+ raw = resp.read().decode("utf-8", errors="replace")
437
+ except urllib.error.HTTPError as e:
438
+ payload = ""
439
+ try:
440
+ payload = e.read().decode("utf-8", errors="replace")[:400]
441
+ except OSError:
442
+ payload = ""
443
+ return "", _google_lens_error(e.code, payload)
444
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
445
+ return "", {"error": f"SerpAPI 图片上传失败({type(e).__name__})",
446
+ "source": "google_lens"}
447
+ try:
448
+ payload = json.loads(raw)
449
+ except (json.JSONDecodeError, ValueError):
450
+ return "", {"error": "SerpAPI 图片上传返回了非 JSON 响应",
451
+ "source": "google_lens"}
452
+ if not isinstance(payload, dict):
453
+ return "", {"error": "SerpAPI 图片上传返回了非对象响应",
454
+ "source": "google_lens"}
455
+ if payload.get("error"):
456
+ return "", {"error": str(payload["error"])[:200], "source": "google_lens"}
457
+ image_id = str(payload.get("image_id") or "").strip()
458
+ if not image_id:
459
+ return "", {"error": "SerpAPI 图片上传成功但没有返回 image_id",
460
+ "source": "google_lens"}
461
+ return image_id, None
462
+
463
+
464
+ def _google_lens_item(item: dict[str, Any], match_label: str, base: float,
465
+ index: int, engine_name: str) -> dict[str, Any] | None:
466
+ """把一条 Lens 条目归一成 Argo 结果;没有可用链接的条目直接丢弃。"""
467
+ link = str(item.get("link") or "").strip()
468
+ if not link:
469
+ return None
470
+ title = str(item.get("title") or "").strip()
471
+ site = str(item.get("source") or "").strip()
472
+ if not title:
473
+ title = site or link
474
+ thumb = str(item.get("thumbnail") or "").strip()
475
+ image = str(item.get("image") or "").strip()
476
+ price = item.get("price")
477
+ price_txt = ""
478
+ if isinstance(price, dict):
479
+ price_txt = str(price.get("value") or price.get("extracted_value") or "").strip()
480
+ elif isinstance(price, str):
481
+ price_txt = price.strip()
482
+ bits = [b for b in (
483
+ match_label,
484
+ f"站点 {site}" if site else "",
485
+ price_txt,
486
+ str(item.get("snippet") or "").strip()[:160],
487
+ ) if b]
488
+ result: dict[str, Any] = {
489
+ "title": title[:200],
490
+ "url": link,
491
+ "snippet": " · ".join(bits)[:300],
492
+ "source": engine_name or "google_lens",
493
+ "score": rank_score(base, index),
494
+ "metadata": {
495
+ "match_type": match_label,
496
+ "site": site,
497
+ "thumbnail": thumb,
498
+ "image": image,
499
+ "position": item.get("position"),
500
+ },
501
+ }
502
+ if thumb:
503
+ result["image_url"] = thumb
504
+ return result
505
+
506
+
507
+ def _build_google_lens_engine(spec: dict[str, Any]) -> Any:
508
+ """Google Lens 反搜图(SerpAPI 托管:付费档,按次计费,免费额度 250 次/月)。"""
509
+ timeout = spec.get("timeout", 30)
510
+ search_type = str(spec.get("search_type") or "all").strip()
511
+ if search_type not in {"all", "exact_matches", "visual_matches"}:
512
+ search_type = "all"
513
+ hl = str(spec.get("hl") or "").strip()
514
+ country = str(spec.get("country") or "").strip()
515
+ res_cap = int(spec.get("num_results", 8) or 8)
516
+
517
+ @safe_search
518
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
519
+ q = (query or "").strip()
520
+ is_local = _local_image_path(q) is not None
521
+ if not is_local and not _IMAGE_URL_RE.match(q):
522
+ return _image_input_error("google_lens", q)
523
+ key = get_env(["ARGO_SERPAPI_API_KEY", "SERPAPI_API_KEY"])
524
+ if not key:
525
+ return [{"error": "缺 ARGO_SERPAPI_API_KEY"
526
+ "(serpapi.com 注册后免费 250 次/月)",
527
+ "source": "google_lens"}]
528
+ params = {
529
+ "engine": "google_lens",
530
+ "type": search_type,
531
+ "api_key": key,
532
+ }
533
+ if hl:
534
+ params["hl"] = hl
535
+ if country:
536
+ params["country"] = country
537
+ if is_local:
538
+ loaded = _load_local_image(q)
539
+ if isinstance(loaded, dict):
540
+ loaded["source"] = "google_lens"
541
+ return [loaded]
542
+ data, filename, mime = loaded
543
+ if mime not in _SERPAPI_IMAGE_MIMES:
544
+ return [{"error": "SerpAPI 图片上传只收 JPEG/PNG/WebP,"
545
+ f"这张是 {mime};请先另存为 JPEG",
546
+ "source": "google_lens"}]
547
+ # 500KB 是 Image API 的硬上限;原图多半超,缩到 1024px 仍认得出,
548
+ # 仍超再退 768/512(每一步都是重新编码,最多三轮)。
549
+ stem = os.path.splitext(filename)[0]
550
+ for side in (1024, 768, 512):
551
+ if len(data) <= _SERPAPI_IMAGE_MAX_BYTES:
552
+ break
553
+ shrunk = _shrink_image_bytes(data, side)
554
+ if shrunk:
555
+ data, mime = shrunk, "image/jpeg"
556
+ filename = f"{stem}.jpg"
557
+ if len(data) > _SERPAPI_IMAGE_MAX_BYTES:
558
+ return [{"error": f"SerpAPI 图片上限 500KB,这张仍有 "
559
+ f"{len(data) // 1024}KB;请先压缩后再搜",
560
+ "source": "google_lens"}]
561
+ image_id, up_err = _serpapi_upload_image(
562
+ data, filename, mime, key, float(_timeout or timeout),
563
+ spec.get("_name", ""),
564
+ )
565
+ if up_err:
566
+ return [up_err]
567
+ params["image_id"] = image_id
568
+ else:
569
+ params["url"] = q
570
+ url = f"{_SERPAPI_ENDPOINT}?{urllib.parse.urlencode(params)}"
571
+ req = urllib.request.Request(url, headers={"Accept": "application/json"})
572
+ try:
573
+ with http_open(req, timeout=_timeout or timeout, engine=spec.get("_name", "")) as resp:
574
+ raw = resp.read().decode("utf-8", errors="replace")
575
+ except urllib.error.HTTPError as e:
576
+ payload = ""
577
+ try:
578
+ payload = e.read().decode("utf-8", errors="replace")[:400]
579
+ except OSError:
580
+ payload = ""
581
+ return [_google_lens_error(e.code, payload)]
582
+ except (urllib.error.URLError, TimeoutError, OSError):
583
+ return []
584
+ try:
585
+ payload = json.loads(raw)
586
+ except (json.JSONDecodeError, ValueError):
587
+ return []
588
+ if not isinstance(payload, dict):
589
+ return []
590
+ if payload.get("error"):
591
+ return [_google_lens_error(0, raw)]
592
+ cap = min(max(int(n), 1), res_cap)
593
+ results: list[dict[str, Any]] = []
594
+ seen: set[str] = set()
595
+ for bucket, label, base in _GOOGLE_LENS_BUCKETS:
596
+ for item in payload.get(bucket) or []:
597
+ if len(results) >= cap:
598
+ return results
599
+ if not isinstance(item, dict):
600
+ continue
601
+ link = str(item.get("link") or "").strip()
602
+ if link in seen:
603
+ continue
604
+ parsed = _google_lens_item(item, label, base, len(results), spec.get("_name", ""))
605
+ if parsed is None:
606
+ continue
607
+ seen.add(link)
608
+ results.append(parsed)
609
+ return results
610
+ return _engine
611
+
612
+
613
+ # ── AnimeTrace(动漫角色识别,免 key、按 IP 限频)────────────────────────────
614
+
615
+ _ANIMETRACE_ENDPOINT = "https://api.animetrace.com/v1/search"
616
+
617
+ # 已实测到的业务码:17728 配额用尽、17737 频率限制。其余码只在 error 里透传原码。
618
+ _ANIMETRACE_CODE_HINT = {
619
+ 17728: "用量上限(配额已用尽,次日或换 key 再试)",
620
+ 17737: "触发频率限制(稍后重试)",
621
+ }
622
+
623
+
624
+ def _animetrace_error(status: int, payload: str) -> dict[str, Any]:
625
+ """把 HTTP 状态 + 上游业务码合成一条可读错误。"""
626
+ code: Any = None
627
+ msg = ""
628
+ try:
629
+ obj = json.loads(payload)
630
+ except (json.JSONDecodeError, ValueError):
631
+ obj = None
632
+ if isinstance(obj, dict):
633
+ code = obj.get("code")
634
+ msg = str(obj.get("zh_message") or obj.get("message") or obj.get("msg") or "").strip()
635
+ elif payload:
636
+ msg = payload.strip()[:120]
637
+ hint = _ANIMETRACE_CODE_HINT.get(code) if isinstance(code, int) else None
638
+ detail = " · ".join(b for b in (
639
+ f"HTTP {status}" if status else "",
640
+ f"code {code}" if code is not None else "",
641
+ msg,
642
+ hint or "",
643
+ ) if b)
644
+ return {"error": detail or "请求失败", "source": "animetrace"}
645
+
646
+
647
+ def _bgm_search_url(work: str) -> str:
648
+ """作品检索入口:AnimeTrace 只给作品名/角色名,不给出处页。
649
+
650
+ 这里给的是 Bangumi 的作品检索页——「下一步去哪儿查证」的确定性入口,
651
+ 不是宣称这张图就出自该页。url 槽必须非空(serp_guard 会丢弃空 url 条目),
652
+ 而填一张不存在的原文页就是造假,故取检索页并如实标注。
653
+ """
654
+ return f"https://bgm.tv/subject_search/{urllib.parse.quote(work)}"
655
+
656
+
657
+ def _shrink_image_bytes(data: bytes, max_side: int = 1024) -> bytes | None:
658
+ """把图片转成长边 ≤ max_side 的 JPEG;Pillow 缺失或解码失败返回 None。"""
659
+ try:
660
+ from PIL import Image as _PILImage
661
+ except ImportError:
662
+ return None
663
+ try:
664
+ img = _PILImage.open(io.BytesIO(data))
665
+ img.load()
666
+ except Exception:
667
+ return None
668
+ if max(img.size) > max_side:
669
+ img.thumbnail((max_side, max_side))
670
+ buf = io.BytesIO()
671
+ img.convert("RGB").save(buf, "JPEG", quality=88)
672
+ return buf.getvalue()
673
+
674
+
675
+ def _image_to_base64(data: bytes, max_side: int = 1024) -> str:
676
+ """把本地图片压成 base64(长边 ≤ max_side 的 JPEG)。
677
+
678
+ AnimeTrace 的 base64 入参对体积敏感(实测 2.9 MB 原图直传会被上游拒),
679
+ 而缩到 1024px 后仍能认出角色与作品。
680
+ """
681
+ shrunk = _shrink_image_bytes(data, max_side)
682
+ return base64.b64encode(shrunk or data).decode("ascii")
683
+
684
+
685
+ def _build_animetrace_engine(spec: dict[str, Any]) -> Any:
686
+ """AnimeTrace 角色识别(免 key,POST JSON 传图片 URL)。"""
687
+ timeout = spec.get("timeout", 20)
688
+ model = str(spec.get("model") or "").strip()
689
+ is_multi = 1 if spec.get("is_multi") else 0
690
+
691
+ @safe_search
692
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
693
+ q = (query or "").strip()
694
+ is_local = _local_image_path(q) is not None
695
+ if not is_local and not _IMAGE_URL_RE.match(q):
696
+ return _image_input_error("animetrace", q)
697
+ body: dict[str, Any] = {}
698
+ if is_local:
699
+ loaded = _load_local_image(q)
700
+ if isinstance(loaded, dict):
701
+ return [loaded]
702
+ body["base64"] = _image_to_base64(loaded[0])
703
+ else:
704
+ body["url"] = q
705
+ if is_multi:
706
+ body["is_multi"] = 1
707
+ if model:
708
+ body["model"] = model
709
+ req = urllib.request.Request(
710
+ _ANIMETRACE_ENDPOINT,
711
+ data=json.dumps(body).encode("utf-8"),
712
+ headers={
713
+ "Content-Type": "application/json",
714
+ "Accept": "application/json",
715
+ "Referer": "https://www.animetrace.com/",
716
+ "Origin": "https://www.animetrace.com",
717
+ },
718
+ )
719
+ try:
720
+ with http_open(req, timeout=_timeout or timeout, engine=spec.get("_name", "")) as resp:
721
+ raw = resp.read().decode("utf-8", errors="replace")
722
+ except urllib.error.HTTPError as e:
723
+ payload = ""
724
+ try:
725
+ payload = e.read().decode("utf-8", errors="replace")[:400]
726
+ except OSError:
727
+ payload = ""
728
+ return [_animetrace_error(e.code, payload)]
729
+ except (urllib.error.URLError, TimeoutError, OSError):
730
+ return []
731
+ try:
732
+ payload = json.loads(raw)
733
+ except (json.JSONDecodeError, ValueError):
734
+ return []
735
+ if not isinstance(payload, dict):
736
+ return []
737
+ code = payload.get("code")
738
+ if code not in (0, None):
739
+ return [_animetrace_error(0, raw)]
740
+ trace_id = str(payload.get("trace_id") or "")
741
+ results: list[dict[str, Any]] = []
742
+ seen: set[tuple[str, str]] = set()
743
+ for box in payload.get("data") or []:
744
+ if len(results) >= max(1, int(n)):
745
+ break
746
+ if not isinstance(box, dict):
747
+ continue
748
+ not_confident = bool(box.get("not_confident"))
749
+ for char in box.get("character") or []:
750
+ if not isinstance(char, dict):
751
+ continue
752
+ work = str(char.get("work") or "").strip()
753
+ name = str(char.get("character") or "").strip()
754
+ if not work and not name:
755
+ continue
756
+ key = (work, name)
757
+ if key in seen:
758
+ continue
759
+ seen.add(key)
760
+ title = " · ".join(b for b in (work, name) if b) or "AnimeTrace 角色识别"
761
+ bits = [b for b in (
762
+ f"角色 {name}" if name else "",
763
+ f"作品 {work}" if work else "",
764
+ "低置信(建议人工复核)" if not_confident else "",
765
+ ) if b]
766
+ results.append({
767
+ "title": title[:200],
768
+ "url": _bgm_search_url(work or name),
769
+ "snippet": " · ".join(bits)[:300],
770
+ "source": spec.get("_name") or "animetrace",
771
+ "score": rank_score(0.55 if not_confident else 0.8, len(results)),
772
+ "metadata": {
773
+ "work": work,
774
+ "character": name,
775
+ "not_confident": not_confident,
776
+ "box": box.get("box"),
777
+ "trace_id": trace_id,
778
+ },
779
+ })
780
+ if len(results) >= max(1, int(n)):
781
+ break
782
+ return results
783
+ return _engine