Peach: Local-first video metadata scraper and media manager.
fix(web): 实体别名入口显示完整作品与筛选统计
longmeidaoc831c378529e
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 8b002e8d2..54566939a 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -453,6 +453,8 @@ Python 复用 MIT 许可的 [Ruff](https://docs.astral.sh/ruff/) 0.16.10,版## 厂牌名称身份+作品列表、分页与筛选统计复用 `entities.resolve_entity` 将名称解析为实体 ID,再用 `web_entity.scope_predicate` 获取关系范围;五类资料实体共用此入口,厂牌覆盖旗下各级 label,事务所覆盖成员作品。未取得唯一身份时返回空集合。+`entities.studio_name_key` 与 `studio_identity_ids` 供入库、元数据落地、名称解析和 `merge_studio_name_variants.py` 共用:NFKC、符号写法及唯一登记别名映射到规范身份。官方标题确认的 [ATTACKERS](https://attackers.net/)、[PREMIUM](https://premium-beauty.com/) 日英并写名和 [kawaii*](https://kawaiikawaii.jp/) 星号写法纳入精确映射。名称冲突保留来源原文;括号两侧须各自唯一指向同一实体;`AVOP` 跨厂牌共用,不作为合并证据。复用项目实体合并、字段归属、SQLite 备份和复核 CSV,无新增依赖。## 原位改字diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.pyindex c9551872a..6d2aa55a7 100644--- a/src/peach/web_catalog.py+++ b/src/peach/web_catalog.py@@ -28,7 +28,7 @@ from .catalog_rules import (solo_performer_clause,tag_cat,)-from .entities import normalize_entity_name, upsert_asset_entity+from .entities import normalize_entity_name, resolve_entity, upsert_asset_entityfrom .catalog_versions import foldable_versions, partition_versions, version_labelsfrom .field_owners import parse_ownersfrom .metadata_policy import SOURCE_SPECS@@ -130,16 +130,6 @@ def tag_not_hidden(asset: str, tag: str) -> str:f"AND p.hidden=1 AND p.normalized_tag={tag})")-#: 「这部作品属于某家事务所」的判据:它的出镜者里有这家的现役成员。-#: 归属是人的属性,作品只是顺着人被算进来的——所以这里比的是 `entity_membership`,-#: 不是给作品另存一个事务所字段。多存一份就会漂移,而漂移的那份没人会发现。-AGENCY_ASSET_CLAUSE = (- "EXISTS(SELECT 1 FROM asset_entity ae "- "JOIN entity_membership m ON m.member_id=ae.entity_id "- "JOIN entity agency ON agency.id=m.agency_id "- "WHERE ae.asset_id=a.id AND agency.kind='agency' AND agency.canonical_name=?)"-)-#: 「未归属」是一个真实的集合,不是详情页上的一句说明文字:22509 部视频里 4566 部#: 没有任何署名人。判据和卡片署名同源(`cardIdentity` 取 creator 或 performer),#: 所以卡片上写着「未归属」的每一条,点进这个集合都必须在里面。厂牌和系列不算归属:@@ -197,6 +187,17 @@ def region_facet_rows(rows) -> list[dict]:"label": region_label(row["k"]) or "未判定"} for row in rows]+def _entity_asset_filter(connection, kind: str, name: str) -> tuple[str, list[int]]:+ """名称按资料页身份解析,作品范围包含旗下厂牌或事务所成员。"""+ from .web_entity import scope_predicate++ entity = resolve_entity(connection, kind, name)+ if entity is None:+ return "0", []+ predicate = scope_predicate(kind, "entity_id")+ return f"a.id IN (SELECT asset_id FROM asset_entity WHERE {predicate})", [entity["id"]]++def catalog_filter(contract: WebContract, args):"""视频列表与侧栏使用同一组筛选条件。"""trash = args.get("state") == "trash"@@ -212,32 +213,14 @@ def catalog_filter(contract: WebContract, args):if args.get("loc"):locs = [x for x in args["loc"].split(",") if x]where.append("a.location IN (%s)" % ",".join("?" * len(locs))); par += locs- if args.get("creator"):- where.append(- "a.id IN (SELECT ae.asset_id FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "- "WHERE e.kind='creator' AND e.canonical_name=?)"- ); par.append(args["creator"])- if args.get("performer"):- where.append(- "a.id IN (SELECT ae.asset_id FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "- "WHERE e.kind='performer' AND e.canonical_name=?)"- ); par.append(args["performer"])- # 片商连同旗下每一级 label 出的片(ADR-0051 修订),和资料页上那个合计是同一批。- if args.get("studio"):- where.append(- "a.id IN (SELECT ae.asset_id FROM asset_entity ae WHERE ae.entity_id IN ("- "WITH RECURSIVE down(id) AS (SELECT id FROM entity WHERE kind='studio' AND canonical_name=?"- " UNION SELECT lm.label_id FROM label_maker lm JOIN down ON lm.maker_id=down.id)"- " SELECT id FROM down))"- ); par.append(args["studio"])- if args.get("series"):- where.append(- "a.id IN (SELECT ae.asset_id FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "- "WHERE e.kind='series' AND e.canonical_name=?)"- ); par.append(args["series"])- # 事务所隔一层:作品是它的成员拍的,`asset_entity` 里没有事务所的行。- if args.get("agency"):- where.append(AGENCY_ASSET_CLAUSE); par.append(args["agency"])+ subjects = [(kind, args[kind]) for kind in ("creator", "performer", "studio", "series", "agency")+ if args.get(kind)]+ if subjects:+ with contract.read_connection() as connection:+ for kind, name in subjects:+ clause, values = _entity_asset_filter(connection, kind, name)+ where.append(clause)+ par.extend(values)# 没有署名人的那批也是一类,和「某某的作品」并列,不是一句写在详情页上的说明。if args.get("owner") == "none":where.append(UNOWNED_ASSET_CLAUSE)@@ -1264,18 +1247,9 @@ def q_facets(if (scope_kind not in {"creator", "performer", "studio", "series", "agency"}or not scope_name):raise ValueError("invalid facet scope")- if scope_kind == "agency":- # 事务所的筛选项必须和它的作品列表同源,否则右栏会给出点进去是 0 条的项。- scope += "AND " + AGENCY_ASSET_CLAUSE + " "- scope_params.append(scope_name)- else:- scope += (- "AND EXISTS(SELECT 1 FROM asset_entity scope_ae "- "JOIN entity scope_e ON scope_e.id=scope_ae.entity_id "- "WHERE scope_ae.asset_id=a.id AND scope_e.kind=? "- "AND scope_e.canonical_name=?) "- )- scope_params.extend((scope_kind, scope_name))+ clause, values = _entity_asset_filter(c, scope_kind, scope_name)+ scope += "AND " + clause + " "+ scope_params.extend(values)out = {}out["locations"] = [dict(r) for r in c.execute("SELECT a.location AS k, count(*) AS n, "diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 37f850498..15b306147 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -421,6 +421,69 @@ class WebDataTests(unittest.TestCase):self.assertEqual([row["k"] for row in item["tags"]], ["足交"])self.assertEqual(item["stats"]["duration"], 1)+ def test_studio_spellings_share_videos_pagination_and_facets(self):+ alias = 'CANONICAL STUDIO(カノニカル)'+ with closing(sqlite3.connect(self.db_path)) as connection, connection:+ connection.execute("INSERT INTO entity_alias VALUES(13,?,?,'merge:test',1)",+ (alias, alias.casefold()))+ expected = rm_web.q_items(self.contract, {'studio': 'Canonical Studio', 'sort': 'new'})+ facets = rm_web.q_facets(self.contract, scope_kind='studio', scope_name='Canonical Studio')+ for name in ('CANONICAL STUDIO', alias):+ with self.subTest(name=name):+ items = rm_web.q_items(self.contract, {'studio': name, 'sort': 'new'})+ self.assertEqual(items['total'], 2)+ self.assertEqual([row['id'] for row in items['items']],+ [row['id'] for row in expected['items']])+ first = rm_web.q_items(self.contract, {'studio': name, 'sort': 'new', 'limit': '1'})+ next_page = rm_web.q_items(self.contract, {'studio': name, 'sort': 'new',+ 'limit': '1', 'offset': '1', 'count': '0'})+ self.assertEqual([row['id'] for row in first['items'] + next_page['items']],+ [row['id'] for row in expected['items']])+ self.assertEqual(rm_web.q_facets(self.contract, scope_kind='studio', scope_name=name), facets)++ def test_profile_kinds_share_registered_alias_scopes(self):+ with closing(sqlite3.connect(self.db_path)) as connection, connection:+ connection.executemany("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) "+ "VALUES(?,?,?,?, 't','t')", [(14,'series','Series','series'),(15,'agency','Agency','agency')])+ connection.execute("INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) VALUES(2,14,'series','test',1)")+ connection.execute("INSERT INTO entity_membership(member_id,agency_id,source,checked_at) "+ "VALUES(11,15,'test','t')")+ connection.executemany("INSERT INTO entity_alias VALUES(?,?,?,'test',1)",+ [(11,'Performer Alias','performer alias'),(12,'Creator Alias','creator alias'),+ (14,'Series Alias','series alias'),(15,'Agency Alias','agency alias')])+ for kind, canonical, alias in [('performer','Canonical Alice','Performer Alias'),+ ('creator','Canonical Creator','Creator Alias'),+ ('series','Series','Series Alias'), ('agency','Agency','Agency Alias')]:+ with self.subTest(kind=kind):+ actual = rm_web.q_items(self.contract, {kind: alias})+ expected = rm_web.q_items(self.contract, {kind: canonical})+ self.assertGreater(actual['total'], 0)+ self.assertEqual([row['id'] for row in actual['items']], [row['id'] for row in expected['items']])+ self.assertEqual(rm_web.q_facets(self.contract, scope_kind=kind, scope_name=alias),+ rm_web.q_facets(self.contract, scope_kind=kind, scope_name=canonical))++ def test_unknown_or_ambiguous_studio_scopes_have_no_videos(self):+ with closing(sqlite3.connect(self.db_path)) as connection, connection:+ connection.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) "+ "VALUES(14,'studio','Other','other','t','t')")+ connection.executemany("INSERT INTO entity_alias VALUES(?,'Shared','shared','test',1)", [(13,),(14,)])+ for name in ('Missing', 'Shared'):+ self.assertEqual(rm_web.q_items(self.contract, {'studio': name})['total'], 0)+ self.assertEqual(rm_web.q_facets(self.contract, scope_kind='studio', scope_name=name)['locations'], [])++ def test_studio_facets_include_descendant_label_videos(self):+ with closing(sqlite3.connect(self.db_path)) as connection, connection:+ connection.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) "+ "VALUES(14,'studio','Label','label','t','t')")+ connection.execute('DELETE FROM asset_entity WHERE asset_id=2 AND entity_id=13')+ connection.execute("INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) VALUES(2,14,'studio','test',1)")+ connection.execute("INSERT INTO label_maker(label_id,maker_id,source,checked_at) "+ "VALUES(14,13,'test','t')")+ videos = rm_web.q_items(self.contract, {'studio': 'Canonical Studio'})+ facets = rm_web.q_facets(self.contract, scope_kind='studio', scope_name='Canonical Studio')+ self.assertEqual(videos['total'], 2)+ self.assertEqual(sum(row['n'] for row in facets['locations']), 2)+def test_facets_and_tops_narrow_to_the_state_the_page_is_showing(self):"""「已标记」页的顶部三层和筛选面板曾走全库口径。