argo-search 2.11.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 (72) hide show
  1. package/README.en.md +25 -21
  2. package/README.es.md +24 -20
  3. package/README.ja.md +25 -21
  4. package/README.ko.md +24 -20
  5. package/README.md +30 -22
  6. package/SKILL.md +6 -6
  7. package/backends/domain_profiles.json +12 -0
  8. package/backends/engine_registry.yaml +26 -1
  9. package/backends/quota_profiles.json +20 -0
  10. package/bin/argo +7 -0
  11. package/config.yaml +18 -3
  12. package/docs/ENGINE_CATALOG.md +8 -6
  13. package/docs/MCP_SETUP.md +16 -4
  14. package/docs/RELEASE_NOTES_v2.11.2.md +116 -0
  15. package/docs/RELEASE_NOTES_v2.12.0.md +65 -0
  16. package/docs/engines/pixiv.md +27 -0
  17. package/engines/specs/pixiv.yaml +52 -0
  18. package/engines/specs/tracemoe.yaml +33 -0
  19. package/package.json +3 -2
  20. package/packages/dsh-plugin/README.md +20 -11
  21. package/packages/dsh-plugin/dsh/client.js +3 -3
  22. package/packages/dsh-plugin/dsh/index.js +22 -176
  23. package/packages/dsh-plugin/dsh/runner.js +12 -2
  24. package/packages/dsh-plugin/dsh/specs.js +133 -0
  25. package/packages/dsh-plugin/package.json +10 -2
  26. package/packages/dsh-plugin/test/client.test.js +4 -4
  27. package/packages/dsh-plugin/test/diagnostics.test.js +1 -1
  28. package/packages/dsh-plugin/test/index.test.js +28 -2
  29. package/scripts/adaptive.py +101 -27
  30. package/scripts/build_route_labels.py +122 -169
  31. package/scripts/caliber_dedupe.py +4 -4
  32. package/scripts/caliber_isolation.py +17 -17
  33. package/scripts/concept_lookup.py +14 -1
  34. package/scripts/config.py +21 -3
  35. package/scripts/engine_admission.py +35 -17
  36. package/scripts/engine_dispatch.py +16 -16
  37. package/scripts/engine_env.py +4 -0
  38. package/scripts/engine_families.py +6 -4
  39. package/scripts/engines.py +5 -0
  40. package/scripts/engines_base.py +1 -1
  41. package/scripts/engines_builders_data.py +10 -10
  42. package/scripts/engines_builders_pixiv.py +633 -0
  43. package/scripts/engines_builders_reverse_image.py +175 -0
  44. package/scripts/env_store.py +216 -0
  45. package/scripts/extend_route_labels_by_capability.py +4 -4
  46. package/scripts/extend_route_labels_full_coverage.py +329 -0
  47. package/scripts/fetch_v3.py +74 -5
  48. package/scripts/job.py +31 -6
  49. package/scripts/local_image.py +22 -8
  50. package/scripts/mcp_compact.py +9 -1
  51. package/scripts/mcp_launch.sh +1 -1
  52. package/scripts/mcp_setup.py +85 -1
  53. package/scripts/mcp_transport.py +1 -1
  54. package/scripts/plan.py +2 -2
  55. package/scripts/pre-commit +4 -1
  56. package/scripts/query_signals.py +35 -20
  57. package/scripts/quota.py +9 -4
  58. package/scripts/recovery.py +38 -13
  59. package/scripts/redskill/redskill_engine.py +33 -10
  60. package/scripts/route.py +2 -2
  61. package/scripts/route_accuracy_eval.py +2 -2
  62. package/scripts/route_combo.py +22 -3
  63. package/scripts/route_domains.py +182 -50
  64. package/scripts/search.py +0 -2
  65. package/scripts/search_entry.py +38 -42
  66. package/scripts/search_output.py +3 -0
  67. package/scripts/search_pipeline.py +3 -8
  68. package/scripts/search_rank.py +22 -7
  69. package/scripts/serp_guard.py +7 -16
  70. package/scripts/settings_page.py +486 -0
  71. package/scripts/straggler_policy.py +8 -4
  72. package/scripts/tfidf_router.py +82 -24
@@ -0,0 +1,633 @@
1
+ #!/usr/bin/env python3
2
+ """Pixiv 公开作品检索:关键词搜索与画师作品列表,匿名 Web 与 OAuth App API 双通道。
3
+
4
+ 配置 refresh token 后只走 App API,避免标签、日期、AI 过滤或内容分级在
5
+ 通道切换时静默改变。Web 与 App 接口均无公开稳定性承诺;结果标出实际
6
+ 取数通道。R-18 是部署级内容边界,默认拒绝,只有显式授权才放行。
7
+ 画师作品列表只有 App 接口能给出可用的图片直链,匿名通道明确返回提示。
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import hashlib
13
+ import json
14
+ import re
15
+ import sys
16
+ import threading
17
+ import time
18
+ import urllib.error
19
+ import urllib.parse
20
+ import urllib.request
21
+ from concurrent.futures import ThreadPoolExecutor
22
+ from datetime import datetime, timezone
23
+ from typing import Any
24
+
25
+ from engine_env import env_flag, get_env
26
+ from engines_base import finalize_image_fields, http_open, rank_score, safe_search
27
+
28
+
29
+ class _LazyLogger:
30
+ """延迟创建 logger,避免 import logging 的重量级 import 链。"""
31
+
32
+ _logger = None
33
+
34
+ def __getattr__(self, name: str):
35
+ if _LazyLogger._logger is None:
36
+ import logging
37
+
38
+ _LazyLogger._logger = logging.getLogger("unified_search.engines")
39
+ if not _LazyLogger._logger.handlers:
40
+ _LazyLogger._logger.setLevel(logging.WARNING)
41
+ _LazyLogger._logger.addHandler(logging.StreamHandler(sys.stderr))
42
+ return getattr(_LazyLogger._logger, name)
43
+
44
+
45
+ logger = _LazyLogger()
46
+
47
+ _WEB_API = "https://www.pixiv.net/ajax/search/artworks"
48
+ _APP_API = "https://app-api.pixiv.net/v1/search/illust"
49
+ _APP_USER_ILLUSTS_API = "https://app-api.pixiv.net/v1/user/illusts"
50
+ _APP_SEARCH_USER_API = "https://app-api.pixiv.net/v1/search/user"
51
+ _OAUTH_API = "https://oauth.secure.pixiv.net/auth/token"
52
+ _WEB_UA = (
53
+ "Mozilla/5.0 (Windows NT 10.0; Win64; x64) "
54
+ "AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36"
55
+ )
56
+ _APP_HEADERS = {
57
+ "App-OS": "ios",
58
+ "App-OS-Version": "14.6",
59
+ "User-Agent": "PixivIOSApp/7.13.3 (iOS 14.6; iPhone13,2)",
60
+ }
61
+ # Pixiv App 的公共客户端参数与请求签名盐,协议参考 pixivpy(Unlicense)。
62
+ _CLIENT_ID = "MOBrBDS8blbauoSck0ZfDbtuzpyT"
63
+ _CLIENT_SECRET = "lsACyCD94FhDUtGTXi3QzcFE2uU1hqtDaKeqrdwj"
64
+ _HASH_SECRET = "28c1fdd170a5204386cb1313c7077b34f83e4aaf4aa829ce78c231e05b0bae2c"
65
+ _APP_ILLUST_DETAIL_API = "https://app-api.pixiv.net/v1/illust/detail"
66
+ _DETAIL_WORKERS = 4
67
+ _WEB_PAGE_SIZE = 60
68
+ _APP_PAGE_SIZE = 30
69
+ _ACCESS_TOKEN_TTL = 3000.0
70
+ _ACCESS_TOKEN_EARLY_REFRESH = 120.0
71
+
72
+ # 进程内只缓存短期 access token;refresh token 每次从环境读取,支持热更新。
73
+ _token_lock = threading.Lock()
74
+ _token_cache: dict[str, Any] = {"refresh_token": "", "access_token": "", "expires_at": 0.0}
75
+
76
+
77
+ def _error(message: str, engine: str) -> list[dict[str, Any]]:
78
+ return [{"error": message, "source": engine}]
79
+
80
+
81
+ # 标签匹配口径:App 与 Web 用两套枚举名,统一到一套对调用方可见的取值。
82
+ _SEARCH_TARGETS = {
83
+ "partial_match_for_tags": "s_tag",
84
+ "exact_match_for_tags": "s_tag_full",
85
+ "title_and_caption": "s_tc",
86
+ }
87
+
88
+
89
+ def _search_target(spec: dict[str, Any], kwargs: dict[str, Any]) -> str:
90
+ target = str(
91
+ kwargs.get("search_target") or spec.get("search_target") or "partial_match_for_tags"
92
+ )
93
+ return target if target in _SEARCH_TARGETS else "partial_match_for_tags"
94
+
95
+
96
+ def _search_url(query: str, *, order: str, target: str) -> str:
97
+ """Web 搜索要求关键词进入路径;动态部分统一按 URL 组件编码。"""
98
+ encoded = urllib.parse.quote(query, safe="")
99
+ params = urllib.parse.urlencode(
100
+ {
101
+ "word": query,
102
+ "p": 1,
103
+ "order": order,
104
+ "mode": "all",
105
+ "lang": "zh",
106
+ "s_mode": _SEARCH_TARGETS.get(target, "s_tag"),
107
+ }
108
+ )
109
+ return f"{_WEB_API}/{encoded}?{params}"
110
+
111
+
112
+ def _web_preview_url(raw_url: str) -> str:
113
+ """把上游的方形裁剪地址换成保持作品宽高比的 master1200 预览图。"""
114
+ parsed = urllib.parse.urlsplit(raw_url)
115
+ if parsed.scheme != "https" or parsed.hostname != "i.pximg.net":
116
+ return ""
117
+ path = parsed.path
118
+ if not path.endswith("_square1200.jpg"):
119
+ return ""
120
+ parts = path.split("/")
121
+ if len(parts) < 5 or parts[1] != "c" or not parts[2] or not parts[-1] or not parts[3]:
122
+ return ""
123
+ preview_path = "/" + "/".join(parts[3:])
124
+ preview_path = preview_path[: -len("_square1200.jpg")] + "_master1200.jpg"
125
+ return urllib.parse.urlunsplit((parsed.scheme, parsed.netloc, preview_path, "", ""))
126
+
127
+
128
+ def _app_image_url(item: dict[str, Any]) -> str:
129
+ images = item.get("image_urls")
130
+ if not isinstance(images, dict):
131
+ return ""
132
+ for key in ("large", "medium"):
133
+ raw = str(images.get(key) or "").strip()
134
+ parsed = urllib.parse.urlsplit(raw)
135
+ if parsed.scheme == "https" and parsed.hostname == "i.pximg.net" and parsed.path:
136
+ return raw
137
+ return ""
138
+
139
+
140
+ def _pximg_https(raw: str) -> str:
141
+ """只接受 i.pximg.net 的 https 直链。"""
142
+ candidate = raw.strip()
143
+ parsed = urllib.parse.urlsplit(candidate)
144
+ if parsed.scheme == "https" and parsed.hostname == "i.pximg.net" and parsed.path:
145
+ return candidate
146
+ return ""
147
+
148
+
149
+ def _original_url_from_detail(illust: dict[str, Any]) -> str:
150
+ """作品详情里的原图直链:单页在 meta_single_page,多页取第一张。"""
151
+ single = illust.get("meta_single_page")
152
+ if isinstance(single, dict):
153
+ url = _pximg_https(str(single.get("original_image_url") or ""))
154
+ if url:
155
+ return url
156
+ pages = illust.get("meta_pages")
157
+ if isinstance(pages, list):
158
+ for page in pages:
159
+ images = page.get("image_urls") if isinstance(page, dict) else None
160
+ if isinstance(images, dict):
161
+ url = _pximg_https(str(images.get("original") or ""))
162
+ if url:
163
+ return url
164
+ return ""
165
+
166
+
167
+ def _app_illust_original(
168
+ illust_id: str, access_token: str, timeout: float, engine: str
169
+ ) -> str:
170
+ params = urllib.parse.urlencode({"illust_id": illust_id, "filter": "for_ios"})
171
+ payload, error = _app_json(
172
+ f"{_APP_ILLUST_DETAIL_API}?{params}", access_token, timeout, engine
173
+ )
174
+ if error or not isinstance(payload, dict):
175
+ return ""
176
+ illust = payload.get("illust")
177
+ return _original_url_from_detail(illust) if isinstance(illust, dict) else ""
178
+
179
+
180
+ def _attach_originals(
181
+ results: list[dict[str, Any]], access_token: str, timeout: float, engine: str
182
+ ) -> None:
183
+ """并发补齐原图直链,预览直链留在 image_url_preview 供超限回退。"""
184
+
185
+ def fetch(row: dict[str, Any]) -> None:
186
+ illust_id = str(row.get("url") or "").rstrip("/").rsplit("/", 1)[-1]
187
+ if not illust_id.isdigit():
188
+ return
189
+ try:
190
+ original = _app_illust_original(illust_id, access_token, timeout, engine)
191
+ except Exception: # 详情失败不影响检索结果
192
+ logger.warning(f"Pixiv 原图直链获取失败: illust_id={illust_id}")
193
+ return
194
+ if original:
195
+ row["image_url_preview"] = row["image_url"]
196
+ row["image_url"] = original
197
+
198
+ if not results:
199
+ return
200
+ with ThreadPoolExecutor(max_workers=min(_DETAIL_WORKERS, len(results))) as pool:
201
+ list(pool.map(fetch, results))
202
+
203
+
204
+ def _result_row(
205
+ item: dict[str, Any], *, channel: str, engine: str, index: int, allow_r18: bool
206
+ ) -> dict[str, Any] | None:
207
+ """把 Web/App 的作品条目归一到同一份 Argo 图片结果契约。"""
208
+ restriction = item.get("xRestrict" if channel == "web" else "x_restrict")
209
+ try:
210
+ is_r18 = int(restriction or 0) != 0
211
+ except (TypeError, ValueError):
212
+ return None
213
+ if is_r18 and not allow_r18:
214
+ return None
215
+ illust_id = str(item.get("id") or "").strip()
216
+ title = str(item.get("title") or "").strip()
217
+ image_url = (
218
+ _web_preview_url(str(item.get("url") or "").strip())
219
+ if channel == "web"
220
+ else _app_image_url(item)
221
+ )
222
+ if not illust_id.isdigit() or not title or not image_url:
223
+ return None
224
+ if channel == "web":
225
+ author = str(item.get("userName") or "").strip()
226
+ created = str(item.get("createDate") or "")[:64]
227
+ page_count = item.get("pageCount")
228
+ else:
229
+ user = item.get("user")
230
+ author = str(user.get("name") or "").strip() if isinstance(user, dict) else ""
231
+ created = str(item.get("create_date") or "")[:64]
232
+ page_count = item.get("page_count")
233
+ tags = []
234
+ for tag in item.get("tags") or []:
235
+ name = str(tag.get("name") or "").strip() if isinstance(tag, dict) else str(tag).strip()
236
+ # R-18 是分级标签不是主题标签,不应进 snippet(bot 会复述)。
237
+ if name and name.upper() not in {"R-18", "R-18G"}:
238
+ tags.append(name)
239
+ snippet_bits = [author and f"作者 {author}"]
240
+ if page_count:
241
+ snippet_bits.append(f"{page_count} 页")
242
+ if tags:
243
+ snippet_bits.append("标签 " + " / ".join(tags[:6]))
244
+ return {
245
+ "title": title[:200],
246
+ "url": f"https://www.pixiv.net/artworks/{illust_id}",
247
+ "snippet": " · ".join(bit for bit in snippet_bits if bit)[:300],
248
+ "author": author[:50],
249
+ "tags": tags[:6],
250
+ "source": engine,
251
+ "channel": channel,
252
+ "score": rank_score(0.8, index),
253
+ "published_at": created,
254
+ "image_url": image_url,
255
+ # 上游宽高描述作品原图;预览图保持同一宽高比。
256
+ "image_width": item.get("width"),
257
+ "image_height": item.get("height"),
258
+ }
259
+
260
+
261
+ def _web_search(
262
+ query: str, n: int, timeout: float, spec: dict[str, Any], target: str
263
+ ) -> list[dict[str, Any]]:
264
+ engine = spec.get("_name", "pixiv")
265
+ order = str(spec.get("order") or "date")
266
+ if order not in {"date", "popular"}:
267
+ order = "date"
268
+ req = urllib.request.Request(
269
+ _search_url(query, order=order, target=target),
270
+ headers={
271
+ "User-Agent": _WEB_UA,
272
+ "Accept": "application/json",
273
+ "Referer": "https://www.pixiv.net/",
274
+ },
275
+ )
276
+ try:
277
+ with http_open(req, timeout=timeout, engine=engine) as resp:
278
+ payload = json.loads(resp.read().decode("utf-8", "replace"))
279
+ except (urllib.error.URLError, OSError, ValueError) as exc:
280
+ logger.warning(f"Pixiv Web 检索失败: {exc}")
281
+ return []
282
+ if not isinstance(payload, dict) or payload.get("error") is not False:
283
+ logger.warning("Pixiv Web 返回业务错误或响应结构变化")
284
+ return []
285
+ body = payload.get("body")
286
+ section = body.get("illustManga") if isinstance(body, dict) else None
287
+ items = section.get("data") if isinstance(section, dict) else None
288
+ if not isinstance(items, list):
289
+ logger.warning("Pixiv Web 响应缺少 illustManga.data")
290
+ return []
291
+ allow_r18 = env_flag("ARGO_PIXIV_ALLOW_R18", default=False, expand=False, strict=True)
292
+ results = []
293
+ for item in items:
294
+ if not isinstance(item, dict):
295
+ continue
296
+ row = _result_row(item, channel="web", engine=engine, index=len(results), allow_r18=allow_r18)
297
+ if row is not None:
298
+ results.append(row)
299
+ if len(results) >= min(n, _WEB_PAGE_SIZE):
300
+ break
301
+ return results
302
+
303
+
304
+ def _refresh_access_token(refresh_token: str, timeout: float, engine: str) -> str:
305
+ """用 refresh token 换短期 access token;失败只给行动提示,不回显密钥。"""
306
+ now = time.monotonic()
307
+ with _token_lock:
308
+ if (
309
+ _token_cache["refresh_token"] == refresh_token
310
+ and _token_cache["access_token"]
311
+ and now < _token_cache["expires_at"]
312
+ ):
313
+ return str(_token_cache["access_token"])
314
+ client_time = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%S+00:00")
315
+ client_hash = hashlib.md5((client_time + _HASH_SECRET).encode("utf-8")).hexdigest()
316
+ body = urllib.parse.urlencode(
317
+ {
318
+ "get_secure_url": 1,
319
+ "client_id": _CLIENT_ID,
320
+ "client_secret": _CLIENT_SECRET,
321
+ "grant_type": "refresh_token",
322
+ "refresh_token": refresh_token,
323
+ }
324
+ ).encode("utf-8")
325
+ req = urllib.request.Request(
326
+ _OAUTH_API,
327
+ data=body,
328
+ method="POST",
329
+ headers={
330
+ **_APP_HEADERS,
331
+ "X-Client-Time": client_time,
332
+ "X-Client-Hash": client_hash,
333
+ "Content-Type": "application/x-www-form-urlencoded",
334
+ "Accept": "application/json",
335
+ },
336
+ )
337
+ try:
338
+ with http_open(req, timeout=timeout, engine=engine) as resp:
339
+ payload = json.loads(resp.read().decode("utf-8", "replace"))
340
+ except urllib.error.HTTPError as exc:
341
+ raise ValueError("Pixiv OAuth 认证失败,请更新 refresh token") from exc
342
+ except (urllib.error.URLError, OSError, ValueError) as exc:
343
+ raise ValueError("Pixiv OAuth 暂时不可用,请检查网络后重试") from exc
344
+ response = payload.get("response") if isinstance(payload, dict) else None
345
+ access_token = str(response.get("access_token") or "").strip() if isinstance(response, dict) else ""
346
+ if not access_token:
347
+ raise ValueError("Pixiv OAuth 未返回 access token,请更新 refresh token")
348
+ expires_in = response.get("expires_in") if isinstance(response, dict) else None
349
+ try:
350
+ ttl = max(60.0, float(expires_in) - _ACCESS_TOKEN_EARLY_REFRESH)
351
+ except (TypeError, ValueError):
352
+ ttl = _ACCESS_TOKEN_TTL
353
+ _token_cache.update(
354
+ refresh_token=refresh_token,
355
+ access_token=access_token,
356
+ expires_at=now + ttl,
357
+ )
358
+ return access_token
359
+
360
+
361
+ def _app_params(query: str, spec: dict[str, Any], kwargs: dict[str, Any]) -> dict[str, Any]:
362
+ target = _search_target(spec, kwargs)
363
+ sort = str(kwargs.get("sort") or spec.get("sort") or "date_desc")
364
+ if sort not in {"date_desc", "date_asc", "popular_desc"}:
365
+ sort = "date_desc"
366
+ params: dict[str, Any] = {
367
+ "word": query,
368
+ "search_target": target,
369
+ "sort": sort,
370
+ "filter": "for_ios",
371
+ }
372
+ for key in ("start_date", "end_date"):
373
+ value = str(kwargs.get(key) or spec.get(key) or "").strip()
374
+ if value:
375
+ params[key] = value
376
+ ai_type = kwargs.get("search_ai_type", spec.get("search_ai_type"))
377
+ if ai_type in (0, 1, "0", "1"):
378
+ params["search_ai_type"] = int(ai_type)
379
+ return params
380
+
381
+
382
+ def _app_search(
383
+ query: str, n: int, timeout: float, spec: dict[str, Any], kwargs: dict[str, Any]
384
+ ) -> list[dict[str, Any]]:
385
+ engine = spec.get("_name", "pixiv")
386
+ refresh_token = get_env("ARGO_PIXIV_REFRESH_TOKEN").strip()
387
+ try:
388
+ access_token = _refresh_access_token(refresh_token, timeout, engine)
389
+ except ValueError as exc:
390
+ return _error(str(exc), engine)
391
+ url = f"{_APP_API}?{urllib.parse.urlencode(_app_params(query, spec, kwargs))}"
392
+ req = urllib.request.Request(
393
+ url,
394
+ headers={**_APP_HEADERS, "Accept": "application/json", "Authorization": f"Bearer {access_token}"},
395
+ )
396
+ try:
397
+ with http_open(req, timeout=timeout, engine=engine) as resp:
398
+ payload = json.loads(resp.read().decode("utf-8", "replace"))
399
+ except urllib.error.HTTPError as exc:
400
+ logger.warning(f"Pixiv App HTTP 错误: {exc.code}")
401
+ if exc.code in (400, 401, 403):
402
+ return _error("Pixiv App 认证或权限不足,请检查 refresh token 与账号状态", engine)
403
+ return _error(f"Pixiv App 请求失败(HTTP {exc.code})", engine)
404
+ except (urllib.error.URLError, OSError, ValueError) as exc:
405
+ logger.warning(f"Pixiv App 检索失败: {type(exc).__name__}")
406
+ return _error("Pixiv App 暂时不可用,请检查网络后重试", engine)
407
+ items = payload.get("illusts") if isinstance(payload, dict) else None
408
+ if not isinstance(items, list):
409
+ logger.warning("Pixiv App 响应缺少 illusts")
410
+ return _error("Pixiv App 返回了无法识别的响应,请稍后重试", engine)
411
+ allow_r18 = env_flag("ARGO_PIXIV_ALLOW_R18", default=False, expand=False, strict=True)
412
+ results = []
413
+ for item in items:
414
+ if not isinstance(item, dict):
415
+ continue
416
+ row = _result_row(item, channel="app", engine=engine, index=len(results), allow_r18=allow_r18)
417
+ if row is not None:
418
+ results.append(row)
419
+ if len(results) >= min(n, _APP_PAGE_SIZE):
420
+ break
421
+ _attach_originals(results, access_token, timeout, engine)
422
+ return results
423
+
424
+
425
+ _USER_URL_RE = re.compile(
426
+ r"^https?://(?:www\.)?pixiv\.net/users/(\d+)(?:[/?#].*)?$", re.IGNORECASE
427
+ )
428
+ _ARTIST_ID_RE = re.compile(
429
+ r"^(?:user|artist|画师|画師)\s*[::]\s*(\d+)$", re.IGNORECASE
430
+ )
431
+ _ARTIST_NAME_RE = re.compile(r"^(?:artist|画师|画師)\s*[::]\s*(\S.*)$", re.IGNORECASE)
432
+ _BARE_ARTIST_ID_RE = re.compile(r"^\d{5,9}$")
433
+
434
+
435
+ def _artist_target(query: str) -> tuple[int | None, str, list[str]]:
436
+ """识别画师作品查询,返回 (画师 id, 画师名, 标签过滤词)。"""
437
+ text = (query or "").replace("\u3000", " ").strip()
438
+ if not text:
439
+ return None, "", []
440
+ parts = text.split(None, 1)
441
+ head = parts[0]
442
+ tags = parts[1].split() if len(parts) > 1 else []
443
+ match = _USER_URL_RE.match(head)
444
+ if match:
445
+ return int(match.group(1)), "", tags
446
+ match = _ARTIST_ID_RE.match(head)
447
+ if match:
448
+ return int(match.group(1)), "", tags
449
+ match = _ARTIST_NAME_RE.match(head)
450
+ if match:
451
+ return None, match.group(1).strip(), tags
452
+ if _BARE_ARTIST_ID_RE.match(head):
453
+ return int(head), "", tags
454
+ return None, "", []
455
+
456
+
457
+ def _item_matches_tags(item: dict[str, Any], tags: list[str]) -> bool:
458
+ """条目标签需覆盖全部过滤词(大小写不敏感,按子串匹配,兼容本土化的长标签)。"""
459
+ names = [
460
+ str(entry.get("name") or "").casefold()
461
+ for entry in item.get("tags") or []
462
+ if isinstance(entry, dict)
463
+ ]
464
+ return all(any(tag.casefold() in name for name in names) for tag in tags)
465
+
466
+
467
+ def _app_json(
468
+ url: str, access_token: str, timeout: float, engine: str
469
+ ) -> tuple[dict[str, Any] | None, str]:
470
+ """请求 App 接口,把网络与业务错误统一成 (None, 可读文案)。"""
471
+ req = urllib.request.Request(
472
+ url,
473
+ headers={
474
+ **_APP_HEADERS,
475
+ "Accept": "application/json",
476
+ "Authorization": f"Bearer {access_token}",
477
+ },
478
+ )
479
+ try:
480
+ with http_open(req, timeout=timeout, engine=engine) as resp:
481
+ payload = json.loads(resp.read().decode("utf-8", "replace"))
482
+ except urllib.error.HTTPError as exc:
483
+ logger.warning(f"Pixiv App HTTP 错误: {exc.code}")
484
+ if exc.code in (400, 401, 403):
485
+ return None, "Pixiv App 认证或权限不足,请检查 refresh token 与账号状态"
486
+ return None, f"Pixiv App 请求失败(HTTP {exc.code})"
487
+ except (urllib.error.URLError, OSError, ValueError):
488
+ logger.warning("Pixiv App 请求失败")
489
+ return None, "Pixiv App 暂时不可用,请检查网络后重试"
490
+ if not isinstance(payload, dict):
491
+ return None, "Pixiv App 返回了无法识别的响应,请稍后重试"
492
+ return payload, ""
493
+
494
+
495
+ def _app_resolve_artist_id(
496
+ name: str, access_token: str, timeout: float, engine: str
497
+ ) -> tuple[int | None, str]:
498
+ """按画师名查账号 id,取搜索结果的第一位。"""
499
+ url = f"{_APP_SEARCH_USER_API}?{urllib.parse.urlencode({'word': name, 'filter': 'for_ios'})}"
500
+ payload, error = _app_json(url, access_token, timeout, engine)
501
+ if error:
502
+ return None, error
503
+ previews = payload.get("user_previews") if payload else None
504
+ if not isinstance(previews, list):
505
+ return None, "Pixiv App 返回了无法识别的响应,请稍后重试"
506
+ for entry in previews:
507
+ user = entry.get("user") if isinstance(entry, dict) else None
508
+ user_id = str(user.get("id") or "").strip() if isinstance(user, dict) else ""
509
+ if user_id.isdigit():
510
+ return int(user_id), ""
511
+ return None, f"没有找到匹配的画师:{name}"
512
+
513
+
514
+ def _app_artist_works(
515
+ artist_id: int,
516
+ n: int,
517
+ timeout: float,
518
+ engine: str,
519
+ access_token: str,
520
+ allow_r18: bool,
521
+ tags: list[str] | None = None,
522
+ ) -> list[dict[str, Any]]:
523
+ """拉取画师作品列表;带标签过滤时多翻几页,R-18 过滤后条数不足时再补一页。"""
524
+ results: list[dict[str, Any]] = []
525
+ filters = tags or []
526
+ offset = 0
527
+ for _ in range(5 if filters else 2):
528
+ params = {
529
+ "user_id": artist_id,
530
+ "type": "illust",
531
+ "filter": "for_ios",
532
+ "offset": offset,
533
+ }
534
+ url = f"{_APP_USER_ILLUSTS_API}?{urllib.parse.urlencode(params)}"
535
+ payload, error = _app_json(url, access_token, timeout, engine)
536
+ if error:
537
+ return results or _error(error, engine)
538
+ items = payload.get("illusts") if payload else None
539
+ if not isinstance(items, list):
540
+ return results or _error(
541
+ "Pixiv App 返回了无法识别的响应,请稍后重试", engine
542
+ )
543
+ for item in items:
544
+ if not isinstance(item, dict):
545
+ continue
546
+ if filters and not _item_matches_tags(item, filters):
547
+ continue
548
+ row = _result_row(
549
+ item,
550
+ channel="app",
551
+ engine=engine,
552
+ index=len(results),
553
+ allow_r18=allow_r18,
554
+ )
555
+ if row is not None:
556
+ results.append(row)
557
+ if len(results) >= n:
558
+ break
559
+ if len(results) >= n or not items or not payload.get("next_url"):
560
+ break
561
+ offset += len(items)
562
+ if not results:
563
+ if filters:
564
+ joined = " / ".join(filters)
565
+ return _error(
566
+ f"该画师的作品里没有同时带这些标签的条目(标签:{joined})", engine
567
+ )
568
+ return _error("该画师的作品里没有可展示的条目(可能都被内容分级过滤)", engine)
569
+ trimmed = results[:n]
570
+ _attach_originals(trimmed, access_token, timeout, engine)
571
+ return trimmed
572
+
573
+
574
+ def _artist_search(
575
+ artist_id: int | None,
576
+ artist_name: str,
577
+ n: int,
578
+ timeout: float,
579
+ spec: dict[str, Any],
580
+ tags: list[str] | None = None,
581
+ ) -> list[dict[str, Any]]:
582
+ engine = spec.get("_name", "pixiv")
583
+ refresh_token = get_env("ARGO_PIXIV_REFRESH_TOKEN").strip()
584
+ if not refresh_token:
585
+ return _error(
586
+ "按画师浏览作品需要登录凭证(Pixiv App 接口),当前是匿名模式,请改用关键词搜索",
587
+ engine,
588
+ )
589
+ try:
590
+ access_token = _refresh_access_token(refresh_token, timeout, engine)
591
+ except ValueError as exc:
592
+ return _error(str(exc), engine)
593
+ if artist_name:
594
+ resolved, error = _app_resolve_artist_id(
595
+ artist_name, access_token, timeout, engine
596
+ )
597
+ if error:
598
+ return _error(error, engine)
599
+ artist_id = resolved
600
+ if not artist_id:
601
+ return _error("没有找到匹配的画师", engine)
602
+ allow_r18 = env_flag(
603
+ "ARGO_PIXIV_ALLOW_R18", default=False, expand=False, strict=True
604
+ )
605
+ return _app_artist_works(
606
+ artist_id, n, timeout, engine, access_token, allow_r18, tags
607
+ )
608
+
609
+
610
+ def _build_pixiv_engine(spec: dict[str, Any]) -> Any:
611
+ timeout = float(spec.get("timeout", 20))
612
+
613
+ @safe_search
614
+ def _engine(
615
+ query: str, n: int = 5, _timeout: float | None = None, **kwargs: Any
616
+ ) -> list[dict[str, Any]]:
617
+ q = (query or "").strip()
618
+ if not q:
619
+ return []
620
+ limit = max(1, int(n))
621
+ to = _timeout or timeout
622
+ artist_id, artist_name, artist_tags = _artist_target(q)
623
+ if artist_id or artist_name:
624
+ results = _artist_search(
625
+ artist_id, artist_name, limit, to, spec, artist_tags
626
+ )
627
+ elif get_env("ARGO_PIXIV_REFRESH_TOKEN").strip():
628
+ results = _app_search(q, limit, to, spec, kwargs)
629
+ else:
630
+ results = _web_search(q, limit, to, spec, _search_target(spec, kwargs))
631
+ return finalize_image_fields(results, spec.get("image_license") or "")
632
+
633
+ return _engine