Peach: Local-first video metadata scraper and media manager.
perf(web): 事务所与片商资料页的图集、样张集和代表作钉住连接顺序
longmeidaof6e6b5445653
diff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex cf15a80b5..93b5cfdd1 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -47,6 +47,11 @@ def scope_predicate(kind: str, column: str, subject: str = "?") -> str:片商的范围是它自己加上 `label_maker` 往下的每一级(ADR-0051 修订):旗下 label出的片都算在它名下,和事务所算成员的片是同一个道理。`UNION` 去重,账本里万一有环也会停下来。++ 这两种范围是 `IN` 子查询,规划器估不出它有几行。和 `asset` 上的 `medium` 过滤+ 同句时,真实账本的统计会让它从 `asset` 那侧按 `medium` 起步,再逐行回查+ `asset_entity`,一家事务所的图集要扫五万张图。所以这类查询用 `CROSS JOIN` 把+ `asset_entity` 钉在外层,从范围出发走 `entity_id` 索引;`=` 那一种本来就这样走。"""if kind == "agency":return (f"{column} IN (SELECT member_id FROM entity_membership"@@ -171,7 +176,7 @@ def q_entity(contract: WebContract, args):scope = scope_predicate(kind, "ae.entity_id")count, rep = c.execute("SELECT count(DISTINCT ae.asset_id),"- "(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "+ "(SELECT a2.id FROM asset_entity ae2 CROSS JOIN asset a2 ON a2.id=ae2.asset_id "" WHERE " + scope_predicate(kind, "ae2.entity_id") +" AND a2.medium='video' AND a2.snapshot_path IS NOT NULL " +(" AND " + solo_performer_clause("a2.id", "ae2.entity_id") if kind == "performer" else "") +@@ -354,7 +359,7 @@ def entity_code_sets(contract: WebContract, c, kind: str, entity_id: int) -> lisworks: dict[str, dict] = {}for row in c.execute("SELECT a.code,a.catalog_title,a.original_title,a.release_date "- "FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "+ "FROM asset_entity ae CROSS JOIN asset a ON a.id=ae.asset_id ""WHERE " + scope_predicate(kind, "ae.entity_id") + " AND " + VISIBLE_CATALOG_ASSET +" AND a.code IS NOT NULL AND a.code<>'' ORDER BY a.id", (entity_id,)):key = sample_images.code_key(row["code"])@@ -393,6 +398,11 @@ def q_entity_photos(contract: WebContract, args):row = resolve_entity(c, kind, name)if not row:return {"error": "not found"}+ # 图集、总数和分页数的是同一批图,`total` 才对得上翻到底的张数。+ scoped = ("FROM asset_entity ae CROSS JOIN asset a ON a.id=ae.asset_id "+ "WHERE " + scope_predicate(kind, "ae.entity_id") ++ " AND a.medium='image' AND a.name IS NOT NULL "+ "AND (a.disposal IS NULL OR a.disposal<>'trash') ")sets = [{"id": item["id"],"kind": "dir",@@ -403,29 +413,14 @@ def q_entity_photos(contract: WebContract, args):"cost": COST.get(item["location"], "metered"),} for item in c.execute(f"SELECT {PHOTO_DIR} dir,min(a.id) id,count(*) n,sum(a.size) bytes,a.location "- "FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "- "WHERE " + scope_predicate(kind, "ae.entity_id") +- " AND a.medium='image' AND a.name IS NOT NULL "- "AND (a.disposal IS NULL OR a.disposal<>'trash') "- f"GROUP BY {PHOTO_DIR},a.location ORDER BY n DESC,dir",+ + scoped + f"GROUP BY {PHOTO_DIR},a.location ORDER BY n DESC,dir",(row["id"],),)]- total = c.execute(- "SELECT count(DISTINCT a.id) "- "FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "- "WHERE " + scope_predicate(kind, "ae.entity_id") +- " AND a.medium='image' AND a.name IS NOT NULL "- "AND (a.disposal IS NULL OR a.disposal<>'trash')",- (row["id"],),- ).fetchone()[0]+ total = c.execute("SELECT count(DISTINCT a.id) " + scoped, (row["id"],)).fetchone()[0]items = [{"id": item["id"], "name": item["name"], "size": item["size"] or 0,"location": item["location"]}for item in c.execute(- f"SELECT a.id,a.name,a.size,a.location,{PHOTO_DIR} dir "- "FROM asset_entity ae JOIN asset a ON a.id=ae.asset_id "- "WHERE " + scope_predicate(kind, "ae.entity_id") +- " AND a.medium='image' AND a.name IS NOT NULL "- "AND (a.disposal IS NULL OR a.disposal<>'trash') "+ f"SELECT a.id,a.name,a.size,a.location,{PHOTO_DIR} dir " + scoped +f"GROUP BY a.id,a.name,a.size,a.location,{PHOTO_DIR} "f"ORDER BY {order} LIMIT ? OFFSET ?",(row["id"], limit, offset),diff --git a/tests/test_agency_entity.py b/tests/test_agency_entity.pyindex aa5ce7f9f..17ecff950 100644--- a/tests/test_agency_entity.py+++ b/tests/test_agency_entity.py@@ -194,11 +194,35 @@ class AgencyLedgerTests(unittest.TestCase):self.logos = root / "logos"; self.logos.mkdir()self.avatars = root / "avatars"; self.avatars.mkdir()self.contract = rm_web.WebContract(- self.db, avatar_root=self.avatars, logo_root=self.logos)+ self.db, avatar_root=self.avatars, logo_root=self.logos, cover_root=root / "covers")def page(self, kind, name):return rm_web.q_entity(self.contract, {"kind": kind, "name": name})+ def photos(self, name):+ return rm_web.q_entity_photos(self.contract, {"kind": "agency", "name": name})++ def add_pictures(self, rows):+ """(id, 路径, 挂在哪几位名下, disposal)。"""+ for asset_id, path, owners, disposal in rows:+ self.con.execute(+ "INSERT INTO asset(id,location,path,name,medium,size,first_seen,disposal)"+ " VALUES(?,'local',?,?,'image',10,'2026-01-01',?)",+ (asset_id, path, path.rsplit("\\", 1)[-1], disposal))+ self.con.executemany(+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence)"+ " VALUES(?,?,'performer','test',1.0)", [(asset_id, owner) for owner in owners])+ self.con.commit()++ def add_samples(self, codes):+ """作品 id → 番号,每个番号配一张官方样张。"""+ for asset_id, code in codes.items():+ self.con.execute("UPDATE asset SET code=? WHERE id=?", (code, asset_id))+ self.con.execute(+ "INSERT INTO code_sample_image(code,position,url,site,source,fetched_at)"+ " VALUES(?,1,'https://pics.dmm.co.jp/x.jpg','dmm','test',?)", (code, STAMP))+ self.con.commit()+def test_every_performer_with_an_agency_gets_exactly_one_membership(self):self.assertEqual(self.con.execute("SELECT count(*) FROM entity_membership").fetchone()[0], 3)@@ -217,6 +241,37 @@ class AgencyLedgerTests(unittest.TestCase):self.assertIn("足交", [tag["k"] for tag inself.page("agency", "Capsule Agency")["tags"]])+ def test_the_agency_representative_is_picked_from_its_members_works(self):+ """ACT 那位的片更大,但不是这家的。"""+ self.con.executemany("UPDATE asset SET snapshot_path='s.jpg',size=? WHERE id=?",+ [(200, 1), (300, 2), (900, 3)])+ self.con.commit()+ self.assertEqual(self.page("agency", "Capsule Agency")["representative_asset_id"], 2)++ def test_the_agency_photos_and_sample_sets_are_those_of_its_members(self):+ """事务所自己不挂图:图集、总数、分页和番号样张集都从成员名下取。++ ACT 那位的图和片不算,回收站里的图也不算。+ """+ self.add_pictures([+ (21, r"R:\Media\summer\01.jpg", [11], None),+ (22, r"R:\Media\summer\02.jpg", [12], None),+ (23, r"R:\Media\winter\01.jpg", [12], None),+ (24, r"R:\Media\summer\03.jpg", [11], "trash"),+ (25, r"R:\Media\act\01.jpg", [13], None)])+ self.add_samples({1: "SSIS-057", 2: "SSIS-058", 3: "IPX-001"})+ photos = self.photos("Capsule Agency")+ self.assertEqual([(item["kind"], item["id"], item["n"]) for item in photos["sets"]],+ [("code", "code:SSIS-057", 1), ("code", "code:SSIS-058", 1),+ ("dir", 21, 2), ("dir", 23, 1)])+ self.assertEqual((photos["total"], photos["sample_total"]), (3, 2))+ self.assertEqual([item["id"] for item in photos["items"]], [21, 22, 23])++ def test_a_picture_of_two_members_is_counted_and_listed_once(self):+ self.add_pictures([(21, r"R:\Media\duo\01.jpg", [11, 12], None)])+ photos = self.photos("Capsule Agency")+ self.assertEqual((photos["total"], [item["id"] for item in photos["items"]]), (1, [21]))+def test_a_performer_profile_points_at_her_agency_entity(self):home = self.page("performer", "七泽美亚")["agency"]self.assertEqual(home["canonical_name"], "Capsule Agency")diff --git a/tests/test_label_maker.py b/tests/test_label_maker.pyindex b9d47fe93..ac7b239be 100644--- a/tests/test_label_maker.py+++ b/tests/test_label_maker.py@@ -46,7 +46,8 @@ class LabelMakerTests(unittest.TestCase):]logos = root / "logos"; logos.mkdir()avatars = root / "avatars"; avatars.mkdir()- self.contract = rm_web.WebContract(self.db, avatar_root=avatars, logo_root=logos)+ self.contract = rm_web.WebContract(self.db, avatar_root=avatars, logo_root=logos,+ cover_root=root / "covers")def apply(self, rows=None, *, create_makers=True):planned = plan(self.con, rows or self.rows, create_makers=create_makers)@@ -151,6 +152,40 @@ class LabelMakerTests(unittest.TestCase):self.assertEqual([(label["k"], label["n"]) for label in top["labels"]],[("K M Produce", 2), ("ABC/妄想族", 1)])+ def test_the_maker_representative_can_be_a_labels_work(self):+ """BAZOOKA 那部最大、归 K M Produce;ABC/妄想族 那部更大,但不归它。"""+ self.apply()+ self.con.executemany("UPDATE asset SET snapshot_path='s.jpg',size=? WHERE id=?",+ [(500, 1), (200, 2), (900, 3)])+ self.con.commit()+ page = rm_web.q_entity(self.contract, {"kind": "studio", "name": "K M Produce"})+ self.assertEqual(page["representative_asset_id"], 1)++ def test_the_maker_photos_and_sample_sets_include_its_labels(self):+ """图集、总数、分页和番号样张集都连同旗下 label 一起算,ABC/妄想族 的不算。"""+ self.apply()+ for asset_id, studio in ((21, 5569), (22, 5607), (23, 8248)):+ path = rf"R:\Media\stills\{asset_id}.jpg"+ self.con.execute(+ "INSERT INTO asset(id,location,path,name,medium,size,first_seen)"+ " VALUES(?,'local',?,?,'image',10,'2026-01-01')", (asset_id, path, f"{asset_id}.jpg"))+ self.con.execute(+ "INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence)"+ " VALUES(?,?,'studio','test',1.0)", (asset_id, studio))+ for asset_id, code in ((1, "SSIS-057"), (2, "SSIS-058"), (3, "IPX-001")):+ self.con.execute("UPDATE asset SET code=? WHERE id=?", (code, asset_id))+ self.con.execute(+ "INSERT INTO code_sample_image(code,position,url,site,source,fetched_at)"+ " VALUES(?,1,'https://pics.dmm.co.jp/x.jpg','dmm','test','2026-09-25T00:00:00Z')",+ (code,))+ self.con.commit()+ photos = rm_web.q_entity_photos(self.contract, {"kind": "studio", "name": "K M Produce"})+ self.assertEqual([(item["kind"], item["id"], item["n"]) for item in photos["sets"]],+ [("code", "code:SSIS-057", 1), ("code", "code:SSIS-058", 1),+ ("dir", 21, 2)])+ self.assertEqual((photos["total"], photos["sample_total"]), (2, 2))+ self.assertEqual([item["id"] for item in photos["items"]], [21, 22])+def test_the_index_lists_makers_with_their_totals_and_folds_labels_in(self):"""索引页只列最上层,数的是合计;搜名字时 label 照常搜得到。"""self.apply()