argo-search 2.10.2 → 2.12.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 (86) hide show
  1. package/README.en.md +36 -21
  2. package/README.es.md +35 -20
  3. package/README.ja.md +36 -21
  4. package/README.ko.md +35 -20
  5. package/README.md +41 -22
  6. package/SKILL.md +19 -18
  7. package/backends/domain_profiles.json +30 -6
  8. package/backends/engine_registry.yaml +63 -13
  9. package/backends/quota_profiles.json +50 -10
  10. package/bin/argo +13 -0
  11. package/config.yaml +34 -20
  12. package/docs/ENGINE_CATALOG.md +14 -9
  13. package/docs/MCP_SETUP.md +16 -4
  14. package/docs/RELEASE_NOTES_v2.11.2.md +166 -0
  15. package/docs/RELEASE_NOTES_v2.12.0.md +65 -0
  16. package/docs/engines/pixiv.md +27 -0
  17. package/engines/specs/animetrace.yaml +35 -0
  18. package/engines/specs/google_lens.yaml +50 -0
  19. package/engines/specs/pixiv.yaml +52 -0
  20. package/engines/specs/saucenao.yaml +45 -0
  21. package/engines/specs/tracemoe.yaml +33 -0
  22. package/package.json +4 -2
  23. package/packages/dsh-plugin/README.md +20 -11
  24. package/packages/dsh-plugin/dsh/client.js +3 -3
  25. package/packages/dsh-plugin/dsh/index.js +27 -176
  26. package/packages/dsh-plugin/dsh/runner.js +19 -3
  27. package/packages/dsh-plugin/dsh/specs.js +133 -0
  28. package/packages/dsh-plugin/package.json +10 -2
  29. package/packages/dsh-plugin/test/client.test.js +4 -4
  30. package/packages/dsh-plugin/test/diagnostics.test.js +1 -1
  31. package/packages/dsh-plugin/test/index.test.js +49 -2
  32. package/scripts/adaptive.py +101 -27
  33. package/scripts/budget.py +13 -3
  34. package/scripts/build_route_labels.py +122 -169
  35. package/scripts/caliber_dedupe.py +4 -4
  36. package/scripts/caliber_isolation.py +17 -17
  37. package/scripts/concept_lookup.py +14 -1
  38. package/scripts/config.py +21 -3
  39. package/scripts/engine_admission.py +35 -17
  40. package/scripts/engine_dispatch.py +18 -17
  41. package/scripts/engine_env.py +4 -0
  42. package/scripts/engine_families.py +10 -4
  43. package/scripts/engines.py +15 -2
  44. package/scripts/engines_base.py +1 -1
  45. package/scripts/engines_builders.py +0 -1
  46. package/scripts/engines_builders_data.py +10 -10
  47. package/scripts/engines_builders_intl.py +4 -4
  48. package/scripts/engines_builders_pixiv.py +633 -0
  49. package/scripts/engines_builders_reverse_image.py +958 -0
  50. package/scripts/engines_builders_tech.py +0 -78
  51. package/scripts/env_store.py +216 -0
  52. package/scripts/extend_route_labels_by_capability.py +4 -4
  53. package/scripts/extend_route_labels_by_language.py +306 -0
  54. package/scripts/extend_route_labels_full_coverage.py +329 -0
  55. package/scripts/fetch_v3.py +74 -5
  56. package/scripts/image_vision/vision_probe +0 -0
  57. package/scripts/job.py +33 -7
  58. package/scripts/lint_spec_contracts.py +110 -0
  59. package/scripts/lint_stub_targets.py +130 -0
  60. package/scripts/local_image.py +25 -11
  61. package/scripts/mcp_compact.py +13 -0
  62. package/scripts/mcp_launch.sh +1 -1
  63. package/scripts/mcp_setup.py +85 -1
  64. package/scripts/mcp_transport.py +1 -1
  65. package/scripts/net_proxy.py +47 -0
  66. package/scripts/plan.py +11 -0
  67. package/scripts/pre-commit +24 -13
  68. package/scripts/query_signals.py +35 -20
  69. package/scripts/quota.py +116 -12
  70. package/scripts/recovery.py +38 -13
  71. package/scripts/redskill/redskill_engine.py +33 -10
  72. package/scripts/route.py +2 -2
  73. package/scripts/route_accuracy_eval.py +2 -2
  74. package/scripts/route_combo.py +22 -3
  75. package/scripts/route_domains.py +182 -50
  76. package/scripts/search.py +13 -14
  77. package/scripts/search_entry.py +38 -42
  78. package/scripts/search_output.py +3 -0
  79. package/scripts/search_pipeline.py +18 -23
  80. package/scripts/search_rank.py +22 -7
  81. package/scripts/serp_guard.py +7 -16
  82. package/scripts/settings_page.py +486 -0
  83. package/scripts/social_engines/twitter_engine.py +35 -2
  84. package/scripts/social_engines/xiaohongshu_engine.py +25 -0
  85. package/scripts/straggler_policy.py +8 -4
  86. package/scripts/tfidf_router.py +82 -24
@@ -0,0 +1,958 @@
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
+ pixiv_id = item_data.get("pixiv_id")
353
+ bits = [b for b in (
354
+ f"相似度 {sim:g}%" if sim > 0 else "",
355
+ f"作品 {pixiv_id}" if pixiv_id else "",
356
+ f"库 {index_name}" if index_name else "",
357
+ f"作者 {author}" if author else "",
358
+ f"素材 {item_data.get('material')}" if item_data.get("material") else "",
359
+ ) if b]
360
+ results.append({
361
+ "title": _saucenao_title(item_data, index_name)[:200],
362
+ "url": page_url,
363
+ "snippet": " · ".join(bits)[:300],
364
+ "author": author,
365
+ "similarity": sim,
366
+ "source": spec.get("_name") or "saucenao",
367
+ "score": rank_score(min(sim / 100.0, 1.0) if sim > 0 else 0.6, len(results)),
368
+ "metadata": {
369
+ "similarity": sim,
370
+ "index_name": index_name,
371
+ "author": author,
372
+ "thumbnail": thumb,
373
+ "pixiv_id": item_data.get("pixiv_id"),
374
+ "ext_urls": item_data.get("ext_urls") or [],
375
+ },
376
+ **({"image_url": thumb} if thumb else {}),
377
+ })
378
+ return results
379
+ return _engine
380
+
381
+
382
+ # ── Google Lens(SerpAPI 托管,付费档)─────────────────────────────────────
383
+
384
+ _SERPAPI_ENDPOINT = "https://serpapi.com/search.json"
385
+ # Image API:本地图上传换 image_id 的入口(google_lens 的 image_id 参数只认
386
+ # 这个通道发出的 id,10 分钟内有效)。上限 500KB,格式只收 JPEG/PNG/WebP。
387
+ _SERPAPI_IMAGE_ENDPOINT = "https://serpapi.com/image"
388
+ _SERPAPI_IMAGE_MAX_BYTES = 500 * 1024
389
+ _SERPAPI_IMAGE_MIMES = frozenset({"image/jpeg", "image/png", "image/webp"})
390
+
391
+ # 抓取顺序即相关度顺序:先「同一张图」(exact),再「长得像的图」(visual),
392
+ # 最后才是「讲到这张图的网页」(organic)。三者混在一列里必须各自带标,
393
+ # 否则调用方会把「视觉相似的另一张图」当成这张图的出处。
394
+ _GOOGLE_LENS_BUCKETS: tuple[tuple[str, str, float], ...] = (
395
+ ("exact_matches", "精确匹配", 0.95),
396
+ ("visual_matches", "视觉相似", 0.78),
397
+ ("organic_results", "相关网页", 0.6),
398
+ )
399
+
400
+
401
+ def _google_lens_error(status: int, payload_text: str) -> dict[str, Any]:
402
+ """SerpAPI 的错误统一走 `error` 字段(无效 key、额度用尽、上游失败)。"""
403
+ msg = ""
404
+ try:
405
+ obj = json.loads(payload_text)
406
+ except (json.JSONDecodeError, ValueError):
407
+ obj = None
408
+ if isinstance(obj, dict):
409
+ msg = str(obj.get("error") or "").strip()
410
+ if not msg:
411
+ msg = (payload_text or "").strip()[:120]
412
+ detail = " · ".join(b for b in (f"HTTP {status}" if status else "", msg) if b)
413
+ return {"error": detail or "请求失败", "source": "google_lens"}
414
+
415
+
416
+ def _serpapi_upload_image(data: bytes, filename: str, mime: str, key: str,
417
+ timeout: float, engine: str) -> tuple[str, dict[str, Any] | None]:
418
+ """上传本地图到 SerpAPI Image API,返回 (image_id, error)。
419
+
420
+ multipart 由标准库拼装:SerpAPI 不在 Cloudflare 后,不需要 TLS 指纹伪造,
421
+ 走 `http_open` 即可复用全仓的代理与失败归因。
422
+ """
423
+ safe_name = (os.path.basename(filename).replace('"', "")
424
+ .replace("\r", "").replace("\n", ""))
425
+ boundary = f"----argo{os.urandom(12).hex()}"
426
+ head = [
427
+ (f"--{boundary}\r\nContent-Disposition: form-data; "
428
+ f"name=\"api_key\"\r\n\r\n{key}\r\n").encode("utf-8"),
429
+ (f"--{boundary}\r\nContent-Disposition: form-data; name=\"image\"; "
430
+ f"filename=\"{safe_name}\"\r\nContent-Type: {mime}\r\n\r\n").encode("utf-8"),
431
+ ]
432
+ body = b"".join(head) + data + f"\r\n--{boundary}--\r\n".encode("utf-8")
433
+ req = urllib.request.Request(
434
+ _SERPAPI_IMAGE_ENDPOINT, data=body, method="POST",
435
+ headers={"Content-Type": f"multipart/form-data; boundary={boundary}",
436
+ "Accept": "application/json"},
437
+ )
438
+ try:
439
+ with http_open(req, timeout=timeout, engine=engine) as resp:
440
+ raw = resp.read().decode("utf-8", errors="replace")
441
+ except urllib.error.HTTPError as e:
442
+ payload = ""
443
+ try:
444
+ payload = e.read().decode("utf-8", errors="replace")[:400]
445
+ except OSError:
446
+ payload = ""
447
+ return "", _google_lens_error(e.code, payload)
448
+ except (urllib.error.URLError, TimeoutError, OSError) as e:
449
+ return "", {"error": f"SerpAPI 图片上传失败({type(e).__name__})",
450
+ "source": "google_lens"}
451
+ try:
452
+ payload = json.loads(raw)
453
+ except (json.JSONDecodeError, ValueError):
454
+ return "", {"error": "SerpAPI 图片上传返回了非 JSON 响应",
455
+ "source": "google_lens"}
456
+ if not isinstance(payload, dict):
457
+ return "", {"error": "SerpAPI 图片上传返回了非对象响应",
458
+ "source": "google_lens"}
459
+ if payload.get("error"):
460
+ return "", {"error": str(payload["error"])[:200], "source": "google_lens"}
461
+ image_id = str(payload.get("image_id") or "").strip()
462
+ if not image_id:
463
+ return "", {"error": "SerpAPI 图片上传成功但没有返回 image_id",
464
+ "source": "google_lens"}
465
+ return image_id, None
466
+
467
+
468
+ def _google_lens_item(item: dict[str, Any], match_label: str, base: float,
469
+ index: int, engine_name: str) -> dict[str, Any] | None:
470
+ """把一条 Lens 条目归一成 Argo 结果;没有可用链接的条目直接丢弃。"""
471
+ link = str(item.get("link") or "").strip()
472
+ if not link:
473
+ return None
474
+ title = str(item.get("title") or "").strip()
475
+ site = str(item.get("source") or "").strip()
476
+ if not title:
477
+ title = site or link
478
+ thumb = str(item.get("thumbnail") or "").strip()
479
+ image = str(item.get("image") or "").strip()
480
+ price = item.get("price")
481
+ price_txt = ""
482
+ if isinstance(price, dict):
483
+ price_txt = str(price.get("value") or price.get("extracted_value") or "").strip()
484
+ elif isinstance(price, str):
485
+ price_txt = price.strip()
486
+ bits = [b for b in (
487
+ match_label,
488
+ f"站点 {site}" if site else "",
489
+ price_txt,
490
+ str(item.get("snippet") or "").strip()[:160],
491
+ ) if b]
492
+ result: dict[str, Any] = {
493
+ "title": title[:200],
494
+ "url": link,
495
+ "snippet": " · ".join(bits)[:300],
496
+ "source": engine_name or "google_lens",
497
+ "score": rank_score(base, index),
498
+ "metadata": {
499
+ "match_type": match_label,
500
+ "site": site,
501
+ "thumbnail": thumb,
502
+ "image": image,
503
+ "position": item.get("position"),
504
+ },
505
+ }
506
+ if thumb:
507
+ result["image_url"] = thumb
508
+ return result
509
+
510
+
511
+ def _build_google_lens_engine(spec: dict[str, Any]) -> Any:
512
+ """Google Lens 反搜图(SerpAPI 托管:付费档,按次计费,免费额度 250 次/月)。"""
513
+ timeout = spec.get("timeout", 30)
514
+ search_type = str(spec.get("search_type") or "all").strip()
515
+ if search_type not in {"all", "exact_matches", "visual_matches"}:
516
+ search_type = "all"
517
+ hl = str(spec.get("hl") or "").strip()
518
+ country = str(spec.get("country") or "").strip()
519
+ res_cap = int(spec.get("num_results", 8) or 8)
520
+
521
+ @safe_search
522
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
523
+ q = (query or "").strip()
524
+ is_local = _local_image_path(q) is not None
525
+ if not is_local and not _IMAGE_URL_RE.match(q):
526
+ return _image_input_error("google_lens", q)
527
+ key = get_env(["ARGO_SERPAPI_API_KEY", "SERPAPI_API_KEY"])
528
+ if not key:
529
+ return [{"error": "缺 ARGO_SERPAPI_API_KEY"
530
+ "(serpapi.com 注册后免费 250 次/月)",
531
+ "source": "google_lens"}]
532
+ params = {
533
+ "engine": "google_lens",
534
+ "type": search_type,
535
+ "api_key": key,
536
+ }
537
+ if hl:
538
+ params["hl"] = hl
539
+ if country:
540
+ params["country"] = country
541
+ if is_local:
542
+ loaded = _load_local_image(q)
543
+ if isinstance(loaded, dict):
544
+ loaded["source"] = "google_lens"
545
+ return [loaded]
546
+ data, filename, mime = loaded
547
+ if mime not in _SERPAPI_IMAGE_MIMES:
548
+ return [{"error": "SerpAPI 图片上传只收 JPEG/PNG/WebP,"
549
+ f"这张是 {mime};请先另存为 JPEG",
550
+ "source": "google_lens"}]
551
+ # 500KB 是 Image API 的硬上限;原图多半超,缩到 1024px 仍认得出,
552
+ # 仍超再退 768/512(每一步都是重新编码,最多三轮)。
553
+ stem = os.path.splitext(filename)[0]
554
+ for side in (1024, 768, 512):
555
+ if len(data) <= _SERPAPI_IMAGE_MAX_BYTES:
556
+ break
557
+ shrunk = _shrink_image_bytes(data, side)
558
+ if shrunk:
559
+ data, mime = shrunk, "image/jpeg"
560
+ filename = f"{stem}.jpg"
561
+ if len(data) > _SERPAPI_IMAGE_MAX_BYTES:
562
+ return [{"error": f"SerpAPI 图片上限 500KB,这张仍有 "
563
+ f"{len(data) // 1024}KB;请先压缩后再搜",
564
+ "source": "google_lens"}]
565
+ image_id, up_err = _serpapi_upload_image(
566
+ data, filename, mime, key, float(_timeout or timeout),
567
+ spec.get("_name", ""),
568
+ )
569
+ if up_err:
570
+ return [up_err]
571
+ params["image_id"] = image_id
572
+ else:
573
+ params["url"] = q
574
+ url = f"{_SERPAPI_ENDPOINT}?{urllib.parse.urlencode(params)}"
575
+ req = urllib.request.Request(url, headers={"Accept": "application/json"})
576
+ try:
577
+ with http_open(req, timeout=_timeout or timeout, engine=spec.get("_name", "")) as resp:
578
+ raw = resp.read().decode("utf-8", errors="replace")
579
+ except urllib.error.HTTPError as e:
580
+ payload = ""
581
+ try:
582
+ payload = e.read().decode("utf-8", errors="replace")[:400]
583
+ except OSError:
584
+ payload = ""
585
+ return [_google_lens_error(e.code, payload)]
586
+ except (urllib.error.URLError, TimeoutError, OSError):
587
+ return []
588
+ try:
589
+ payload = json.loads(raw)
590
+ except (json.JSONDecodeError, ValueError):
591
+ return []
592
+ if not isinstance(payload, dict):
593
+ return []
594
+ if payload.get("error"):
595
+ return [_google_lens_error(0, raw)]
596
+ cap = min(max(int(n), 1), res_cap)
597
+ results: list[dict[str, Any]] = []
598
+ seen: set[str] = set()
599
+ for bucket, label, base in _GOOGLE_LENS_BUCKETS:
600
+ for item in payload.get(bucket) or []:
601
+ if len(results) >= cap:
602
+ return results
603
+ if not isinstance(item, dict):
604
+ continue
605
+ link = str(item.get("link") or "").strip()
606
+ if link in seen:
607
+ continue
608
+ parsed = _google_lens_item(item, label, base, len(results), spec.get("_name", ""))
609
+ if parsed is None:
610
+ continue
611
+ seen.add(link)
612
+ results.append(parsed)
613
+ return results
614
+ return _engine
615
+
616
+
617
+ # ── AnimeTrace(动漫角色识别,免 key、按 IP 限频)────────────────────────────
618
+
619
+ _ANIMETRACE_ENDPOINT = "https://api.animetrace.com/v1/search"
620
+
621
+ # 已实测到的业务码:17728 配额用尽、17737 频率限制。其余码只在 error 里透传原码。
622
+ _ANIMETRACE_CODE_HINT = {
623
+ 17728: "用量上限(配额已用尽,次日或换 key 再试)",
624
+ 17737: "触发频率限制(稍后重试)",
625
+ }
626
+
627
+
628
+ def _animetrace_error(status: int, payload: str) -> dict[str, Any]:
629
+ """把 HTTP 状态 + 上游业务码合成一条可读错误。"""
630
+ code: Any = None
631
+ msg = ""
632
+ try:
633
+ obj = json.loads(payload)
634
+ except (json.JSONDecodeError, ValueError):
635
+ obj = None
636
+ if isinstance(obj, dict):
637
+ code = obj.get("code")
638
+ msg = str(obj.get("zh_message") or obj.get("message") or obj.get("msg") or "").strip()
639
+ elif payload:
640
+ msg = payload.strip()[:120]
641
+ hint = _ANIMETRACE_CODE_HINT.get(code) if isinstance(code, int) else None
642
+ detail = " · ".join(b for b in (
643
+ f"HTTP {status}" if status else "",
644
+ f"code {code}" if code is not None else "",
645
+ msg,
646
+ hint or "",
647
+ ) if b)
648
+ return {"error": detail or "请求失败", "source": "animetrace"}
649
+
650
+
651
+ def _bgm_search_url(work: str) -> str:
652
+ """作品检索入口:AnimeTrace 只给作品名/角色名,不给出处页。
653
+
654
+ 这里给的是 Bangumi 的作品检索页——「下一步去哪儿查证」的确定性入口,
655
+ 不是宣称这张图就出自该页。url 槽必须非空(serp_guard 会丢弃空 url 条目),
656
+ 而填一张不存在的原文页就是造假,故取检索页并如实标注。
657
+ """
658
+ return f"https://bgm.tv/subject_search/{urllib.parse.quote(work)}"
659
+
660
+
661
+ def _shrink_image_bytes(data: bytes, max_side: int = 1024) -> bytes | None:
662
+ """把图片转成长边 ≤ max_side 的 JPEG;Pillow 缺失或解码失败返回 None。"""
663
+ try:
664
+ from PIL import Image as _PILImage
665
+ except ImportError:
666
+ return None
667
+ try:
668
+ img = _PILImage.open(io.BytesIO(data))
669
+ img.load()
670
+ except Exception:
671
+ return None
672
+ if max(img.size) > max_side:
673
+ img.thumbnail((max_side, max_side))
674
+ buf = io.BytesIO()
675
+ img.convert("RGB").save(buf, "JPEG", quality=88)
676
+ return buf.getvalue()
677
+
678
+
679
+ def _image_to_base64(data: bytes, max_side: int = 1024) -> str:
680
+ """把本地图片压成 base64(长边 ≤ max_side 的 JPEG)。
681
+
682
+ AnimeTrace 的 base64 入参对体积敏感(实测 2.9 MB 原图直传会被上游拒),
683
+ 而缩到 1024px 后仍能认出角色与作品。
684
+ """
685
+ shrunk = _shrink_image_bytes(data, max_side)
686
+ return base64.b64encode(shrunk or data).decode("ascii")
687
+
688
+
689
+ def _build_animetrace_engine(spec: dict[str, Any]) -> Any:
690
+ """AnimeTrace 角色识别(免 key,POST JSON 传图片 URL)。"""
691
+ timeout = spec.get("timeout", 20)
692
+ model = str(spec.get("model") or "").strip()
693
+ is_multi = 1 if spec.get("is_multi") else 0
694
+
695
+ @safe_search
696
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
697
+ q = (query or "").strip()
698
+ is_local = _local_image_path(q) is not None
699
+ if not is_local and not _IMAGE_URL_RE.match(q):
700
+ return _image_input_error("animetrace", q)
701
+ body: dict[str, Any] = {}
702
+ if is_local:
703
+ loaded = _load_local_image(q)
704
+ if isinstance(loaded, dict):
705
+ return [loaded]
706
+ body["base64"] = _image_to_base64(loaded[0])
707
+ else:
708
+ body["url"] = q
709
+ if is_multi:
710
+ body["is_multi"] = 1
711
+ if model:
712
+ body["model"] = model
713
+ req = urllib.request.Request(
714
+ _ANIMETRACE_ENDPOINT,
715
+ data=json.dumps(body).encode("utf-8"),
716
+ headers={
717
+ "Content-Type": "application/json",
718
+ "Accept": "application/json",
719
+ "Referer": "https://www.animetrace.com/",
720
+ "Origin": "https://www.animetrace.com",
721
+ },
722
+ )
723
+ try:
724
+ with http_open(req, timeout=_timeout or timeout, engine=spec.get("_name", "")) as resp:
725
+ raw = resp.read().decode("utf-8", errors="replace")
726
+ except urllib.error.HTTPError as e:
727
+ payload = ""
728
+ try:
729
+ payload = e.read().decode("utf-8", errors="replace")[:400]
730
+ except OSError:
731
+ payload = ""
732
+ return [_animetrace_error(e.code, payload)]
733
+ except (urllib.error.URLError, TimeoutError, OSError):
734
+ return []
735
+ try:
736
+ payload = json.loads(raw)
737
+ except (json.JSONDecodeError, ValueError):
738
+ return []
739
+ if not isinstance(payload, dict):
740
+ return []
741
+ code = payload.get("code")
742
+ if code not in (0, None):
743
+ return [_animetrace_error(0, raw)]
744
+ trace_id = str(payload.get("trace_id") or "")
745
+ results: list[dict[str, Any]] = []
746
+ seen: set[tuple[str, str]] = set()
747
+ for box in payload.get("data") or []:
748
+ if len(results) >= max(1, int(n)):
749
+ break
750
+ if not isinstance(box, dict):
751
+ continue
752
+ not_confident = bool(box.get("not_confident"))
753
+ for char in box.get("character") or []:
754
+ if not isinstance(char, dict):
755
+ continue
756
+ work = str(char.get("work") or "").strip()
757
+ name = str(char.get("character") or "").strip()
758
+ if not work and not name:
759
+ continue
760
+ key = (work, name)
761
+ if key in seen:
762
+ continue
763
+ seen.add(key)
764
+ title = " · ".join(b for b in (work, name) if b) or "AnimeTrace 角色识别"
765
+ bits = [b for b in (
766
+ f"角色 {name}" if name else "",
767
+ f"作品 {work}" if work else "",
768
+ "低置信(建议人工复核)" if not_confident else "",
769
+ ) if b]
770
+ results.append({
771
+ "title": title[:200],
772
+ "url": _bgm_search_url(work or name),
773
+ "snippet": " · ".join(bits)[:300],
774
+ "source": spec.get("_name") or "animetrace",
775
+ "score": rank_score(0.55 if not_confident else 0.8, len(results)),
776
+ "metadata": {
777
+ "work": work,
778
+ "character": name,
779
+ "not_confident": not_confident,
780
+ "box": box.get("box"),
781
+ "trace_id": trace_id,
782
+ },
783
+ })
784
+ if len(results) >= max(1, int(n)):
785
+ break
786
+ return results
787
+ return _engine
788
+
789
+
790
+ # ── trace.moe(动画场景识别,免 key、按 IP 限频)────────────────────────────
791
+
792
+ _TRACEMOE_ENDPOINT = "https://api.trace.moe/search"
793
+
794
+ # 上游 error 字段的语义:error 非空 = 上游没查成(拉不到图、配额用尽等),
795
+ # 不能当「没找到」。quota/quotaUsed 用于配额可见性,非失败信号。
796
+
797
+
798
+ def _tracemoe_error(payload: str) -> dict[str, Any]:
799
+ """把上游 error 文本合成一条可读错误。"""
800
+ msg = ""
801
+ try:
802
+ obj = json.loads(payload)
803
+ except (json.JSONDecodeError, ValueError):
804
+ obj = None
805
+ if isinstance(obj, dict):
806
+ msg = str(obj.get("error") or "").strip()
807
+ elif payload:
808
+ msg = payload.strip()[:160]
809
+ return {"error": msg or "请求失败", "source": "tracemoe"}
810
+
811
+
812
+ def _tracemoe_get(image_url: str, timeout: float, engine: str) -> str | None:
813
+ """GET 查询 trace.moe;上游在 Cloudflare 之后,须走 TLS 指纹伪造。
814
+
815
+ 返回响应文本;失败返回 None。走 curl_cffi impersonate(与 SauceNAO 同口径)。
816
+ 实测:POST JSON 上游回 400,GET query 参数 200 可用。
817
+ """
818
+ try:
819
+ from curl_cffi import requests as cr
820
+ except ImportError:
821
+ return None
822
+ proxies = None
823
+ try:
824
+ from net_proxy import resolve_proxy
825
+ # 显式 override:ARGO_TRACEMOE_PROXY 优先于 config.yaml 域规则;
826
+ # 未设置(get_env 回 None)时照走 rules→全局→标准 env 的常规链
827
+ p = resolve_proxy(_TRACEMOE_ENDPOINT,
828
+ override=get_env("ARGO_TRACEMOE_PROXY"))
829
+ if p:
830
+ proxies = {"https": p}
831
+ except Exception:
832
+ proxies = None
833
+ last: Exception | None = None
834
+ for fp in ("chrome", "safari"):
835
+ try:
836
+ resp = cr.get(_TRACEMOE_ENDPOINT, params={"url": image_url},
837
+ headers={"Accept": "application/json"},
838
+ timeout=timeout, impersonate=fp, proxies=proxies)
839
+ except Exception as e:
840
+ last = e
841
+ continue
842
+ if resp.status_code == 200:
843
+ return resp.text
844
+ last = RuntimeError(f"HTTP {resp.status_code} · {resp.text[:120]}")
845
+ return None
846
+
847
+
848
+ def _tracemoe_episode(item: dict[str, Any]) -> str:
849
+ """把 episode 字段归一成可读文本;上游可能是 int、str 或 null。"""
850
+ ep = item.get("episode")
851
+ if ep is None:
852
+ return ""
853
+ if isinstance(ep, str) and "|" in ep:
854
+ return f"第 {ep} 话"
855
+ try:
856
+ return f"第 {int(ep)} 话"
857
+ except (TypeError, ValueError):
858
+ return f"第 {ep} 话"
859
+
860
+
861
+ def _tracemoe_timestamp(seconds: float) -> str:
862
+ """把秒数归一成 mm:ss;上游 from/to 是浮点秒。"""
863
+ try:
864
+ total = int(float(seconds))
865
+ except (TypeError, ValueError):
866
+ return ""
867
+ return f"{total // 60:02d}:{total % 60:02d}"
868
+
869
+
870
+ def _build_tracemoe_engine(spec: dict[str, Any]) -> Any:
871
+ """trace.moe 动画场景识别(免 key,POST JSON 传图片 URL)。
872
+
873
+ 上游返回「这张截图出自动画第几集的哪个时间点」,条目带 similarity(0-1)
874
+ 与 AniList ID。url 槽填 AniList 作品页(下一步去哪儿查证的入口),不是
875
+ 宣称这张图就出自该页——与 AnimeTrace 同口径。
876
+ """
877
+ timeout = spec.get("timeout", 20)
878
+ min_sim = float(spec.get("min_similarity", 0.7) or 0.7)
879
+
880
+ @safe_search
881
+ def _engine(query: str, n: int = 5, _timeout: float | None = None, **kwargs) -> list[dict[str, Any]]:
882
+ q = (query or "").strip()
883
+ is_local = _local_image_path(q) is not None
884
+ if not is_local and not _IMAGE_URL_RE.match(q):
885
+ return _image_input_error("tracemoe", q)
886
+ if is_local:
887
+ # trace.moe 只收公网可访问的图片 URL,没有上传端点。本地图直接
888
+ # 返回可读错误——把 base64 塞进 url 参数上游会回 400/422,不如
889
+ # 在入口说清「这条路走不通」。
890
+ return [{"error": "trace.moe 只收公网图片 URL,不支持本地图片上传;"
891
+ f"收到本地路径「{q}」",
892
+ "source": "tracemoe"}]
893
+ raw = _tracemoe_get(q, float(_timeout or timeout), spec.get("_name", ""))
894
+ if raw is None:
895
+ return []
896
+ try:
897
+ payload = json.loads(raw)
898
+ except (json.JSONDecodeError, ValueError):
899
+ return []
900
+ if not isinstance(payload, dict):
901
+ return []
902
+ if payload.get("error"):
903
+ return [_tracemoe_error(raw)]
904
+ results: list[dict[str, Any]] = []
905
+ seen: set[int] = set()
906
+ for item in payload.get("result") or []:
907
+ if len(results) >= max(1, int(n)):
908
+ break
909
+ if not isinstance(item, dict):
910
+ continue
911
+ anilist_id = item.get("anilist")
912
+ if isinstance(anilist_id, int) and anilist_id in seen:
913
+ continue
914
+ if isinstance(anilist_id, int):
915
+ seen.add(anilist_id)
916
+ try:
917
+ sim = float(item.get("similarity") or 0)
918
+ except (TypeError, ValueError):
919
+ sim = 0.0
920
+ if sim < min_sim:
921
+ continue
922
+ filename = str(item.get("filename") or "").strip()
923
+ episode = _tracemoe_episode(item)
924
+ at = _tracemoe_timestamp(item.get("at"))
925
+ thumb = str(item.get("image") or "").strip()
926
+ video = str(item.get("video") or "").strip()
927
+ bits = [b for b in (
928
+ f"相似度 {sim * 100:.1f}%" if sim > 0 else "",
929
+ f"作品 {anilist_id}" if anilist_id else "",
930
+ episode,
931
+ f"时间点 {at}" if at else "",
932
+ f"文件 {filename[:80]}" if filename else "",
933
+ ) if b]
934
+ title = filename[:200] or f"trace.moe 匹配 {anilist_id}"
935
+ url = f"https://anilist.co/anime/{anilist_id}" if anilist_id else video or thumb
936
+ if not url:
937
+ continue
938
+ results.append({
939
+ "title": title,
940
+ "url": url,
941
+ "snippet": " · ".join(bits)[:300],
942
+ "source": spec.get("_name") or "tracemoe",
943
+ "score": rank_score(min(sim, 1.0) if sim > 0 else 0.6, len(results)),
944
+ "metadata": {
945
+ "similarity": sim,
946
+ "anilist_id": anilist_id,
947
+ "filename": filename,
948
+ "episode": item.get("episode"),
949
+ "at": item.get("at"),
950
+ "video": video,
951
+ "image": thumb,
952
+ "quota": payload.get("quota"),
953
+ "quota_used": payload.get("quotaUsed"),
954
+ },
955
+ **({"image_url": thumb} if thumb else {}),
956
+ })
957
+ return results
958
+ return _engine