Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

fix(metadata): 补打码标题、截图封面让位真封面、多人作品不做代表作

longmeidaoe93f3ffe56dc
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 50661ebc3..423e90aed 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -338,7 +338,8 @@ Python、npm 与 GitHub Actions 的版本由 `.github/dependabot.yml` 每周检
批量流程不请求社区来源,历史快照里的社区站记录只借厂牌;既有库采集在官方渠道落空时经
`peach.community_catalog` 查 AVBase、JavBus 与 javdb(后两家是 `peach.sources` 契约下的站;AVBase 搜索页 `/works?q=` 的 `__NEXT_DATA__`,
2026-09-14 实测可取;资料取商品号认得出这个番号的那条店铺条目,名寄せ的作品标题可能来自收录本作的
- 合集),封面按 dHash 先求两个图源一致,只有一个图源时照用并留空 `verified_by`,
+ 合集),封面按 dHash 先求两个图源一致(取景不同时再用 OpenCV ORB 特征点,相似变换内点 ≥60
+ 算同一张),只有一个图源时照用并留空 `verified_by`,
遇验证页不绕过(ADR-0030、ADR-0032)。DUGA Web API 需代理店应用 ID,未配置前
只复用成功日志的精确 URL。MDC-NG 公共仓库只证明 Amazon 日本渠道存在,后端匹配逻辑未公开,故只留
POC 候选。该流程不新增依赖、不写 ledger,操作步骤见 `peach-jav-cover-workflow`。
diff --git a/src/peach/avatar_cover_face.py b/src/peach/avatar_cover_face.py
index 952d5e49e..3b50fb77a 100644
--- a/src/peach/avatar_cover_face.py
+++ b/src/peach/avatar_cover_face.py
@@ -69,6 +69,11 @@ def faces(connection, cover_root: Path, entity_id: int, probe) -> list[CoverFace
面具、眼罩、脸贴照样算脸:梨奈的四张高清封面都戴着,YuNet 在默认门槛上全认了出来。
没认出来的那几张不靠降门槛去捞——同几张图上 0.2 到 0.45 分的框落在手、胸口和
身体上,比真脸还宽,按脸宽排序会排到最前面。
+
+ 截出来的那块方图上也要再检得出脸(`readable_cut`)。卖家自己打了模糊的商品图,
+ 整张缩小着看检得出一张很宽的脸,截出来放大就只剩一团色块:石川祐奈的
+ `FC2-PPV-3202758` 脸宽 616 像素排在最前,装上的头像认不出是谁,同一个人另两部片的
+ 封面却清清楚楚。
"""
found: list[CoverFace] = []
seen: set[str] = set()
@@ -84,7 +89,7 @@ def faces(connection, cover_root: Path, entity_id: int, probe) -> list[CoverFace
record = probe.on_bytes(body)
px = (record or {}).get("px") or [0, 0]
candidate = CoverFace(asset_id, key, body, int(px[0]), int(px[1]), record or {})
- if candidate.face_px > 0:
+ if candidate.face_px > 0 and readable_cut(candidate, probe):
found.append(candidate)
found.sort(key=lambda face: (face.face_px, face.width * face.height), reverse=True)
return found
@@ -130,6 +135,27 @@ def cut(face: CoverFace) -> tuple[bytes, dict] | None:
"face_px": face.face_px, "identity_verified": False}
+def _has_face(probe, body: bytes | None) -> bool:
+ return body is not None and isinstance((probe.on_bytes(body) or {}).get("face"), dict)
+
+
+def readable_cut(face: CoverFace, probe) -> bool:
+ """这张封面截出来的那块方图上还检得出脸。"""
+ cropped = cut(face)
+ return cropped is not None and _has_face(probe, cropped[0])
+
+
+def installed_face_readable(avatar_root: Path, kind: str, entity_id: int, probe) -> bool:
+ """装着的那张头像上检得出脸。检不出的封面截图不管当时脸多宽,任何一张认得出的脸都比它强。"""
+ from .previews import entity_image_key
+
+ try:
+ body = (Path(avatar_root) / f"{entity_image_key(kind, int(entity_id))}.img").read_bytes()
+ except OSError:
+ return False
+ return _has_face(probe, body)
+
+
def installed_face_px(avatar_root: Path, kind: str, entity_id: int) -> int | None:
"""装着的那张如果是这一档截的,返回它当时那张脸的像素宽;别的来源(或没有)是 None。
diff --git a/src/peach/avatar_followup.py b/src/peach/avatar_followup.py
index a2e0aab75..ded73593e 100644
--- a/src/peach/avatar_followup.py
+++ b/src/peach/avatar_followup.py
@@ -391,7 +391,8 @@ def _install_cover_face(contract, providers_root, avatar_root, kind: str,
`found` 是 `avatar_cover_face.faces` 的结果,按脸宽排好;图库比对用的也是这一份。
`cropped_px` 是装着的那张封面截图当时的脸宽(没装、或不是这一档装的是 None):
- 新挑出来的脸不比它宽就不换,免得每跑一次都把同一张图重写一遍。
+ 新挑出来的脸不比它宽就不换,免得每跑一次都把同一张图重写一遍。装着的那张上检不出
+ 脸时按 0 算:那是从打了模糊的封面上截的,脸再宽也认不出是谁。
"""
summary = {"name": name, "matched": matched}
if not found:
@@ -403,6 +404,8 @@ def _install_cover_face(contract, providers_root, avatar_root, kind: str,
for other in found[1:MAX_KEPT_FACES]:
if (extra := avatar_cover_face.cut(other)) is not None:
avatar_picker.keep(providers_root, entity_id, *extra)
+ if cropped_px and not avatar_cover_face.installed_face_readable(avatar_root, kind, entity_id, probe):
+ cropped_px = 0
if cropped_px is not None and face.face_px <= cropped_px:
return {**summary, "outcome": "已是最清楚的封面人脸", "source": face.code}
cut = avatar_cover_face.cut(face)
diff --git a/src/peach/catalog_rules.py b/src/peach/catalog_rules.py
index ae592ea62..c4002dc06 100644
--- a/src/peach/catalog_rules.py
+++ b/src/peach/catalog_rules.py
@@ -1181,3 +1181,38 @@ def photo_set_title(directory: str) -> str:
if leaf.casefold() in GENERIC_PHOTO_DIRS and len(parts) > 1:
return parts[-2]
return leaf
+
+
+def solo_performer_clause(asset: str, entity: str) -> str:
+ """`asset` 这部作品的出演者只有 `entity` 这一位。
+
+ 代表作头像是从接触印相里裁脸:多人作品的那一帧不一定是她,而同一部作品的每个
+ 出演者都会拿到同一张脸——HOISW-002 的三位在首页顶排就是三个一样的头像。
+ """
+ return (f"NOT EXISTS(SELECT 1 FROM asset_entity solo WHERE solo.asset_id={asset} "
+ f"AND solo.role='performer' AND solo.entity_id<>{entity})")
+
+
+#: FC2 站方替敏感词打的码:一个星号顶一个字(`10代**生` 原文是 `10代現役生`)。
+MASKED_TITLE_CHARS = "**"
+
+
+def fill_masked_title(masked: str, originals) -> str | None:
+ """用别家的原文补上 `masked` 里的码,补不上返回 None。
+
+ 每个星号按一个字配,其余字逐字对齐;原文里只取配上的那一段,镜像站在标题前后加的
+ 促销语(`初撮影・顔出し!3日間限定1980pt!!`)不跟着进来。几份原文补出的结果不一致
+ 时不补:那说明对齐落到了不同的地方,没有一份能单独作数。
+ """
+ text = str(masked or "")
+ if not any(char in text for char in MASKED_TITLE_CHARS):
+ return None
+ if not "".join(char for char in text if char not in MASKED_TITLE_CHARS).strip():
+ return None
+ pattern = re.compile("".join(
+ "[^**]" if char in MASKED_TITLE_CHARS else re.escape(char) for char in text))
+ filled = {found.group(0) for original in originals
+ if (candidate := str(original or ""))
+ and not any(char in candidate for char in MASKED_TITLE_CHARS)
+ and (found := pattern.search(candidate))}
+ return filled.pop() if len(filled) == 1 else None
diff --git a/src/peach/community_catalog.py b/src/peach/community_catalog.py
index d87c0c51d..0861661f8 100644
--- a/src/peach/community_catalog.py
+++ b/src/peach/community_catalog.py
@@ -7,6 +7,8 @@
MGS 的 5/23、标题带 MGS 附注、演员里有男优,所以社区来源的资料一律要两家一致才免复核。
封面比对用 dHash:两张图宽高比相差不超过 4%、64 位指纹相差不超过 10 位就算同一张。
+对不上时再比一次特征点(`same_scene`):javdb 给 FC2 的封面是同一张商品图另取景的
+276×276 方图,JavArchive 转存的是竖版,整图指纹两边差 39 位,特征点却有近三百个对得上。
同一张图出现在两个不同的图源(DMM、DUGA、MGS、JavBus、javdb 各算一个)就算印证;官方渠道
只取到小图时,那张小图也参加比对。可用的图全出自一个图源、没有别家可比时,取其中最大的
那张,印证图源留空(ADR-0032);两个图源各给了图却对不上,是有证据的冲突,不用。
@@ -34,6 +36,12 @@ IMAGE_ORIGINS = (("dmm", ("dmm.co.jp", "dmm.com")), ("duga", ("duga.jp",)),
ORIGIN_REFERERS = {JAVBUS.name: JAVBUS.referer, JAVDB.name: JAVDB.referer}
ASPECT_TOLERANCE = 0.04
HASH_DISTANCE = 10
+#: 两张图按一个相似变换对上的特征点至少这么多才算同一张。2026-09-24 实测:同一张商品图
+#: 的方图、竖图与水印框缩略图两两 275~301 个;本机 FC2 封面同卖家 28 张、随机 60 张两两
+#: 比下来最高 28 个(同一场拍摄拼成的两张图,共用一帧),其余不过 10 个。
+SCENE_INLIERS = 60
+#: 算特征点前把长边缩到这么长:几百像素已经够认,原图 3000 多像素只是白算。
+SCENE_SIDE = 400
#: 采集任务问社区来源的顺序。AVBase 与 JavBus 各一次请求,javdb 两次且配额紧,排在最后。
COMMUNITY_SOURCES = (AVBASE.name, JAVBUS.name, JAVDB.name)
@@ -109,40 +117,96 @@ def picture(candidate: Candidate, data: bytes) -> Picture:
def same_picture(one: Picture, other: Picture) -> bool:
ratio, other_ratio = one.size[0] / one.size[1], other.size[0] / other.size[1]
- return (abs(ratio - other_ratio) <= ASPECT_TOLERANCE * ratio
- and bin(one.fingerprint ^ other.fingerprint).count("1") <= HASH_DISTANCE)
+ if (abs(ratio - other_ratio) <= ASPECT_TOLERANCE * ratio
+ and bin(one.fingerprint ^ other.fingerprint).count("1") <= HASH_DISTANCE):
+ return True
+ return same_scene(one.data, other.data)
-def _pictures(transport, urls: dict[str, Candidate], reference, *,
- deadline: float | None) -> tuple[list[Picture], int]:
- """官方小图(有的话)加上社区来源里下载得到、宽度够小图门槛的静态图;再报下载到了几张。
+def _scene_features(data: bytes):
+ import cv2
+ import numpy
+
+ image = cv2.imdecode(numpy.frombuffer(data, numpy.uint8), cv2.IMREAD_GRAYSCALE)
+ if image is None or not image.size:
+ return None
+ scale = SCENE_SIDE / max(image.shape)
+ if scale < 1:
+ image = cv2.resize(image, None, fx=scale, fy=scale, interpolation=cv2.INTER_AREA)
+ return cv2.ORB_create(1000).detectAndCompute(image, None)
+
+
+def same_scene(data: bytes, other: bytes) -> bool:
+ """两张图是不是同一张照片的不同取景:ORB 特征点按相似变换对上 `SCENE_INLIERS` 个以上。
+
+ 整图指纹管不了取景不同:裁成方图、缩成竖图、套上水印框,dHash 就全变了。相似变换
+ 只许平移、等比缩放与旋转,两张不同的照片凑不出几十个同时满足它的点;同一场拍摄的
+ 两帧会有少量重合(背景、床单),所以门槛远高于实测的那几个。缺 vision 依赖组时退回
+ 只认整图指纹。
+ """
+ try:
+ import cv2
+ import numpy
+ except ImportError: # pragma: no cover - 缺 vision 依赖组
+ return False
+ first, second = _scene_features(data), _scene_features(other)
+ if not first or not second or first[1] is None or second[1] is None:
+ return False
+ (points, descriptors), (other_points, other_descriptors) = first, second
+ pairs = cv2.BFMatcher(cv2.NORM_HAMMING).knnMatch(descriptors, other_descriptors, k=2)
+ good = [best for best, runner in (pair for pair in pairs if len(pair) == 2)
+ if best.distance < 0.75 * runner.distance]
+ if len(good) < SCENE_INLIERS:
+ return False
+ source = numpy.float32([points[match.queryIdx].pt for match in good])
+ target = numpy.float32([other_points[match.trainIdx].pt for match in good])
+ _, mask = cv2.estimateAffinePartial2D(source, target, method=cv2.RANSAC,
+ ransacReprojThreshold=4)
+ return mask is not None and int(mask.sum()) >= SCENE_INLIERS
+
+
+def _download(transport, candidate: Candidate, *, deadline: float | None) -> tuple[Picture | None, bool]:
+ """一张候选图:下载得到、宽度够小图门槛的静态图,再报下载到没有。"""
+ try:
+ data = _fetch(transport, candidate.url, referer=candidate.referer, limit=IMAGE_LIMIT, deadline=deadline)
+ except (NotFound, Unavailable, SourcePaused, httpx.TransportError, OSError):
+ return None, False
+ try:
+ found = picture(candidate, data)
+ except (OSError, ValueError, Image.DecompressionBombError):
+ return None, True
+ return (found if found.size[0] >= SMALL_MIN_WIDTH else None), True
+
+
+def _pictures(transport, urls: dict[str, Candidate], reference, siblings: tuple[Candidate, ...], *,
+ deadline: float | None) -> tuple[list[Picture], int, int]:
+ """官方小图与它的同页图(有的话)加上社区来源里能用的图;再报社区来源下载到了几张、能用几张。
下载到了却不能用(动图、太窄)和没下载到是两回事:前者再问一遍还是这几张。
"""
pool = [picture(reference[0], reference[2])] if reference is not None else []
+ seen = {pool[0].candidate.url} if pool else set()
+ for candidate in siblings:
+ if candidate.url not in seen and candidate.url not in urls:
+ seen.add(candidate.url)
+ found, _ = _download(transport, candidate, deadline=deadline)
+ pool += [found] if found else []
+ official = len(pool)
fetched = 0
for url, candidate in urls.items():
- if reference is not None and url == reference[0].url:
- continue
- try:
- data = _fetch(transport, url, referer=candidate.referer, limit=IMAGE_LIMIT, deadline=deadline)
- except (NotFound, Unavailable, SourcePaused, httpx.TransportError, OSError):
+ if url in seen:
continue
- fetched += 1
- try:
- found = picture(candidate, data)
- except (OSError, ValueError, Image.DecompressionBombError):
- continue
- if found.size[0] >= SMALL_MIN_WIDTH:
- pool.append(found)
- return pool, fetched
+ found, downloaded = _download(transport, candidate, deadline=deadline)
+ fetched += downloaded
+ pool += [found] if found else []
+ return pool, fetched, len(pool) - official
def _unverified(pool: list[Picture], usable: int,
fetched: int) -> tuple[Candidate, tuple[int, int], bytes, tuple[str, ...]]:
"""没有两个图源对得上时的退路:图全出自一个图源就取最大那张,印证图源留空。
- `usable` 是池子里社区来源那几张,不算官方小图。"""
+ `usable` 是池子里社区来源那几张,不算官方小图与它的同页图。"""
if not usable:
if fetched:
raise NotFound("社区来源给的封面都是动图或太小")
@@ -156,22 +220,28 @@ def _unverified(pool: list[Picture], usable: int,
def verified_cover(transport, code: str, works: list[tuple[str, dict]], *,
reference: tuple[Candidate, tuple[int, int], bytes] | None = None,
+ siblings: tuple[Candidate, ...] = (),
deadline: float | None = None) -> tuple[Candidate, tuple[int, int], bytes, tuple[str, ...]]:
"""社区来源给的封面里,至少两个图源对得上的最大那张;返回值末尾是参与印证的图源。
`reference` 是官方渠道取到的小图,它也算一个图源:javdb 的大图和 DMM 的小图是同一张
时,大图就有了官方印证。没有第二个图源可比时按 `_unverified` 取图,末尾为空。
+
+ `siblings` 是官方渠道同一页上的其余几张,也下下来参加比对。官方那一档按尺寸挑出来的
+ 未必是封面:JavArchive 给 `FC2-PPV-3264420` 转存了 605×364 的正片截图、菱形水印框、
+ GIF 预览和 510×616 的竖版商品图,最宽的是截图,和 javdb 那张方图对得上的是竖版。
"""
urls = {url: _candidate(url) for _source, payload in works for url in payload.get("cover_urls") or []
if not is_cross_product_cover(code, url)}
if not urls:
raise NotFound("社区来源没有这部片的封面")
- pool, fetched = _pictures(transport, urls, reference, deadline=deadline)
+ siblings = tuple(one for one in siblings if not is_cross_product_cover(code, one.url))
+ pool, fetched, usable = _pictures(transport, urls, reference, siblings, deadline=deadline)
best = None
for one in pool:
origins = {other.origin for other in pool if same_picture(one, other)}
if len(origins) >= 2 and (best is None or one.pixels > best[0].pixels):
best = (one, tuple(sorted(origins)))
if best is None:
- return _unverified(pool, len(pool) - (reference is not None), fetched)
+ return _unverified(pool, usable, fetched)
return best[0].candidate, best[0].size, best[0].data, best[1]
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index b6efe0199..2baa2397b 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -152,6 +152,32 @@ def cover_settled(path):
return size is not None and max(size) >= MIN_WIDTH
+def _corrects_kept_cover(target, candidate, data, verified_by):
+ """本机那张更宽,却是没经印证的另一张图,而问来的这张经过了印证:照样换。
+
+ 官方那一档只按尺寸挑图,挑中的可能是正片截图:`FC2-PPV-3264420` 装上的是 JavArchive
+ 转存的 605×364 截图,真正的商品图是同页 510×616 那张竖版,javdb 的方图与它对得上。
+ 按宽度比,截图永远留着。所以本机那张 `.scraping.json` 里没有印证图源、和问来的这张
+ 又不是同一张图时,印证过的这张胜出;FC2 官方存储上的图是卖家自己传的商品图,不当错图换,
+ 没有来路记录的也不动。
+ """
+ from .community_catalog import picture, same_picture
+ from .scripting import host_under, hostname_of
+ if not verified_by:
+ return False
+ try:
+ evidence = json.loads(target.with_suffix('.scraping.json').read_text(encoding='utf-8'))
+ kept = picture(candidate, target.read_bytes())
+ fresh = picture(candidate, data)
+ except (OSError, ValueError, Image.DecompressionBombError):
+ return False
+ if not isinstance(evidence, dict) or evidence.get('verified_by'):
+ return False
+ if host_under(hostname_of(str(evidence.get('source_url') or '')), ('contents.fc2.com',)):
+ return False
+ return not same_picture(kept, fresh)
+
+
class LibraryMetadataProvider:
"""来源链各档的入口:按来源配置的传输,站经 `sources.SITE_SOURCES` 问(`site`),封面走 `cover`。
@@ -404,10 +430,10 @@ class LibraryMetadataProvider:
if cover_settled(target):
return False
kept = measure_image_file(target)
- official, verified_by, problems = None, (), []
+ official, verified_by, problems, siblings = None, (), [], ()
try:
- official = best_cover(self.transport, code, 0, deadline=deadline,
- prior_candidates=self._official_candidates(code, evidence, deadline=deadline),
+ siblings = self._official_candidates(code, evidence, deadline=deadline)
+ official = best_cover(self.transport, code, 0, deadline=deadline, prior_candidates=siblings,
minimum_width=SMALL_MIN_WIDTH)
except NotFound:
pass
@@ -417,7 +443,8 @@ class LibraryMetadataProvider:
if official is None or official[1][0] < MIN_WIDTH:
try:
*picked, verified_by = verified_cover(self.transport, code, self.community(code, deadline=deadline),
- reference=official, deadline=deadline)
+ reference=official, siblings=siblings if official else (),
+ deadline=deadline)
chosen = tuple(picked)
except NotFound:
pass
@@ -428,7 +455,7 @@ class LibraryMetadataProvider:
candidate, size, data = chosen
# 比宽度,不比面积:同一张缩略图各处转存常差一行像素(276×154 与 276×155),
# 按面积判就会拿一张一样糊的图换掉另一张。
- if kept and size[0] <= kept[0]:
+ if kept and size[0] <= kept[0] and not _corrects_kept_cover(target, candidate, data, verified_by):
if problems:
# 有来源这一趟没问成(冷却、配额、超时),它那里可能有原图:不能记成一周不问。
raise Unavailable(';'.join(problems))
diff --git a/src/peach/metadata_auto_apply.py b/src/peach/metadata_auto_apply.py
index e715a2f3b..e66adda6f 100644
--- a/src/peach/metadata_auto_apply.py
+++ b/src/peach/metadata_auto_apply.py
@@ -20,6 +20,7 @@ from pathlib import Path
from .catalog_rules import (
code_release_date,
collapse_superseded_taste_tags,
+ fill_masked_title,
is_korean_mib_code,
normalise_code_key,
release_code_from_filename,
@@ -484,6 +485,25 @@ def _evidence_candidates(row: dict, field: str = "") -> list[dict]:
and not blacklisted(field, str(c.get("source") or "").strip())]
+def _unmasked_titles(field: str, candidates: list[dict], current: str = "") -> list[dict]:
+ """标题候选里被站方打了码的,用别家原文或账本现值补上(`fill_masked_title`)。
+
+ FC2 官方页与镜像 fc2cmadb 把敏感词换成星号,JavArchive、javdb 给的是原文;链上
+ fc2 排在前面,不补的话打码那份就压过原文落进账本。账本现值也算一份原文:存量补好
+ 之后下一轮只剩打码那一家时,补出来的还是现值,不会被星号覆盖回去。
+ """
+ if field not in {"title", "original_title"}:
+ return candidates
+ originals = [str(c.get("display_value") or "") for c in candidates] + [current]
+ rows = []
+ for candidate in candidates:
+ filled = fill_masked_title(str(candidate.get("display_value") or ""), originals)
+ rows.append(candidate if filled is None else {
+ **candidate, "value": filled, "display_value": filled,
+ "masked_value": str(candidate.get("display_value") or "")})
+ return rows
+
+
def _settled_candidates(connection, field: str, code: str, candidates: list[dict],
resolve=None) -> tuple[list[dict], str | None, list[dict]]:
"""取值只剩一个的那组候选、据以取舍的规则,以及被压下的那些取值。
@@ -656,7 +676,8 @@ def metadata_auto_apply_candidate(connection, row: dict, *,
return None
resolve = _planning_alias_resolver(connection, row, snapshot_root)
candidates, settled_by, overruled = _settled_candidates(
- connection, field, code, _evidence_candidates(row, field), resolve)
+ connection, field, code, _unmasked_titles(
+ field, _evidence_candidates(row, field), str(row.get("current_value") or "")), resolve)
if not candidates:
return None
replaces_current = bool(str(row.get("current_value") or "").strip())
diff --git a/src/peach/taste_history.py b/src/peach/taste_history.py
index e4262cc78..16b9f68b5 100644
--- a/src/peach/taste_history.py
+++ b/src/peach/taste_history.py
@@ -693,6 +693,19 @@ def _epoch(value: object) -> float | None:
return None
+def _solo_representatives(linked: list[tuple[int, int, str, str]]) -> dict[str, int]:
+ """女优的代表作只取她单独出演的片:多人作品的封面裁脸,每个出演者都会拿到同一张脸。"""
+ performers: dict[int, set[int]] = defaultdict(set)
+ for aid, entity_id, kind, _ in linked:
+ if kind == "performer":
+ performers[aid].add(entity_id)
+ chosen: dict[str, int] = {}
+ for aid, _, kind, normalized in linked:
+ if kind == "performer" and len(performers[aid]) == 1:
+ chosen.setdefault(normalized, aid)
+ return chosen
+
+
def _peach_dashboard_evidence(connection: sqlite3.Connection, since: str | None) -> dict[str, object]:
since_epoch = datetime.fromisoformat(since).timestamp() if since else None
rows = connection.execute(
@@ -735,6 +748,7 @@ def _peach_dashboard_evidence(connection: sqlite3.Connection, since: str | None)
representatives: dict[str, dict[str, int]] = defaultdict(dict)
if assets:
ids = list(assets)
+ linked: list[tuple[int, int, str, str]] = []
for offset in range(0, len(ids), 800):
batch = ids[offset:offset + 800]
placeholders = ",".join("?" for _ in batch)
@@ -750,10 +764,12 @@ def _peach_dashboard_evidence(connection: sqlite3.Connection, since: str | None)
labels[kind][normalized] = str(entity["canonical_name"])
entity_ids[kind][normalized] = int(entity["entity_id"])
representatives[kind].setdefault(normalized, aid)
+ linked.append((aid, int(entity["entity_id"]), kind, normalized))
entity_kinds[aid].add(kind)
if assets[aid]["positive"]:
scores[kind][normalized] += float(assets[aid]["positive"])
items[kind][normalized].add(aid)
+ representatives["performer"] = _solo_representatives(linked)
for aid, asset in assets.items():
for kind, column in (("creator", "creator"), ("studio", "studio")):
diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.py
index 5dbd95ae8..bb44ec2c7 100644
--- a/src/peach/web_catalog.py
+++ b/src/peach/web_catalog.py
@@ -23,6 +23,7 @@ from .catalog_rules import (
normalise_code_key,
ordered_multipart_items,
part_marker,
+ solo_performer_clause,
tag_cat,
)
from .entities import normalize_entity_name, upsert_asset_entity
@@ -1039,6 +1040,7 @@ def q_tops(contract: WebContract, n=28, jav=False, seed="", state="", page=0):
"SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) n,"
"(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "
" WHERE ae2.entity_id=e.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL "
+ " AND (e.kind<>'performer' OR " + solo_performer_clause("a2.id", "e.id") + ") "
" ORDER BY (a2.play_count IS NULL),a2.size DESC LIMIT 1) rep "
"FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
"JOIN asset a ON a.id=ae.asset_id "
diff --git a/src/peach/web_entity.py b/src/peach/web_entity.py
index 45907b5a9..1528a5825 100644
--- a/src/peach/web_entity.py
+++ b/src/peach/web_entity.py
@@ -15,7 +15,7 @@ import time
from urllib.parse import urlsplit
from . import entry_links, feeds, web_feeds
-from .catalog_rules import LENGTH_TAGS, dir_expr, photo_set_title, tag_cat
+from .catalog_rules import LENGTH_TAGS, dir_expr, photo_set_title, solo_performer_clause, tag_cat
from .entities import normalize_entity_name, resolve_entity, rewrite_flat_projection
from .social_links import ARCHIVE_HOSTS, is_archive
from .web_catalog import (
@@ -170,7 +170,8 @@ def q_entity(contract: WebContract, args):
"SELECT count(DISTINCT ae.asset_id),"
"(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "
" WHERE " + scope_predicate(kind, "ae2.entity_id") +
- " AND a2.medium='video' AND a2.snapshot_path IS NOT NULL "
+ " AND a2.medium='video' AND a2.snapshot_path IS NOT NULL " +
+ (" AND " + solo_performer_clause("a2.id", "ae2.entity_id") if kind == "performer" else "") +
" ORDER BY a2.size DESC LIMIT 1) "
"FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "
"WHERE " + scope + " AND a.medium='video'", (d["id"], d["id"]),
@@ -203,7 +204,7 @@ def q_entity(contract: WebContract, args):
" WHERE ae.entity_id=person.id AND a.medium='video') n,"
"(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "
" WHERE ae2.entity_id=person.id AND a2.medium='video' "
- " AND a2.snapshot_path IS NOT NULL "
+ " AND a2.snapshot_path IS NOT NULL AND " + solo_performer_clause("a2.id", "person.id") +
" ORDER BY COALESCE(a2.play_count,0) DESC,COALESCE(a2.play_seconds,0) DESC,"
" COALESCE(a2.width,0)*COALESCE(a2.height,0) DESC,a2.size DESC LIMIT 1) rep "
"FROM entity_membership m JOIN entity person ON person.id=m.member_id "
@@ -214,7 +215,7 @@ def q_entity(contract: WebContract, args):
"SELECT person.id,person.canonical_name k,count(DISTINCT scope.asset_id) n,"
"(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "
" WHERE ae2.entity_id=person.id AND a2.medium='video' "
- " AND a2.snapshot_path IS NOT NULL "
+ " AND a2.snapshot_path IS NOT NULL AND " + solo_performer_clause("a2.id", "person.id") +
" ORDER BY COALESCE(a2.play_count,0) DESC,COALESCE(a2.play_seconds,0) DESC,"
" COALESCE(a2.width,0)*COALESCE(a2.height,0) DESC,a2.size DESC LIMIT 1) rep "
"FROM asset_entity scope "
@@ -485,7 +486,8 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")
entity_kind = INDEX_ENTITY_KINDS[kind]
sql = ("SELECT e.id entity_id,e.canonical_name k,count(DISTINCT ae.asset_id) n,"
"(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "
- " WHERE ae2.entity_id=e.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL "
+ " WHERE ae2.entity_id=e.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL " +
+ (" AND " + solo_performer_clause("a2.id", "e.id") if entity_kind == "performer" else "") +
" ORDER BY COALESCE(a2.play_count,0) DESC,COALESCE(a2.play_seconds,0) DESC,"
" COALESCE(a2.width,0)*COALESCE(a2.height,0) DESC,a2.size DESC LIMIT 1) rep "
"FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "
diff --git a/tests/test_community_catalog.py b/tests/test_community_catalog.py
index f834d7559..8914750cd 100644
--- a/tests/test_community_catalog.py
+++ b/tests/test_community_catalog.py
@@ -326,6 +326,55 @@ class VerifiedCoverTests(unittest.TestCase):
self.assertEqual(candidate.url, still)
+def photo(seed, crop=None, size=None):
+ """一张有纹理的「照片」:随机色块再糊一点,特征点才找得到角。`crop` 取其中一块,`size` 缩放。"""
+ import random
+ from PIL import ImageDraw, ImageFilter
+ rng = random.Random(seed)
+ image = Image.new("RGB", (800, 900), (128, 128, 128))
+ draw = ImageDraw.Draw(image)
+ for _ in range(400):
+ x, y = rng.randrange(800), rng.randrange(900)
+ draw.rectangle((x, y, x + rng.randrange(10, 80), y + rng.randrange(10, 80)),
+ fill=tuple(rng.randrange(256) for _ in range(3)))
+ image = image.filter(ImageFilter.GaussianBlur(1))
+ if crop:
+ image = image.crop(crop)
+ if size:
+ image = image.resize(size, Image.Resampling.LANCZOS)
+ buffer = io.BytesIO()
+ image.save(buffer, format="JPEG", quality=90)
+ return buffer.getvalue()
+
+
[email protected](__import__("importlib").util.find_spec("cv2"), "缺 vision 依赖组")
+class SameSceneTests(unittest.TestCase):
+ """javdb 给 FC2 的是商品图另取景的方图,JavArchive 转存的是竖版:整图指纹对不上,特征点对得上。"""
+
+ def test_a_square_crop_of_the_same_photo_is_the_same_picture(self):
+ from peach.community_catalog import same_scene
+ portrait = photo(1, size=(510, 574))
+ square = photo(1, crop=(100, 150, 700, 750), size=(276, 276))
+ self.assertTrue(same_scene(portrait, square))
+ self.assertFalse(same_scene(portrait, photo(2, crop=(100, 150, 700, 750), size=(276, 276))))
+
+ def test_the_official_pages_other_pictures_take_part_in_the_comparison(self):
+ """官方那一档按尺寸挑中的是截图;同页那张竖版商品图才和 javdb 的方图对得上。"""
+ screenshot = Candidate("img.javstore.net", "https://img.javstore.net/images/FC2PPV-3264420.jpg")
+ portrait = "https://img.javstore.net/images/FC2PPV-3264420PS.jpg"
+ square = "https://c0.jdbstatic.com/covers/ab/AbCd.jpg"
+ pages = {portrait: photo(1, size=(510, 574)),
+ square: photo(1, crop=(100, 150, 700, 750), size=(276, 276))}
+ works = [("javdb", {"cover_urls": [square]})]
+ reference = (screenshot, (605, 364), photo(3, size=(605, 364)))
+ with self.assertRaisesRegex(Unavailable, "不是同一张图"):
+ verified_cover(serve(pages), "FC2-PPV-3264420", works, reference=reference)
+ candidate, size, _data, origins = verified_cover(
+ serve(pages), "FC2-PPV-3264420", works, reference=reference,
+ siblings=(screenshot, Candidate("img.javstore.net", portrait)))
+ self.assertEqual((candidate.url, size, origins), (portrait, (510, 574), ("img.javstore.net", "javdb")))
+
+
class SourceChoiceTests(unittest.TestCase):
def test_an_fc2_product_number_only_goes_to_javdb(self):
"""AVBase 与 JavBus 的目录里没有 FC2,问了只是各撞一次空搜索。"""
diff --git a/tests/test_followups.py b/tests/test_followups.py
index 9410eee86..8bdbf4ed1 100644
--- a/tests/test_followups.py
+++ b/tests/test_followups.py
@@ -368,7 +368,9 @@ class CoverFaceFollowupTests(LedgerTestCase):
entity = AvatarFollowupTests.entity
#: 封面宽 → 脸框(相对宽度)。没列的宽度是一张检不出脸的封面,比如戴着面具的原图。
+ #: 截出来的方图脸在正中;绿底的是卖家打了模糊的封面,截出来那块检不出脸。
FACES = {600: 0.15, 276: 0.2, 1000: 0.3, 900: 0.5}
+ BLURRED = (40, 200, 40)
def setUp(self):
super().setUp()
@@ -383,9 +385,14 @@ class CoverFaceFollowupTests(LedgerTestCase):
unavailable = ""
def on_bytes(self, body):
- from peach.images import measure_image_size
- width, height = measure_image_size(body)
+ import io
+
+ from PIL import Image
+ image = Image.open(io.BytesIO(body)).convert("RGB")
+ width, height = image.size
share = faces.get(width)
+ if width == height:
+ share = None if image.getpixel((width // 2, height // 2))[1] > 150 else 0.4
face = ({"cx": 0.5, "cy": 0.4, "w": share, "h": share, "score": 0.9}
if share else None)
return {"ratio": width / height, "px": [width, height], "face": face}
@@ -399,11 +406,11 @@ class CoverFaceFollowupTests(LedgerTestCase):
self.addCleanup(sidecar.stop)
def work(self, asset_id: int, code: str, size: tuple[int, int] | None,
- performers: tuple[int, ...] = ()) -> None:
+ performers: tuple[int, ...] = (), colour="gray") -> None:
from PIL import Image
if size:
- Image.new("RGB", size, "gray").save(self.covers / f"{code}.jpg", format="JPEG")
+ Image.new("RGB", size, colour).save(self.covers / f"{code}.jpg", format="JPEG")
with self.database.write_transaction(notify=False) as connection:
connection.execute(
"INSERT INTO asset(id,location,path,name,medium,code,size) "
@@ -486,6 +493,22 @@ class CoverFaceFollowupTests(LedgerTestCase):
self.assertEqual(self.run_followup()["source"], "作品封面 FC2-PPV-5")
self.assertEqual(self.provenance()["face_px"], 300)
+ def test_a_blurred_cover_is_passed_over_even_with_the_widest_face(self):
+ """卖家打了模糊的商品图:整张检得出很宽的脸,截出来那块认不出人,挑下一张。"""
+ self.work(1, "FC2-PPV-1", (900, 600), colour=self.BLURRED)
+ self.work(2, "FC2-PPV-2", (276, 154))
+ self.assertEqual(self.run_followup()["source"], "作品封面 FC2-PPV-2")
+
+ def test_an_unreadable_crop_installed_earlier_gives_way_to_a_narrower_face(self):
+ self.work(2, "FC2-PPV-2", (276, 154))
+ (self.avatars / f"performer-{self.person}.img.provenance.json").write_text(
+ json.dumps({"provider": "cover-face", "face_px": 450}), encoding="utf-8")
+ from PIL import Image
+ Image.new("RGB", (400, 400), self.BLURRED).save(
+ self.avatars / f"performer-{self.person}.img", format="JPEG")
+ self.assertEqual(self.run_followup()["source"], "作品封面 FC2-PPV-2")
+ self.assertEqual(self.provenance()["face_px"], 55)
+
def test_a_whole_cover_installed_earlier_gives_way_to_any_face(self):
self.work(2, "FC2-PPV-2", (276, 154))
(self.avatars / f"performer-{self.person}.img").write_bytes(b"jpeg")
diff --git a/tests/test_metadata_library.py b/tests/test_metadata_library.py
index 0834eae3b..c285c3956 100644
--- a/tests/test_metadata_library.py
+++ b/tests/test_metadata_library.py
@@ -920,6 +920,57 @@ class LibraryNfoTests(unittest.TestCase):
self.assertNotIsInstance(raised.exception, CoverKept)
self.assertEqual((covers / 'FC2-PPV-3.jpg').read_bytes(), before)
+ def test_a_verified_cover_replaces_a_wider_unverified_picture_of_something_else(self):
+ """官方那一档按尺寸挑中的是正片截图:同页竖版商品图经 javdb 印证后,窄一点也换上。
+
+ FC2 官方存储上那张是卖家自己传的商品图,没印证也不当错图换;已经印证过的也不换。
+ """
+ from peach.jav_cover_fetch import Candidate
+ from peach.library_processing import CoverKept, LibraryMetadataProvider
+ provider = LibraryMetadataProvider.__new__(LibraryMetadataProvider)
+ provider.transport = Mock()
+ portrait_url = 'https://img.javstore.net/images/FC2PPV-1PS.jpg'
+ siblings = (Candidate('img.javstore.net', portrait_url),)
+ provider._official_candidates = Mock(return_value=siblings)
+ provider.community = Mock(return_value=[('javdb', {'cover_urls': ['https://c0.jdbstatic.com/covers/x.jpg']})])
+ covers = self.root / 'covers'
+ covers.mkdir()
+
+ def gradient(size, rising):
+ image = Image.new('L', size)
+ image.putdata([int(255 * (x if rising else size[0] - 1 - x) / (size[0] - 1))
+ for x in range(size[0])] * size[1])
+ buffer = io.BytesIO()
+ image.convert('RGB').save(buffer, format='JPEG')
+ return buffer.getvalue()
+
+ screenshot = (Candidate('img.javstore.net', 'https://img.javstore.net/images/FC2PPV-1.jpg'),
+ (605, 364), gradient((605, 364), True))
+ portrait = (siblings[0], (510, 616), gradient((510, 616), False), ('img.javstore.net', 'javdb'))
+
+ def kept(code, **evidence):
+ (covers / f'{code}.jpg').write_bytes(screenshot[2])
+ (covers / f'{code}.scraping.json').write_text(json.dumps(
+ {'source_url': screenshot[0].url, 'verified_by': [], **evidence}), encoding='utf-8')
+
+ kept('FC2-PPV-1')
+ with patch('peach.jav_cover_fetch.best_cover', return_value=screenshot), \
+ patch('peach.community_catalog.verified_cover', return_value=portrait) as verified:
+ self.assertTrue(provider.cover('FC2-PPV-1', covers))
+ self.assertEqual(verified.call_args.kwargs['siblings'], siblings)
+ self.assertEqual((covers / 'FC2-PPV-1.jpg').read_bytes(), portrait[2])
+ evidence = json.loads((covers / 'FC2-PPV-1.scraping.json').read_text(encoding='utf-8'))
+ self.assertEqual((evidence['width'], evidence['verified_by']), (510, ['img.javstore.net', 'javdb']))
+
+ kept('FC2-PPV-2', source_url='https://storage71000.contents.fc2.com/file/1.jpg')
+ kept('FC2-PPV-3', verified_by=['dmm', 'javdb'])
+ for code in ('FC2-PPV-2', 'FC2-PPV-3'):
+ with patch('peach.jav_cover_fetch.best_cover', return_value=screenshot), \
+ patch('peach.community_catalog.verified_cover', return_value=portrait), \
+ self.assertRaises(CoverKept):
+ provider.cover(code, covers)
+ self.assertEqual((covers / f'{code}.jpg').read_bytes(), screenshot[2])
+
@windows_ledger_roots
def test_codes_r18_does_not_know_are_collected_from_the_community_sources(self):
"""r18.dev 没有的番号问 AVBase 与 javdb,两家各留一条候选;免不免复核由落库那道闸按几家一致判。"""
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 6b0a4dca8..418e08f3e 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -495,6 +495,26 @@ class WebDataTests(unittest.TestCase):
self.assertEqual([row["rep"] for row in tops], [1], "代表作仍会被选出来")
self.assertEqual([row["has_avatar"] for row in tops], [False])
+ def test_a_work_with_several_performers_is_nobodys_representative(self):
+ """代表作头像是从接触印相里裁脸:多人作品的每个出演者都会拿到同一张脸。"""
+ con = sqlite3.connect(self.db_path)
+ con.execute("UPDATE asset SET snapshot_path='one.jpg' WHERE id IN (1,2)")
+ con.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) "
+ "VALUES(14,'performer','Carol','carol','2026-01-01','2026-01-01')")
+ con.executemany("INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) "
+ "VALUES(?,?,'performer','test',1.0)", [(1, 14), (2, 11)])
+ con.commit()
+ con.close()
+ self.contract.cache_bust()
+ tops = {row["k"]: row["rep"] for row in rm_web.q_tops(self.contract, 30)["performers"]}
+ self.assertEqual(tops, {"Canonical Alice": 2, "Carol": None})
+ pages = {name: rm_web.q_entity(self.contract, {"kind": "performer", "name": name})
+ for name in ("Carol", "Canonical Alice")}
+ self.assertEqual({name: page["representative_asset_id"] for name, page in pages.items()},
+ {"Carol": None, "Canonical Alice": 2})
+ studios = {row["k"]: row["rep"] for row in rm_web.q_tops(self.contract, 30)["studios"]}
+ self.assertIsNotNone(studios["Canonical Studio"], "厂牌不看出演人数")
+
def _install_snapshot(self, asset_id=1):
"""给一条作品配一份真的印相文件,让它的代表作头像变成取得到。"""
snapshot = Path(self.tmp.name).resolve() / f"snapshot-{asset_id}.jpg"
diff --git a/tests/test_web_review.py b/tests/test_web_review.py
index 75b694df0..4da4b70c0 100644
--- a/tests/test_web_review.py
+++ b/tests/test_web_review.py
@@ -835,6 +835,35 @@ class ReviewQueueTests(unittest.TestCase):
self.assertEqual(_fc2_seller_as_label("studio", "ABP-001", {"value": "Prestige"}),
{"value": "Prestige"})
+ def test_a_title_the_seller_site_masked_is_filled_in_from_another_source(self):
+ """FC2 与 fc2cmadb 把敏感字打成 `*`,javdb 留着原文:落库的是补全的那一句。"""
+ masked = "10代**生、奇跡の美**しほちゃん"
+ whole = "10代女子生、奇跡の美少女しほちゃん"
+ self._asset(131, "FC2-PPV-2683017", "FC2-PPV-2683017.mp4")
+ self._asset(132, "FC2-PPV-2683018", "FC2-PPV-2683018.mp4")
+ self.write_metadata_rows([
+ {"item_key": "MASKED:title", "field": "title", "current": "", "code": "FC2-PPV-2683017",
+ "candidates": [{"source": "fc2", "value": masked}, {"source": "javdb", "value": whole}]},
+ {"item_key": "LONE:title", "field": "title", "current": "", "code": "FC2-PPV-2683018",
+ "candidates": [{"source": "fc2", "value": masked}]},
+ ])
+ self._auto()
+ con = sqlite3.connect(self.db_path)
+ try:
+ titles = dict(con.execute("SELECT id,catalog_title FROM asset WHERE id IN (131,132)"))
+ finally:
+ con.close()
+ self.assertEqual(titles[131], whole)
+ self.assertEqual(titles[132], masked, "没有别家原文可对时照旧用站方给的那句")
+ from peach.catalog_rules import fill_masked_title
+ self.assertEqual(fill_masked_title("【無修正】**ちゃん", ["[FC2] 【無修正】ゆあちゃん 中出し"]),
+ "【無修正】ゆあちゃん")
+ self.assertIsNone(fill_masked_title("****", [whole]), "全是码的一句对不出位置")
+ self.assertIsNone(fill_masked_title(masked, ["10代女子生、奇跡の美少女しほちゃん",
+ "10代男子生、奇跡の美少年しほちゃん"]),
+ "两家原文各补出一句时不猜")
+ self.assertIsNone(fill_masked_title(whole, [whole]))
+
def test_library_collection_fills_an_empty_field_from_a_lone_community_source(self):
"""官方落空时只有 javdb 一家也补空,note 里分得清是一家还是两家一致(ADR-0034)。"""
self._asset(90, "ABW-358", "ABW-358.mp4")