Peach: Local-first video metadata scraper and media manager.
feat(javdb): 刮削改用匿名接口,类别按 id 换回详情页原词
longmeidao6c93e73a1336
diff --git a/scripts/generate_javdb_genres.py b/scripts/generate_javdb_genres.pynew file mode 100644index 000000000..81eb28821--- /dev/null+++ b/scripts/generate_javdb_genres.py@@ -0,0 +1,104 @@+"""从同一作品的 JavDB 详情页快照与匿名接口资料生成类别 id 到详情页原词的对照。++输入是 JSON Lines,每行一部作品:`type`(接口作品类型)、`api`(接口类别 `[{id, name}]`,原样顺序)、+`html`(详情页 `?locale=zh` 的类别原词,原样顺序)。两边顺序相同,接口里同一类别可能重复。++1. 去重后长度相等的作品逐位对齐;同一个 (类型, id) 对到两个原词时整项排除,交人核对。+2. 接口多出几项、其余逐位对得上的作品,多出的那几项算「详情页不显示」的证据;至少两部作品为证、+ 从没对到过原词的才收进 `HIDDEN`。+3. 去掉 `HIDDEN` 后长度相等的作品再对齐一轮,补上只在这些作品里出现的类别。+"""+from pathlib import Path+import argparse+import json+import re+import sys++PROJECT_ROOT = Path(__file__).resolve().parent.parent+SRC_DIR = PROJECT_ROOT / 'src'+if str(SRC_DIR) not in sys.path:+ sys.path.insert(0, str(SRC_DIR))++from peach.javdb_genres import genre_key++#: 一个类别至少在这么多部作品里多出来,才认作详情页不显示。+HIDDEN_EVIDENCE = 2+++def _keys(row):+ """接口类别的键,去重保序。"""+ keys = []+ for tag in row.get('api') or []:+ key = genre_key(row.get('type'), tag.get('id') if isinstance(tag, dict) else None)+ if key and key not in keys:+ keys.append(key)+ return keys+++def _words(row):+ return [str(word).strip() for word in row.get('html') or [] if str(word).strip()]+++def _pair(seen, keys, words):+ for key, word in zip(keys, words):+ seen.setdefault(key, set()).add(word)+++def align(rows):+ """返回 (对照, 详情页不显示的类别, 冲突, 没参与对齐的作品数)。"""+ seen: dict[str, set[str]] = {}+ longer = []+ for row in rows:+ keys, words = _keys(row), _words(row)+ if keys and len(keys) == len(words):+ _pair(seen, keys, words)+ elif words and len(keys) > len(words):+ longer.append((keys, words))+ known = {key: next(iter(words)) for key, words in seen.items() if len(words) == 1}+ votes: dict[str, int] = {}+ for keys, words in longer:+ extra = [key for key in keys if key not in seen]+ if extra and [known.get(key) for key in keys if key in seen] == words:+ for key in extra:+ votes[key] = votes.get(key, 0) + 1+ hidden = sorted((key for key, count in votes.items() if count >= HIDDEN_EVIDENCE), key=_order)+ skipped = len(rows) - sum(1 for row in rows if _keys(row) and len(_keys(row)) == len(_words(row)))+ for keys, words in longer:+ shown = [key for key in keys if key not in hidden]+ if len(shown) == len(words):+ _pair(seen, shown, words)+ skipped -= 1+ table = {key: next(iter(words)) for key, words in seen.items() if len(words) == 1}+ conflicts = {key: sorted(words) for key, words in seen.items() if len(words) > 1}+ return dict(sorted(table.items(), key=lambda item: _order(item[0]))), hidden, conflicts, skipped+++def _order(key):+ kind, _, number = key.partition(':')+ return int(kind), int(number) if number.isdigit() else 0, number+++def main():+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument('aligned', nargs='+', type=Path, help='对齐样本 JSON Lines')+ args = parser.parse_args()+ rows = [json.loads(line) for path in args.aligned+ for line in path.read_text(encoding='utf-8').splitlines() if line.strip()]+ table, hidden, conflicts, skipped = align(rows)+ target = PROJECT_ROOT / 'src/peach/javdb_genres.py'+ block = ('# BEGIN GENERATED_JAVDB_GENRES\nGENRES = '+ + json.dumps(table, ensure_ascii=False, indent=4)+ + '\nHIDDEN = frozenset(' + json.dumps(hidden, ensure_ascii=False, indent=4)+ + ')\n# END GENERATED_JAVDB_GENRES')+ source, count = re.subn(r'# BEGIN GENERATED_JAVDB_GENRES.*?# END GENERATED_JAVDB_GENRES',+ lambda _match: block, target.read_text(encoding='utf-8'), flags=re.S)+ if count != 1:+ raise ValueError('需要唯一的 JavDB 类别区块')+ target.write_text(source, encoding='utf-8', newline='\n')+ print(f'对照 {len(table)} 项,详情页不显示 {len(hidden)} 项,冲突 {len(conflicts)} 项,未对齐 {skipped} 部')+ for key, words in conflicts.items():+ print(f'冲突 {key}:' + '、'.join(words))+++if __name__ == '__main__':+ main()diff --git a/src/peach/community_catalog.py b/src/peach/community_catalog.pyindex 422b9211b..8920fb17a 100644--- a/src/peach/community_catalog.py+++ b/src/peach/community_catalog.py@@ -166,7 +166,10 @@ def same_scene(data: bytes, other: bytes) -> bool:def _download(transport, candidate: Candidate, *, deadline: float | None) -> tuple[Picture | None, str]:"""一张候选图:下载得到、宽度够小图门槛的静态图,再报这一张的下落:`fetched` 下载到了,- `paused` 来源正在冷却,`failed` 断在连接、5xx 或 404 上。"""+ `paused` 来源正在冷却,`failed` 断在连接、5xx 或 404 上。++ JavDB 匿名接口的图床可能给 XOR 包装过的字节,先按公开前端的包装解开再比对。"""+ from .javdb_public import decode_image, public_image_urltry:data = _fetch(transport, candidate.url, referer=candidate.referer, limit=IMAGE_LIMIT, deadline=deadline)except SourcePaused:@@ -174,7 +177,7 @@ def _download(transport, candidate: Candidate, *, deadline: float | None) -> tupexcept (NotFound, Unavailable, httpx.TransportError, OSError):return None, "failed"try:- found = picture(candidate, data)+ found = picture(candidate, decode_image(data, original=True) if public_image_url(candidate.url) else data)except (OSError, ValueError, Image.DecompressionBombError):return None, "fetched"return (found if found.size[0] >= SMALL_MIN_WIDTH else None), "fetched"diff --git a/src/peach/javdb_genres.py b/src/peach/javdb_genres.pynew file mode 100644index 000000000..4f299cce2--- /dev/null+++ b/src/peach/javdb_genres.py@@ -0,0 +1,46 @@+"""JavDB 匿名接口的类别 id 换回详情页的类别原词。++接口按作品给出类别名,是译名:同一个 (作品类型, 类别 id) 在不同作品上会写成不同的词+(`美臀` 与 `屁股`,`肛門・肛交` 与 `肛交`),不能直接交给 `genre_taxonomy`。这里按类别 id+换回详情页 `?locale=zh` 的原词,词表与用户的 genre 决定照旧按原词工作(ADR-0100、ADR-0140)。++对照由 `scripts/generate_javdb_genres.py` 把同一作品的详情页快照与接口资料按位置对齐生成;+同一个 id 对到两个原词的整项不收。`HIDDEN` 是接口给、详情页不显示的类别(如 `数位马赛克`),+不投出,否则有码作品会比详情页多出「有码」这类标签,与既有落库结果不一致。+"""+from __future__ import annotations++from collections.abc import Mapping++# BEGIN GENERATED_JAVDB_GENRES+GENRES = {}+HIDDEN = frozenset([])+# END GENERATED_JAVDB_GENRES+++def genre_key(kind: object, genre_id: object) -> str:+ """对照表的键:`<作品类型>:<类别 id>`;类型或 id 不是来源写法时返回空串。"""+ if type(kind) is not int or kind < 0:+ return ""+ value = str(genre_id or "").strip()+ return f"{kind}:{value}" if value.isdigit() else ""+++def page_genres(movie: Mapping) -> tuple[str, ...] | None:+ """接口作品的类别按详情页原词交出。++ 有一个类别不在对照表里就返回 `None`:这一站这次不给标签。只交认得出的那几个,+ ADR-0100 的自动重判会把那个类别此前落下的标签撤掉;把接口译名交出去,又会按+ 另一个词落库。两种都比不给更糟,未知类别补进对照表后自然恢复。+ """+ words = []+ for tag in movie.get("tags") or []:+ key = genre_key(movie.get("type"), tag.get("id") if isinstance(tag, Mapping) else None)+ if key in HIDDEN:+ continue+ word = GENRES.get(key)+ if not word:+ return None+ if word not in words:+ words.append(word)+ return tuple(words)diff --git a/src/peach/library_processing.py b/src/peach/library_processing.pyindex 0d8b49519..bb92ef869 100644--- a/src/peach/library_processing.py+++ b/src/peach/library_processing.py@@ -11,7 +11,7 @@ import threadingimport timeimport uuidimport xml.etree.ElementTree as ET-from contextlib import closing, contextmanager+from contextlib import closing, contextmanager, nullcontextfrom contextvars import copy_contextfrom concurrent.futures import ThreadPoolExecutor, wait, FIRST_COMPLETEDfrom dataclasses import dataclass@@ -109,7 +109,7 @@ SOURCE_LABELS = {'r18dev': 'r18.dev', 'dmm': 'DMM / FANZA', 'avbase': 'AVBase','sougouwiki': '素人系総合 Wiki', 'av_neme': 'このAV女優の名前教えてwiki','av_name': 'AV女優の名前特定wiki'}PROVIDER_NAMES = {'local_nfo': 'local-nfo', 'r18dev': 'r18-json', 'dmm': 'dmm-graphql', 'avbase': 'avbase-search',- 'javbus': 'javbus-page', 'javdb': 'javdb-page', 'fc2': 'fc2-article',+ 'javbus': 'javbus-page', 'javdb': 'javdb-api', 'fc2': 'fc2-article','fc2cmadb': 'fc2cmadb-article', 'fc2ppvdb': 'fc2ppvdb-page', 'javten': 'javten-page','javarchive': 'javarchive-page','1pondo': '1pondo-json',@@ -332,18 +332,25 @@ class LibraryMetadataProvider:`secrets_root` 是凭据根本身(`peach-data/secrets`),不是它底下的 `follow`:`CredentialStore` 自己会拼上那一层。多给一层的表现不是报错,是每个来源都读成「没有凭据」——采集设置里贴好的 JavBus、javdb Cookie 一条都不会被带上。++ `public_cache` 是匿名 JavDB 资料的快照目录(`<生成目录>/jav-public`),与新作页、发现共用;+ 不给就只在本进程内存里复用。"""- def __init__(self, secrets_root, *, tools_root=None):+ def __init__(self, secrets_root, *, tools_root=None, public_cache=None):from .scraping_access import SourceTransportfrom .jav_cover_fetch import HostLimitedTransportself.secrets_root = Path(secrets_root)#: amane 桥的 venv 所在的工具区(`<Peach 数据目录>/tools`);不给就用配置里的默认位置。self.tools_root = Path(tools_root) if tools_root is not None else None+ self.public_cache = Path(public_cache) if public_cache is not None else Noneself.transport = HostLimitedTransport(SourceTransport(secrets_root, max_requests=MAX_SOURCE_REQUESTS,max_bytes=MAX_SOURCE_BYTES, max_seconds=MAX_SOURCE_SECONDS),2.0, limiter=SOURCE_LIMITER)+ #: 匿名 JavDB 资料的快照目录;没有时只在进程内存里复用。+ public_cache = None+#: 由本机浏览器过验证的来源累计等人点验证的秒数(`_excuse`)。调用方拿它前后相减,把这段时间#: 从单项动作预算里扣掉:一个站第一次弹验证窗口时,那一问要等 `min(40, timeout) + 120` 秒,#: 超过一部片 90 秒的资料预算,不扣掉的话这部片会被记成「预算内未取得」(ADR-0065 第二条)。@@ -654,8 +661,10 @@ class LibraryMetadataProvider:没取到抛的是 `SourceFailure`:`not_found` 那一档由 `is_missing` 认,其余由 `describe_failure`写成一句。冷却、动作预算与连接失败由传输层抛出、原样放过。"""+ from .javdb_public import public_cache_scopefrom .sources import SITE_SOURCES, Session- return SITE_SOURCES[source]().query(code, session=Session(self.transport, deadline)).payload()+ with public_cache_scope(self.public_cache) if self.public_cache is not None else nullcontext():+ return SITE_SOURCES[source]().query(code, session=Session(self.transport, deadline)).payload()def query(self, code, source='r18dev', *, deadline=None):"""有码与素人链上逐个成档的官方来源:默认是 r18.dev(`sources/r18dev.py`),有码链上它之后是 DMM 的@@ -1139,6 +1148,26 @@ def _candidate_review_mode(groups, row, field, source, value, local_fields, verireturn 'review' if verify_existing and baseline and (not local or current) else 'fill'+def _previous_order(group, source, value):+ """同一来源再给的出演者只换了次序时沿用上一份。++ 候选身份按取值算(`_candidate_identity`),次序一变身份就变,已批准的那一行会被当成来源+ 换了说法、重新摆回复核页。javdb 的详情页与匿名接口列女优的次序不同,人却是同一批。+ """+ try:+ previous = next(entry['value'] for entry in json.loads(group['candidates_json'])+ if entry.get('source') == source)+ except (StopIteration, KeyError, TypeError, ValueError):+ return value+ fresh = value['value']+ if (not isinstance(previous, list) or not isinstance(fresh, list) or previous == fresh+ or sorted(json.dumps(one, ensure_ascii=False, sort_keys=True) for one in previous)+ != sorted(json.dumps(one, ensure_ascii=False, sort_keys=True) for one in fresh)):+ return value+ return {**value, 'value': previous,+ 'display_value': '、'.join(str(person.get('name') or '') for person in previous if isinstance(person, dict))}++def _merge_candidates(groups, row, code, source, document, evidence_path, genre_decisions, local_fields=(),*, verify_existing=False):"""把 `document` 里认得出的字段并进 `groups`:同来源的旧候选换掉,别的来源保留。@@ -1150,6 +1179,8 @@ def _merge_candidates(groups, row, code, source, document, evidence_path, genre_official = bool(spec and spec.official)for field, value in _fields(document, genre_decisions).items():key = f"asset:{row['id']}:{field}"+ if field == 'performers':+ value = _previous_order(groups.get(key), source, value)if not local and field == 'performers' and field in local_fields:_merge_local_performer_profiles(groups, key, value, source)mode = _candidate_review_mode(groups, row, field, source, value, local_fields, verify_existing)@@ -1471,8 +1502,9 @@ class _RemoteSession:def provider(self):if self._provider is None:self._provider = (self._factory() if self._factory- else LibraryMetadataProvider(self._config.directory('secrets'),- tools_root=self._config.directory('tools')))+ else LibraryMetadataProvider(+ self._config.directory('secrets'), tools_root=self._config.directory('tools'),+ public_cache=self._config.directory('generated') / 'jav-public'))return self._providerdef reset(self):diff --git a/src/peach/sources/__init__.py b/src/peach/sources/__init__.pyindex 36748e246..58c33915d 100644--- a/src/peach/sources/__init__.py+++ b/src/peach/sources/__init__.py@@ -10,7 +10,7 @@ from .fc2cmadb import FC2CMADB, Fc2cmadbSourcefrom .fc2ppvdb import FC2PPVDB, Fc2ppvdbSourcefrom .javarchive import JAVARCHIVE, JavArchiveSourcefrom .javbus import JAVBUS, JavBusSource-from .javdb import JAVDB, JavDBSource+from .javdb import JAVDB, JavDBPublicSource, JavDBSourcefrom .javten import JAVTEN, JavtenSourcefrom .onepondo import ONEPONDO, OnePondoSourcefrom .r18dev import R18DEV, R18DevSource@@ -30,7 +30,8 @@ SITE_SOURCES: dict[str, type[SiteSource]] = {JAVARCHIVE.name: JavArchiveSource,AVBASE.name: AVBaseSource,JAVBUS.name: JavBusSource,- JAVDB.name: JavDBSource,+ # 刮削走匿名接口(ADR-0140);详情页那一路的 `JavDBSource` 由视频预览直接取。+ JAVDB.name: JavDBPublicSource,**WIKI_SOURCES,}@@ -39,4 +40,4 @@ __all__ = ["COOLDOWN_ACTIONS", "PERMANENT_REASONS", "REASON_KINDS", "SITE_SOURCE"AVBASE", "DMM", "FC2", "FC2CMADB", "FC2PPVDB", "JAVARCHIVE", "JAVBUS", "JAVDB", "JAVTEN", "ONEPONDO","R18DEV", "SEESAA","AVBaseSource", "DmmSource", "Fc2Source", "Fc2cmadbSource", "Fc2ppvdbSource", "JavArchiveSource",- "JavBusSource", "JavDBSource", "JavtenSource", "OnePondoSource", "R18DevSource", "SeesaaSource"]+ "JavBusSource", "JavDBPublicSource", "JavDBSource", "JavtenSource", "OnePondoSource", "R18DevSource", "SeesaaSource"]diff --git a/src/peach/sources/javdb.py b/src/peach/sources/javdb.pyindex 8107eceae..13f01553d 100644--- a/src/peach/sources/javdb.py+++ b/src/peach/sources/javdb.py@@ -8,17 +8,24 @@ MGS 的 5/23、标题带 MGS 附注、演员里有男优,各字段按 Peach有隐藏 `origin-title` 时用作原标题,`current-title` 单独保存为显示标题;两者不互相改写。一部分页面要登录才给,回的是登入页而不是 401/403(`peach.javdb.LOGIN`),搜索页与详情页都要认。++刮削不读详情页,走 `JavDBPublicSource` 的匿名接口(ADR-0140):不带 Cookie,不占 javdb.com+的出口配额,字段投影成与详情页同形的记录。详情页解析留给视频预览。"""from __future__ import annotations+import dataclassesimport re+import timeimport urllib.parsefrom bs4 import BeautifulSoupfrom ..catalog_rules import same_release_codefrom ..javdb import LOGIN, clean+from ..javdb_genres import page_genresfrom ..javdb_identity import RULE+from ..javdb_public import actor_gender, public_image_urlfrom .base import FailureReason, Page, Session, SiteConfig, SiteRecord, SiteSource, SourceFailure#: 主机间隔由用户定(2026-09-22 定为 3 秒,每分钟 20 页)。参照面:每分钟 40~50 页会招来 3~7 天@@ -26,6 +33,14 @@ from .base import FailureReason, Page, Session, SiteConfig, SiteRecord, SiteSourJAVDB = SiteConfig(name="javdb", label="javdb", provider="javdb-page",base_url="https://javdb.com", domains=("javdb.com", "jdbstatic.com", "jdbimgs.com"),stage="community", interval=3.0, cookie=True)+#: 刮削那一问的配置。来源名、域名与 Cookie 仍是 `javdb` 这一站的(视频预览照旧读详情页,+#: 冷却按这个名字记);解析器名另起,候选与账本证据分得清是哪一种取法。接口自己的间隔、冷却与+#: 请求预算在 `peach.javdb_public`,这一问不经会话的传输。+JAVDB_PUBLIC = dataclasses.replace(JAVDB, provider="javdb-api")+#: 一问的请求上限:签名常量两次(一天一次)、搜索、详情。+PUBLIC_REQUESTS = 4+#: 会话没有动作截止时刻时,一问最多等这么久。+PUBLIC_SECONDS = 90.0_BOX = re.compile(r'<a href="(/v/[A-Za-z0-9]+)" class="box" title="[^"]*">.*?<strong>([^<]+)</strong>', re.S)_PANEL = re.compile(r'<div class="panel-block[^"]*">\s*<strong>([^<::]+)[::]</strong>\s*(?: )?\s*'@@ -120,6 +135,69 @@ class JavDBSource(SiteSource):'source_id': urllib.parse.urlsplit(page.url).path.rsplit('/', 1)[-1], 'javdb_rule': RULE})+def public_record(movie: dict) -> SiteRecord:+ """匿名接口的作品资料,投影成与详情页同形的记录。++ `origin_title` 对应详情页隐藏的原题,`title` 是显示标题;女优按接口的明确性别字段认。+ FC2 作品(`type` 3)的 `maker_name` 是卖家:按 `peach.sources.fc2` 的约定记进只作证据的+ `label`,不进厂牌。类别按 id 换回详情页原词,有表外 id 时不给标签(`javdb_genres.page_genres`)。+ """+ movie_id = str(movie.get("id") or "")+ fc2 = movie.get("type") == 3+ maker = maker_writing(clean(str(movie.get("maker_name") or "")))+ origin = clean(str(movie.get("origin_title") or ""))+ display = clean(str(movie.get("title") or ""))+ duration = movie.get("duration")+ cover = movie.get("cover_url")+ performers = tuple(+ {"japanese_name": clean(str(actor.get("name"))), "profile_source": "javdb",+ "external_id": str(actor.get("id") or "")}+ for actor in movie.get("actors") or []+ if isinstance(actor, dict) and actor_gender(actor) == "female" and clean(str(actor.get("name") or "")))+ return SiteRecord(+ source=JAVDB_PUBLIC.name, provenance=JAVDB_PUBLIC.provider, code=clean(str(movie.get("number") or "")),+ source_url=f"{JAVDB.base_url}/v/{movie_id}", title=origin or display, performers=performers,+ studio="" if fc2 else maker,+ label=clean(str(movie.get("publisher_name") or "")) or (maker if fc2 else ""),+ series=clean(str(movie.get("series_name") or "")), director=clean(str(movie.get("director_name") or "")),+ release_date=clean(str(movie.get("release_date") or "")),+ runtime=duration if type(duration) is int and duration > 0 else None,+ tags=page_genres(movie), cover_urls=(cover,) if public_image_url(cover) else (),+ extra={"origin_title": origin, "display_title": display, "source_id": movie_id, "javdb_rule": RULE})+++class JavDBPublicSource(JavDBSource):+ """刮削的 javdb 一问:匿名接口取资料,失败按缺失、歧义、冷却与未取得分档。++ 接口的问题不写 `javdb` 的来源冷却:那份冷却管的是详情页那条路(视频预览),+ 接口自己按 `PUBLIC_API` 的冷却停下,这里翻成 `SourcePaused`,本趟记作没轮到。+ """++ DEFAULT = JAVDB_PUBLIC++ def query(self, code: str, *, session: Session) -> SiteRecord:+ from ..javdb_public import (PUBLIC_API, PublicBudgetExceeded, PublicIdentityAmbiguous, PublicNotFound,+ PublicRequestBudget, PublicSourcePaused, PublicSourceUnavailable)+ from ..scraping_access import SourcePaused+ seconds = PUBLIC_SECONDS if session.deadline is None else session.deadline - time.monotonic()+ budget = PublicRequestBudget(max_requests=PUBLIC_REQUESTS, max_seconds=max(1.0, seconds))+ with self.holding(session):+ try:+ with PUBLIC_API.request_budget(budget):+ movie = PUBLIC_API.movie(code)+ except PublicIdentityAmbiguous as error:+ raise SourceFailure(FailureReason.PARSE_ERROR, f"javdb {error}", detail="identity_ambiguous") from None+ except PublicNotFound:+ raise SourceFailure(FailureReason.NOT_FOUND, "javdb 没有这个番号") from None+ except PublicSourcePaused as error:+ raise SourcePaused(f"javdb:{error}") from None+ except PublicBudgetExceeded:+ raise SourceFailure(FailureReason.TIMEOUT, "javdb 作品资料在本次预算内未取得") from None+ except PublicSourceUnavailable as error:+ raise SourceFailure(FailureReason.NETWORK, f"javdb:{error}") from None+ return public_record(movie)++_COMMENT_LINK = re.compile(r"(?:magnet:\?[^\s<>\"']+|ed2k://\|file\|[^\r\n<>]+?\|/|https?://[^\s<>\"']+)", re.I)_ED2K = re.compile(r"ed2k://\|file\|([^|]+)\|(\d+)\|([a-f0-9]{32})\|(?:[^\r\n]*?\|)?/", re.I)diff --git a/tests/test_community_catalog.py b/tests/test_community_catalog.pyindex b00119741..094fece6b 100644--- a/tests/test_community_catalog.py+++ b/tests/test_community_catalog.py@@ -9,13 +9,17 @@ from unittest.mock import patchimport httpxfrom PIL import Image-from peach.community_catalog import COMMUNITY_SOURCES, IMAGE_LIMIT, community_sources_for, verified_cover+from peach.community_catalog import COMMUNITY_SOURCES, IMAGE_LIMIT, _download, community_sources_for, verified_coverfrom peach.http import HttpResponsefrom peach.jav_cover_fetch import Candidate, NotFound, Unavailable, _fetch+from peach.javdb_genres import page_genres+from peach.javdb_public import (PUBLIC_API, PublicIdentityAmbiguous, PublicNotFound, PublicSourcePaused,+ PublicSourceUnavailable)+from peach.library_processing import _previous_orderfrom peach.scraping_access import SourcePaused-from peach.sources import (SITE_SOURCES, AVBaseSource, FailureReason, JavBusSource, JavDBSource, Page, Session,- SourceFailure)-from peach.sources.javdb import actresses as javdb_actresses+from peach.sources import (SITE_SOURCES, AVBaseSource, FailureReason, JavBusSource, JavDBPublicSource, JavDBSource,+ Page, Session, SourceFailure)+from peach.sources.javdb import actresses as javdb_actresses, public_recorddef gradient(width, height, rising=True):@@ -478,5 +482,115 @@ class SourceChoiceTests(unittest.TestCase):self.assertEqual(community_sources_for("AIN-203"), ())+#: 接口类别按 (作品类型, id) 换回详情页原词;测试只登记这几项。+PUBLIC_GENRES = {"0:28": "單體作品", "0:57": "美臀", "0:74": "肛門・肛交", "3:11": "私人攝影"}+PUBLIC_MOVIE = {+ "id": "Zb7mX", "type": 0, "number": "ABW-358", "title": "顯示標題", "origin_title": TITLE,+ "maker_name": "PRESTIGE,プレステージ", "publisher_name": None, "series_name": None, "director_name": None,+ "release_date": "2023-05-23", "duration": 210,+ "cover_url": "https://tp.spfcas.com/rhe951l4q/covers/zb/Zb7mX.jpg",+ "actors": [{"id": "a", "name": "涼森れむ", "gender": 0}, {"id": "m", "name": "男優", "gender": 1}],+ "tags": [{"id": "28", "name": "单体作品"}, {"id": "57", "name": "屁股"}, {"id": "74", "name": "肛交"},+ {"id": "299", "name": "数位马赛克"}]}+++class PublicSourceTests(unittest.TestCase):+ """刮削的 javdb 一问走匿名接口:记录与详情页同形,类别按 id 换回原词,失败按缺失、歧义、冷却分档。"""++ def setUp(self):+ for patcher in (patch.dict("peach.javdb_genres.GENRES", PUBLIC_GENRES, clear=True),+ patch("peach.javdb_genres.HIDDEN", frozenset({"0:299"}))):+ patcher.start()+ self.addCleanup(patcher.stop)++ def test_public_record_has_the_page_snapshot_shape_and_page_genre_words(self):+ payload = public_record(PUBLIC_MOVIE).payload()+ page = JavDBSource().parse(Page("https://javdb.com/v/Zb7mX", JAVDB_PAGE), "ABW-358").payload()+ self.assertEqual(set(payload), set(page))+ self.assertEqual(payload["genres"], ["單體作品", "美臀", "肛門・肛交"], "译名不进词表,详情页不显示的类别不投出")+ self.assertEqual((payload["title"], payload["display_title"], payload["origin_title"]),+ (TITLE, "顯示標題", TITLE))+ self.assertEqual(payload["actresses"], [{"japanese_name": "涼森れむ", "profile_source": "javdb", "external_id": "a"}])+ self.assertEqual((payload["maker"], payload["label"], payload["source_url"], payload["source_id"]),+ ("プレステージ", "", "https://javdb.com/v/Zb7mX", "Zb7mX"))+ record = public_record(PUBLIC_MOVIE)+ self.assertEqual((record.source, record.provenance), ("javdb", "javdb-api"))++ def test_an_unknown_genre_id_withholds_tags_instead_of_guessing(self):+ movie = {**PUBLIC_MOVIE, "tags": [*PUBLIC_MOVIE["tags"], {"id": "91", "name": "乳房"}]}+ self.assertIsNone(page_genres(movie))+ self.assertNotIn("genres", public_record(movie).payload())+ self.assertEqual(page_genres({**PUBLIC_MOVIE, "type": 1, "tags": [{"id": "28", "name": "单体作品"}]}), None,+ "类别 id 按作品类型分开登记")++ def test_fc2_seller_is_evidence_label_not_studio(self):+ movie = {**PUBLIC_MOVIE, "type": 3, "number": "FC2-1108030", "maker_name": "至高ぷれみあ!",+ "tags": [{"id": "11", "name": "ハメ撮り"}]}+ payload = public_record(movie).payload()+ self.assertEqual((payload["maker"], payload["label"], payload["genres"]), ("", "至高ぷれみあ!", ["私人攝影"]))++ def test_query_maps_public_failures_without_holding_the_page_cooldown(self):+ session = Session(serve({}))+ cases = ((PublicNotFound("没有"), SourceFailure, FailureReason.NOT_FOUND),+ (PublicIdentityAmbiguous("同番号对应多个作品"), SourceFailure, FailureReason.PARSE_ERROR),+ (PublicSourceUnavailable("未取得"), SourceFailure, FailureReason.NETWORK),+ (PublicSourcePaused("暂时不可用"), SourcePaused, None))+ for error, kind, reason in cases:+ with self.subTest(error=type(error).__name__), patch.object(PUBLIC_API, "movie", side_effect=error):+ with self.assertRaises(kind) as caught:+ JavDBPublicSource().query("ABW-358", session=session)+ if reason is not None:+ self.assertEqual(caught.exception.reason, reason)+ self.assertEqual(caught.exception.cooldown_action, "")+ with patch.object(PUBLIC_API, "movie", side_effect=PublicIdentityAmbiguous("x")):+ with self.assertRaises(SourceFailure) as caught:+ JavDBPublicSource().query("ABW-358", session=session)+ self.assertEqual(caught.exception.detail, "identity_ambiguous")+ self.assertIs(SITE_SOURCES["javdb"], JavDBPublicSource)++ def test_query_returns_the_public_record(self):+ with patch.object(PUBLIC_API, "movie", return_value=PUBLIC_MOVIE) as movie:+ record = JavDBPublicSource().query("ABW-358", session=Session(serve({})))+ movie.assert_called_once_with("ABW-358")+ self.assertEqual((record.code, record.studio, record.runtime), ("ABW-358", "プレステージ", 210))++ def test_wrapped_public_cover_is_unwrapped_before_comparison(self):+ body = gradient(800, 538)+ wrapped = bytes(value ^ 0x7F for value in body)+ url = PUBLIC_MOVIE["cover_url"]+ found, outcome = _download(serve({url: wrapped}), Candidate("tp.spfcas.com", url, ""), deadline=None)+ self.assertEqual((outcome, found.size), ("fetched", (800, 538)))++ def test_same_people_in_another_order_keep_the_previous_candidate_order(self):+ first = [{"name": "七沢みあ", "external_id": "NPD3"}, {"name": "初川みなみ", "external_id": "E6MM"}]+ group = {"candidates_json": json.dumps([{"source": "javdb", "value": first}], ensure_ascii=False)}+ swapped = {"value": list(reversed(first)), "display_value": "初川みなみ、七沢みあ", "warnings": []}+ self.assertEqual(_previous_order(group, "javdb", swapped)["value"], first)+ self.assertEqual(_previous_order(group, "javdb", swapped)["display_value"], "七沢みあ、初川みなみ")+ other = {"value": [first[0]], "display_value": "七沢みあ", "warnings": []}+ self.assertIs(_previous_order(group, "javdb", other), other)+ self.assertIs(_previous_order(group, "javbus", swapped), swapped)+ self.assertIs(_previous_order(None, "javdb", swapped), swapped)++ def test_genre_table_aligns_by_position_infers_hidden_genres_and_refuses_conflicts(self):+ from scripts.generate_javdb_genres import align+ rows = [{"type": 0, "api": [{"id": "57", "name": "屁股"}, {"id": "299", "name": "数位马赛克"}],+ "html": ["美臀"]},+ {"type": 0, "api": [{"id": "57", "name": "美臀"}, {"id": "30", "name": "女大学生"}],+ "html": ["美臀", "女大學生"]},+ {"type": 1, "api": [{"id": "30", "name": "3P"}], "html": ["3P"]},+ {"type": 0, "api": [{"id": "30", "name": "3P"}], "html": ["3P"]},+ {"type": 0, "api": [{"id": "8", "name": "精选综合"}], "html": []},+ {"type": 0, "api": [{"id": "65", "name": "苗条"}, {"id": "65", "name": "苗条"}], "html": ["苗條"]},+ {"type": 0, "api": [{"id": "57", "name": "美臀"}, {"id": "390", "name": "LTX破解"}], "html": ["美臀"]},+ {"type": 0, "api": [{"id": "65", "name": "苗条"}, {"id": "299", "name": "数位马赛克"}], "html": ["苗條"]}]+ table, hidden, conflicts, skipped = align(rows)+ self.assertEqual(table, {"0:57": "美臀", "0:65": "苗條", "1:30": "3P"},+ "重复类别先去重;只多出详情页不显示的那项时其余照样对齐")+ self.assertEqual(hidden, ["0:299"], "只有一部作品为证的 390 不算详情页不显示")+ self.assertEqual(conflicts, {"0:30": ["3P", "女大學生"]})+ self.assertEqual(skipped, 2)++if __name__ == "__main__":unittest.main()diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.pyindex 082a22354..f66e6b9ec 100644--- a/tests/test_metadata_library.py+++ b/tests/test_metadata_library.py@@ -1875,7 +1875,7 @@ class LibraryNfoTests(unittest.TestCase):self.assertEqual(sorted((c['source'], c['provider'], c['source_kind'], c['official'], c['provider_id'])for c in title),[('avbase', 'avbase-search', 'community', False, 'ORETD-615'),- ('javdb', 'javdb-page', 'community', False, 'ORETD-615')])+ ('javdb', 'javdb-api', 'community', False, 'ORETD-615')])self.assertEqual(rows['title']['source_profile'], 'library')self.assertEqual(len(json.loads(rows['release_date']['candidates_json'])), 2)