Peach: Local-first video metadata scraper and media manager.
feat(names): 复核过的名字清理走同一个脚本
longmeidaob27082ecdc34
diff --git a/scripts/split_composite_aliases.py b/scripts/split_composite_aliases.pyindex 58382c59a..65f19990b 100644--- a/scripts/split_composite_aliases.py+++ b/scripts/split_composite_aliases.py@@ -15,6 +15,9 @@ r18.dev 的罗马字字段本身就是 `现用名 (曾用名, 曾用名)` 这个- `快慢扳机(接稿中)`、`るかぴあ(X:復帰しました)`:括号里是接稿状态或公告。- `kitty(1)`、`Mana(23)`:去重后缀或数字。+形状分不开的那些交人工:在复核 CSV 里把 `verdict` 改成 `split`(别名拆成几条)或+`strip`(规范名换成 `target`,旧名留作别名),填好 `target`,再用 `--from-review` 跑。+拆分不可逆。默认只产出复核 CSV,`--apply` 才写 ledger 且必须给 `--backup`。"""from __future__ import annotations@@ -22,6 +25,7 @@ from __future__ import annotationsimport argparseimport sqlite3import sys+import timefrom collections import Counterfrom pathlib import Path@@ -32,9 +36,9 @@ if str(SRC_DIR) not in sys.path:from peach.config import GENERATED_DIR # noqa: E402from peach.entities import ( # noqa: E402- normalize_entity_name, split_composite_person_name,+ normalize_entity_name, rewrite_flat_projection, split_composite_person_name,)-from peach.review_csv import write_rows # noqa: E402+from peach.review_csv import read_rows, write_rows # noqa: E402from peach.scripting import ( # noqa: E402add_ledger_write_args, counts_of, open_for_write, verify_after_write,)@@ -43,7 +47,10 @@ from peach.scripting import ( # noqa: E402PERSON_KINDS = ("performer", "creator")FIELDS = ("verdict", "kind", "entity_id", "canonical_name", "field",- "value", "source", "parts", "note")+ "value", "source", "parts", "target", "note")++#: 人工判定改写规范名时,换下来的旧名记在这个来源下。它不是哪个站给的,是用户定的。+CLEANUP_SOURCE = "user:name-cleanup"EXTRA_COUNTS = {"composite_alias": (@@ -96,7 +103,8 @@ def collect(connection: sqlite3.Connection) -> list[dict[str, object]]:rows.append({"verdict": verdict, "kind": kind, "entity_id": int(entity_id),"canonical_name": canonical, "field": field, "value": value,- "source": source or "", "parts": " | ".join(parts), "note": note,+ "source": source or "", "parts": " | ".join(parts),+ "target": " | ".join(parts) if verdict == "auto" else "", "note": note,})rows.sort(key=lambda row: (row["verdict"] != "auto", str(row["kind"]),int(row["entity_id"])))@@ -128,6 +136,60 @@ def apply_rows(connection: sqlite3.Connection,return {"added": added, "removed": removed}+def _blocked(connection: sqlite3.Connection, entity_id: int,+ names: list[str]) -> str:+ """人工判定也过一遍碰撞:撞上另一条实体的规范名要走合并,不是改个名了事。"""+ return ";".join(hit for hit in (_collision(connection, entity_id, name)+ for name in names) if hit)+++def apply_review(connection: sqlite3.Connection,+ rows: list[dict[str, str]]) -> dict[str, object]:+ """按人工填好的 `verdict` 与 `target` 改名字。++ `split`:把一条别名换成 `target` 里那几条,来源不变。+ `strip`:把规范名换成 `target` 的第一段,旧名留作别名,扁平投影跟着改。+ """+ done = {"split": 0, "strip": 0, "flat": 0, "blocked": []}+ for row in rows:+ verdict = str(row.get("verdict", "")).strip()+ targets = [part.strip() for part in str(row.get("target", "")).split("|")+ if part.strip()]+ if verdict not in {"split", "strip"} or not targets:+ continue+ entity_id, value = int(row["entity_id"]), str(row["value"])+ blocked = _blocked(connection, entity_id, targets)+ if blocked:+ done["blocked"].append(f"{value}:{blocked}")+ continue+ if verdict == "split":+ source = str(row.get("source", ""))+ for target in targets:+ connection.execute(+ "INSERT OR IGNORE INTO entity_alias"+ "(entity_id,alias,normalized_alias,source) VALUES(?,?,?,?)",+ (entity_id, target, normalize_entity_name(target), source))+ connection.execute(+ "DELETE FROM entity_alias WHERE entity_id=? AND alias=? AND source=?",+ (entity_id, value, source))+ done["split"] += 1+ continue+ target = targets[0]+ stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+ connection.execute(+ "UPDATE entity SET canonical_name=?,normalized_name=?,updated_at=? WHERE id=?",+ (target, normalize_entity_name(target), stamp, entity_id))+ # 旧名留作别名:它是这条实体真的用过的写法,也是回退的入口。+ connection.execute(+ "INSERT OR IGNORE INTO entity_alias"+ "(entity_id,alias,normalized_alias,source,confidence) VALUES(?,?,?,?,1.0)",+ (entity_id, value, normalize_entity_name(value), CLEANUP_SOURCE))+ done["flat"] += rewrite_flat_projection(+ connection, str(row["kind"]), entity_id, value, target)+ done["strip"] += 1+ return done++def build_parser() -> argparse.ArgumentParser:parser = argparse.ArgumentParser(description=__doc__,formatter_class=argparse.RawDescriptionHelpFormatter)@@ -135,10 +197,48 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--review-csv", type=Path,default=GENERATED_DIR / "review" / "composite-names.csv",help="复核 CSV 输出路径")+ parser.add_argument("--from-review", type=Path,+ help="按这份人工判定过的 CSV 执行 split / strip,不再重新扫描")return parser+def _report(before: dict[str, int], after: dict[str, int],+ connection: sqlite3.Connection) -> int:+ _integrity, violations = verify_after_write(connection)+ for key in before:+ mark = "" if before[key] == after[key] else " <-- 变化"+ print(f" {key}: {before[key]} -> {after[key]}{mark}")+ print(f" foreign_key_check 违规 {violations} 条")+ return 1 if violations else 0+++def run_review(args: argparse.Namespace) -> int:+ connection = open_for_write(args)+ try:+ rows = read_rows(args.from_review)+ acting = [row for row in rows+ if str(row.get("verdict", "")).strip() in {"split", "strip"}]+ print(f"人工判定 {len(acting)} 行:{args.from_review}")+ for row in acting:+ print(f" {row['verdict']} [{row['entity_id']}] {row['value']}"+ f" -> {row['target']}")+ if not args.apply:+ print(" 未写 ledger(加 --apply --backup 才写)")+ return 0+ print(f" 已备份到 {args.backup}")+ before = counts_of(connection, EXTRA_COUNTS)+ with connection:+ done = apply_review(connection, acting)+ after = counts_of(connection, EXTRA_COUNTS)+ print(" 结果:", done)+ return _report(before, after, connection)+ finally:+ connection.close()++def run(args: argparse.Namespace) -> int:+ if args.from_review:+ return run_review(args)connection = open_for_write(args)try:rows = collect(connection)@@ -162,13 +262,8 @@ def run(args: argparse.Namespace) -> int:with connection:moved = apply_rows(connection, rows)after = counts_of(connection, EXTRA_COUNTS)- _integrity, violations = verify_after_write(connection)print(" 拆分结果:", moved)- for key in before:- mark = "" if before[key] == after[key] else " <-- 变化"- print(f" {key}: {before[key]} -> {after[key]}{mark}")- print(f" foreign_key_check 违规 {violations} 条")- return 1 if violations else 0+ return _report(before, after, connection)finally:connection.close()diff --git a/src/peach/entities.py b/src/peach/entities.pyindex 42bb8a184..6aca37c9a 100644--- a/src/peach/entities.py+++ b/src/peach/entities.py@@ -127,6 +127,42 @@ def canonicalize_entity_name(kind: str, name: str | None) -> str:return canonical+#: 规范名有一份扁平投影(ADR-0005):女优落在 `asset_tag` 的 `演员:` 标签里,其余三种+#: 落在 `asset` 的同名列里。只改实体名不改这一份,卡片上还写着旧名、按旧名也照样查得到,+#: 资料页和卡片就各说各话了。+FLAT_COLUMN = {"studio": "studio", "creator": "creator", "series": "series"}+++def rewrite_flat_projection(connection: Connection, kind: str, entity_id: int,+ old_name: str, new_name: str) -> int:+ """规范名换写法之后,把扁平投影一并改过来,返回改动的资产数。++ 资料页的统称选择器和账本清理脚本改的是同一件事,共用这一份:投影跟不上实体名的+ 后果不是报错,是卡片和资料页各说各话,而且按旧名还照样搜得到。+ """+ column = FLAT_COLUMN.get(kind)+ if column:+ connection.execute(f"UPDATE asset SET {column}=? WHERE {column}=?",+ (new_name, old_name))+ return connection.execute("SELECT changes()").fetchone()[0]+ rewritten = 0+ old_tag, new_tag = f"演员:{old_name}", f"演员:{new_name}"+ for item in connection.execute(+ "SELECT DISTINCT asset_id FROM asset_entity WHERE entity_id=?", (entity_id,)+ ):+ asset_id = int(item[0])+ # 置信度与来源跟着旧标签走:换的是写法,不是这条标注的可信程度。+ connection.execute(+ "INSERT OR IGNORE INTO asset_tag(asset_id,tag,confidence,source) "+ "SELECT asset_id,?,confidence,source FROM asset_tag WHERE asset_id=? AND tag=?",+ (new_tag, asset_id, old_tag))+ connection.execute("DELETE FROM asset_tag WHERE asset_id=? AND tag=?",+ (asset_id, old_tag))+ if connection.execute("SELECT changes()").fetchone()[0]:+ rewritten += 1+ return rewritten++def merge_entity(connection: Connection, *, target_id: int, source_id: int,source_name: str, alias_source: str, now: str | None = None,diff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex 7a55207d8..d8ae8680a 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -15,7 +15,7 @@ import timefrom urllib.parse import urlsplitfrom .catalog_rules import LENGTH_TAGS, dir_expr, photo_set_title, tag_cat-from .entities import normalize_entity_name, resolve_entity+from .entities import normalize_entity_name, resolve_entity, rewrite_flat_projectionfrom .web_catalog import (COST,attach_avatar_availability,@@ -314,34 +314,6 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")#: 刮削留的是站点名;分得开才答得出「这个名字是谁定的」。PREFERRED_NAME_SOURCE = "user:preferred-name"-#: 规范名有一份扁平投影(ADR-0005):女优落在 `asset_tag` 的 `演员:` 标签里,其余三种-#: 落在 `asset` 的同名列里。只改实体名不改这一份,卡片上还写着旧名、按旧名也照样查得到,-#: 资料页和卡片就各说各话了。-_FLAT_COLUMN = {"studio": "studio", "creator": "creator", "series": "series"}---def _rewrite_flat_projection(c, kind, entity_id, old_name, new_name):- column = _FLAT_COLUMN.get(kind)- if column:- c.execute(f"UPDATE asset SET {column}=? WHERE {column}=?", (new_name, old_name))- return c.execute("SELECT changes()").fetchone()[0]- rewritten = 0- old_tag, new_tag = f"演员:{old_name}", f"演员:{new_name}"- for item in c.execute(- "SELECT DISTINCT asset_id FROM asset_entity WHERE entity_id=?", (entity_id,)- ):- asset_id = int(item[0])- # 置信度与来源跟着旧标签走:换的是写法,不是这条标注的可信程度。- c.execute(- "INSERT OR IGNORE INTO asset_tag(asset_id,tag,confidence,source) "- "SELECT asset_id,?,confidence,source FROM asset_tag WHERE asset_id=? AND tag=?",- (new_tag, asset_id, old_tag))- c.execute("DELETE FROM asset_tag WHERE asset_id=? AND tag=?", (asset_id, old_tag))- if c.execute("SELECT changes()").fetchone()[0]:- rewritten += 1- return rewritten--def w_entity_name(contract: WebContract, body):"""把这个实体已有的某个名字提为统称,旧规范名转成别名。@@ -388,6 +360,6 @@ def w_entity_name(contract: WebContract, body):"INSERT OR IGNORE INTO entity_alias(entity_id,alias,normalized_alias,source,confidence)"" VALUES(?,?,?,?,1.0)",(entity_id, current, normalize_entity_name(current), PREFERRED_NAME_SOURCE))- flat = _rewrite_flat_projection(c, kind, entity_id, current, known[chosen_key])+ flat = rewrite_flat_projection(c, kind, entity_id, current, known[chosen_key])return {"ok": True, "canonical_name": known[chosen_key], "changed": True,"previous_name": current, "flat_rewritten": flat}diff --git a/tests/test_composite_name_split.py b/tests/test_composite_name_split.pyindex 222d02f4b..918159369 100644--- a/tests/test_composite_name_split.py+++ b/tests/test_composite_name_split.py@@ -6,7 +6,9 @@ from pathlib import Pathfrom peach.entities import split_composite_person_namefrom peach.migrations import upgrade-from scripts.split_composite_aliases import apply_rows, collect+from scripts.split_composite_aliases import (+ CLEANUP_SOURCE, apply_review, apply_rows, collect,+)ROOT = Path(__file__).resolve().parents[1]@@ -113,5 +115,109 @@ class CompositeAliasSplitTests(unittest.TestCase):.fetchone()[0], "アスナ(SAO)")+class ReviewedNameCleanupTests(unittest.TestCase):+ """形状分不开、只有人能判的那些:复核 CSV 填 `verdict` 与 `target` 再执行。"""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ self.db = Path(self.tmp.name).resolve() / "ledger.db"+ upgrade(self.db, ROOT / "migrations")+ self.con = sqlite3.connect(self.db)+ self.addCleanup(self.con.close)+ self.con.executemany(+ "INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at)"+ " VALUES(?,?,?,?,'t','t')",+ [(20, "creator", "幼月月@一日目(土)東オ54a", "幼月月@一日目(土)東オ54a"),+ (21, "studio", "プレステージプレミアム", "プレステージプレミアム"),+ (22, "performer", "白石亚子", "白石亚子"),+ (23, "creator", "みどりふう", "みどりふう")])+ self.con.execute(+ "INSERT INTO entity_alias(entity_id,alias,normalized_alias,source,confidence)"+ " VALUES(21,'プレステージプレミアム(PRESTIGEPREMIUM)',"+ "'プレステージプレミアム(prestigepremium)','javdb:studio',1.0)")+ self.con.executemany(+ "INSERT INTO asset(id,location,path,name,medium,creator)"+ " VALUES(?,'online',?,?,'image',?)",+ [(1, "pixiv/1", "a", "幼月月@一日目(土)東オ54a"),+ (2, "pixiv/2", "b", "幼月月@一日目(土)東オ54a"),+ (3, "pixiv/3", "c", "みどりふう")])+ self.con.execute(+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence)"+ " VALUES(1,20,'creator','pixiv',1.0)")+ self.con.commit()++ def _row(self, verdict, entity_id, value, target, kind="creator", source=""):+ return {"verdict": verdict, "kind": kind, "entity_id": str(entity_id),+ "value": value, "target": target, "source": source}++ def test_stripping_a_booth_suffix_renames_the_entity_and_its_assets(self):+ done = apply_review(self.con, [+ self._row("strip", 20, "幼月月@一日目(土)東オ54a", "幼月月")])+ self.assertEqual((done["strip"], done["flat"]), (1, 2))+ self.assertEqual(+ self.con.execute("SELECT canonical_name,normalized_name FROM entity"+ " WHERE id=20").fetchone(), ("幼月月", "幼月月"))+ # 扁平投影跟着改,否则卡片还写着旧名、按旧名照样搜得到。+ self.assertEqual(+ sorted(name for (name,) in self.con.execute(+ "SELECT creator FROM asset WHERE creator IS NOT NULL")),+ ["みどりふう", "幼月月", "幼月月"])++ def test_the_stripped_name_stays_as_an_alias_under_the_cleanup_source(self):+ apply_review(self.con, [self._row("strip", 20, "幼月月@一日目(土)東オ54a", "幼月月")])+ self.assertEqual(+ self.con.execute("SELECT alias,source FROM entity_alias WHERE entity_id=20")+ .fetchall(), [("幼月月@一日目(土)東オ54a", CLEANUP_SOURCE)])++ def test_splitting_a_studio_alias_keeps_the_source_that_gave_it(self):+ done = apply_review(self.con, [+ self._row("split", 21, "プレステージプレミアム(PRESTIGEPREMIUM)",+ "プレステージプレミアム | PRESTIGEPREMIUM",+ kind="studio", source="javdb:studio")])+ self.assertEqual(done["split"], 1)+ self.assertEqual(+ sorted(alias for (alias,) in self.con.execute(+ "SELECT alias FROM entity_alias WHERE entity_id=21")),+ ["PRESTIGEPREMIUM", "プレステージプレミアム"])++ def test_a_target_taken_by_another_entity_is_refused_not_written(self):+ # 撞上另一条实体的规范名意味着两条可能该合并,那是合并要回答的问题。+ done = apply_review(self.con, [+ self._row("strip", 20, "幼月月@一日目(土)東オ54a", "みどりふう")])+ self.assertEqual(done["strip"], 0)+ self.assertEqual(len(done["blocked"]), 1)+ self.assertIn("撞 entity 23", done["blocked"][0])+ self.assertEqual(+ self.con.execute("SELECT canonical_name FROM entity WHERE id=20").fetchone()[0],+ "幼月月@一日目(土)東オ54a")++ def test_rows_left_at_review_do_nothing(self):+ done = apply_review(self.con, [+ self._row("review", 20, "幼月月@一日目(土)東オ54a", "幼月月"),+ self._row("strip", 20, "幼月月@一日目(土)東オ54a", "")])+ self.assertEqual((done["strip"], done["split"], done["flat"]), (0, 0, 0))+ self.assertEqual(+ self.con.execute("SELECT canonical_name FROM entity WHERE id=20").fetchone()[0],+ "幼月月@一日目(土)東オ54a")++ def test_a_performer_strip_rewrites_the_flat_tag(self):+ self.con.execute(+ "INSERT INTO asset(id,location,path,name,medium)"+ " VALUES(4,'online','pixiv/4','d','image')")+ self.con.execute(+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence)"+ " VALUES(4,22,'performer','javdb',1.0)")+ self.con.execute(+ "INSERT INTO asset_tag(asset_id,tag,confidence,source)"+ " VALUES(4,'演员:白石亚子',1.0,'javdb')")+ done = apply_review(self.con, [+ self._row("strip", 22, "白石亚子", "白石 あこ", kind="performer")])+ self.assertEqual((done["strip"], done["flat"]), (1, 1))+ self.assertEqual(+ [tag for (tag,) in self.con.execute(+ "SELECT tag FROM asset_tag WHERE asset_id=4")], ["演员:白石 あこ"])++if __name__ == "__main__":unittest.main()