Peach: Local-first video metadata scraper and media manager.
perf(portraits): 非 JAV 女优不再送去 JAV 图库白查
longmeidaoa56dd51270b4
diff --git a/scripts/audit_performer_portraits.py b/scripts/audit_performer_portraits.pyindex 29538b4c5..a09fabd86 100644--- a/scripts/audit_performer_portraits.py+++ b/scripts/audit_performer_portraits.py@@ -51,6 +51,7 @@ from peach.avatar_provider import (mark_duplicate_candidates,provenance_now,)+from peach.catalog_rules import is_jav_codefrom peach.config import DATABASE_PATH, GENERATED_DIRfrom peach.http import HttpRequest, HttpTransport, HttpxTransportfrom peach.review_csv import read_rows, write_rows@@ -351,8 +352,24 @@ def load_performers(connection: sqlite3.Connection) -> list[dict]:jp = ""records[entity_id] = {"entity_id": entity_id, "canonical": canonical or "",- "aliases": [], "jp": jp,+ "aliases": [], "jp": jp, "jav": True, "known_works": 0,}+ # 作品里有一个 JAV 番号就算 JAV。判据复用 catalog_rules.is_jav_code,不自己认番号+ # 形态——番号识别在别处已经统一过一次,这里再写一套只会两边漂。+ #+ # 「看不见作品」和「看得见但没有一个是 JAV」是两回事:前者是未知,后者才是证据。+ # 默认按未知处理(照查不误),只有拿到反面证据才跳过;把未知也当成非 JAV,+ # 任何一次取数疏漏都会静默地把人整批排除掉。+ for entity_id, total, codes in connection.execute(+ "SELECT ae.entity_id, count(*), group_concat(DISTINCT a.code) "+ "FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "+ "WHERE a.medium='video' GROUP BY ae.entity_id"):+ record = records.get(entity_id)+ if record is None:+ continue+ record["known_works"] = int(total or 0)+ record["jav"] = (not total) or any(+ is_jav_code(code) for code in str(codes or "").split(",") if code)for entity_id, alias in connection.execute("SELECT entity_id, alias FROM entity_alias ORDER BY alias"):record = records.get(entity_id)@@ -382,16 +399,44 @@ def lookup_chain(record: dict) -> list[tuple[str, str]]:def missing_targets(connection: sqlite3.Connection, avatar_dir: Path,limit: int) -> list[dict]:- """只选缺 performer-<id>.img 的 performer;有作品多者优先。"""+ """只选缺 performer-<id>.img 的 **JAV** performer;有作品多者优先。++ Gfriends 是 JAV 图库,拿非 JAV 的人去查必然落空。实测 567 位有作品的 performer 里+ 26 位不是 JAV,缺头像的 72 位里有 19 位属于此类(`桉X`、`古河君`、`Cola酱` 这些+ 中文素人创作者)。查它们不只是白费 19 次往返——更糟的是它们混进 `no_match`,把真正+ 的 JAV 缺口盖住,让人以为图库覆盖比实际差。++ 跳过不等于忽略:它们照样进审计表,只是判定写成 `skipped_not_jav`,说明「这个人需要+ 另一个来源」而不是「这个人查不到」。悄悄丢掉才是最糟的处理。+ """counts = {entity_id: n for entity_id, n in connection.execute("SELECT entity_id, count(*) FROM asset_entity GROUP BY entity_id")}targets = [record for record in load_performers(connection)- if not (avatar_dir / f"performer-{record['entity_id']}.img").exists()]+ if record.get("jav")+ and not (avatar_dir / f"performer-{record['entity_id']}.img").exists()]targets.sort(key=lambda record: (-counts.get(record["entity_id"], 0),record["entity_id"]))return targets[:limit] if limit else targets+def skipped_targets(connection: sqlite3.Connection, avatar_dir: Path) -> list[dict]:+ """缺头像但不走 JAV 图库的人。它们要出现在审计表里,不能凭空消失。"""+ return [record for record in load_performers(connection)+ if not record.get("jav")+ and not (avatar_dir / f"performer-{record['entity_id']}.img").exists()]+++def audit_skipped(record: dict) -> dict:+ row = {field: "" for field in FIELDS}+ row["section"] = "missing"+ row["entity_id"] = record["entity_id"]+ row["current_name"] = record["canonical"]+ row["policy_version"] = POLICY_VERSION+ row["verdict"] = "skipped_not_jav"+ row["note"] = "作品里没有 JAV 番号;Gfriends 是 JAV 图库,需要另一个来源"+ return row++def audit_missing(record: dict, index: dict, transport: HttpTransport, args: argparse.Namespace,cache: AvatarCandidateCache | None = None, health: SourceHealth | None = None,@@ -658,9 +703,14 @@ def run(args: argparse.Namespace, transport: HttpTransport | None = None) -> inttargets = targets[:args.limit]# 孤立审计纯本地、确定性:每轮全量重算,替换旧轮的 orphan 行。- rows = [row for row in rows if row.get("section") != "orphan"]+ rows = [row for row in rows if row.get("section") != "orphan"+ and row.get("verdict") != "skipped_not_jav"]orphan_rows = audit_orphans(connection, args.avatars)- print(f"缺口待审 {len(targets)} 位;孤立头像 {len(orphan_rows)} 个", flush=True)+ # 非 JAV 的人不查 JAV 图库,但要在表里留一行说明原因——悄悄消失最糟。+ skipped_rows = [audit_skipped(record)+ for record in skipped_targets(connection, args.avatars)]+ print(f"缺口待审 {len(targets)} 位;非 JAV 跳过 {len(skipped_rows)} 位;"+ f"孤立头像 {len(orphan_rows)} 个", flush=True)guard = threading.Lock()finished = 0@@ -675,7 +725,7 @@ def run(args: argparse.Namespace, transport: HttpTransport | None = None) -> intfinished += 1# 边跑边落盘:断电或断网不该丢掉已完成的部分。if finished % 20 == 0:- partial = [*rows, *orphan_rows]+ partial = [*rows, *orphan_rows, *skipped_rows]mark_duplicate_candidates(partial, installed_hashes)write_csv(args.out, partial)write_candidates(args.candidates, partial)@@ -683,6 +733,7 @@ def run(args: argparse.Namespace, transport: HttpTransport | None = None) -> intok = sum(1 for r in rows if r.get("verdict") == "ok")print(f" {finished}/{len(targets)} 已判定,命中 {ok}", flush=True)rows.extend(orphan_rows)+ rows.extend(skipped_rows)mark_duplicate_candidates(rows, installed_hashes)duplicates = sum(1 for row in rows if row.get("verdict") == "duplicate")if duplicates:diff --git a/tests/test_performer_portrait_audit.py b/tests/test_performer_portrait_audit.pyindex 85768ab56..678aca224 100644--- a/tests/test_performer_portrait_audit.py+++ b/tests/test_performer_portrait_audit.py@@ -64,7 +64,14 @@ def payload(obj) -> FakeResponse:def make_ledger(path: Path, entities: list[dict], aliases: list[tuple[int, str]],- asset_links: list[int] | None = None):+ asset_links: list[int] | None = None,+ codes: dict[int, str] | None = None):+ """`codes` 给某个 performer 的作品指定番号;不给就按 JAV 处理。++ 真实账本里 performer 是通过 `asset` 认出「是不是 JAV」的,而这个助手原本只建+ `asset_entity` 不建 `asset`——取像脚本一旦按作品判断来源,测试就整片报+ `no such table: asset`。补上这张表是让测试和真实 schema 对齐,不是为了迁就实现。+ """connection = sqlite3.connect(path)connection.execute("CREATE TABLE entity(id INTEGER PRIMARY KEY, kind TEXT,"" canonical_name TEXT, normalized_name TEXT, metadata_json TEXT)")@@ -74,6 +81,7 @@ def make_ledger(path: Path, entities: list[dict], aliases: list[tuple[int, str]]for link in asset_links or []:counts[link] = counts.get(link, 0) + 1connection.execute("CREATE TABLE asset_entity(asset_id INTEGER, entity_id INTEGER)")+ connection.execute("CREATE TABLE asset(id INTEGER PRIMARY KEY, medium TEXT, code TEXT)")for entity in entities:connection.execute("INSERT INTO entity(id, kind, canonical_name, normalized_name, metadata_json)"@@ -87,8 +95,11 @@ def make_ledger(path: Path, entities: list[dict], aliases: list[tuple[int, str]](entity_id, alias, alias.lower(), "test"))for entity_id, count in counts.items():for index in range(count):- connection.execute("INSERT INTO asset_entity VALUES(?,?)",- (entity_id * 100 + index, entity_id))+ asset_id = entity_id * 100 + index+ connection.execute("INSERT INTO asset_entity VALUES(?,?)", (asset_id, entity_id))+ connection.execute("INSERT INTO asset(id, medium, code) VALUES(?,?,?)",+ (asset_id, "video",+ (codes or {}).get(entity_id, "ABW-001")))connection.commit()connection.close()@@ -291,6 +302,64 @@ class PerformerPortraitAuditTests(unittest.TestCase):self.assertEqual(health["fetched"], "0")self.assertEqual(health["succeeded"], "1")+ def _performers(self, db):+ module = self.module+ connection = module.open_readonly(db)+ try:+ return {record["entity_id"]: record+ for record in module.load_performers(connection)}+ finally:+ connection.close()++ def test_a_performer_with_no_jav_release_is_not_sent_to_a_jav_library(self):+ """Gfriends 是 JAV 图库,拿非 JAV 的人去查必然落空。++ 实测 567 位有作品的 performer 里 26 位不是 JAV,缺头像的 72 位里 19 位属于此类+ (中文素人创作者)。查它们不只是白费往返——更糟的是它们混进 no_match,把真正+ 的 JAV 缺口盖住,让人以为图库覆盖比实际差。+ """+ db = self.tmp / "ledger.db"+ make_ledger(db,+ [{"id": 1, "canonical": "立花美涼", "metadata": {}},+ {"id": 2, "canonical": "Cola酱", "metadata": {}}],+ aliases=[], asset_links=[1, 2],+ codes={2: ""}) # 2 号的作品没有番号:非 JAV 的反面证据+ records = self._performers(db)+ self.assertTrue(records[1]["jav"])+ self.assertFalse(records[2]["jav"])+ targets = self.module.missing_targets(+ self.module.open_readonly(db), self.tmp / "avatars", 0)+ self.assertEqual([t["entity_id"] for t in targets], [1])++ def test_a_skipped_performer_still_appears_in_the_audit_table(self):+ """跳过不等于忽略。++ 悄悄丢掉最糟:复核的人看不到这个人,只会以为她根本不缺头像。所以照样出一行,+ 判定写成 skipped_not_jav,说明「需要另一个来源」而不是「查不到」。+ """+ db = self.tmp / "ledger.db"+ make_ledger(db, [{"id": 2, "canonical": "Cola酱", "metadata": {}}],+ aliases=[], asset_links=[2], codes={2: ""})+ skipped = self.module.skipped_targets(+ self.module.open_readonly(db), self.tmp / "avatars")+ self.assertEqual([record["entity_id"] for record in skipped], [2])+ row = self.module.audit_skipped(skipped[0])+ self.assertEqual(row["verdict"], "skipped_not_jav")+ self.assertEqual(row["section"], "missing")+ self.assertIn("JAV", row["note"])++ def test_a_performer_with_no_visible_works_is_still_looked_up(self):+ """看不见作品是未知,不是反面证据。++ 把未知也当成非 JAV,任何一次取数疏漏都会静默地把人整批排除掉——而那种失效+ 不会报错,只会让缺口悄悄变小。+ """+ db = self.tmp / "ledger.db"+ make_ledger(db, [{"id": 3, "canonical": "查无作品", "metadata": {}}], aliases=[])+ records = self._performers(db)+ self.assertTrue(records[3]["jav"], "没有作品证据时应当照查,不该跳过")+ self.assertEqual(records[3]["known_works"], 0)+def test_a_stale_index_cache_is_refetched_instead_of_reused_forever(self):"""索引缓存要有保鲜期,否则「找不到」这个结论会被永久固化。