Peach: Local-first video metadata scraper and media manager.
fix(western): 罗马字单名只在是页面主名时进别名,资料链接冲突只进回执
longmeidao733042c22780
diff --git a/scripts/harvest_western_profiles.py b/scripts/harvest_western_profiles.pyindex cb1544f40..65793136e 100644--- a/scripts/harvest_western_profiles.py+++ b/scripts/harvest_western_profiles.py@@ -4,7 +4,6 @@ from __future__ import annotationsimport argparseimport jsonimport sys-import timefrom pathlib import Pathfrom datetime import datetime, timezone@@ -12,7 +11,8 @@ sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))from peach.config import REVIEW_DIRfrom peach.http import HttpxTransport-from peach.scripting import add_ledger_write_args, open_for_write, open_readonly, counts_of, verify_after_write+from peach.scripting import (HostLimiter, add_ledger_write_args, open_for_write, open_readonly, counts_of,+ verify_after_write)from peach.western_profiles import profile, land@@ -28,6 +28,9 @@ def run(args):try:with connection:for record in records:+ if 'issue' in record:+ result['entities'].append({'entity_id':record['entity_id'],'skipped':record['issue']})+ continueresult['entities'].append(land(connection, record['entity_id'], record['name'], record, batch=result['batch']))integrity, violations = verify_after_write(connection)if integrity != 'ok' or {tuple(row) for row in connection.execute('PRAGMA foreign_key_check')} != baseline:@@ -40,25 +43,34 @@ def run(args):return resultif not args.entity or len(set(args.entity)) > 16 or args.delay < 1:raise ValueError('每轮 1–16 位艺人,请求间隔至少 1 秒')- http = HttpxTransport()+ return collect(args, HttpxTransport(), HostLimiter({}, default_interval=args.delay))+++def collect(args, http, limiter) -> dict:+ """逐位取资料;一位失败记成问题行,已取得的照常写进计划,每位取完就落盘。"""connection = open_readonly(args.db)records = []+ destination = args.plan or args.out+ destination.parent.mkdir(parents=True,exist_ok=True)try:for entity_id in sorted(set(args.entity)):row = connection.execute("SELECT canonical_name FROM entity WHERE id=? AND kind IN ('performer','creator')",(entity_id,)).fetchone()if not row:- raise ValueError(f'艺人 {entity_id} 不存在')- aliases = [r[0] for r in connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?',(entity_id,))]- url = dict(args.profile_url or []).get(str(entity_id), '')- records.append({'entity_id':entity_id, 'name':row[0], **profile(http,row[0],aliases,profile_url=url)})- time.sleep(args.delay)+ records.append({'entity_id':entity_id, 'issue':'艺人不存在或不是出演者、账号'})+ else:+ aliases = [r[0] for r in connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?',(entity_id,))]+ url = dict(args.profile_url or []).get(str(entity_id), '')+ limiter.wait(url or 'https://www.babepedia.com/')+ try:+ records.append({'entity_id':entity_id, 'name':row[0], **profile(http,row[0],aliases,profile_url=url)})+ except Exception as error:+ records.append({'entity_id':entity_id, 'name':row[0], 'issue':f'{type(error).__name__}: {str(error)[:200]}'})+ destination.write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf8')finally:connection.close()http.close()- destination = args.plan or args.out- destination.parent.mkdir(parents=True,exist_ok=True)- destination.write_text(json.dumps(records,ensure_ascii=False,indent=2),encoding='utf8')- return {'profiles':len(records),'plan':str(destination)}+ return {'profiles':sum('issue' not in record for record in records),+ 'issues':sum('issue' in record for record in records),'plan':str(destination)}if __name__ == '__main__':diff --git a/scripts/repair_western_single_aliases.py b/scripts/repair_western_single_aliases.pynew file mode 100644index 000000000..0582cd7b0--- /dev/null+++ b/scripts/repair_western_single_aliases.py@@ -0,0 +1,87 @@+"""存量修正:西方资料页写下的罗马字单名别名(`performer_alias_followup.latin_rejection`)。++`Lena`、`Mara`、`Kitten` 这种单个词不是艺名,同名的人很多;按别名唯一命中归并出演者时+会把别人挂到她名下。这里把指定来源写下、按现判据不收的别名删掉。页面主名本身是单个词的+不删:给 `--plan` 时从采集清单读每位的 `matched_name`。++默认只列计划(只读打开账本);`--apply` 必须同时给 `--backup`。++ repair_western_single_aliases.py --source auto:babepedia-profile --output <回执.json> \+ --plan <复核目录>/babepedia-person-profiles-plan-1.json --plan <复核目录>/western-profiles-plan.json+"""+from __future__ import annotations++import argparse+import json+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))++from peach.performer_alias_followup import latin_rejection # noqa: E402+from peach.entities import name_rank # noqa: E402+from peach.scripting import ( # noqa: E402+ add_ledger_write_args, counts_of, open_for_write, verify_after_write)+++def primaries(paths: list[Path]) -> dict[int, str]:+ """采集清单里每位的页面主名。"""+ found: dict[int, str] = {}+ for path in paths:+ for record in json.loads(path.read_text(encoding="utf-8")):+ if record.get("entity_id") and record.get("matched_name"):+ found[int(record["entity_id"])] = str(record["matched_name"])+ return found+++def plan(connection, source: str, primary: dict[int, str]) -> list[dict]:+ """这个来源写下、按现判据不收的罗马字别名。"""+ rows = []+ for entity_id, name, alias, batch in connection.execute(+ "SELECT a.entity_id,e.canonical_name,a.alias,a.source FROM entity_alias a"+ " JOIN entity e ON e.id=a.entity_id WHERE substr(a.source,1,?)=?"+ " ORDER BY a.entity_id,a.alias", (len(source) + 1, source + "@")):+ if name_rank(alias) < 3:+ continue+ reason = latin_rejection(alias, primary.get(int(entity_id), ""))+ if reason:+ rows.append({"entity_id": entity_id, "entity": name, "alias": alias,+ "source": batch, "reason": reason})+ return rows+++def build_parser() -> argparse.ArgumentParser:+ parser = add_ledger_write_args(argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter))+ parser.add_argument("--source", default="auto:babepedia-profile")+ parser.add_argument("--plan", type=Path, action="append", default=[])+ parser.add_argument("--output", type=Path, required=True)+ return parser+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ connection = open_for_write(args)+ try:+ before = counts_of(connection)+ rows = plan(connection, args.source, primaries(args.plan))+ receipt = {"apply": args.apply, "source": args.source, "before": before, "aliases": rows}+ if args.apply:+ for row in rows:+ connection.execute("DELETE FROM entity_alias WHERE entity_id=? AND alias=? AND source=?",+ (row["entity_id"], row["alias"], row["source"]))+ connection.commit()+ integrity, violations = verify_after_write(connection)+ receipt.update(after=counts_of(connection), integrity=integrity, foreign_keys=violations)+ args.output.parent.mkdir(parents=True, exist_ok=True)+ args.output.write_text(json.dumps(receipt, ensure_ascii=False, indent=2), encoding="utf-8")+ for row in rows:+ print(f" - {row['entity']}({row['entity_id']}){row['alias']}:{row['reason']}")+ print(json.dumps({"aliases": len(rows), "apply": args.apply}, ensure_ascii=False))+ return 0 if not args.apply or receipt["integrity"] == "ok" else 1+ finally:+ connection.close()+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/peach/performer_alias_followup.py b/src/peach/performer_alias_followup.pyindex baf92ba77..27bff4388 100644--- a/src/peach/performer_alias_followup.py+++ b/src/peach/performer_alias_followup.py@@ -17,7 +17,7 @@`metadata_alias_resolve` 的判据不收,也不拿去检索。4. **短单名不收**:两个字以内的写法(`舞香`、`茜`)与三个字以内的纯假名(`そら`、`みく`)只是名、不带姓,会命中别人(`entities.is_short_single_name`);罗马字写法也不收,日文站和- 图库都用不上它。+ 图库都用不上它。西方资料页收罗马字,单个词只在它就是页面主名时收(`latin_rejection`)。5. **四种不写**,与 `scripts/apply_alias_candidates.py` 同一口径:已有、被另一条实体占用、统称已变、查无此人。6. **两条实体合成一条**(ADR-0064):minnano-av 或 av_neme 的名字栏把她和账本里另一条女优@@ -150,6 +150,22 @@ def rejection(name: str) -> str:return ""+def latin_rejection(name: str, primary: str) -> str:+ """允许罗马字的来源(西方资料页)里,这个写法不收的原因;收得下返回空串。++ `Lena`、`Anna`、`Mara` 这种单个词是名不是艺名,同名的人成百上千;只有它就是这一页的+ 主名(页面把它当作这个人的完整艺名)时才收。企划名义的判据按日文的名字边界切分,+ 罗马字的名与姓之间就是空格,不适用;描述性称呼照旧不收。+ """+ if len(name.split()) < 2 and match_key(name) != match_key(primary):+ return "罗马字单名,会命中别人"+ if len(match_key(name)) < 4:+ return "短单名,会命中别人"+ if is_descriptive(name):+ return "描述性称呼"+ return ""++def match_key(name: str) -> str:"""比名字用的键:全半角、空白、大小写与日本字形都折掉(`涼森` 与 `凉森` 同键)。"""return fold_glyphs(name_key(name))@@ -674,7 +690,11 @@ def _owners(connection: sqlite3.Connection, *, allow_creator: bool = False) -> ddef land(connection: sqlite3.Connection, entity_id: int, expected_name: str, site: str,url: str, names: list[str], batch: str, *, allow_latin: bool = False,allow_creator: bool = False) -> list[dict]:- """把一页上的写法逐个判完,该写的写进 `entity_alias`。返回每个写法一行判词。"""+ """把一页上的写法逐个判完,该写的写进 `entity_alias`。返回每个写法一行判词。++ `allow_latin` 给西方资料页用:`names[0]` 必须是页面主名,罗马字写法按+ `latin_rejection` 判。+ """base = {"entity_id": entity_id, "canonical_name": expected_name, "site": site,"page": url, "batch": ""}current = _names(connection, entity_id, allow_creator=allow_creator)@@ -688,8 +708,8 @@ def land(connection: sqlite3.Connection, entity_id: int, expected_name: str, sitowners, rows = _owners(connection, allow_creator=allow_creator), []for name in dict.fromkeys(names):reason = rejection(name)- if allow_latin and reason == '罗马字写法':- reason = '' if len(match_key(name)) >= 4 else '短单名,会命中别人'+ if allow_latin and reason == "罗马字写法":+ reason = latin_rejection(name, names[0])others = sorted(owners.get(match_key(name), set()) - {entity_id})if reason:rows.append({**base, "alias": name, "action": SKIP, "detail": reason})diff --git a/src/peach/western_profiles.py b/src/peach/western_profiles.pyindex 551cb7b9b..bf0e71287 100644--- a/src/peach/western_profiles.py+++ b/src/peach/western_profiles.py@@ -11,6 +11,7 @@ from .http import public_https_urlfrom .western_artwork import babepedia_pagefrom .performer_profiles import read_profile, write_profilefrom .performer_alias_followup import land as land_aliases+from .social_links import canonical_url, handle, host_of, platformMONTHS = {name: i for i, name in enumerate(('January', 'February', 'March', 'April', 'May','June', 'July', 'August', 'September', 'October', 'November', 'December'), 1)}@@ -46,11 +47,12 @@ def profile(http, name: str, aliases=(), *, profile_url='') -> dict:cup = re.search(r'\bJP:\s*\d+([A-Z]+)', fields.get('Bra/cup size', ''))if cup:result['cup'] = cup[1]- years = re.match(r'(\d{4})\s*[-–]\s*(present|\d{4})\b', fields.get('Years active', ''))- if years:- result['debut_year'] = int(years[1])- if years[2] != 'present':- result['active_until'] = int(years[2])+ # `2014 - 2017, 2019 - present` 是几段:出道取第一段的起点,引退取最后一段的终点。+ spans = re.findall(r'(\d{4})\s*[-–]\s*(present|\d{4})\b', fields.get('Years active', ''))+ if spans:+ result['debut_year'] = int(spans[0][0])+ if spans[-1][1] != 'present':+ result['active_until'] = int(spans[-1][1])birthplace = fields.get('Birthplace', '')if birthplace:result['birthplace'] = re.sub(r'\s*\(#\d+\)', '', birthplace).strip()@@ -82,11 +84,16 @@ def land(connection, entity_id: int, expected_name: str, record: dict, *, batch:aliases = land_aliases(connection, entity_id, expected_name, 'Babepedia', record['profile_url'],[record['matched_name'], *record['aliases']], batch, allow_latin=True,allow_creator=True)- added = []+ added, conflicts = [], []stamp = datetime.now(timezone.utc).isoformat()for link in record['links']:- url = link['url']- if connection.execute('SELECT 1 FROM entity_link WHERE entity_id=? AND url=?', (entity_id,url)).fetchone():+ url = canonical_url(link['url'])+ existing = connection.execute('SELECT link_kind,url FROM entity_link WHERE entity_id=?', (entity_id,)).fetchall()+ if any(canonical_url(held) == url for _kind, held in existing):+ continue+ reason = link_conflict(link['link_kind'], url, existing)+ if reason:+ conflicts.append({'url': url, 'link_kind': link['link_kind'], 'reason': reason})continuemetadata = json.dumps({'source':batch.split('@', 1)[0], 'batch':batch,'source_url':record['profile_url']}, ensure_ascii=False)@@ -94,4 +101,22 @@ def land(connection, entity_id: int, expected_name: str, record: dict, *, batch:(entity_id, link['link_kind'], link['label'], url, urlsplit(url).hostname, metadata,stamp,stamp))added.append(cursor.lastrowid)return {'entity_id':entity_id,'name':expected_name,'profile_written':written,- 'preserved_profile':held is not None,'aliases':aliases,'added_links':added,'source':batch}+ 'preserved_profile':held is not None,'aliases':aliases,'added_links':added,+ 'link_conflicts':conflicts,'source':batch}+++def link_conflict(link_kind: str, url: str, existing: list) -> str:+ """资料页给的链接与账本已有链接说法不一时的原因;不冲突返回空串。++ 已有官网就不再添第二个官网;同一平台已登记另一个账号、同一目录站已登记另一页,+ 都是两处来源说法不一,留在回执里等人看。+ """+ if link_kind == 'official' and any(kind == 'official' for kind, _url in existing):+ return '已有官网'+ site = platform(url)+ for _kind, held in existing:+ if site and platform(held) == site and handle(held) != handle(url):+ return f'{site} 已登记另一个账号'+ if not site and link_kind != 'official' and host_of(held) == host_of(url):+ return f'{host_of(url)} 已登记另一页'+ return ''diff --git a/tests/test_western_profiles.py b/tests/test_western_profiles.pyindex 403964e8a..518fdd28d 100644--- a/tests/test_western_profiles.py+++ b/tests/test_western_profiles.py@@ -46,6 +46,50 @@ class WesternProfileTests(unittest.TestCase):self.assertNotIn(key,facts)self.assertEqual(facts['active_until'],2025)+ def test_split_active_years_use_the_first_start_and_the_last_end(self):+ for raw, until in [('2014 - 2017, 2019 - 2021', 2021), ('2014 - 2017, 2019 - present', None)]:+ with self.subTest(raw=raw):+ body = self.page(self.cell('Years active', raw))+ facts = profile(lambda *a, body=body: HttpResponse(200, {}, body), 'Christy White')['profile']+ self.assertEqual(facts['debut_year'], 2014)+ self.assertEqual(facts.get('active_until'), until)++ def test_profile_links_that_disagree_with_held_links_are_reported_not_written(self):+ with tempfile.TemporaryDirectory() as directory, closing(sqlite3.connect(fresh_ledger(Path(directory).resolve()))) as connection:+ entity_id = connection.execute("INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at) VALUES('performer','Christy White','christy white','t','t')").lastrowid+ connection.executemany("INSERT INTO entity_link(entity_id,link_kind,label,url,hostname,created_at,updated_at) VALUES(?,?,?,?,?,'t','t')",+ [(entity_id, 'social', 'X', 'https://x.com/christy_a', 'x.com'),+ (entity_id, 'official', '官网', 'https://christy.example/', 'christy.example')])+ body = self.page() + (b'<div id="socialicons"><a class="proficon x" href="https://twitter.com/christy_b">X</a>'+ b'<a class="proficon www" href="https://linktr.ee/christy">Web</a>'+ b'<a class="proficon instagram" href="https://www.instagram.com/christy">IG</a></div>')+ record = profile(lambda *a: HttpResponse(200, {}, body), 'Christy White')+ with connection:+ result = land(connection, entity_id, 'Christy White', record, batch='auto:babepedia-profile@links')+ self.assertEqual([item['reason'] for item in result['link_conflicts']], ['X 已登记另一个账号', '已有官网'])+ self.assertEqual(len(result['added_links']), 1)+ self.assertEqual(connection.execute('SELECT count(*) FROM entity_link WHERE entity_id=?', (entity_id,)).fetchone()[0], 3)++ def test_one_failed_profile_keeps_the_others_in_the_plan(self):+ from types import SimpleNamespace+ from scripts import harvest_western_profiles as harvest++ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ path = fresh_ledger(root)+ with closing(sqlite3.connect(path)) as connection, connection:+ connection.executemany("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) VALUES(?,'performer',?,?,'t','t')",+ [(1, 'Christy White', 'christy white'), (2, 'Someone Else', 'someone else')])+ waits = []+ limiter = SimpleNamespace(wait=waits.append)+ http = lambda *a: HttpResponse(200, {}, self.page())+ http.close = lambda: None+ args = SimpleNamespace(db=path, entity=[2, 1, 3], profile_url=None, plan=root / 'plan.json', out=root / 'out.json')+ self.assertEqual(harvest.collect(args, http, limiter)['issues'], 2)+ records = json.loads((root / 'plan.json').read_text(encoding='utf8'))+ self.assertEqual([(record['entity_id'], 'issue' in record) for record in records], [(1, False), (2, True), (3, True)])+ self.assertEqual(len(waits), 2)+def test_babepedia_alias_identity_is_required_for_all_profile_fields(self):with self.assertRaisesRegex(ValueError,'身份不一致'):profile(lambda *a:HttpResponse(200,{},self.page()),'Someone Else')@@ -65,6 +109,41 @@ class WesternProfileTests(unittest.TestCase):self.assertIn('Kurumi Momota',[r[0] for r in connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?',(entity_id,))])self.assertGreater(facts['name_groups']['total'],1)+ def test_single_latin_names_land_only_as_the_page_primary_name(self):+ with tempfile.TemporaryDirectory() as directory, closing(sqlite3.connect(fresh_ledger(Path(directory).resolve()))) as connection:+ first = connection.execute("INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at) VALUES('performer','Lena Anderson','lena anderson','t','t')").lastrowid+ body = b'<h1 id="babename">Blaire Ivory</h1><h2 id="aka"><small>Also known as:</small>Lena Anderson - Lena - Mara - Mara Watson - Colett</h2>'+ record = profile(lambda *a: HttpResponse(200, {}, body), 'Lena Anderson')+ with connection:+ land(connection, first, 'Lena Anderson', record, batch='auto:babepedia-profile@single')+ self.assertEqual(sorted(r[0] for r in connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?', (first,))),+ ['Blaire Ivory', 'Mara Watson'])+ second = connection.execute("INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at) VALUES('performer','Kitten Doe','kitten doe','t','t')").lastrowid+ body = b'<h1 id="babename">Kittenx</h1><h2 id="aka"><small>Also known as:</small>Kitten Doe - Kitty</h2>'+ record = profile(lambda *a: HttpResponse(200, {}, body), 'Kitten Doe')+ with connection:+ land(connection, second, 'Kitten Doe', record, batch='auto:babepedia-profile@primary')+ self.assertEqual([r[0] for r in connection.execute('SELECT alias FROM entity_alias WHERE entity_id=?', (second,))], ['Kittenx'])++ def test_repair_drops_stored_single_latin_aliases_except_the_page_primary_name(self):+ from scripts import repair_western_single_aliases as repair++ with tempfile.TemporaryDirectory() as directory:+ root = Path(directory).resolve()+ path = fresh_ledger(root)+ with closing(sqlite3.connect(path)) as connection, connection:+ connection.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) VALUES(1,'performer','Lena Anderson','lena anderson','t','t')")+ connection.executemany("INSERT INTO entity_alias(entity_id,alias,normalized_alias,source) VALUES(1,?,?,?)",+ [('Lena', 'lena', 'auto:babepedia-profile@1'), ('Mara Watson', 'mara watson', 'auto:babepedia-profile@1'),+ ('Kittenx', 'kittenx', 'auto:babepedia-profile@1'), ('Anna', 'anna', 'user:alias')])+ (root / 'plan.json').write_text(json.dumps([{'entity_id': 1, 'matched_name': 'Kittenx'}]), encoding='utf-8')+ common = ['--db', str(path), '--plan', str(root / 'plan.json'), '--output', str(root / 'receipt.json')]+ self.assertEqual(repair.main(common), 0)+ self.assertEqual(repair.main([*common, '--apply', '--backup', str(root / 'backup.db')]), 0)+ with closing(sqlite3.connect(path)) as connection:+ self.assertEqual(sorted(r[0] for r in connection.execute('SELECT alias FROM entity_alias')),+ ['Anna', 'Kittenx', 'Mara Watson'])+def test_named_person_gallery_adds_candidates_and_excludes_other_people(self):body = self.page() + b'<div id="profbox2"><a class="img" href="/pics/Christy.jpg"></a></div><div class="useruploads2"><a class="img" href="/user-uploads/Christy.jpg"><img alt="Christy White"></a><a class="img" href="/user-uploads/Other.jpg"><img alt="Someone Else"></a></div><a class="img" href="/pics/related.jpg"><img alt="Christy White"></a>'found = babepedia_portraits(lambda *a:HttpResponse(200,{},body),'Christy White')