Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: localize series names from official Japanese metadata

longmeidao4666725a98fe
diff --git a/scripts/localize_series_names.py b/scripts/localize_series_names.py
new file mode 100644
index 000000000..b48e7311a
--- /dev/null
+++ b/scripts/localize_series_names.py
@@ -0,0 +1,354 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""用 r18dev 同一响应中的官方日文系列名修正 Peach 规范实体。
+
+输入是 ``scrape_codes.py`` 生成的字段候选 CSV。脚本会回读每条候选引用的原始
+快照,只接受 r18dev 响应 ``translations`` 中明确标为日文的系列名。默认只输出
+审计 CSV;真实写入必须同时使用 ``--apply --backup``。证据冲突、兼容投影不一致
+或缺少日文原文的实体一律跳过。
+"""
+from __future__ import annotations
+
+import argparse
+import csv
+import json
+import re
+import sqlite3
+from collections import Counter, defaultdict
+from datetime import datetime, timezone
+from pathlib import Path
+
+from peach.config import DATABASE_PATH, GENERATED_DIR
+from peach.entities import merge_entity, normalize_entity_name
+from peach.metadata import collapse_repeated_phrase
+from peach.migrations import sqlite_backup
+
+
+SOURCE = "r18dev:series-localization"
+MERGE_SOURCE = "merge:series-localization"
+FIELDS = (
+ "entity_id", "current_name", "target_name", "assets", "codes",
+ "evidence_codes", "raw_snapshots", "action", "reason", "merge_target_id",
+ "revision",
+)
+
+
+def _contains_latin(value: str) -> bool:
+ return bool(re.search(r"[A-Za-z]", value or ""))
+
+
+def _truthy(value: object) -> bool:
+ return value is True or str(value).strip().lower() in {"1", "true", "yes"}
+
+
+def _code_key(value: str) -> str:
+ return re.sub(r"[^A-Z0-9]", "", str(value or "").upper())
+
+
+def _snapshot_japanese_series(path: Path) -> str:
+ try:
+ wrapper = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, UnicodeError, ValueError, TypeError):
+ return ""
+ if str(wrapper.get("source") or "") != "r18dev":
+ return ""
+ payload = wrapper.get("result")
+ if not isinstance(payload, dict):
+ return ""
+ for translation in payload.get("translations") or []:
+ if not isinstance(translation, dict):
+ continue
+ if not str(translation.get("language") or "").lower().startswith("ja"):
+ continue
+ value, _ = collapse_repeated_phrase(str(translation.get("series") or ""))
+ return value.strip()
+ return ""
+
+
+def read_evidence(path: Path) -> dict[str, list[dict[str, str]]]:
+ """回读候选及原始快照,返回按规范番号分组的可验证日文系列名。"""
+ by_code: dict[str, list[dict[str, str]]] = defaultdict(list)
+ with path.open(encoding="utf-8-sig", newline="") as handle:
+ for row in csv.DictReader(handle):
+ if row.get("field") != "series":
+ continue
+ query = _code_key(str(row.get("query") or row.get("code") or ""))
+ try:
+ candidates = json.loads(row.get("candidates_json") or "[]")
+ except (TypeError, ValueError):
+ continue
+ for candidate in candidates if isinstance(candidates, list) else []:
+ if not isinstance(candidate, dict):
+ continue
+ if (candidate.get("source") != "r18dev"
+ or candidate.get("source_kind") != "official_mirror"
+ or not _truthy(candidate.get("official"))):
+ continue
+ raw_value = str(candidate.get("raw_snapshot") or "").strip()
+ if not raw_value:
+ continue
+ snapshot = Path(raw_value)
+ if not snapshot.is_absolute():
+ snapshot = path.parent / snapshot
+ japanese = _snapshot_japanese_series(snapshot)
+ candidate_value, _ = collapse_repeated_phrase(
+ str(candidate.get("value") or ""))
+ if not japanese or japanese != candidate_value.strip():
+ continue
+ by_code[query].append({
+ "target": japanese,
+ "snapshot": str(snapshot.resolve()),
+ "source_url": str(candidate.get("source_url") or ""),
+ })
+ return dict(by_code)
+
+
+def collect(
+ connection: sqlite3.Connection,
+ evidence: dict[str, list[dict[str, str]]],
+ revision: str,
+) -> list[dict[str, object]]:
+ connection.row_factory = sqlite3.Row
+ entity_rows = connection.execute(
+ "SELECT id,canonical_name,normalized_name FROM entity "
+ "WHERE kind='series' ORDER BY id"
+ ).fetchall()
+ owners = {str(row["normalized_name"]): int(row["id"]) for row in entity_rows}
+ rows: list[dict[str, object]] = []
+
+ for entity in entity_rows:
+ entity_id = int(entity["id"])
+ assets = connection.execute(
+ "SELECT DISTINCT a.id,a.code,a.series FROM asset a "
+ "JOIN asset_entity ae ON ae.asset_id=a.id "
+ "WHERE ae.entity_id=? AND ae.role='series' AND a.medium='video' "
+ "ORDER BY a.id",
+ (entity_id,),
+ ).fetchall()
+ codes = sorted({_code_key(str(row["code"] or "")) for row in assets
+ if str(row["code"] or "").strip()})
+ mismatched_assets = [
+ int(row["id"]) for row in assets
+ if str(row["series"] or "").strip()
+ and normalize_entity_name(str(row["series"])) != str(entity["normalized_name"])
+ ]
+ proofs = [proof for code in codes for proof in evidence.get(code, [])]
+ targets = sorted({proof["target"] for proof in proofs}, key=str.casefold)
+ base: dict[str, object] = {
+ "entity_id": entity_id,
+ "current_name": str(entity["canonical_name"]),
+ "target_name": "",
+ "assets": len(assets),
+ "codes": "|".join(codes),
+ "evidence_codes": "|".join(sorted(
+ code for code in codes if evidence.get(code))),
+ "raw_snapshots": "|".join(sorted({proof["snapshot"] for proof in proofs})),
+ "action": "",
+ "reason": "",
+ "merge_target_id": "",
+ "revision": revision,
+ "_proofs": proofs,
+ }
+ if mismatched_assets:
+ base.update(
+ action="skip-projection-mismatch",
+ reason="asset.series 与规范系列关系不一致:" +
+ ",".join(map(str, mismatched_assets)),
+ )
+ elif not _contains_latin(str(entity["canonical_name"])):
+ base.update(
+ target_name=str(entity["canonical_name"]),
+ action="keep-localized", reason="规范名已无拉丁字母",
+ )
+ elif not targets:
+ base.update(action="skip-no-japanese-evidence", reason="没有可验证的官方日文系列名")
+ elif len(targets) != 1:
+ base.update(
+ action="skip-evidence-conflict",
+ reason="同一系列关联番号返回多个日文名:" + " | ".join(targets),
+ )
+ else:
+ target = targets[0]
+ normalized = normalize_entity_name(target)
+ base["target_name"] = target
+ if normalized == str(entity["normalized_name"]):
+ base.update(action="keep-source-same", reason="官方日文原文与当前规范名相同")
+ elif normalized in owners and owners[normalized] != entity_id:
+ base.update(
+ action="merge-into-existing", reason="日文规范实体已存在",
+ merge_target_id=owners[normalized],
+ )
+ else:
+ base.update(action="rename", reason="官方日文翻译证据唯一")
+ rows.append(base)
+ return rows
+
+
+def _insert_alias(
+ connection: sqlite3.Connection, entity_id: int, alias: str, revision: str,
+) -> int:
+ normalized = normalize_entity_name(alias)
+ canonical = connection.execute(
+ "SELECT normalized_name FROM entity WHERE id=?", (entity_id,)
+ ).fetchone()[0]
+ if not normalized or normalized == canonical:
+ return 0
+ connection.execute(
+ "INSERT OR IGNORE INTO entity_alias(entity_id,alias,normalized_alias,source,confidence) "
+ "VALUES(?,?,?,?,1.0)",
+ (entity_id, alias, normalized, f"{SOURCE}@{revision[:12]}"),
+ )
+ return int(connection.execute("SELECT changes()").fetchone()[0])
+
+
+def _write_provenance(
+ connection: sqlite3.Connection, entity_id: int, row: dict[str, object], revision: str,
+) -> None:
+ raw = connection.execute(
+ "SELECT metadata_json FROM entity WHERE id=?", (entity_id,)
+ ).fetchone()[0]
+ try:
+ metadata = json.loads(raw or "{}")
+ except (TypeError, ValueError):
+ metadata = {}
+ metadata["series_name_localization"] = {
+ "source": "r18dev",
+ "source_kind": "official_mirror",
+ "revision": revision,
+ "previous_name": str(row["current_name"]),
+ "japanese_name": str(row["target_name"]),
+ "evidence_codes": str(row["evidence_codes"]).split("|")
+ if row["evidence_codes"] else [],
+ "raw_snapshots": str(row["raw_snapshots"]).split("|")
+ if row["raw_snapshots"] else [],
+ }
+ connection.execute(
+ "UPDATE entity SET metadata_json=? WHERE id=?",
+ (json.dumps(metadata, ensure_ascii=False, separators=(",", ":")), entity_id),
+ )
+
+
+def _sync_projection(connection: sqlite3.Connection, entity_id: int, target: str) -> int:
+ connection.execute(
+ "UPDATE asset SET series=? WHERE id IN ("
+ "SELECT asset_id FROM asset_entity WHERE entity_id=? AND role='series'"
+ ") AND COALESCE(series,'')<>?",
+ (target, entity_id, target),
+ )
+ return int(connection.execute("SELECT changes()").fetchone()[0])
+
+
+def apply_rows(
+ connection: sqlite3.Connection, rows: list[dict[str, object]], revision: str,
+) -> dict[str, int]:
+ counts = Counter()
+ stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")
+ for row in rows:
+ action = str(row["action"])
+ if action not in {"rename", "merge-into-existing"}:
+ continue
+ entity_id = int(row["entity_id"])
+ target = str(row["target_name"])
+ if action == "merge-into-existing":
+ target_id = int(row["merge_target_id"])
+ moved = merge_entity(
+ connection, target_id=target_id, source_id=entity_id,
+ source_name=str(row["current_name"]), alias_source=MERGE_SOURCE,
+ )
+ counts["merged"] += 1
+ counts["relations_moved"] += moved["assets"]
+ counts["dropped_refs"] += moved["dropped_refs"]
+ counts["aliases"] += _insert_alias(
+ connection, target_id, str(row["current_name"]), revision)
+ counts["projections"] += _sync_projection(connection, target_id, target)
+ _write_provenance(connection, target_id, row, revision)
+ counts["provenance"] += 1
+ continue
+
+ connection.execute(
+ "UPDATE entity SET canonical_name=?,normalized_name=?,updated_at=? WHERE id=?",
+ (target, normalize_entity_name(target), stamp, entity_id),
+ )
+ counts["renamed"] += int(connection.execute("SELECT changes()").fetchone()[0])
+ counts["aliases"] += _insert_alias(
+ connection, entity_id, str(row["current_name"]), revision)
+ counts["projections"] += _sync_projection(connection, entity_id, target)
+ _write_provenance(connection, entity_id, row, revision)
+ counts["provenance"] += 1
+ return dict(counts)
+
+
+def write_csv(path: Path, rows: list[dict[str, object]]) -> None:
+ path.parent.mkdir(parents=True, exist_ok=True)
+ with path.open("w", encoding="utf-8-sig", newline="") as handle:
+ writer = csv.DictWriter(handle, fieldnames=FIELDS)
+ writer.writeheader()
+ writer.writerows({field: row.get(field, "") for field in FIELDS} for row in rows)
+
+
+def counts_of(connection: sqlite3.Connection) -> dict[str, int]:
+ return {
+ "asset": connection.execute("SELECT count(*) FROM asset").fetchone()[0],
+ "entity": connection.execute("SELECT count(*) FROM entity").fetchone()[0],
+ "series": connection.execute(
+ "SELECT count(*) FROM entity WHERE kind='series'").fetchone()[0],
+ "latin_series": connection.execute(
+ "SELECT count(*) FROM entity WHERE kind='series' "
+ "AND canonical_name GLOB '*[A-Za-z]*'").fetchone()[0],
+ "asset_entity": connection.execute("SELECT count(*) FROM asset_entity").fetchone()[0],
+ "entity_alias": connection.execute("SELECT count(*) FROM entity_alias").fetchone()[0],
+ }
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="用官方日文证据本地化系列规范名")
+ parser.add_argument("--db", type=Path, default=DATABASE_PATH)
+ parser.add_argument("--candidates", type=Path, required=True)
+ parser.add_argument("--revision", required=True)
+ parser.add_argument(
+ "--audit-csv", type=Path,
+ default=GENERATED_DIR / "series-name-localization.csv",
+ )
+ parser.add_argument("--apply", action="store_true")
+ parser.add_argument("--backup", type=Path, help="--apply 必需")
+ return parser
+
+
+def run(args: argparse.Namespace) -> int:
+ if args.apply and not args.backup:
+ raise SystemExit("--apply 必须同时给 --backup")
+ evidence = read_evidence(args.candidates)
+ connection = sqlite3.connect(args.db)
+ connection.execute("PRAGMA foreign_keys=ON")
+ try:
+ rows = collect(connection, evidence, args.revision)
+ write_csv(args.audit_csv, rows)
+ print(f"已审计 series {len(rows)} 个;审计 CSV:{args.audit_csv}")
+ print(" 动作分布:", dict(Counter(str(row["action"]) for row in rows)))
+ if not args.apply:
+ print(" 未写 ledger(加 --apply --backup 才写)")
+ return 0
+
+ before = counts_of(connection)
+ sqlite_backup(args.db, args.backup)
+ print(f" 已备份到 {args.backup}")
+ with connection:
+ changed = apply_rows(connection, rows, args.revision)
+ after = counts_of(connection)
+ integrity = connection.execute("PRAGMA integrity_check").fetchone()[0]
+ foreign_keys = connection.execute("PRAGMA foreign_key_check").fetchall()
+ print(" 写入结果:", changed)
+ for key in before:
+ print(f" {key}: {before[key]} -> {after[key]}")
+ print(f" integrity_check={integrity};foreign_key_check={len(foreign_keys)}")
+ return 1 if integrity != "ok" or foreign_keys else 0
+ finally:
+ connection.close()
+
+
+def main(argv: list[str] | None = None) -> int:
+ return run(build_parser().parse_args(argv))
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/scripts/scrape_codes.py b/scripts/scrape_codes.py
index 21f7baa45..59544ff85 100644
--- a/scripts/scrape_codes.py
+++ b/scripts/scrape_codes.py
@@ -204,6 +204,10 @@ def build_parser() -> argparse.ArgumentParser:
help="explicit Peach source preset; default baseline")
source_group.add_argument("--sources", help="compatible comma-separated Javinizer scraper names")
parser.add_argument("--health", type=Path, default=None)
+ parser.add_argument(
+ "--codes-file", type=Path,
+ help="只处理文件中列出的番号;每行一个,空行和 # 注释忽略",
+ )
parser.add_argument("--limit", type=int, default=0)
parser.add_argument("--delay", type=float, default=1.2)
parser.add_argument("--refresh", action="store_true", help="ignore reusable raw snapshots")
@@ -211,6 +215,42 @@ def build_parser() -> argparse.ArgumentParser:
return parser
+def _requested_codes(path: Path) -> list[str]:
+ requested: list[str] = []
+ seen: set[str] = set()
+ for raw in path.read_text(encoding="utf-8-sig").splitlines():
+ value = raw.split("#", 1)[0].strip()
+ if not value:
+ continue
+ query = normalise(value)
+ if query not in seen:
+ seen.add(query)
+ requested.append(query)
+ return requested
+
+
+def _select_requested_codes(
+ codes: list[tuple[str, float, int]], path: Path,
+) -> list[tuple[str, float, int]]:
+ requested = _requested_codes(path)
+ available: dict[str, tuple[str, float, int]] = {}
+ for code, size_gb, videos in codes:
+ query = normalise(code)
+ previous = available.get(query)
+ if previous is None:
+ available[query] = (code, size_gb, videos)
+ else:
+ available[query] = (
+ previous[0], previous[1] + size_gb, previous[2] + videos,
+ )
+ missing = [query for query in requested if query not in available]
+ if missing:
+ preview = "、".join(missing[:10])
+ suffix = f" 等 {len(missing)} 个" if len(missing) > 10 else ""
+ raise ValueError(f"番号文件含 ledger 中不存在的番号:{preview}{suffix}")
+ return [available[query] for query in requested]
+
+
def _health_output(output: Path) -> Path:
name = output.name.replace("metadata-field-candidates-", "metadata-source-health-", 1)
if name == output.name:
@@ -276,6 +316,11 @@ def main(argv: list[str] | None = None, *, provider: JavinizerGoProvider | None
codes = [row for row in codes if policy.allows_code(
row[0], include_fc2=args.include_fc2, explicit_sources=explicit_sources,
)]
+ if args.codes_file:
+ try:
+ codes = _select_requested_codes(codes, args.codes_file)
+ except (OSError, UnicodeError, ValueError) as error:
+ parser.error(str(error))
if args.limit:
codes = codes[:max(args.limit, 0)]
log(f"字段候选批次:profile {policy.profile},番号 {len(codes)},来源 {','.join(sources)};只读查询,不写 ledger")
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index e138d0a68..e10a50576 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -26,6 +26,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"metadata": ("test_metadata*.py", "test_fc2*.py", "test_babepedia_match.py",
"test_jav*.py", "test_code_creators.py", "test_logo_provider.py",
"test_avatar_provider.py", "test_performer*.py",
+ "test_series_localization.py",
"test_duplicate_identity_merge.py", "test_entity_merge.py",
"test_stash_entity_import.py", "test_migrations.py"),
"tooling": ("test_scripts.py", "test_agent_worktree.py", "test_versioning.py",
diff --git a/tests/test_scripts.py b/tests/test_scripts.py
index 413d4f5d9..aef4c07c5 100644
--- a/tests/test_scripts.py
+++ b/tests/test_scripts.py
@@ -759,6 +759,47 @@ class OperationalScriptTests(unittest.TestCase):
self.assertEqual(asset, (None, None, None))
self.assertEqual(relation_count, 0)
+ def test_javinizer_scrape_codes_file_limits_batch_in_file_order(self):
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp)
+ db = root / "ledger.db"
+ sqlite3.connect(db).close()
+ upgrade(db, MIGRATIONS)
+ connection = sqlite3.connect(db)
+ connection.executemany(
+ "INSERT INTO asset(id,location,path,name,medium,code,size) "
+ "VALUES(?,'local',?,?,'video',?,?)",
+ [(1, "large.mp4", "large.mp4", "AAA-001", 10_000),
+ (2, "small.mp4", "small.mp4", "BBB-002", 1_000)],
+ )
+ connection.commit()
+ connection.close()
+ codes_file = root / "codes.txt"
+ codes_file.write_text("# exact batch\nBBB002\n", encoding="utf-8")
+
+ class FakeProvider:
+ def __init__(self):
+ self.calls = []
+
+ def query(self, code, source):
+ self.calls.append((code, source))
+ return {"source": source, "series": "Series B"}
+
+ provider = FakeProvider()
+ output = root / "candidates.csv"
+ with redirect_stdout(io.StringIO()):
+ result = self.scrape_codes.main([
+ "--db", str(db), "--out", str(output),
+ "--raw-dir", str(root / "raw"), "--log-dir", str(root / "logs"),
+ "--delay", "0", "--sources", "r18dev",
+ "--codes-file", str(codes_file),
+ ], provider=provider)
+ self.assertEqual(result, 0)
+ self.assertEqual(provider.calls, [("BBB-002", "r18dev")])
+ with output.open(encoding="utf-8-sig", newline="") as handle:
+ rows = list(csv.DictReader(handle))
+ self.assertEqual({row["query"] for row in rows}, {"BBB-002"})
+
def test_metadata_health_distinguishes_snapshot_empty_error_and_cooldown(self):
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
diff --git a/tests/test_series_localization.py b/tests/test_series_localization.py
new file mode 100644
index 000000000..e4ecfd819
--- /dev/null
+++ b/tests/test_series_localization.py
@@ -0,0 +1,156 @@
+"""系列日文规范名迁移:官方证据、冲突跳过、别名与兼容投影。"""
+import argparse
+import csv
+import json
+import sqlite3
+import tempfile
+import unittest
+from pathlib import Path
+
+from peach.migrations import upgrade
+from scripts.localize_series_names import apply_rows, collect, read_evidence, run
+
+
+ROOT = Path(__file__).resolve().parents[1]
+
+
+class SeriesLocalizationTests(unittest.TestCase):
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ root = Path(self.tmp.name)
+ self.db = root / "ledger.db"
+ upgrade(self.db, ROOT / "migrations")
+ self.con = sqlite3.connect(self.db)
+ self.con.executemany(
+ "INSERT INTO asset(id,location,path,name,medium,code,series) "
+ "VALUES(?,'local',?,?,'video',?,?)",
+ [(1, "1.mp4", "1.mp4", "ABC-001", "Raw Creampies"),
+ (2, "2.mp4", "2.mp4", "DEF-002", "Japanese Existing"),
+ (3, "3.mp4", "3.mp4", "GHI-003", "wrong-flat-value"),
+ (4, "4.mp4", "4.mp4", "JKL-004", "Conflicting Series"),
+ (5, "5.mp4", "5.mp4", "MNO-005", "Conflicting Series"),
+ (6, "6.mp4", "6.mp4", "PQR-006", "Prestige English")],
+ )
+ self.con.executemany(
+ "INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) "
+ "VALUES(?,'series',?,?, 't','t')",
+ [(10, "Raw Creampies", "raw creampies"),
+ (11, "なまなかだし", "なまなかだし"),
+ (12, "Japanese Existing", "japanese existing"),
+ (13, "Projection Mismatch", "projection mismatch"),
+ (14, "Conflicting Series", "conflicting series"),
+ (15, "Prestige English", "prestige english")],
+ )
+ self.con.executemany(
+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) "
+ "VALUES(?,?,'series','r18:series',1.0)",
+ [(1, 10), (2, 12), (3, 13), (4, 14), (5, 14), (6, 15)],
+ )
+ self.con.commit()
+ self.candidates = root / "candidates.csv"
+ self.raw = root / "raw"
+ self._write_candidate("ABC-001", "なまなかだし")
+ self._write_candidate("DEF-002", "なまなかだし")
+ self._write_candidate("GHI-003", "投影")
+ self._write_candidate("JKL-004", "企画一")
+ self._write_candidate("MNO-005", "企画二", append=True)
+ self._write_candidate("PQR-006", "【プレステージ企画】", append=True)
+
+ def tearDown(self):
+ self.con.close()
+ self.tmp.cleanup()
+
+ def _write_candidate(self, code, japanese, append=False):
+ snapshot = self.raw / code / "r18dev.json"
+ snapshot.parent.mkdir(parents=True, exist_ok=True)
+ snapshot.write_text(json.dumps({
+ "source": "r18dev",
+ "result": {"translations": [{"language": "ja-JP", "series": japanese}]},
+ }, ensure_ascii=False), encoding="utf-8")
+ fields = ["code", "query", "field", "candidates_json"]
+ mode = "a" if append or self.candidates.exists() else "w"
+ with self.candidates.open(mode, encoding="utf-8-sig", newline="") as handle:
+ writer = csv.DictWriter(handle, fieldnames=fields)
+ if mode == "w":
+ writer.writeheader()
+ writer.writerow({
+ "code": code, "query": code, "field": "series",
+ "candidates_json": json.dumps([{
+ "source": "r18dev", "source_kind": "official_mirror",
+ "official": True, "value": japanese,
+ "raw_snapshot": str(snapshot),
+ "source_url": f"https://r18.dev/videos/vod/movies/detail/-/id={code}/",
+ }], ensure_ascii=False),
+ })
+
+ def plan(self):
+ return collect(self.con, read_evidence(self.candidates), "r18-test")
+
+ def test_collect_accepts_only_unique_official_japanese_and_skips_mismatch(self):
+ rows = {int(row["entity_id"]): row for row in self.plan()}
+ self.assertEqual(rows[10]["action"], "merge-into-existing")
+ self.assertEqual(rows[10]["merge_target_id"], 11)
+ self.assertEqual(rows[12]["action"], "merge-into-existing")
+ self.assertEqual(rows[12]["merge_target_id"], 11)
+ self.assertEqual(rows[13]["action"], "skip-projection-mismatch")
+ self.assertEqual(rows[14]["action"], "skip-evidence-conflict")
+ self.assertEqual(rows[15]["action"], "rename")
+
+ def test_apply_merges_preserves_old_names_and_syncs_flat_projection(self):
+ counts = apply_rows(self.con, self.plan(), "r18-test")
+ self.con.commit()
+ self.assertIsNone(self.con.execute("SELECT id FROM entity WHERE id=10").fetchone())
+ self.assertIsNone(self.con.execute("SELECT id FROM entity WHERE id=12").fetchone())
+ aliases = {row[0] for row in self.con.execute(
+ "SELECT alias FROM entity_alias WHERE entity_id=11")}
+ self.assertTrue({"Raw Creampies", "Japanese Existing"} <= aliases)
+ projections = dict(self.con.execute(
+ "SELECT id,series FROM asset WHERE id IN (1,2) ORDER BY id"))
+ self.assertEqual(projections, {1: "なまなかだし", 2: "なまなかだし"})
+ metadata = json.loads(self.con.execute(
+ "SELECT metadata_json FROM entity WHERE id=11").fetchone()[0])
+ self.assertEqual(metadata["series_name_localization"]["source"], "r18dev")
+ renamed = self.con.execute(
+ "SELECT canonical_name FROM entity WHERE id=15").fetchone()[0]
+ self.assertEqual(renamed, "【プレステージ企画】")
+ self.assertEqual(self.con.execute(
+ "SELECT series FROM asset WHERE id=6").fetchone()[0], "【プレステージ企画】")
+ self.assertEqual(self.con.execute(
+ "SELECT alias FROM entity_alias WHERE entity_id=15").fetchone()[0],
+ "Prestige English")
+ self.assertEqual(counts["merged"], 2)
+ self.assertEqual(counts["renamed"], 1)
+ self.assertEqual(self.con.execute("PRAGMA foreign_key_check").fetchall(), [])
+
+ def test_raw_snapshot_without_japanese_translation_is_rejected(self):
+ snapshot = self.raw / "NOJ-006" / "r18dev.json"
+ snapshot.parent.mkdir(parents=True)
+ snapshot.write_text(json.dumps({
+ "source": "r18dev", "result": {"series": "English fallback"},
+ }), encoding="utf-8")
+ extra = Path(self.tmp.name) / "no-japanese.csv"
+ with extra.open("w", encoding="utf-8-sig", newline="") as handle:
+ writer = csv.DictWriter(
+ handle, fieldnames=["code", "query", "field", "candidates_json"])
+ writer.writeheader()
+ writer.writerow({
+ "code": "NOJ-006", "query": "NOJ-006", "field": "series",
+ "candidates_json": json.dumps([{
+ "source": "r18dev", "source_kind": "official_mirror",
+ "official": True, "value": "English fallback",
+ "raw_snapshot": str(snapshot),
+ }]),
+ })
+ self.assertEqual(read_evidence(extra), {})
+
+ def test_apply_requires_backup(self):
+ args = argparse.Namespace(
+ db=self.db, candidates=self.candidates, revision="r18-test",
+ audit_csv=Path(self.tmp.name) / "audit.csv", apply=True, backup=None,
+ )
+ with self.assertRaises(SystemExit):
+ run(args)
+
+
+if __name__ == "__main__":
+ unittest.main()