Peach: Local-first video metadata scraper and media manager.
fix(links): 官方链接的标签跟着域名归属走
longmeidao80f4379a78cb
diff --git a/scripts/harvest_performer_links.py b/scripts/harvest_performer_links.pyindex 86a0bd8bd..0cbc08c83 100644--- a/scripts/harvest_performer_links.py+++ b/scripts/harvest_performer_links.py@@ -32,7 +32,9 @@ from peach.jobs import job_main # noqa: E402from peach.review_csv import write_rows # noqa: E402from peach.scripting import USER_AGENT, open_readonly # noqa: E402# 平台判据与选人规则和目录型采集器共用,定义在 peach.social_links;这里只保留 minnano-av 的解析。-from peach.social_links import classify, load_performers, under # noqa: E402,F401+from peach.social_links import ( # noqa: E402,F401+ classify, host_owners, load_performers, under,+)SEARCH = "https://www.minnano-av.com/search_result.php?search_scope=actress&search_word="ACTRESS_PAGE = re.compile(r"/actress(\d+)\.html")@@ -76,8 +78,13 @@ def profile_text(html: str, label: str) -> str:return ""-def scan(http, name: str, timeout: float) -> tuple[list[dict], str, str, str]:- """返回(链接行, actress_id, 所属事务所, 判定说明)。"""+def scan(http, name: str, timeout: float, owner_of=None) -> tuple[list[dict], str, str, str]:+ """返回(链接行, actress_id, 所属事务所, 判定说明)。++ 「所属事務所」和「公式サイト」是资料表里两行不同的事实,别把前者当成后者的名字:+ 専属女优的「公式サイト」填的常是片商的宣传页,贴上事务所名就等于替两家公司说话。+ `owner_of` 把域名归属交给 `classify` 判,事务所名另行写进实体元数据。+ """response = http(HttpRequest("GET", search_url(name), {"User-Agent": USER_AGENT}),timeout, 4 << 20)if response.status != 200:@@ -92,7 +99,7 @@ def scan(http, name: str, timeout: float) -> tuple[list[dict], str, str, str]:if label not in LINK_LABELS:continuefor url in urls:- link_kind, link_label = classify(url, agency)+ link_kind, link_label = classify(url, agency, owner_of)rows.append({"link_kind": link_kind, "label": link_label, "url": url,"evidence": f"minnano-av actress{found_id} 资料表「{label}」"})note = (f"命中 actress{found_id},{len(rows)} 条外链" if rows@@ -116,6 +123,7 @@ def run(args) -> int:connection = open_readonly(args.db)try:performers = load_performers(connection, args.min_assets)+ owners = host_owners(connection)finally:connection.close()if args.limit:@@ -135,7 +143,8 @@ def run(args) -> int:time.sleep(wait)last = time.monotonic()try:- rows, found_id, agency, note = scan(http, candidate, args.timeout)+ rows, found_id, agency, note = scan(http, candidate, args.timeout,+ owners.get)except Exception as exc:rows, found_id, agency, note = [], "", "", f"未取得:{type(exc).__name__}"used = candidatediff --git a/scripts/repair_link_labels.py b/scripts/repair_link_labels.pynew file mode 100644index 000000000..d8d765353--- /dev/null+++ b/scripts/repair_link_labels.py@@ -0,0 +1,196 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+"""把女优官方链接的标签改成按域名归属写,并把事务所名移到它自己的位置。++采集时 `harvest_performer_links.py` 从 minnano-av 资料表读「所属事務所」,然后把这个名字+贴到同一页找到的每一条 official 链接上。资料表里「所属事務所」和「公式サイト」是两行不同+的事实:白石亚子的事务所是 T-POWERS,公式サイト填的却是 Prestige 的専属宣传页。于是资料页+上出现一个同时替两家公司说话的控件——文字写着 T-POWERS,图标和落点都是 Prestige。++这里做两件事,一次做完:++1. **标签改成按域名归属写**(`peach.social_links.host_owners`)。域名归谁就写谁的名字;+ 账本不知道它归谁才保留原标签。Facebook 和 Linktree 此前不在平台表里、走了 official+ 分支,顺带归位成 social。+2. **事务所名写进 `entity.metadata_json.agency`**,带来源和采集时间。它是有用的信息,+ 只是不该住在链接标签里——标签的语义是「点过去会看到什么」,装不下「她签在谁名下」。+ 女优会移籍,所以这里带时间戳、按最新覆盖。++改标签可逆(原值写进复核 CSV 就能改回去),但仍按真实写入对待:默认只产出复核 CSV,+`--apply` 才写 ledger 且必须给 `--backup`。+"""+from __future__ import annotations++import argparse+import json+import sqlite3+import sys+import time+from pathlib import Path++PROJECT_ROOT = Path(__file__).resolve().parent.parent+SRC_DIR = PROJECT_ROOT / "src"+if str(SRC_DIR) not in sys.path:+ sys.path.insert(0, str(SRC_DIR))++from peach.config import GENERATED_DIR # noqa: E402+from peach.review_csv import write_rows # noqa: E402+from peach.scripting import ( # noqa: E402+ add_ledger_write_args, counts_of, open_for_write, verify_after_write,+)+from peach.social_links import classify, host_owners, owner_key # noqa: E402++FIELDS = ("verdict", "entity_id", "performer", "link_id", "hostname",+ "label", "new_label", "link_kind", "new_link_kind", "agency", "note")++#: 不承诺点过去会见到谁的兜底标签。它没有说错话,所以不算需要修的。+GENERIC_LABEL = "官方网站"++EXTRA_COUNTS = {+ "official_link": "SELECT count(*) FROM entity_link WHERE link_kind='official'",+ "social_link": "SELECT count(*) FROM entity_link WHERE link_kind='social'",+ "有事务所的女优": (+ "SELECT count(*) FROM entity WHERE kind='performer'"+ " AND json_extract(metadata_json,'$.agency.name') IS NOT NULL"),+}+++def studio_names(connection: sqlite3.Connection) -> set[str]:+ """厂牌的规范名。标签等于其中之一时它说的是片商,不是事务所。"""+ return {row[0] for row in connection.execute(+ "SELECT canonical_name FROM entity WHERE kind='studio'")}+++def agency_from_label(label: str, hostname: str, studios: set[str]) -> str:+ """这条标签里装着的事务所名,没装就返回空。++ 事务所名眼下只存在于标签里,别处没有第二份。所以改标签之前先把它取出来——直接覆盖+ 等于把这个事实删掉,而它正是用户要的那个信息。+ """+ label = label.strip()+ if not label or label == GENERIC_LABEL or label in studios:+ return ""+ # 标签就是域名本身(`tma.co.jp`)时它是采集兜底,不是谁的名字。+ return "" if label.strip("/") in {hostname, f"www.{hostname}"} else label+++def collect(connection: sqlite3.Connection) -> list[dict[str, object]]:+ """每条女优 official 链接的重判结果。"""+ owners = host_owners(connection)+ studios = studio_names(connection)+ rows: list[dict[str, object]] = []+ for link_id, entity_id, performer, kind, label, url, hostname in connection.execute(+ "SELECT l.id,l.entity_id,e.canonical_name,l.link_kind,l.label,l.url,l.hostname"+ " FROM entity_link l JOIN entity e ON e.id=l.entity_id"+ " WHERE e.kind='performer' AND l.link_kind='official' ORDER BY l.id"+ ):+ agency = agency_from_label(label, hostname, studios)+ new_kind, new_label = classify(url, agency, owners.get)+ owner = owners.get(owner_key(hostname), "")+ if (new_kind, new_label) == (kind, label):+ verdict, note = "keep", "标签与域名归属一致"+ elif new_kind != kind:+ verdict, note = "auto", f"{hostname} 是平台账号,不是 official"+ elif owner:+ verdict, note = "auto", f"{hostname} 归 {owner}"+ else:+ # 归属未知时 classify 会把原标签原样还回来,走不到这里;留着兜底。+ verdict, note = "review", f"{hostname} 归属未取得"+ rows.append({+ "verdict": verdict, "entity_id": entity_id, "performer": performer,+ "link_id": link_id, "hostname": hostname, "label": label,+ "new_label": new_label, "link_kind": kind, "new_link_kind": new_kind,+ "agency": agency, "note": note})+ # 域名归属未取得、标签却写着一个名字的:孤证,没有第二条链接能佐证它。+ for row in rows:+ if (row["verdict"] == "keep" and row["agency"]+ and not owners.get(owner_key(str(row["hostname"])))):+ row["verdict"] = "review"+ row["note"] = f"{row['hostname']} 归属未取得,标签只有这一条孤证"+ rows.sort(key=lambda row: ({"auto": 0, "review": 1, "keep": 2}[str(row["verdict"])],+ int(row["link_id"])))+ return rows+++def apply_rows(connection: sqlite3.Connection,+ rows: list[dict[str, object]], stamp: str) -> dict[str, int]:+ """改标签、归位 link_kind,并把事务所写进实体元数据。++ 事务所对每位女优只留一条:她现在签在谁名下。移籍是常态,所以按最新覆盖,+ 同时记下这一条是什么时候、从哪里取到的——没有时间戳就分不清哪一份更新。+ """+ relabelled = moved = agencies = 0+ for row in rows:+ if row["agency"]:+ entity_id = int(row["entity_id"])+ current = connection.execute(+ "SELECT metadata_json FROM entity WHERE id=?", (entity_id,)).fetchone()+ try:+ metadata = json.loads(current[0] or "{}")+ except (TypeError, ValueError):+ metadata = {}+ metadata["agency"] = {"name": str(row["agency"]),+ "source": "minnano-av 资料表「所属事務所」",+ "checked_at": stamp}+ connection.execute(+ "UPDATE entity SET metadata_json=?,updated_at=? WHERE id=?",+ (json.dumps(metadata, ensure_ascii=False), stamp, entity_id))+ agencies += 1+ if row["verdict"] not in {"auto"}:+ continue+ connection.execute(+ "UPDATE entity_link SET label=?,link_kind=?,updated_at=? WHERE id=?",+ (row["new_label"], row["new_link_kind"], stamp, int(row["link_id"])))+ relabelled += 1+ if row["new_link_kind"] != row["link_kind"]:+ moved += 1+ return {"改了标签": relabelled, "其中归位成 social": moved, "写下事务所": agencies}+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__,+ formatter_class=argparse.RawDescriptionHelpFormatter)+ add_ledger_write_args(parser)+ parser.add_argument("--review-csv", type=Path,+ default=GENERATED_DIR / "review" / "link-labels.csv",+ help="复核 CSV 输出路径")+ return parser+++def run(args: argparse.Namespace) -> int:+ connection = open_for_write(args)+ try:+ rows = collect(connection)+ args.review_csv.parent.mkdir(parents=True, exist_ok=True)+ write_rows(args.review_csv, FIELDS, rows)+ tally: dict[str, int] = {}+ for row in rows:+ tally[str(row["verdict"])] = tally.get(str(row["verdict"]), 0) + 1+ print(f"{len(rows)} 条女优官方链接 -> {args.review_csv}")+ print(" ", tally)+ for row in rows:+ if row["verdict"] == "auto":+ print(f" [{row['entity_id']}] {row['performer']}:"+ f"{row['label']} -> {row['new_label']}({row['note']})")+ if not args.apply:+ print(" 未写 ledger(加 --apply --backup 才写)")+ return 0+ print(f" 已备份到 {args.backup}")+ before = counts_of(connection, EXTRA_COUNTS)+ stamp = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())+ with connection:+ done = apply_rows(connection, rows, stamp)+ after = counts_of(connection, EXTRA_COUNTS)+ _integrity, violations = verify_after_write(connection)+ print(" 结果:", done)+ 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+ finally:+ connection.close()+++if __name__ == "__main__":+ raise SystemExit(run(build_parser().parse_args()))diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 093a711aa..404c746bf 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -49,7 +49,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"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",- "test_link_rediscovery.py"),+ "test_link_rediscovery.py", "test_link_label_owner.py"),"tooling": ("test_scripts.py", "test_cli.py", "test_script_policy.py","test_agent_worktree.py", "test_dependency_policy.py","test_restart_windows_tray.py",diff --git a/src/peach/social_links.py b/src/peach/social_links.pyindex 93c5d3823..3e295e81b 100644--- a/src/peach/social_links.py+++ b/src/peach/social_links.py@@ -12,16 +12,25 @@ import htmlimport reimport sqlite3import unicodedata+from collections.abc import Callablefrom urllib.parse import urlsplit, urlunsplitfrom .catalog_rules import is_jav_codefrom .entities import name_chain-SOCIAL_HOSTS = ("x.com", "twitter.com", "instagram.com", "tiktok.com", "youtube.com")+#: Facebook 和 Linktree 也在这里:它们此前不在表里,于是走了 official 分支,被贴上+#: 事务所名——古川伊织的个人 Facebook 页在资料页上写着「T-POWERS」。本人账号就该按+#: 本人账号显示,事务所名是另一件事。+SOCIAL_HOSTS = ("x.com", "twitter.com", "instagram.com", "tiktok.com", "youtube.com",+ "facebook.com", "linktr.ee")#: 博客也是本人的社交存在,但它没有 handle 概念,标签另算。-BLOG_HOSTS = ("ameblo.jp", "lineblog.me", "note.com", "livedoor.jp", "hatenablog.com")+#: `livedoor.biz` 与 `livedoor.jp` 是同一家的两个域,`plaza.rakuten.co.jp` 和+#: `blog.dmm.co.jp` 同样是博客托管——它们不在表里时都走了 official 分支,被贴上事务所名。+BLOG_HOSTS = ("ameblo.jp", "lineblog.me", "note.com", "livedoor.jp", "livedoor.biz",+ "hatenablog.com", "plaza.rakuten.co.jp", "blog.dmm.co.jp")PLATFORM_NAMES = {("x.com", "twitter.com"): "X", ("instagram.com",): "Instagram",- ("tiktok.com",): "TikTok", ("youtube.com",): "YouTube"}+ ("tiktok.com",): "TikTok", ("youtube.com",): "YouTube",+ ("facebook.com",): "Facebook", ("linktr.ee",): "Linktree"}#: 这些首段不是 handle,是平台的路径前缀:`youtube.com/channel/UC…`、`youtube.com/c/名字`。PATH_PREFIXES = frozenset({"channel", "c", "user"})#: 这些首段是平台功能页,不是任何人的账号:`x.com/intent/follow?…`、`instagram.com/p/…`。@@ -112,11 +121,18 @@ def handle(url: str) -> str:return account_segment(url).casefold()-def classify(url: str, agency: str = "") -> tuple[str, str]:+def classify(url: str, agency: str = "",+ owner_of: Callable[[str], str] | None = None) -> tuple[str, str]:"""(link_kind, label)。label 就是资料页上那行链接文字,所以要说清点过去是什么。- 事务所页面用事务所名当标签(`T-POWERS` 而不是通用的「官方网站」):用户要的正是- 厂商链接,而这个名字资料表里已经给了,退回通用词等于把取到的信息扔掉。+ **标签跟着域名走,不跟着事务所字段走。** minnano-av 的资料表里「所属事務所」和+ 「公式サイト」是两行不同的事实:白石亚子的事务所是 T-POWERS,公式サイト填的却是+ Prestige 的専属宣传页。把事务所名贴到这条链接上,一个控件就同时替两家公司说话——+ 图标按域名取,于是页面上写着 T-POWERS、图标和落点都是 Prestige。++ `owner_of(hostname)` 给出账本已知的域名归属(厂牌官网、事务所自己的站)。知道归谁+ 就用谁的名字;不知道才退回事务所名,那时它至少没有和已知事实矛盾。两样都没有就写+ 「官方网站」——这个词不承诺点过去会见到谁,是唯一诚实的兜底。"""name = platform(url)if name:@@ -125,9 +141,58 @@ def classify(url: str, agency: str = "") -> tuple[str, str]:if name == "YouTube" and re.fullmatch(r"UC[\w-]{22}", shown):shown = ""return "social", (f"{name} @{shown}" if shown else name)- if under(host_of(url), BLOG_HOSTS):+ host = host_of(url)+ if under(host, BLOG_HOSTS):return "social", "博客"- return "official", (agency.strip() or "官方网站")+ # `owner_of` 常常就是某个 dict 的 `.get`,未命中给的是 None 不是空串。+ owner = str(owner_of(host) or "" if owner_of else "").strip()+ return "official", (owner or agency.strip() or "官方网站")+++#: 一个域名要被多少条链接指认成同一家,才算「账本知道它归谁」。+#: 1 会让香西咲个人站 `saki-k.com` 上那一条孤证自我确认成 T-POWERS 的站。+OWNER_QUORUM = 3+++def owner_key(hostname: str) -> str:+ """归属表的键。++ 同一家站在账本里两种写法都有(`bambi.ne.jp` 与 `www.bambi.ne.jp`),落成哪一种是+ 采集时抓到什么决定的。键和 `host_of` 用同一条归一规则,写入和查询才对得上——+ 两边各归一各的,`www.` 那一半就永远查不到归属、白白退回事务所名。+ """+ return (hostname or "").casefold().removeprefix("www.")+++def host_owners(connection: sqlite3.Connection) -> dict[str, str]:+ """域名 → 账本知道的归属方名字。++ 两种证据,厂牌优先:厂牌实体自己挂的官网链接直接指认(`www.prestige-av.com` 是+ Prestige 的),这是一手的。其次是女优 official 链接里已经形成共识的那些——+ `www.t-powers.co.jp` 上 37 条都写着 T-POWERS,那它就是 T-POWERS 的站。++ 共识要够多条才作数。孤证会自我确认:香西咲的个人站只出现过一次、恰好被贴了+ T-POWERS,采信它等于把错误当成证据再用一遍。+ """+ owners: dict[str, str] = {}+ votes: dict[str, dict[str, int]] = {}+ for host, label in connection.execute(+ "SELECT hostname,label FROM entity_link l JOIN entity e ON e.id=l.entity_id"+ " WHERE e.kind='performer' AND l.link_kind='official' AND l.hostname<>''"+ ):+ host = owner_key(host)+ votes.setdefault(host, {})[label] = votes.setdefault(host, {}).get(label, 0) + 1+ for host, tally in votes.items():+ label, count = max(tally.items(), key=lambda item: item[1])+ if count >= OWNER_QUORUM and label != "官方网站":+ owners[host] = label+ # 厂牌那一手证据后写,压过女优链接里的共识。+ for host, name in connection.execute(+ "SELECT hostname,canonical_name FROM entity_link l JOIN entity e ON e.id=l.entity_id"+ " WHERE e.kind='studio' AND l.link_kind='official' AND l.hostname<>''"+ ):+ owners[owner_key(host)] = name+ return ownersdef name_key(name: str) -> str:diff --git a/tests/test_link_label_owner.py b/tests/test_link_label_owner.pynew file mode 100644index 000000000..d36bc4386--- /dev/null+++ b/tests/test_link_label_owner.py@@ -0,0 +1,133 @@+"""链接标签跟着域名归属走,事务所名搬进实体元数据。"""+import json+import sqlite3+import tempfile+import unittest+from pathlib import Path++from peach.migrations import upgrade+from peach.social_links import OWNER_QUORUM, host_owners, owner_key+from scripts.repair_link_labels import agency_from_label, apply_rows, collect++ROOT = Path(__file__).resolve().parents[1]+STAMP = "2026-09-04T00:00:00Z"+++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, 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')",+ [(1, "studio", "Prestige", "prestige"),+ (10, "performer", "白石亚子", "白石亚子"),+ (11, "performer", "大槻响", "大槻响"),+ (12, "performer", "凉森玲梦", "凉森玲梦"),+ (13, "performer", "羽咲美晴", "羽咲美晴"),+ (14, "performer", "香西咲", "香西咲"),+ (15, "performer", "古川伊织", "古川伊织")])+ self.link_id = 0+ self.link(1, "official", "官方网站", "https://www.prestige-av.com/")+ # 事务所自家站上的共识:三条都写着 T-POWERS,够 quorum。+ for entity_id in (11, 12, 13):+ self.link(entity_id, "official", "T-POWERS",+ f"http://www.t-powers.co.jp/official/talent/{entity_id}")+ self.link(10, "official", "T-POWERS",+ "http://www.prestige-av.com/special/shiraishi_ako.php")+ self.link(14, "official", "T-POWERS", "http://saki-k.com")+ self.link(15, "official", "T-POWERS",+ "https://www.facebook.com/miho.tanaka.334491")+ self.con.commit()++ def link(self, entity_id, kind, label, url):+ self.link_id += 1+ host = url.split("//", 1)[1].split("/", 1)[0]+ self.con.execute(+ "INSERT INTO entity_link(id,entity_id,link_kind,label,url,hostname,"+ "created_at,updated_at) VALUES(?,?,?,?,?,?,'t','t')",+ (self.link_id, entity_id, kind, label, url, host))++ def _rows(self):+ return {int(row["entity_id"]): row for row in collect(self.con)}+++class HostOwnerTests(LedgerFixture):+ def test_a_studio_owns_the_domain_its_own_link_points_at(self):+ self.assertEqual(host_owners(self.con)["prestige-av.com"], "Prestige")++ def test_enough_performer_links_agreeing_establish_an_agency_domain(self):+ self.assertEqual(host_owners(self.con)["t-powers.co.jp"], "T-POWERS")++ def test_a_lone_link_does_not_get_to_certify_its_own_label(self):+ """孤证会自我确认:香西咲的个人站只出现过一次、恰好被贴了 T-POWERS。"""+ self.assertNotIn("saki-k.com", host_owners(self.con))+ self.assertGreater(OWNER_QUORUM, 1)++ def test_both_spellings_of_one_host_land_on_one_key(self):+ # 证据落在带不带 www 的哪一种,是采集时抓到什么决定的;键和 `host_of` 同一条规则。+ owners = host_owners(self.con)+ self.assertEqual(owner_key("www.prestige-av.com"), "prestige-av.com")+ self.assertNotIn("www.prestige-av.com", owners)+++class LabelRepairTests(LedgerFixture):+ def test_an_agency_label_on_a_studio_domain_is_rewritten(self):+ row = self._rows()[10]+ self.assertEqual((row["verdict"], row["new_label"]), ("auto", "Prestige"))+ self.assertEqual(row["agency"], "T-POWERS")++ def test_an_agency_label_on_its_own_domain_is_left_alone(self):+ self.assertEqual(self._rows()[11]["verdict"], "keep")++ def test_a_platform_account_stops_being_an_official_link(self):+ row = self._rows()[15]+ self.assertEqual((row["verdict"], row["new_link_kind"]), ("auto", "social"))+ self.assertEqual(row["new_label"], "Facebook @miho.tanaka.334491")++ def test_an_unverifiable_label_is_kept_but_reported(self):+ # 个人站的归属账本说不出来,改不改都是猜——留原样,写进复核表交人工。+ row = self._rows()[14]+ self.assertEqual((row["verdict"], row["new_label"]), ("review", "T-POWERS"))++ def test_a_generic_label_carries_no_agency(self):+ self.assertEqual(agency_from_label("官方网站", "www.prestige-av.com", set()), "")+ self.assertEqual(agency_from_label("Prestige", "x.jp", {"Prestige"}), "")+ # 标签就是域名本身时它是采集兜底,不是谁的名字。+ self.assertEqual(agency_from_label("tma.co.jp", "tma.co.jp", set()), "")++ def test_applying_moves_the_agency_into_entity_metadata(self):+ done = apply_rows(self.con, collect(self.con), STAMP)+ self.assertEqual(done["改了标签"], 2)+ self.assertEqual(done["其中归位成 social"], 1)+ agency = json.loads(self.con.execute(+ "SELECT metadata_json FROM entity WHERE id=10").fetchone()[0])["agency"]+ self.assertEqual(agency["name"], "T-POWERS")+ # 女优会移籍,没有时间戳就分不清哪一份更新。+ self.assertEqual(agency["checked_at"], STAMP)+ self.assertIn("minnano-av", agency["source"])++ def test_applying_rewrites_the_label_and_the_kind_in_place(self):+ apply_rows(self.con, collect(self.con), STAMP)+ self.assertEqual(+ self.con.execute("SELECT label FROM entity_link WHERE entity_id=10")+ .fetchone()[0], "Prestige")+ self.assertEqual(+ self.con.execute("SELECT link_kind FROM entity_link WHERE entity_id=15")+ .fetchone()[0], "social")++ def test_applying_leaves_the_rows_it_could_not_verify_untouched(self):+ apply_rows(self.con, collect(self.con), STAMP)+ for entity_id in (11, 14):+ self.assertEqual(+ self.con.execute("SELECT label,link_kind FROM entity_link"+ " WHERE entity_id=?", (entity_id,)).fetchone(),+ ("T-POWERS", "official"))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_performer_link_harvest.py b/tests/test_performer_link_harvest.pyindex 899c0a688..9630ed829 100644--- a/tests/test_performer_link_harvest.py+++ b/tests/test_performer_link_harvest.py@@ -67,7 +67,7 @@ class ParseTests(unittest.TestCase):("official", "官方网站"))def test_an_agency_page_is_labelled_with_the_agency_name(self):- """用户要的就是厂商链接,而事务所名资料表已经给了。+ """域名归属未知时才退回事务所名:那时它至少没有和已知事实矛盾。退回通用的「官方网站」等于把取到的信息扔掉——资料页上一排链接全叫同一个名字,点之前看不出哪个是事务所。@@ -76,6 +76,36 @@ class ParseTests(unittest.TestCase):self.module.classify("http://www.t-powers.co.jp/official/talent/x", "T-POWERS"),("official", "T-POWERS"))+ def test_the_label_follows_the_domain_not_the_agency_field(self):+ """白石亚子的「所属事務所」是 T-POWERS,「公式サイト」却是 Prestige 的宣传页。++ 这是资料表里两行不同的事实。把事务所名贴到这条链接上,一个控件就同时替两家公司+ 说话:文字写着 T-POWERS,图标和落点都是 Prestige。+ """+ # 归属表的键和 `host_of` 用同一条归一规则,都不带 `www.`。+ owners = {"prestige-av.com": "Prestige"}+ self.assertEqual(+ self.module.classify("http://www.prestige-av.com/special/shiraishi_ako.php",+ "T-POWERS", owners.get),+ ("official", "Prestige"))+ # 域名确实归事务所时,两条规则给出同一个答案。+ self.assertEqual(+ self.module.classify("http://www.t-powers.co.jp/official/talent/x", "T-POWERS",+ {"t-powers.co.jp": "T-POWERS"}.get),+ ("official", "T-POWERS"))++ def test_a_personal_platform_account_is_not_an_agency_page(self):+ """Facebook 和 Linktree 此前不在平台表里,走了 official 分支、被贴上事务所名。"""+ self.assertEqual(+ self.module.classify("https://www.facebook.com/miho.tanaka.334491", "T-POWERS"),+ ("social", "Facebook @miho.tanaka.334491"))+ self.assertEqual(+ self.module.classify("http://linktr.ee/sawa_sasaki", "GG"),+ ("social", "Linktree @sawa_sasaki"))+ self.assertEqual(+ self.module.classify("http://kawakami-yuu.livedoor.biz/", "Ys Promotion"),+ ("social", "博客"))+def test_a_blog_is_social_not_an_official_site(self):"""`blog.livedoor.jp/kaede_fuyutuki/` 是本人的博客,不是公式站。diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex 4fe0fc42d..61a787577 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -3889,6 +3889,16 @@ class WebUiSourceTests(unittest.TestCase):self.assertPageContains("(d.display_aliases||[]).length")self.assertPageLacks("(d.aliases||[]).length?'别名")+ def test_the_agency_reads_as_identity_not_as_a_link(self):+ """事务所此前寄居在官方链接的标签里,那个控件于是同时替两家公司说话。++ 它没有网址,做不成链接;它是这个人签在谁名下,和别名、作品数是同一类事实。+ """+ self.assertCode("const agencyName=(d.metadata||{}).agency?.name||'';")+ self.assertPageContains("agencyName?` · 事务所 ${esc(agencyName)}`:''")+ # 链接标签写的是域名归谁,不是事务所名。+ self.assertPageContains("标签写的是这个域名归谁")+def test_entity_name_picker_offers_only_this_entity_existing_names(self):# 候选取的是身份契约 `aliases`(完整),不是收窄过的展示别名:罗马字也是# 这个人真的用过的写法,用户想拿它当统称就该能选。diff --git a/web/app.js b/web/app.jsindex 944cf9412..a4c57c7b1 100644--- a/web/app.js+++ b/web/app.js@@ -5805,8 +5805,8 @@ async function openEntity(kind,name,push=true){/* 厂牌页的官网链接不放图标,直接给网址。这一页的头像就是厂牌 logo,旁边再放一枚同品牌的小图标只是把同一个东西说两遍;- 而域名本身就是名字,比图标说得更清楚。女优页不一样:那里的头像是人,事务所- 图标不构成重复,标签也是事务所名而非域名。 */+ 而域名本身就是名字,比图标说得更清楚。女优页不一样:那里的头像是人,站点图标+ 不构成重复,标签写的是这个域名归谁——图标、文字和落点因此说的是同一件事。 */if(kind==='studio')return `<a class="urllink" href="${esc(x.url)}" target="_blank" rel="noreferrer" title="${esc(x.label)}"><span class="entitylinklabel">${esc(linkHost(x.url)||x.label)}</span></a>`;return `<a href="${esc(x.url)}" target="_blank" rel="noreferrer" title="${esc(x.label)}"><span class="entitylinkicon">${icon('globe')}<img class="entityfavicon" src="${esc(linkMarkUrl(x))}" alt="" loading="lazy" referrerpolicy="no-referrer" data-drop="self"></span><span class="entitylinklabel">${esc(x.label)}</span></a>`;@@ -5825,6 +5825,10 @@ async function openEntity(kind,name,push=true){标题上是他的偏好,账本里没有能推出答案的字段。菜单只列这条实体名下已有的写法:换统称是换显示的那一个,不是改名——改名要有来源和证据,不该由一次点击完成。只有一个写法时不出这个控件,那里没有可选的东西。 */+ /* 事务所是身份信息,不是链接。它此前寄居在官方链接的标签里,于是那个控件同时替+ 两家公司说话——文字是事务所名,图标和落点却是片商的站。名字归名字、链接归链接,+ 它就跟着别名和作品数排在同一行。 */+ const agencyName=(d.metadata||{}).agency?.name||'';const nameChoices=[d.canonical_name,...(d.aliases||[])].filter((option,index,all)=>option&&all.indexOf(option)===index);const namePick=nameChoices.length>1?`<div class="namepick" data-namepick>@@ -5838,7 +5842,8 @@ async function openEntity(kind,name,push=true){$('#index').dataset.entityKind=kind;$('#index').dataset.entityName=name;$('#index').innerHTML=`<div class="entityhero"><div class="entityportrait ${kind==='performer'||kind==='creator'?'':'square'}">${image}<span>${esc(name.slice(0,1))}</span></div><div><div class="entitytitle"><h2>${esc(d.canonical_name)}</h2>${namePick}</div>- <div class="alias">${(d.display_aliases||[]).length?`${d.display_aliases.map(esc).join(' / ')} · `:''}<b>${d.asset_count.toLocaleString()}</b> 个视频</div>+ <div class="alias">${(d.display_aliases||[]).length?`${d.display_aliases.map(esc).join(' / ')} · `:''}<b>${d.asset_count.toLocaleString()}</b> 个视频${+ agencyName?` · 事务所 ${esc(agencyName)}`:''}</div>${links?`<div class="entitylinks">${links}</div>`:''}</div></div>${related?`<div class="entitymeta"><section aria-label="同台艺人"><div class="relatedpeople">${related}</div></section></div>`:''}${(tags||mediaToggle)?`<section class="entitytagbar" aria-label="媒体与标签"><div class="entitytags">${mediaToggle}${tags}</div></section>`:''}