Peach: Local-first video metadata scraper and media manager.
feat(tooling): 批量写入登记 review_decision,并支持跳过个别番号
longmeidao69bb6f4bb968
diff --git a/scripts/apply_metadata_tags.py b/scripts/apply_metadata_tags.pyindex 54915be55..030b3ae2f 100644--- a/scripts/apply_metadata_tags.py+++ b/scripts/apply_metadata_tags.py@@ -37,19 +37,49 @@ def select_candidate(row: dict, source: str) -> dict | None:return None-def plan(rows: list[dict], source: str, field: str) -> list[tuple[dict, dict]]:+def plan(rows: list[dict], source: str, field: str,+ skip_codes: frozenset[str] = frozenset()) -> list[tuple[dict, dict]]:+ """选出要写的组。`skip_codes` 里的番号原样留在 CSV 里,只是不写库。++ 批量放行总有几条明显不对的,比如 javbus 在 `MY-*` 系列的标题栏放的是+ 「演员名+序号」。这种既不该混进批量写入,也不该从复核产物里删掉——+ 删了就没人再看见它。所以是跳过,不是过滤 CSV。+ """+ skip = {code.strip().upper() for code in skip_codes if code.strip()}selected: list[tuple[dict, dict]] = []for row in rows:if str(row.get("field") or "").strip() != field:continueif str(row.get("status") or "").strip() != "candidate":continue+ if str(row.get("code") or "").strip().upper() in skip:+ continuecandidate = select_candidate(row, source)if candidate is not None:selected.append((row, candidate))return selected+def _record_decision(connection, group: dict, candidate: dict, note: str, now: str) -> None:+ """把写入登记成 approved,留痕形状与 `/review` 手工批准完全一致。++ 不登记的后果实测过:2026-09-02 那 119 组标签写完仍原样挂在 `/review` 里,+ 看不出已经处理过。留痕里必须带 `candidate_key`——`_metadata_decision_is_stale`+ 正是靠它判断「这条旧批准指向的候选还在不在」,缺了它以后新来源就压不进来。+ """+ connection.execute(+ "INSERT INTO review_decision(category,item_key,status,note,updated_at) "+ "VALUES('metadata_fields',?,'approved',?,?) "+ "ON CONFLICT(category,item_key) DO UPDATE SET status=excluded.status,"+ "note=excluded.note,updated_at=excluded.updated_at",+ (str(group.get("item_key") or ""), json.dumps({+ "candidate_key": candidate.get("candidate_key"),+ "source": candidate.get("source"),+ "user_note": note,+ }, ensure_ascii=False, separators=(",", ":")), now),+ )++def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description="把字段候选里的标签直接写进 ledger")parser.add_argument("candidates", type=Path, help="scrape_codes 产出的字段候选 CSV")@@ -58,6 +88,10 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--field", default="tags", help="只写这个字段")parser.add_argument("--apply", action="store_true", help="写库;默认只统计")parser.add_argument("--backup", type=Path, help="--apply 必需:写库前的 SQLite 备份路径")+ parser.add_argument("--skip-codes", default="",+ help="逗号分隔的番号,留在 CSV 里但不写库")+ parser.add_argument("--note", default="批量直接写入(用户当轮授权)",+ help="写进 review_decision 留痕的说明")return parser@@ -65,8 +99,10 @@ def run(args: argparse.Namespace) -> int:if args.apply and not args.backup:raise SystemExit("--apply 必须同时给 --backup")rows = list(read_rows(args.candidates))- selected = plan(rows, args.source, args.field)- print(f"候选 {len(rows)} 组,来源 {args.source} 的 {args.field} 候选 {len(selected)} 组")+ skip = frozenset(str(args.skip_codes or "").split(","))+ selected = plan(rows, args.source, args.field, skip)+ print(f"候选 {len(rows)} 组,来源 {args.source} 的 {args.field} 候选 {len(selected)} 组"+ + (f",跳过番号 {args.skip_codes}" if args.skip_codes else ""))if not selected:return 0if not args.apply:@@ -92,16 +128,20 @@ def run(args: argparse.Namespace) -> int:for group, candidate in selected:try:assets += _apply_metadata_candidate(connection, group, candidate, now)- applied += 1except ValueError as error:# 逐组失败不该拖垮整批:番号已清库、候选值不规范都是常态。failures.append(f"{group.get('item_key')}: {error}")+ continue+ applied += 1+ _record_decision(connection, group, candidate, args.note, now)after = connection.execute("SELECT count(*) FROM asset_tag WHERE source LIKE 'javinizer:%:tag'").fetchone()[0]integrity = connection.execute("PRAGMA integrity_check").fetchone()[0]+ tag_delta = (f"javinizer 标签行 {before} -> {after};"+ if args.field == "tags" else "")print(f" 写入 {applied} 组、覆盖资产 {assets} 条;"- f"javinizer 标签行 {before} -> {after};integrity_check {integrity}")+ f"{tag_delta}integrity_check {integrity}")if failures:print(f" 跳过 {len(failures)} 组:")for line in failures[:10]:diff --git a/tests/test_scripts.py b/tests/test_scripts.pyindex 6ef25fc3f..98ec2cc91 100644--- a/tests/test_scripts.py+++ b/tests/test_scripts.py@@ -1451,6 +1451,23 @@ class ApplyMetadataTagsTests(unittest.TestCase):self.assertEqual([(group["item_key"], candidate["value"]) for group, candidate in selected],[("AAA-001:tags", ["素人"])])+ def test_skipped_codes_stay_in_the_csv_but_do_not_reach_the_ledger(self):+ """批量放行里总有几条明显不对,跳过它们,但不许从复核产物里抹掉。++ 实例:javbus 在 `MY-*` 系列的标题栏放的是「演员名+序号」而不是标题。+ 过滤 CSV 会让这几条从此没人看见;跳过则它们仍在 `/review` 里等人处理。+ """+ rows = [+ {"item_key": "MY-101:title", "code": "MY-101", "field": "title",+ "status": "candidate",+ "candidates_json": json.dumps([{"source": "javbus", "value": "最上彩奈1"}])},+ {"item_key": "TRE-080:title", "code": "TRE-080", "field": "title",+ "status": "candidate",+ "candidates_json": json.dumps([{"source": "javbus", "value": "なまなかだし"}])},+ ]+ selected = self.apply_tags.plan(rows, "javbus", "title", frozenset({"my-101"}))+ self.assertEqual([group["item_key"] for group, _ in selected], ["TRE-080:title"])+def test_apply_writes_tags_and_entities_for_the_whole_code(self):with tempfile.TemporaryDirectory() as tmp:root = Path(tmp)@@ -1496,7 +1513,15 @@ class ApplyMetadataTagsTests(unittest.TestCase):"SELECT count(*) FROM asset_entity WHERE role='tag' ""AND source='javinizer:javbus:tag'").fetchone()[0], 4,"标签实体那一半不能漏")+ row = connection.execute(+ "SELECT status,note FROM review_decision "+ "WHERE category='metadata_fields' AND item_key='TRE-080:tags'").fetchone()connection.close()+ self.assertIsNotNone(row, "写完不登记,这一组会永远挂在 /review 里")+ self.assertEqual(row[0], "approved")+ self.assertEqual(json.loads(row[1])["candidate_key"],+ "TRE-080:tags:javbus:abc",+ "留痕必须带候选身份,_metadata_decision_is_stale 靠它判过期")def test_dry_run_never_touches_the_database(self):with tempfile.TemporaryDirectory() as tmp: