Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: 按事务所重问一遍所属,把移籍写回实体元数据

longmeidaoe09923835e34
diff --git a/scripts/resync_performer_agency.py b/scripts/resync_performer_agency.py
new file mode 100644
index 000000000..d34271ca8
--- /dev/null
+++ b/scripts/resync_performer_agency.py
@@ -0,0 +1,197 @@
+"""重新问一遍这几位女优现在签在谁名下,把答案写回 `entity.metadata_json.agency`。
+
+事务所会拆、会改名、会被并购,而账本里那一行停在采集当天的答案。LIGHT 就是一例:
+2026-09-05 实测,她的成员在 minnano-av 上的「所属事務所」已经分别写着
+`ELTRA(エルトラ)旧・LIGHT` 和 `EST(エスト)旧・LIGHT`,一家变成了两家。
+
+这个脚本只做证据那一半:按最新一次采集覆盖 `metadata.agency`,带来源和时间戳。把它
+变成实体和归属是 `install_agencies.py` 的事——`entity_membership` 主键在成员一侧,
+它用 REPLACE 写,所以移籍在那一步自然成立,这里不碰归属表。
+
+**站上写什么就记什么,括号不拆。** `ELTRA(エルトラ)旧・LIGHT` 整串存下来,拆成现用名
+和别名是 `install_agencies.py` 的判断。两边各拆一次的话,改了一边的规则就会得出两种
+结论,而复核件上看不出是哪一边改的。
+
+选人有两种,可以一起给:`--agency` 按现在的归属选整家,`--only` 直接点名。默认
+dry-run,只出复核 CSV;`--apply` 必须同时给 `--backup`。
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sys
+import time
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from peach.config import REVIEW_DIR, STATE_DIR # noqa: E402
+from peach.http import HttpRequest, HttpxTransport # noqa: E402
+from peach.jobs import job_main # noqa: E402
+from peach.minnano_av import actress_id, profile_text, search_url # noqa: E402
+from peach.review_csv import write_rows # noqa: E402
+from peach.scripting import ( # noqa: E402
+ USER_AGENT, add_ledger_write_args, counts_of, open_for_write, verify_after_write,
+)
+
+FIELDS = ("entity_id", "performer", "current_agency", "site_agency", "verdict", "evidence")
+
+MOVED, SAME, GONE, MISSING = "移籍", "未变", "站上没有事务所", "未取得"
+
+#: 这一行是从哪儿来的。和 `repair_link_labels.py` 写的那一条同源,所以两条路径
+#: 采到的同一件事在账本里长得一样。
+AGENCY_SOURCE = "minnano-av 资料表「所属事務所」"
+
+EXTRA_COUNTS = {
+ "有事务所的女优": (
+ "SELECT count(*) FROM entity WHERE kind='performer'"
+ " AND json_extract(metadata_json,'$.agency.name') IS NOT NULL"),
+}
+
+
+def targets(connection, agencies: list[str], only: list[str]) -> list[dict[str, object]]:
+ """要问的人:(entity_id, 规范名, 账本里现在写着的事务所)。
+
+ 两个条件是并集而不是交集:`--agency LIGHT --only 北野未奈` 要问的是这一家加上
+ 这个人,而不是「这一家里叫这个名字的」——移籍时人已经不在原来那一家名下了。
+ """
+ found: dict[int, dict[str, object]] = {}
+ for name in agencies:
+ for row in connection.execute(
+ "SELECT e.id, e.canonical_name,"
+ " json_extract(e.metadata_json,'$.agency.name') AS agency"
+ " FROM entity e JOIN entity_membership m ON m.member_id=e.id"
+ " JOIN entity a ON a.id=m.agency_id"
+ " WHERE a.kind='agency' AND a.canonical_name=?", (name,)):
+ found[row["id"]] = {"entity_id": row["id"], "performer": row["canonical_name"],
+ "current_agency": row["agency"] or ""}
+ for name in only:
+ for row in connection.execute(
+ "SELECT id, canonical_name,"
+ " json_extract(metadata_json,'$.agency.name') AS agency"
+ " FROM entity WHERE kind='performer' AND canonical_name=?", (name,)):
+ found[row["id"]] = {"entity_id": row["id"], "performer": row["canonical_name"],
+ "current_agency": row["agency"] or ""}
+ return [found[key] for key in sorted(found)]
+
+
+def ask(http, name: str, timeout: float) -> tuple[str, str, str]:
+ """问站点:这个人现在的「所属事務所」写的是什么。返回(事务所, actress_id, 说明)。
+
+ 只采信重定向。检索页正文里那一堆 `actressNNN.html` 是「相关女优」,按正文解析
+ 会把别人的事务所安到这个人头上。
+ """
+ try:
+ response = http(HttpRequest("GET", search_url(name), {"User-Agent": USER_AGENT}),
+ timeout, 4 << 20)
+ except Exception as error: # noqa: BLE001 取不到就是取不到,写进复核件等重跑
+ return "", "", f"未取得:{type(error).__name__}"
+ if response.status != 200:
+ return "", "", f"未取得:HTTP {response.status}"
+ found_id = actress_id(response.url or "")
+ if not found_id:
+ return "", "", "未取得:检索页未唯一命中,需人工消歧"
+ html = response.body.decode("utf-8", "replace")
+ return (profile_text(html, "所属事務所"), found_id,
+ f"minnano-av actress{found_id} 资料表「所属事務所」")
+
+
+def plan(connection, http, args) -> list[dict[str, object]]:
+ rows: list[dict[str, object]] = []
+ people = targets(connection, args.agency, args.only)
+ print(f"待问 {len(people)} 位 performer")
+ last = 0.0
+ for person in people:
+ wait = args.interval - (time.monotonic() - last)
+ if wait > 0:
+ time.sleep(wait)
+ last = time.monotonic()
+ shown, _, note = ask(http, str(person["performer"]), args.timeout)
+ if not note.startswith("minnano-av"):
+ verdict = MISSING
+ elif not shown:
+ verdict = GONE
+ elif shown == person["current_agency"]:
+ verdict = SAME
+ else:
+ verdict = MOVED
+ rows.append({**person, "site_agency": shown, "verdict": verdict, "evidence": note})
+ print(f"{str(person['performer'])[:12]:<12} {verdict} {shown}")
+ return rows
+
+
+def apply_rows(connection, rows: list[dict[str, object]], stamp: str) -> dict[str, int]:
+ """只改 `metadata.agency`,只改判定为移籍的那几行。
+
+ 「站上没有事务所」不清空账本里那一行:站点某天不显示这一格,和这个人真的解约了,
+ 在页面上长得一模一样,而清空是不可逆的一半——归属表跟着 `install_agencies.py`
+ 走,这里一清那边就没有依据了。要清由人单独决定。
+ """
+ done = {"事务所": 0}
+ for row in rows:
+ if row["verdict"] != MOVED:
+ continue
+ current = connection.execute(
+ "SELECT metadata_json FROM entity WHERE id=?", (int(row["entity_id"]),)
+ ).fetchone()
+ try:
+ metadata = json.loads(current[0] or "{}")
+ except (TypeError, ValueError):
+ metadata = {}
+ metadata["agency"] = {"name": str(row["site_agency"]),
+ "source": AGENCY_SOURCE, "checked_at": stamp}
+ connection.execute(
+ "UPDATE entity SET metadata_json=?,updated_at=? WHERE id=?",
+ (json.dumps(metadata, ensure_ascii=False), stamp, int(row["entity_id"])))
+ done["事务所"] += 1
+ return done
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description=__doc__)
+ add_ledger_write_args(parser)
+ parser.add_argument("--output", type=Path,
+ default=REVIEW_DIR / "performer-agency-resync.csv")
+ parser.add_argument("--agency", nargs="*", default=[],
+ help="把这几家现在的成员全部再问一遍,按 canonical_name 给")
+ parser.add_argument("--only", nargs="*", default=[],
+ help="再问这几位,按 performer 的 canonical_name 给")
+ parser.add_argument("--interval", type=float, default=1.5)
+ parser.add_argument("--timeout", type=float, default=25.0)
+ parser.add_argument("--lock", type=Path, default=STATE_DIR / ".performer-agency.lock")
+ return parser
+
+
+def run(args) -> int:
+ if not args.agency and not args.only:
+ raise SystemExit("要问谁:--agency 给事务所,--only 给人名,至少给一个")
+ connection = open_for_write(args)
+ http = HttpxTransport()
+ try:
+ before = counts_of(connection, EXTRA_COUNTS)
+ rows = plan(connection, http, args)
+ write_rows(args.output, FIELDS, rows, atomic=True, fill_missing=True)
+ stats = {verdict: sum(1 for row in rows if row["verdict"] == verdict)
+ for verdict in (MOVED, SAME, GONE, MISSING)}
+ print({"复核行": len(rows), **stats, "output": str(args.output)})
+ if not args.apply:
+ print("dry-run:没有写入。加 --apply --backup <路径> 才真的写。")
+ return 0
+ stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
+ done = apply_rows(connection, rows, stamp)
+ connection.commit()
+ after = counts_of(connection, EXTRA_COUNTS)
+ integrity, violations = verify_after_write(connection)
+ print("写入:" + ",".join(f"{key} {value}" for key, value in done.items()))
+ for key in sorted(before):
+ print(f" {key}: {before[key]} -> {after[key]}")
+ print(f"integrity_check={integrity} foreign_key_check={violations}")
+ return 0
+ finally:
+ http.close()
+ connection.close()
+
+
+if __name__ == "__main__":
+ sys.stdout.reconfigure(encoding="utf-8", errors="replace")
+ raise SystemExit(job_main(build_parser, run))
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index bcb9b2978..5e02b53f1 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -47,6 +47,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_entity_link_install.py", "test_studio_site_harvest.py",
"test_performer_link_harvest.py", "test_directory_link_harvest.py",
"test_minnano_av.py", "test_agency_roster_harvest.py",
+ "test_performer_agency_resync.py",
"test_studio_name_localization.py", "test_studio_icon_variants.py",
"test_mgstage_maker_harvest.py", "test_studio_name_variant_merge.py",
"test_javdb_cn_names.py",
diff --git a/tests/test_performer_agency_resync.py b/tests/test_performer_agency_resync.py
new file mode 100644
index 000000000..8ba6ad4ad
--- /dev/null
+++ b/tests/test_performer_agency_resync.py
@@ -0,0 +1,202 @@
+"""重问所属事务所:选人是并集,判词按站上写的那一串,写入只碰移籍的那几行。"""
+import contextlib
+import io
+import json
+import sqlite3
+import tempfile
+import types
+import unittest
+from pathlib import Path
+
+from peach.entities import normalize_entity_name
+from peach.migrations import upgrade
+from scripts.resync_performer_agency import (
+ GONE, MISSING, MOVED, SAME, apply_rows, ask, plan, targets,
+)
+
+ROOT = Path(__file__).resolve().parents[1]
+MIGRATIONS = ROOT / "migrations"
+STAMP = "2026-09-05T00:00:00Z"
+
+
+def profile_html(shown: str) -> str:
+ return ('<table><tr><td><span>所属事務所</span><p>'
+ f'<a href="actress_list.php?production=1251">{shown}</a>'
+ '</p></td></tr></table>')
+
+
+class Response:
+ def __init__(self, status: int, url: str, body: str = ""):
+ self.status = status
+ self.url = url
+ self.body = body.encode("utf-8")
+
+
+class Http:
+ """按检索地址发页的取数器替身。没登记的名字停在检索页,等同未唯一命中。"""
+
+ def __init__(self, pages: dict[str, Response]):
+ self.pages = pages
+ self.asked: list[str] = []
+
+ def __call__(self, request, timeout, limit):
+ self.asked.append(request.url)
+ return self.pages.get(
+ request.url, Response(200, "https://www.minnano-av.com/search_result.php"))
+
+ def close(self):
+ pass
+
+
+class AskTests(unittest.TestCase):
+ """站点那一问只有三种结果:命中、没这一格、取不到。"""
+
+ def page(self, shown: str) -> Http:
+ from scripts.resync_performer_agency import search_url
+ return Http({search_url("松本一香"): Response(
+ 200, "https://www.minnano-av.com/actress21661.html", profile_html(shown))})
+
+ def test_the_shown_name_comes_back_whole(self):
+ """括号里那一段是拆名字那一步要用的,采集这一步不动它。"""
+ shown, found, note = ask(self.page("ELTRA(エルトラ)旧・LIGHT"), "松本一香", 1.0)
+ self.assertEqual(shown, "ELTRA(エルトラ)旧・LIGHT")
+ self.assertEqual(found, "21661")
+ self.assertIn("actress21661", note)
+
+ def test_a_search_page_that_did_not_redirect_is_not_read(self):
+ """检索页正文里那一堆女优是「相关女优」,信号只在最终地址里。"""
+ shown, found, note = ask(self.page("ELTRA"), "查无此人", 1.0)
+ self.assertEqual((shown, found), ("", ""))
+ self.assertIn("未取得", note)
+
+ def test_a_transport_failure_is_a_row_not_a_crash(self):
+ class Broken:
+ def __call__(self, *args):
+ raise TimeoutError("connect")
+
+ shown, _, note = ask(Broken(), "松本一香", 1.0)
+ self.assertEqual(shown, "")
+ self.assertIn("未取得", note)
+
+
+class LedgerFixture(unittest.TestCase):
+ """一家事务所、三位成员,外加一位没有归属的人。"""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.db = Path(self.tmp.name).resolve() / "ledger.db"
+ upgrade(self.db, MIGRATIONS)
+ self.con = sqlite3.connect(self.db)
+ self.con.row_factory = sqlite3.Row
+ self.addCleanup(self.con.close)
+ held = json.dumps({"agency": {"name": "LIGHT", "source": "t", "checked_at": STAMP}},
+ ensure_ascii=False)
+ self.con.executemany(
+ "INSERT INTO entity(id,kind,canonical_name,normalized_name,metadata_json,"
+ "created_at,updated_at) VALUES(?,?,?,?,?,'t','t')",
+ [(11, "performer", "松本一香", normalize_entity_name("松本一香"), held),
+ (12, "performer", "宫西光", normalize_entity_name("宫西光"), held),
+ (13, "performer", "小泉日向", normalize_entity_name("小泉日向"), held),
+ (14, "performer", "北野未奈", normalize_entity_name("北野未奈"), "{}"),
+ (30, "agency", "LIGHT", normalize_entity_name("LIGHT"), "{}")])
+ self.con.executemany(
+ "INSERT INTO entity_membership(member_id,agency_id,source,confidence,checked_at)"
+ " VALUES(?,30,'minnano-av:所属事務所',1.0,?)",
+ [(11, STAMP), (12, STAMP), (13, STAMP)])
+ self.con.commit()
+
+ def agency_of(self, entity_id: int) -> dict:
+ row = self.con.execute(
+ "SELECT metadata_json FROM entity WHERE id=?", (entity_id,)).fetchone()
+ return json.loads(row[0] or "{}").get("agency") or {}
+
+
+class TargetTests(LedgerFixture):
+
+ def test_a_whole_agency_can_be_asked_again(self):
+ found = targets(self.con, ["LIGHT"], [])
+ self.assertEqual([row["performer"] for row in found],
+ ["松本一香", "宫西光", "小泉日向"])
+ self.assertEqual(found[0]["current_agency"], "LIGHT")
+
+ def test_a_named_outsider_joins_the_batch(self):
+ """移籍时人已经不在原来那一家名下,两个条件是并集才问得到她。"""
+ found = targets(self.con, ["LIGHT"], ["北野未奈"])
+ self.assertEqual(len(found), 4)
+ self.assertEqual(found[-1]["current_agency"], "")
+
+ def test_the_same_person_named_twice_is_asked_once(self):
+ self.assertEqual(len(targets(self.con, ["LIGHT"], ["松本一香"])), 3)
+
+
+class PlanTests(LedgerFixture):
+
+ def args(self, **overrides):
+ base = {"agency": ["LIGHT"], "only": [], "interval": 0.0, "timeout": 1.0}
+ return types.SimpleNamespace(**{**base, **overrides})
+
+ def http(self, answers: dict[str, str]) -> Http:
+ from scripts.resync_performer_agency import search_url
+ return Http({search_url(name): Response(
+ 200, f"https://www.minnano-av.com/actress{2000 + index}.html",
+ profile_html(shown))
+ for index, (name, shown) in enumerate(answers.items())})
+
+ def run_plan(self, answers: dict[str, str]):
+ """进度是打给人看的,测试把它接走:控制台是 GBK,中点写不进去。"""
+ with contextlib.redirect_stdout(io.StringIO()):
+ return plan(self.con, self.http(answers), self.args())
+
+ def test_each_person_lands_on_exactly_one_verdict(self):
+ rows = self.run_plan({"松本一香": "ELTRA(エルトラ)旧・LIGHT", "宫西光": "LIGHT",
+ "小泉日向": ""})
+ self.assertEqual({str(row["performer"]): str(row["verdict"]) for row in rows},
+ {"松本一香": MOVED, "宫西光": SAME, "小泉日向": GONE})
+
+ def test_a_page_that_never_arrived_is_not_a_departure(self):
+ """取不到和「这一格是空的」必须分得开,否则重跑一次就把人清空了。"""
+ rows = self.run_plan({})
+ self.assertEqual({str(row["verdict"]) for row in rows}, {MISSING})
+
+
+class ApplyTests(LedgerFixture):
+
+ def rows(self, **overrides):
+ base = {"entity_id": 11, "performer": "松本一香", "current_agency": "LIGHT",
+ "site_agency": "ELTRA(エルトラ)旧・LIGHT", "verdict": MOVED,
+ "evidence": "t"}
+ return [{**base, **overrides}]
+
+ def test_a_move_overwrites_the_name_with_a_fresh_stamp(self):
+ apply_rows(self.con, self.rows(), "2026-09-06T00:00:00Z")
+ found = self.agency_of(11)
+ self.assertEqual(found["name"], "ELTRA(エルトラ)旧・LIGHT")
+ self.assertEqual(found["checked_at"], "2026-09-06T00:00:00Z")
+
+ def test_an_unchanged_row_is_left_alone(self):
+ apply_rows(self.con, self.rows(site_agency="LIGHT", verdict=SAME), "later")
+ self.assertEqual(self.agency_of(11)["checked_at"], STAMP)
+
+ def test_an_empty_cell_never_clears_the_ledger(self):
+ """站点某天不显示这一格,和这个人真的解约了,在页面上长得一模一样。"""
+ apply_rows(self.con, self.rows(site_agency="", verdict=GONE), "later")
+ self.assertEqual(self.agency_of(11)["name"], "LIGHT")
+
+ def test_membership_is_left_to_the_installer(self):
+ """归属表主键在成员一侧,移籍要走 REPLACE,那是 install_agencies 的事。"""
+ apply_rows(self.con, self.rows(), STAMP)
+ self.assertEqual(self.con.execute(
+ "SELECT agency_id FROM entity_membership WHERE member_id=11").fetchone()[0], 30)
+
+ def test_other_metadata_survives_the_rewrite(self):
+ self.con.execute(
+ "UPDATE entity SET metadata_json=? WHERE id=11",
+ (json.dumps({"agency": {"name": "LIGHT"}, "note": "留着"}, ensure_ascii=False),))
+ apply_rows(self.con, self.rows(), STAMP)
+ row = self.con.execute("SELECT metadata_json FROM entity WHERE id=11").fetchone()
+ self.assertEqual(json.loads(row[0])["note"], "留着")
+
+
+if __name__ == "__main__":
+ unittest.main()