Peach: Local-first video metadata scraper and media manager.
fix(metadata): Gfriends 索引退回旧缓存时告警,未收录不记结论
longmeidaoe62f35fd01f8
diff --git a/docs/SOURCING.md b/docs/SOURCING.mdindex 2c378b340..a63a73cb5 100644--- a/docs/SOURCING.md+++ b/docs/SOURCING.md@@ -223,6 +223,19 @@ av911.tv,三条候选已进复核队列。Cloudflare 拦,njav 有验证墙,jav321 无独立女优字段。被 Cloudflare 拦的站一律放弃,不绕过机器人检测。javdb.com 抓得到,但它自己按出口 IP 封速率(2026-09-04 封 3~7 日),只能小批量慢跑,见下文。Gfriends 只按 `Filetree.json` 和单张 raw 媒体当外部 Provider 用,不克隆图库、不把图片放进 Git。+ 索引缓存按 mtime 计龄(一天),取不到新索引就退回旧缓存并在输出里告警;那一轮的「未收录」+ 记 error 不记 no_match,否则 `--resume` 会把一次网络失败固化成永久答案。+- **DMM 女优一览页可达,但它的头像只有 125×125,对头像缺口没有用(2026-09-11 实测)。**+ `https://www.dmm.co.jp/mono/dvd/-/actress/=/keyword=<假名行>/` 经 Peach 的 `dmm` 来源设置+ 回 200、125 KB 的完整列表页(一页 120 位,带站内 actress id 与括号里的旧艺名),没有出现+ 区域拦截那句「このページはお住まいの地域からご利用になることができません」;+ `pics.dmm.co.jp/mono/actjpgs/<罗马字>.jpg` 不带 Referer 也回 200,确认无防盗链。+ 问题在尺寸:`actjpgs/<名>.jpg` 是 125×125、`actjpgs/medium/<名>.jpg` 是 100×100,长边 ≥500、+ 短边 ≥300 的候选门槛和 320px 的显示门槛都过不了。而且这批图 Gfriends 已经整批收着——+ `z-DMM(步)` 7011 条、`z-DMM(骑)` 14596 条,就排在质量档位的最后一档。所以不为它另起 provider:+ 同一个来源接第二遍,还少了档位排序和 AI 修复版。取证与重放脚本在仓库外的+ `attic/evidence/20260911-dmm-actress-probe/`。这个页面真正有价值的是名字不是头像:+ 一页 120 位日文名带旧艺名和站内 ID,要用就用在名字链与消歧上。- javdatabase 的入口必须是账本里的番号,不能按名字拼 slug。它一个艺名一页,slug 与人不是一对一:`/idols/rin-natsuki/` 打开的是 `Rin Oka` 的资料页;站内搜索也不给 idol 页,只回作品列表。链路固定为番号 → `/movies/<code>/` → 页面上给出的 idol 链接 → 名字,每一步都由上一步的页面给出diff --git a/scripts/audit_performer_portraits.py b/scripts/audit_performer_portraits.pyindex a534efd02..58a5bdb69 100644--- a/scripts/audit_performer_portraits.py+++ b/scripts/audit_performer_portraits.py@@ -26,6 +26,11 @@ r"""女优高清头像缺口审计:只产候选与缓存证据,不写 ledger- 外部图只进入候选专用内容寻址缓存,不写 `generated/avatars`;- 判定写入审计、`/review` 候选与来源健康 CSV;`--resume` 跳过已判定行,重试 error 和缺少 P2 缓存/provenance 的旧版 ok 行。++索引缓存的四条语义:判定不联网(索引一次性载入内存,逐人匹配纯离线)、按 mtime+计龄过期(`INDEX_MAX_AGE_SECONDS`)、取不到新索引时退回旧缓存并告警、写缓存用+临时文件加 `os.replace`。退回旧缓存那一轮的「未收录」记 error 不记 no_match,+理由见 `audit_missing`。"""from __future__ import annotations@@ -89,7 +94,7 @@ CANDIDATE_FIELDS = ()HEALTH_FIELDS = ("source", "profile", "policy_version", "index_cache_reused", "index_cache_stale",- "index_fetched",+ "index_cache_fallback", "index_fetched","attempted", "snapshot_reused", "fetched", "succeeded", "no_match","rejected", "duplicates", "errors", "bytes_fetched", "elapsed_ms","last_error_kind", "last_error_status", "last_error_message",@@ -138,7 +143,8 @@ class SourceHealth:self.row: dict[str, object] = {"source": "gfriends", "profile": "external_fallback","policy_version": POLICY_VERSION,- "index_cache_reused": 0, "index_cache_stale": 0, "index_fetched": 0,+ "index_cache_reused": 0, "index_cache_stale": 0,+ "index_cache_fallback": 0, "index_fetched": 0,"attempted": 0,"snapshot_reused": 0, "fetched": 0, "succeeded": 0,"no_match": 0, "rejected": 0, "duplicates": 0, "errors": 0,@@ -166,6 +172,7 @@ class SourceHealth:def parse_gfriends(body: bytes) -> dict[str, list[tuple[str, str]]]:+ """Filetree.json 字节 -> 日文名映射到 [(来源目录, 文件名)],按质量档位排序,最优在前。"""content = json.loads(body)["Content"]index: dict[str, list[tuple[str, str]]] = {}for category, items in content.items():@@ -178,18 +185,6 @@ def parse_gfriends(body: bytes) -> dict[str, list[tuple[str, str]]]:return index-def load_gfriends(transport: HttpTransport) -> dict[str, list[tuple[str, str]]]:- """日文名 -> [(来源目录, 文件名)],按质量档位排序,最优在前。"""- response = transport(- HttpRequest("GET", GFRIENDS_RAW + "Filetree.json",- {"Accept": "application/json"}),- 60, 32 * 1024 * 1024,- )- if response.status != 200:- raise RuntimeError(f"Gfriends 索引不可用:HTTP {response.status}")- return parse_gfriends(response.body)--#: 索引缓存的保鲜期。Gfriends 是持续增补的图库,缓存不能永不过期:只要文件在就一直#: 复用的话,快照那天没收录的人会被判成 `no_match`,此后每次重跑都照抄同一个结论,#: 没有任何时机被重新审视。实测:2026-08-25 的缓存里没有「釈アリス」,当天之后@@ -208,7 +203,13 @@ def _index_cache_age(cache_path: Path) -> float | None:def load_gfriends_cached(transport: HttpTransport, cache_dir: Path, refresh: bool, health: SourceHealth,-) -> dict[str, list[tuple[str, str]]]:+) -> tuple[dict[str, list[tuple[str, str]]], bool]:+ """返回 (索引, 是否是取不到新索引后退回的旧缓存)。++ 第二个值不是统计口径而是本轮结论的有效范围:拿旧索引跑出来的 `no_match` 只说明+ 「快照那天没有这个人」,不说明现在没有。调用方据此把那些行降级成可重试,+ 并在输出里说出来——旧缓存兜住的是流程,不是结论。+ """cache_path = cache_dir / "gfriends-filetree.json"age = _index_cache_age(cache_path)stale = age is None or age > INDEX_MAX_AGE_SECONDS@@ -216,7 +217,7 @@ def load_gfriends_cached(try:index = parse_gfriends(cache_path.read_bytes())health.add("index_cache_reused")- return index+ return index, Falseexcept (OSError, KeyError, TypeError, ValueError):health.error("invalid_index_cache", message=str(cache_path))if stale and cache_path.is_file():@@ -237,10 +238,12 @@ def load_gfriends_cached(except (KeyError, TypeError, ValueError) as error:health.error("index_payload", status=200, message=str(error))else:+ # 临时文件加 os.replace:换索引这一步没有中间态,别的进程读到的要么是+ # 上一份完整索引,要么是这一份,不会是半个 JSON。atomic_write(cache_path, response.body)health.add("index_fetched")health.add("bytes_fetched", len(response.body))- return index+ return index, Falseelif response is not None:health.error("index_http", status=response.status,message=f"Gfriends index HTTP {response.status}")@@ -248,7 +251,8 @@ def load_gfriends_cached(try:index = parse_gfriends(cache_path.read_bytes())health.add("index_cache_reused")- return index+ health.add("index_cache_fallback")+ return index, Trueexcept (OSError, KeyError, TypeError, ValueError):passraise RuntimeError("Gfriends 索引不可用,且没有有效本地缓存")@@ -409,6 +413,7 @@ def audit_skipped(record: dict) -> dict:def audit_missing(record: dict, index: dict, transport: HttpTransport, args: argparse.Namespace,cache: AvatarCandidateCache | None = None, health: SourceHealth | None = None,+ stale_index: bool = False,) -> dict:row = {field: "" for field in FIELDS}row["section"] = "missing"@@ -427,6 +432,15 @@ def audit_missing(entries = candidatebreakif not entries:+ if stale_index:+ # 索引这一轮没取到,手上只有旧缓存。「旧索引里没有这个人」不是结论,+ # 写成 no_match 会被 --resume 当成已判定,从此再没有重新问一次的时机——+ # 釈アリス 就是这么被固化过一次的。按网络失败处理,下一轮重试。+ row["verdict"] = "error"+ row["note"] = "Gfriends 索引为过期缓存,本轮未收录不算结论"+ if health is not None:+ health.error("stale_index_no_match", message=row["current_name"])+ return rowrow["verdict"] = "no_match"row["note"] = "Gfriends 未收录该名字链上的任何写法"if health is not None:@@ -646,7 +660,8 @@ def run(args: argparse.Namespace, transport: HttpTransport | None = None) -> inttry:print("拉取 Gfriends 索引…", flush=True)try:- index = load_gfriends_cached(client, args.cache_dir, args.refresh, health)+ index, stale_index = load_gfriends_cached(+ client, args.cache_dir, args.refresh, health)except RuntimeError as error:health.error("index_unavailable", message=str(error))write_health(args.health, health)@@ -654,6 +669,12 @@ def run(args: argparse.Namespace, transport: HttpTransport | None = None) -> intprint(f"来源健康 → {args.health}", flush=True)return 2print(f"索引就绪:{len(index)} 个名字键", flush=True)+ if stale_index:+ # 一行也不能省:旧缓存和新索引跑出来的 CSV 看起来一模一样,不说就没人知道+ # 这一轮的「找不到」只代表快照那天。+ age = _index_cache_age(args.cache_dir / "gfriends-filetree.json") or 0+ print(f"告警:未取到最新 Gfriends 索引,改用 {round(age / 3600)} 小时前的"+ f"本地缓存;本轮未收录一律记 error,网络恢复后重跑", flush=True)connection = open_readonly(args.db)targets = missing_targets(connection, args.avatars, 0)@@ -685,7 +706,8 @@ def run(args: argparse.Namespace, transport: HttpTransport | None = None) -> intfinished = 0def process_one(record: dict) -> dict:- return audit_missing(record, index, client, args, cache, health)+ return audit_missing(record, index, client, args, cache, health,+ stale_index)with futures.ThreadPoolExecutor(max(1, args.workers)) as pool:for row in pool.map(process_one, targets):diff --git a/tests/test_performer_portrait_audit.py b/tests/test_performer_portrait_audit.pyindex ff97cd9db..12e7ab70c 100644--- a/tests/test_performer_portrait_audit.py+++ b/tests/test_performer_portrait_audit.py@@ -1,3 +1,4 @@+import contextlibimport csvimport osimport importlib.util@@ -255,8 +256,7 @@ class PerformerPortraitAuditTests(unittest.TestCase):"0-Hand-Storage": {"篠田ゆう.jpg": "AI-Fix-篠田ゆう.jpg?t=2"},"7-S1": {"篠田ゆう.jpg": "篠田ゆう.jpg?t=3"},}}- transport = FakeTransport({"Filetree.json": payload(tree)})- index = module.load_gfriends(transport)+ index = module.parse_gfriends(payload(tree).body)categories = [entry[0] for entry in index["篠田ゆう"]]self.assertEqual(categories, ["0-Hand-Storage", "7-S1", "z-DMM(骑)"])# 键是展示名、值才是真实文件名,二者可以不同。@@ -268,7 +268,7 @@ class PerformerPortraitAuditTests(unittest.TestCase):"?Future": {"Remu Suzumori.jpg": "future.jpg?t=1"},"7-S1": {"remu suzumori.jpg": "known.jpg?t=2"},}}- index = module.load_gfriends(FakeTransport({"Filetree.json": payload(tree)}))+ index = module.parse_gfriends(payload(tree).body)self.assertEqual(index["remu suzumori"],[("7-S1", "known.jpg"), ("?Future", "future.jpg")])@@ -394,6 +394,73 @@ class PerformerPortraitAuditTests(unittest.TestCase):self.assertEqual(health.get("index_cache_stale"), "1","过期重取要和「本来就没缓存」在健康报告里分得开")+ def _run_on_stale_fallback(self, db: Path) -> str:+ """先跑一轮建好缓存,再把缓存放旧、让索引取不到,返回第二轮的输出。"""+ module = self.module+ first = FakeTransport({+ "Filetree.json": payload(GFRIENDS_TREE),+ "AI-Fix": FakeResponse(200, jpeg_bytes(500, 600)),+ })+ self.assertEqual(module.run(self.args(db), transport=first), 0)+ cache = next(self.tmp.rglob("gfriends-filetree.json"))+ aged = time.time() - module.INDEX_MAX_AGE_SECONDS - 60+ os.utime(cache, (aged, aged))++ printed = io.StringIO()+ with contextlib.redirect_stdout(printed):+ self.assertEqual(module.run(self.args(db), transport=FakeTransport({})), 0)+ return printed.getvalue()++ def test_falling_back_to_a_stale_index_is_announced_and_counted(self):+ """取不到新索引而用旧缓存,必须当场说出来,健康报告也要与正常复用分开。++ 两种情况产出的 CSV 长得一模一样:同一批人、同一批判定。不声明的话,一次+ GitHub 抖动就会让「这一轮的结论只代表快照那天」这件事无人知晓。+ """+ db = self.tmp / "ledger.db"+ make_ledger(db, [{"id": 1, "canonical": "立花美涼", "metadata": {}}], aliases=[])+ output = self._run_on_stale_fallback(db)+ self.assertIn("告警", output)+ self.assertIn("本地缓存", output)+ with self.health.open(encoding="utf-8-sig", newline="") as handle:+ health = next(csv.DictReader(handle))+ self.assertEqual(health["index_cache_fallback"], "1")+ self.assertEqual(health["index_cache_stale"], "1")+ # 已经缓存过的图不再出网,旧索引照样能把命中那位判成 ok。+ rows = {row["entity_id"]: row for row in self.rows() if row["section"] == "missing"}+ self.assertEqual(rows["1"]["verdict"], "ok")++ def test_a_stale_index_fallback_does_not_freeze_no_match(self):+ """旧索引里没有这个人,只说明快照那天没有,不能当成结论写进 CSV。++ no_match 是终态,`--resume` 见到就永远跳过。索引取不到时照写 no_match,+ 等于把一次网络失败变成一个再也不会被重新审视的答案——釈アリス 那次就是+ 这么固化的,区别只在于上一次的原因是缓存不过期,这一次是兜底缓存。+ """+ module = self.module+ db = self.tmp / "ledger.db"+ make_ledger(db, [+ {"id": 1, "canonical": "立花美涼", "metadata": {}},+ {"id": 2, "canonical": "釈アリス", "metadata": {}},+ ], aliases=[])+ self._run_on_stale_fallback(db)+ rows = {row["entity_id"]: row for row in self.rows() if row["section"] == "missing"}+ self.assertEqual(rows["2"]["verdict"], "error")+ self.assertIn("过期缓存", rows["2"]["note"])++ # 索引恢复后续跑:那一行必须被重新问一次,而不是被 --resume 跳过。+ grown = dict(GFRIENDS_TREE["Content"])+ grown["0-Hand-Storage"] = dict(grown["0-Hand-Storage"])+ grown["0-Hand-Storage"]["釈アリス.jpg"] = "AI-Fix-釈アリス.jpg?t=3"+ healthy = FakeTransport({+ "Filetree.json": payload({"Content": grown}),+ # 与 1 号那张不同的字节,否则会被同图去重判成 duplicate 而不是 ok。+ "AI-Fix": FakeResponse(200, jpeg_bytes(520, 620)),+ })+ self.assertEqual(module.run(self.args(db, resume=True), transport=healthy), 0)+ rows = {row["entity_id"]: row for row in self.rows() if row["section"] == "missing"}+ self.assertEqual(rows["2"]["verdict"], "ok")+def test_exact_duplicate_image_is_evidence_but_not_a_review_candidate(self):module = self.moduledb = self.tmp / "ledger.db"