Peach: Local-first video metadata scraper and media manager.
feat(catalog): 厂牌加一层 label 归属:详情与资料页显示所属厂商,label 不当厂商处理
longmeidaod2fd86db263b
diff --git a/docs/adr/0049-labels-belong-to-a-maker-without-becoming-one.md b/docs/adr/0049-labels-belong-to-a-maker-without-becoming-one.mdnew file mode 100644index 000000000..42e9bf302--- /dev/null+++ b/docs/adr/0049-labels-belong-to-a-maker-without-becoming-one.md@@ -0,0 +1,39 @@+# ADR-0049:label 归属厂商,但不当厂商处理++- 状态:Accepted+- 日期:2026-09-23++## 背景++账本里的厂牌只有一层 `kind='studio'`。同一家母公司旗下的 label 在账本里有三种记法:++- 各自独立成一条厂牌,彼此没有关联(`BAZOOKA` 与 `K M Produce`);+- 通过别名并进母公司(`PRESTIGE PREMIUM` 挂在 `Prestige` 名下);+- 把「label/母公司」写成一个名字(`ABC/妄想族`)。++这样一来,按母公司查看全部作品做不到。合并脚本还会把 label 当成母公司的另一种写法吞掉,而合并不可逆。++用户 2026-09-23 的要求是「加一层 label 在详情里展示,但是不作为厂商处理」。++## 决策++新增表 `label_maker(label_id, maker_id, source, confidence, checked_at)`,迁移为 `0035`。++- **label 仍是厂牌**:作品照旧挂在 label 自己身上,不改名,不合并,也不改写作品上的厂牌字段。这张表只多记一件事:label 归哪家厂商。+- **只有一层**:label 不能再挂 label,厂商自己也不能是别家的 label。装入脚本遇到这两种情况会拒收。+- **主键在 label 一侧**:一个 label 只有一家现役厂商。label 转手时覆盖原来那一行,不新增一行;做法与 `entity_membership` 相同。+- **厂商可以没有作品**:`妄想族` 的作品全挂在旗下 label 上,它自己是一条没有作品的 `studio` 实体,由装入脚本加 `--create-makers` 新建。+- **合并时关系跟着走**:`merge_entity` 两个方向都迁移。label 并入自己的厂商时,那一行会变成自己指向自己,直接删掉。+- **页面上只是链接**:+ - 作品详情里,厂牌一组旁边多一组「厂商」;+ - label 的资料页,在归属那一格链到厂商;+ - 厂商的资料页,另起一行「旗下」列出 label。++ 作品数各算各的,厂商页不把 label 的作品算进来。++数据来源是各家母公司的官方名录:KMP 的 `km-produce.com/label`、Prestige 的 `prestige-av.com`、妄想族的 `mousouzoku-av.com`。复核 CSV 的列为 `label,maker,evidence`,由 `scripts/install_label_makers.py` 装入。脚本默认 dry-run,`--apply` 必须同时给 `--backup`。++## 不做的事++- 不按厂商聚合筛选作品。需要时另开一条查询,把 label 并起来,不去改动归属本身。+- 不把已经作为别名并进母公司的 label(如 `PRESTIGE PREMIUM`)拆出来。拆分需要逐部作品判断归属,属于另一项任务。diff --git a/migrations/0035_label_maker.sql b/migrations/0035_label_maker.sqlnew file mode 100644index 000000000..73b04a781--- /dev/null+++ b/migrations/0035_label_maker.sql@@ -0,0 +1,24 @@+--+-- label 属于哪家厂商(ADR-0049)。+--+-- 为什么这么改:账本里厂牌只有一层。同一个母公司旗下的 label 有三种记法:独立成一条+-- 厂牌(BAZOOKA 与 K M Produce 互不相识)、被别名并进母公司(PRESTIGE PREMIUM 挂在+-- Prestige 名下)、「label/母公司」写成一串(`ABC/妄想族`)。按母公司看全部作品做不到,+-- 合并脚本还会把 label 当成母公司的另一种写法吞掉,而合并不可逆。+--+-- label 仍是 `kind='studio'` 的实体,作品照旧挂在它自己身上;这张表只多记一件事:它归+-- 哪家厂商。label 不当成厂商处理:不改名、不合并、不改写作品上的厂牌。+--+-- 主键在 label 一侧,一个 label 只有一家现役母公司,转手是覆盖,不是再加一行;做法同+-- `entity_membership`。+CREATE TABLE label_maker(+ label_id INTEGER PRIMARY KEY REFERENCES entity(id) ON DELETE CASCADE,+ maker_id INTEGER NOT NULL REFERENCES entity(id) ON DELETE CASCADE,+ source TEXT NOT NULL,+ confidence REAL NOT NULL DEFAULT 1.0,+ checked_at TEXT NOT NULL,+ CHECK(label_id<>maker_id)+);++-- 厂商资料页要列「旗下有哪些 label」,没有索引就是全表扫。+CREATE INDEX idx_label_maker_maker ON label_maker(maker_id);diff --git a/scripts/install_label_makers.py b/scripts/install_label_makers.pynew file mode 100644index 000000000..5cef6d1c5--- /dev/null+++ b/scripts/install_label_makers.py@@ -0,0 +1,162 @@+"""把复核过的「label 属于哪家厂商」装进 ledger 的 `label_maker`(ADR-0049)。++输入是复核 CSV,列为 `label,maker,evidence`。两边都按 `kind='studio'` 的规范名或唯一别名+解析;厂商在账本里还没有实体(妄想族就是:作品全挂在旗下 label 上)时,加+`--create-makers` 才新建,否则那一行跳过并写明原因。++只有一层:label 不能再挂 label,厂商自己也不能是别家的 label。多一层资料页就要递归+展开,而这批数据里没有哪一家真的需要。++默认 dry-run,只打印计划。`--apply` 必须同时给 `--backup`:这是真实账本写入。重跑是+幂等的,已是同一家的跳过;label 转手时覆盖成新厂商,计划里写成 update。+"""+from __future__ import annotations++import argparse+import sqlite3+import sys+from datetime import datetime, timezone+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))++from peach.entities import normalize_entity_name, resolve_entity # noqa: E402+from peach.review_csv import read_rows # noqa: E402+from peach.scripting import ( # noqa: E402+ BACKUP_REQUIRED,+ add_ledger_write_args,+ open_for_write,+ verify_after_write,+)+++def plan(connection: sqlite3.Connection, rows: list[dict], *,+ create_makers: bool) -> list[dict]:+ """逐行给出动作与原因;不合法的行照样列出,动作写成 skip。"""+ planned: list[dict] = []+ makers_in_plan = {normalize_entity_name(str(row.get("maker") or "").strip())+ for row in rows}+ labels_in_plan = {normalize_entity_name(str(row.get("label") or "").strip())+ for row in rows}+ for row in rows:+ label_name = str(row.get("label") or "").strip()+ maker_name = str(row.get("maker") or "").strip()+ item = {"label": label_name, "maker": maker_name, "label_id": None,+ "maker_id": None, "action": "skip", "reason": "",+ "evidence": str(row.get("evidence") or "").strip()}+ planned.append(item)+ if not label_name or not maker_name:+ item["reason"] = "label 或 maker 为空"+ continue+ if not item["evidence"]:+ item["reason"] = "没有证据"+ continue+ label = resolve_entity(connection, "studio", label_name)+ if label is None:+ item["reason"] = f"厂牌「{label_name}」在账本里找不到或别名撞名"+ continue+ item["label_id"] = int(label["id"])+ maker = resolve_entity(connection, "studio", maker_name)+ if maker is None and not create_makers:+ item["reason"] = f"厂商「{maker_name}」在账本里没有实体;确认后加 --create-makers"+ continue+ item["maker_id"] = int(maker["id"]) if maker is not None else None+ if item["maker_id"] == item["label_id"]:+ item["reason"] = "label 与厂商是同一条实体"+ continue+ if normalize_entity_name(label_name) in makers_in_plan or connection.execute(+ "SELECT 1 FROM label_maker WHERE maker_id=?", (item["label_id"],)).fetchone():+ item["reason"] = "这条 label 自己是别家的厂商;只支持一层"+ continue+ if normalize_entity_name(maker_name) in labels_in_plan or (+ item["maker_id"] is not None and connection.execute(+ "SELECT 1 FROM label_maker WHERE label_id=?", (item["maker_id"],)).fetchone()):+ item["reason"] = "厂商自己是别家的 label;只支持一层"+ continue+ current = connection.execute(+ "SELECT maker_id FROM label_maker WHERE label_id=?", (item["label_id"],)).fetchone()+ if current and item["maker_id"] is not None and int(current[0]) == item["maker_id"]:+ item["reason"] = "已是这家,跳过"+ elif current:+ item.update(action="update", reason=f"转手:厂商实体 {current[0]} → {maker_name}")+ else:+ item.update(action="insert",+ reason="新建厂商实体" if item["maker_id"] is None else "")+ return planned+++def ensure_maker(connection: sqlite3.Connection, name: str, stamp: str) -> int:+ """厂商实体不存在时按规范名新建一条 `kind='studio'`,已存在则返回它。"""+ found = resolve_entity(connection, "studio", name)+ if found is not None:+ return int(found["id"])+ connection.execute(+ "INSERT INTO entity(kind,canonical_name,normalized_name,metadata_json,created_at,updated_at) "+ "VALUES('studio',?,?,'{}',?,?)", (name, normalize_entity_name(name), stamp, stamp))+ return int(connection.execute("SELECT last_insert_rowid()").fetchone()[0])+++def install(connection: sqlite3.Connection, planned: list[dict], *, source: str) -> int:+ stamp = datetime.now(timezone.utc).isoformat(timespec="seconds")+ written = 0+ for item in planned:+ if item["action"] not in {"insert", "update"}:+ continue+ maker_id = item["maker_id"] or ensure_maker(connection, item["maker"], stamp)+ connection.execute(+ "INSERT INTO label_maker(label_id,maker_id,source,confidence,checked_at) "+ "VALUES(?,?,?,1.0,?) ON CONFLICT(label_id) DO UPDATE SET "+ "maker_id=excluded.maker_id,source=excluded.source,"+ "confidence=excluded.confidence,checked_at=excluded.checked_at",+ (item["label_id"], maker_id, f"review:{source}", stamp))+ written += 1+ return written+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])+ parser.add_argument("--input", type=Path, required=True, help="复核 CSV:label,maker,evidence")+ parser.add_argument("--create-makers", action="store_true",+ help="厂商在账本里没有实体时新建")+ return add_ledger_write_args(parser)+++def main(argv: list[str] | None = None) -> int:+ args = build_parser().parse_args(argv)+ if args.apply and not args.backup:+ print(f"[stop] {BACKUP_REQUIRED}")+ return 2+ connection = open_for_write(args)+ if args.apply:+ print(f"已备份:{args.backup}")+ connection.execute("PRAGMA foreign_keys=ON")+ rows = read_rows(args.input)+ try:+ before = connection.execute("SELECT count(*) FROM label_maker").fetchone()[0]+ planned = plan(connection, rows, create_makers=args.create_makers)+ for item in planned:+ mark = {"insert": "+", "update": "~"}.get(item["action"], " ")+ print(f" {mark} {item['label'][:24]:<24} → {item['maker'][:14]:<14} {item['reason']}")+ changes = [item for item in planned if item["action"] != "skip"]+ print({"输入": len(rows), "将写入": len(changes), "跳过": len(planned) - len(changes),+ "写入前 label_maker": before})+ if not args.apply:+ print("dry-run;确认无误后加 --apply --backup <路径>")+ return 0+ with connection:+ written = install(connection, planned, source=args.input.name)+ after = connection.execute("SELECT count(*) FROM label_maker").fetchone()[0]+ integrity, orphans = verify_after_write(connection)+ inserted = sum(item["action"] == "insert" for item in planned)+ print({"实际写入": written, "写入后 label_maker": after, "差值": after - before,+ "integrity_check": integrity, "foreign_key_check": orphans})+ if after - before != inserted or integrity != "ok" or orphans:+ print("[warn] 前后差值、完整性或外键与预期不符,请人工核对")+ return 1+ finally:+ connection.close()+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 1a409c34a..8b2c0cb77 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -90,7 +90,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_link_rediscovery.py", "test_link_label_owner.py","test_link_repair.py","test_resource_identification.py",- "test_agency_entity.py"),+ "test_agency_entity.py", "test_label_maker.py"),"tooling": ("test_scripts.py", "test_trash_junk.py", "test_auth.py", "test_access.py", "test_cli.py", "test_script_policy.py","test_scan.py", "test_push_discovery.py", "test_media_probe.py", "test_subtitles.py", "test_onboarding.py", "test_configuration_sources.py", "test_folder_picker.py", "test_ledger_backups.py", "test_clear_camera_filename_codes.py","test_agent_worktree.py", "test_test_evidence.py", "test_dependency_policy.py",@@ -119,7 +119,8 @@ SCOPES: dict[str, tuple[str, ...]] = {"web": ("test_frontend_build.py", "test_web_ui.py", "test_web_js.py", "test_web_e2e.py","test_legacy_shell_routes.py","test_web_perf.py", "test_copy_final_state.py",- "test_agency_entity.py", "test_dependency_policy.py", "test_desktop_settings.py",+ "test_agency_entity.py", "test_label_maker.py", "test_dependency_policy.py",+ "test_desktop_settings.py","test_fastapi_api.py", "test_follow_assets.py", "test_follow_web.py","test_metadata_library.py", "test_studio_icon_variants.py", "test_web_settings.py"),"core": ("test_access.py", "test_auth.py", "test_config.py", "test_field_owners.py",diff --git a/src/peach/entities.py b/src/peach/entities.pyindex f68a0e6d5..888848e6a 100644--- a/src/peach/entities.py+++ b/src/peach/entities.py@@ -202,7 +202,7 @@ def merge_entity("""stamp = now or datetime.now(timezone.utc).isoformat()moved = {"assets": 0, "aliases": 0, "refs": 0, "links": 0, "terms": 0,- "dropped_refs": 0, "memberships": 0, "members": 0}+ "dropped_refs": 0, "memberships": 0, "members": 0, "labels": 0}# 被并入的名字本身留作别名,否则按旧名搜索会落空。connection.execute(@@ -264,6 +264,19 @@ def merge_entity("UPDATE entity_membership SET agency_id=? WHERE agency_id=?", (target_id, source_id))moved["members"] = connection.execute("SELECT changes()").fetchone()[0]+ # label 的母公司(ADR-0049)同理:label 一侧一条现役,母公司一侧整批改指向。label 并进+ # 自己的母公司时那一条会变成自己指自己,表上的 CHECK 不收,先删掉。+ connection.execute(+ "INSERT OR IGNORE INTO label_maker(label_id,maker_id,source,confidence,checked_at)"+ " SELECT ?,maker_id,source,confidence,checked_at FROM label_maker"+ " WHERE label_id=? AND maker_id<>?", (target_id, source_id, target_id))+ connection.execute("DELETE FROM label_maker WHERE label_id=?", (source_id,))+ connection.execute("DELETE FROM label_maker WHERE label_id=? AND maker_id=?",+ (target_id, source_id))+ connection.execute(+ "UPDATE label_maker SET maker_id=? WHERE maker_id=?", (target_id, source_id))+ moved["labels"] = connection.execute("SELECT changes()").fetchone()[0]+connection.execute("UPDATE entity SET updated_at=? WHERE id=?", (stamp, target_id))connection.execute("DELETE FROM entity WHERE id=?", (source_id,))return moveddiff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.pyindex 559ada84a..0dddeb3ec 100644--- a/src/peach/web_catalog.py+++ b/src/peach/web_catalog.py@@ -709,6 +709,20 @@ def q_parts(contract: WebContract, args):items.append(item)return {"title": code or str(seed["code"]), "count": len(items), "items": items}+def label_makers(contract: WebContract, c, aid) -> dict[int, dict]:+ """这部作品上哪些厂牌是某家厂商旗下的 label(ADR-0049),键是 label 的实体 id。++ 值是要并进那条厂牌引用的 `{"maker": {...}}`:详情里厂牌组旁多一组「厂商」,只是+ 一格链接,作品仍挂在 label 上。+ """+ return {label_id: {"maker": {"id": maker_id, "name": name,+ "has_logo": contract.has_logo(name)}}+ for label_id, maker_id, name in c.execute(+ "SELECT lm.label_id,e.id,e.canonical_name FROM asset_entity ae "+ "JOIN label_maker lm ON lm.label_id=ae.entity_id "+ "JOIN entity e ON e.id=lm.maker_id WHERE ae.asset_id=?", (aid,))}++def q_item(contract: WebContract, aid):"""按 id 直取。⚠️ 没有这个接口时,前端只能用「带筛选条件再查一遍然后 find」的绕法:@@ -760,6 +774,7 @@ def q_item(contract: WebContract, aid):+ tag_not_hidden("ae.asset_id", "e.normalized_name") + ") ""ORDER BY e.kind,e.canonical_name", (aid,),))+ makers = label_makers(contract, c, aid)legacy = [row[0] for row in legacy_rows]official_tag_names = {normalize_entity_name(tag)@@ -817,6 +832,7 @@ def q_item(contract: WebContract, aid):# 后者会从「本来能取到图」退化成永远首字母。for ref in d["entity_refs"]["studio"]:ref["has_logo"] = contract.has_logo(ref["name"])+ ref.update(makers.get(ref["id"], {}))d["has_studio_logo"] = contract.has_logo(d.get("studio"))# 「女优」是番号发行物的行业称谓;creator clip 即使长得像番号也仍是普通内容。attach_jav_display_fields(diff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex d9b928c08..1658a926e 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -69,6 +69,25 @@ def _performer_entries(contract: WebContract, c, d: dict, alias_rows) -> dict:return out+def label_layer(contract: WebContract, c, kind: str, entity_id: int) -> tuple[dict | None, list[dict]]:+ """厂牌资料页的 label 一层(ADR-0049):它归哪家厂商,和它旗下有哪些 label。++ 两边都只是链接,作品、计数和头像各算各的——label 不是厂商的另一种写法。+ """+ if kind != "studio":+ return None, []+ maker = c.execute(+ "SELECT e.id,e.canonical_name name FROM label_maker lm "+ "JOIN entity e ON e.id=lm.maker_id WHERE lm.label_id=?", (entity_id,)).fetchone()+ refs = ([dict(maker)] if maker else []) + [dict(row) for row in c.execute(+ "SELECT e.id,e.canonical_name name FROM label_maker lm "+ "JOIN entity e ON e.id=lm.label_id WHERE lm.maker_id=? "+ "ORDER BY e.canonical_name", (entity_id,))]+ for ref in refs:+ ref["has_logo"] = contract.has_logo(ref["name"])+ return (refs[0], refs[1:]) if maker else (None, refs)++def q_entity(contract: WebContract, args):"""女优、厂牌、事务所等实体的资料页。@@ -204,6 +223,7 @@ def q_entity(contract: WebContract, args):"WHERE m.member_id=?", (d["id"],)).fetchone()if home:d["agency"] = dict(home)+ d["maker"], d["labels"] = label_layer(contract, c, kind, d["id"])# 公司那个大位先取 `/logo`、取不到才退到别的图。没装标识时直接跳过这一环,省掉# 必然 404 的那一跳。标识按名字落盘,厂牌和事务所是同一个仓、同一条取图链。if kind in ("studio", "agency"):diff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex f3dce215c..e26b8aad3 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -66,6 +66,9 @@ CREATE TABLE asset_entity(CREATE TABLE entity_membership(member_id INTEGER PRIMARY KEY,agency_id INTEGER,source TEXT,confidence REAL DEFAULT 1.0,checked_at TEXT);+CREATE TABLE label_maker(+ label_id INTEGER PRIMARY KEY,maker_id INTEGER,source TEXT,+ confidence REAL DEFAULT 1.0,checked_at TEXT);CREATE TABLE watch_queue(profile_id TEXT,asset_id INTEGER,added_at TEXT,source TEXT,PRIMARY KEY(profile_id,asset_id));CREATE TABLE playlist(diff --git a/tests/test_label_maker.py b/tests/test_label_maker.pynew file mode 100644index 000000000..2d190d89b--- /dev/null+++ b/tests/test_label_maker.py@@ -0,0 +1,137 @@+"""label 属于厂商,但不当厂商处理(ADR-0049)。"""+import sqlite3+import tempfile+import unittest+from pathlib import Path++from peach import web_contract as rm_web+from peach.entities import merge_entity+from peach.migrations import upgrade+from scripts.install_label_makers import install, plan++ROOT = Path(__file__).resolve().parents[1]+MIGRATIONS = ROOT / "migrations"+++class LabelMakerTests(unittest.TestCase):+ """KMP 旗下两个 label、妄想族旗下一个,妄想族自己在账本里还没有实体。"""++ def setUp(self):+ self.tmp = tempfile.TemporaryDirectory()+ self.addCleanup(self.tmp.cleanup)+ root = Path(self.tmp.name).resolve()+ self.db = root / "ledger.db"+ upgrade(self.db, MIGRATIONS)+ self.con = sqlite3.connect(self.db)+ self.con.row_factory = sqlite3.Row+ self.addCleanup(self.con.close)+ self.con.executemany(+ "INSERT INTO asset(id,location,path,name,medium,size,first_seen)"+ " VALUES(?,'local',?,?,'video',100,'2026-01-01')",+ [(1, r"R:\Media\a.mp4", "a.mp4"), (2, r"R:\Media\b.mp4", "b.mp4"),+ (3, r"R:\Media\c.mp4", "c.mp4")])+ self.con.executemany(+ "INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at)"+ " VALUES(?,'studio',?,?,'t','t')",+ [(5607, "K M Produce", "k m produce"), (5569, "BAZOOKA", "bazooka"),+ (5638, "S級素人", "s級素人"), (8248, "ABC/妄想族", "abc/妄想族")])+ self.con.executemany(+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence)"+ " VALUES(?,?,'studio','test',1.0)", [(1, 5569), (2, 5607), (3, 8248)])+ self.con.commit()+ self.rows = [+ {"label": "BAZOOKA", "maker": "K M Produce", "evidence": "KMP 名录"},+ {"label": "S級素人", "maker": "K M Produce", "evidence": "KMP 名录"},+ {"label": "ABC/妄想族", "maker": "妄想族", "evidence": "妄想族名录"},+ ]+ logos = root / "logos"; logos.mkdir()+ avatars = root / "avatars"; avatars.mkdir()+ self.contract = rm_web.WebContract(self.db, avatar_root=avatars, logo_root=logos)++ def apply(self, rows=None, *, create_makers=True):+ planned = plan(self.con, rows or self.rows, create_makers=create_makers)+ with self.con:+ install(self.con, planned, source="t.csv")+ return planned++ def maker_of(self, label_id):+ row = self.con.execute(+ "SELECT e.canonical_name FROM label_maker lm JOIN entity e ON e.id=lm.maker_id"+ " WHERE lm.label_id=?", (label_id,)).fetchone()+ return row[0] if row else None++ def test_a_maker_missing_from_the_ledger_is_only_created_when_asked(self):+ planned = plan(self.con, self.rows, create_makers=False)+ self.assertEqual([item["action"] for item in planned], ["insert", "insert", "skip"])+ self.assertIn("--create-makers", planned[2]["reason"])+ self.apply()+ self.assertEqual(self.maker_of(8248), "妄想族")++ def test_rerunning_the_same_table_writes_nothing(self):+ self.apply()+ self.assertEqual({item["action"] for item in self.apply()}, {"skip"})+ self.assertEqual(self.con.execute("SELECT count(*) FROM label_maker").fetchone()[0], 3)++ def test_a_label_changing_hands_is_overwritten_not_added(self):+ self.apply()+ planned = self.apply([{"label": "BAZOOKA", "maker": "妄想族", "evidence": "转手"}])+ self.assertEqual(planned[0]["action"], "update")+ self.assertEqual(self.maker_of(5569), "妄想族")++ def test_only_one_layer_is_accepted(self):+ """label 不能再挂 label,厂商自己也不能是别家的 label。"""+ self.apply()+ planned = plan(self.con, [+ {"label": "K M Produce", "maker": "妄想族", "evidence": "x"},+ {"label": "S級素人", "maker": "BAZOOKA", "evidence": "x"},+ ], create_makers=True)+ self.assertEqual([item["action"] for item in planned], ["skip", "skip"])++ def test_the_label_page_points_at_its_maker_and_keeps_its_own_works(self):+ self.apply()+ page = rm_web.q_entity(self.contract, {"kind": "studio", "name": "BAZOOKA"})+ self.assertEqual(page["maker"]["name"], "K M Produce")+ self.assertEqual(page["asset_count"], 1)+ self.assertEqual(page["labels"], [])++ def test_the_maker_page_lists_its_labels_without_absorbing_their_works(self):+ self.apply()+ page = rm_web.q_entity(self.contract, {"kind": "studio", "name": "K M Produce"})+ self.assertEqual([label["name"] for label in page["labels"]], ["BAZOOKA", "S級素人"])+ self.assertEqual(page["asset_count"], 1)+ self.assertIsNone(page["maker"])++ def test_the_detail_carries_the_maker_beside_the_label(self):+ self.apply()+ studio = rm_web.q_item(self.contract, 3)["entity_refs"]["studio"]+ self.assertEqual([ref["name"] for ref in studio], ["ABC/妄想族"])+ self.assertEqual(studio[0]["maker"]["name"], "妄想族")+ self.assertNotIn("maker", rm_web.q_item(self.contract, 2)["entity_refs"]["studio"][0])++ def test_merging_a_label_carries_its_maker_over(self):+ self.apply()+ self.con.execute(+ "INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at)"+ " VALUES(9000,'studio','BAZOOKA!','bazooka!','t','t')")+ merge_entity(self.con, target_id=9000, source_id=5569, source_name="BAZOOKA", alias_source="test")+ self.assertEqual(self.maker_of(9000), "K M Produce")+ self.assertIsNone(self.maker_of(5569))++ def test_merging_a_maker_moves_its_labels(self):+ self.apply()+ self.con.execute(+ "INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at)"+ " VALUES(9001,'studio','KMP','kmp','t','t')")+ merge_entity(self.con, target_id=9001, source_id=5607, source_name="K M Produce", alias_source="test")+ self.assertEqual({self.maker_of(5569), self.maker_of(5638)}, {"KMP"})++ def test_merging_a_label_into_its_own_maker_drops_the_self_link(self):+ self.apply()+ merge_entity(self.con, target_id=5607, source_id=5569, source_name="BAZOOKA", alias_source="test")+ self.assertIsNone(self.maker_of(5607))+ self.assertEqual(self.con.execute(+ "SELECT count(*) FROM label_maker WHERE label_id=maker_id").fetchone()[0], 0)+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_migrations.py b/tests/test_migrations.pyindex dfe30d545..6c7a89f44 100644--- a/tests/test_migrations.py+++ b/tests/test_migrations.py@@ -25,7 +25,7 @@ class MigrationTests(unittest.TestCase):backup = self.root / "before.db"done = upgrade(self.db, MIGRATIONS, backup)self.assertEqual([m.version for m in done],- ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034"])+ ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035"])self.assertTrue(backup.exists())con = sqlite3.connect(self.db)tables = {row[0] for row in con.execute(@@ -42,7 +42,7 @@ class MigrationTests(unittest.TestCase):"playlist", "playlist_item","asset_tag_preference", "asset_search", "follow_playback","genre_decision", "asset_subtitle", "task_run", "schema_migration"} <= tables)- self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034"])+ self.assertEqual(versions, ["0000", "0001", "0002", "0003", "0004", "0005", "0006", "0007", "0008", "0009", "0010", "0011", "0012", "0013", "0014", "0015", "0016", "0017", "0018", "0019", "0020", "0021", "0022", "0023", "0024", "0025", "0026", "0027", "0028", "0029", "0030", "0031", "0032", "0033", "0034", "0035"])self.assertEqual(upgrade(self.db, MIGRATIONS), [])self.assertEqual(plan(self.db, MIGRATIONS)[1], [])diff --git a/tests/test_studio_name_variant_merge.py b/tests/test_studio_name_variant_merge.pyindex 087e34bcd..69b93b691 100644--- a/tests/test_studio_name_variant_merge.py+++ b/tests/test_studio_name_variant_merge.py@@ -279,6 +279,8 @@ class ApplyTests(unittest.TestCase):" purpose TEXT, source TEXT, created_at TEXT, UNIQUE(entity_id, term));""CREATE TABLE entity_membership(member_id INTEGER PRIMARY KEY,"" agency_id INTEGER, source TEXT, confidence REAL, checked_at TEXT);"+ "CREATE TABLE label_maker(label_id INTEGER PRIMARY KEY,"+ " maker_id INTEGER, source TEXT, confidence REAL, checked_at TEXT);""CREATE TABLE asset(id INTEGER PRIMARY KEY, code TEXT, studio TEXT);""CREATE TABLE asset_entity(asset_id INTEGER, entity_id INTEGER, role TEXT,"" source TEXT, confidence REAL, metadata_json TEXT, first_seen_at TEXT,"diff --git a/tests/test_tag_renames.py b/tests/test_tag_renames.pyindex 0bc5c0030..c5daf2b1d 100644--- a/tests/test_tag_renames.py+++ b/tests/test_tag_renames.py@@ -47,6 +47,9 @@ CREATE TABLE entity_search_term(CREATE TABLE entity_membership(member_id INTEGER PRIMARY KEY, agency_id INTEGER, source TEXT,confidence REAL DEFAULT 1.0, checked_at TEXT);+CREATE TABLE label_maker(+ label_id INTEGER PRIMARY KEY, maker_id INTEGER, source TEXT,+ confidence REAL DEFAULT 1.0, checked_at TEXT);"""diff --git a/web/app.js b/web/app.jsindex 3b6ef5c26..ea167d136 100644--- a/web/app.js+++ b/web/app.js@@ -8219,6 +8219,13 @@ async function openEntity(kind,name,push=true){几个人」这个它唯一独有的读数消失。 */const memberHtml=kind==='agency'?` · <b>${(d.member_count||0).toLocaleString()}</b> 位艺人`:'';+ /* label 一层(ADR-0049):label 页在归属那一格给出所属厂商,厂商页另起一行列旗下+ label。两边都只是去处,作品数各算各的——label 不是厂商的另一种写法。 */+ const studioLink=target=>`<a class="entitylink" href="${esc(entityPath('studio',target))}"+ data-studio-link="${esc(target)}">${esc(target)}</a>`;+ const makerHtml=d.maker?` · ${studioLink(d.maker.name)}`:'';+ const labelsHtml=(d.labels||[]).length+ ?`<div class="alias entitylabels">旗下 ${d.labels.map(label=>studioLink(label.name)).join(' / ')}</div>`:'';const nameChoices=[d.canonical_name,...(d.aliases||[])].filter((option,index,all)=>option&&all.indexOf(option)===index);/* 这枚下拉恒在。只有一个名字时整块不画的话,「她还叫过别的」这件事在页面上就没有@@ -8245,7 +8252,8 @@ async function openEntity(kind,name,push=true){<div class="entityprofile"><div class="entityportraitwrap"><div class="entityportrait ${people?'':'square'}" data-fit-native="${company?'mark':'portrait'}">${image}<span>${esc(name.slice(0,1))}</span></div>${people?'<span data-avatar-picker></span>':''}</div><div class="entityidentity"><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> 个视频${memberHtml}${agencyHtml}</div>+ <div class="alias">${(d.display_aliases||[]).length?`${d.display_aliases.map(esc).join(' / ')} · `:''}<b>${d.asset_count.toLocaleString()}</b> 个视频${memberHtml}${agencyHtml}${makerHtml}</div>+ ${labelsHtml}${links?`<div class="entitylinks">${links}</div>`:''}${entryMarks?`<div class="entrymarks">${entryMarks}</div>`:''}</div></div>${related?`<div class="entityfoot" aria-label="同台艺人"><div class="relatedpeople">${related}</div></div>`:''}</section>@@ -8273,6 +8281,8 @@ async function openEntity(kind,name,push=true){// 站内跳转走同一个 SPA 入口,不让浏览器整页重载。$('#index').querySelectorAll('[data-agency]').forEach(a=>a.onclick=event=>{event.preventDefault();openEntity('agency',a.dataset.agency)});+ $('#index').querySelectorAll('[data-studio-link]').forEach(a=>a.onclick=event=>{+ event.preventDefault();openEntity('studio',a.dataset.studioLink)});/* 同台艺人、标签和窄屏那排外链都是 `overflow-x:auto` 加隐藏滚动条:能滚,但鼠标没有一个够得着的入口——滚轮是竖向的,滚动条不画出来,于是第 8 位之后的人和标签看得见够不着。全站横向行的那套拖动加滚轮映射就是为这个写的,登记上即可。外链那排宽屏下@@ -9365,6 +9375,8 @@ async function openItem(id,push=true,queueContext=null,anchor=null){const studioFallback=studioRef?[]:(it.studio?[{id:null,name:it.studio,has_logo:it.has_studio_logo}]:[]);const studioList=[...(refs.studio||[]),...studioFallback].filter(ref=>fresh(ref.name));+ // 厂牌是某家厂商旗下的 label 时(ADR-0049),厂商另起一组摆在它旁边;作品仍只挂在 label 上。+ const makerList=studioList.map(ref=>ref.maker).filter(maker=>maker&&fresh(maker.name));const creatorList=(refs.creator||[]).filter(ref=>fresh(ref.name));const seriesList=(refs.series||[]).filter(ref=>fresh(ref.name));@@ -9415,7 +9427,8 @@ async function openItem(id,push=true,queueContext=null,anchor=null){(unowned?unownedGroup:idGroup(performerLabel(it),'performer',castList,castOverflow?`<button class="castmore" id="castMore">还有 ${castOverflow} 位</button>`:''))- +idGroup('厂牌','studio',studioList);+ +idGroup('厂牌','studio',studioList)+ +idGroup('厂商','studio',makerList);const identityRows=(primaryIdentity?`<div class="identityprimary">${primaryIdentity}</div>`:'')+idGroup('创作者','creator',creatorList)