Peach: Local-first video metadata scraper and media manager.
perf(api): 顶栏候选池、统计、名册与筛选项按读到的表缓存
longmeidao8f3a1624ae27
diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.pyindex f1b1ab633..48dc429d7 100644--- a/src/peach/web_catalog.py+++ b/src/peach/web_catalog.py@@ -1205,6 +1205,9 @@ def state_clause(state: str) -> str:#: 又能真的换一批。倍数太大就会开始出现只有一两部作品的冷门项。TOPS_POOL_FACTOR = 4+#: 顶部两排候选池读到的账本表:作品与实体三张、「已标记」读的偏好、「稍后看」读的队列。+TOPS_TABLES = GROUP_TABLES + ("asset_preference", "watch_queue")+def q_tops(contract: WebContract, n=28, jav=False, seed="", state="", page=0, filters=None):"""顶部三层用的数据:女优圆头像 / 厂牌 / 内容标签。@@ -1216,48 +1219,58 @@ def q_tops(contract: WebContract, n=28, jav=False, seed="", state="", page=0, fi`page` 给横滚续接用。第一页那 n 个是从数量前 `n * TOPS_POOL_FACTOR` 里抽的,续页要是再回到那一段就会把同一个人给两次,所以那一段归第一页独占,续页从它的- 末尾往后按数量数下去。库里六百多位女优,一排给到头才是「滚到底还能接着滚」。"""- with contract.read_connection() as c:- scope = PRESENT_ASSET_CLAUSE + (JAV_ASSET_CLAUSE if jav else "") + state_clause(state)- folder_params = []- if filters and filters.get('folder'):- conditions, folder_params = catalog_filter(contract, filters)- scope += ' AND ' + ' AND '.join(conditions)- base = (- "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) n,"- "(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "- " WHERE ae2.entity_id=e.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL "- " AND (e.kind<>'performer' OR " + solo_performer_clause("a2.id", "e.id") + ") "- " ORDER BY (a2.play_count IS NULL),a2.size DESC LIMIT 1) rep "- "FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "- "JOIN asset a ON a.id=ae.asset_id "- "WHERE a.medium='video' AND e.kind=? " + scope +- "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ? OFFSET ?"- )- first_page_span = n * TOPS_POOL_FACTOR if seed else n-- def read(kind, limit, skip):- return [{"id": entity_id, "k": k, "n": cnt, "rep": representative}- for entity_id, k, cnt, representative- in c.execute(base, (kind, *folder_params, limit, skip))]-- def pick(kind):- """按数量取候选池,再按种子确定性抽样。种子为空时退回严格前 N。"""- if page:- return read(kind, n, first_page_span + (page - 1) * n)- pool = read(kind, first_page_span, 0)- if not seed or len(pool) <= n:- return pool[:n]- # 同一个种子必须给出同一批人:翻页和重绘之间不能抖动。- digest = hashlib.blake2b(f"{seed}:{kind}".encode(), digest_size=8).digest()- rng = random.Random(int.from_bytes(digest, "big"))- chosen = rng.sample(pool, n)- # 抽完仍按数量排序,免得常见身份被排到末尾。- return sorted(chosen, key=lambda row: -row["n"])-- out = {}- out["performers"] = pick("performer")- out["studios"] = pick("studio")+ 末尾往后按数量数下去。库里六百多位女优,一排给到头才是「滚到底还能接着滚」。++ 两条分组 SQL 各要三百毫秒上下,结果只取决于账本与口径,与种子无关:候选池按+ `TOPS_TABLES` 的版本缓存,种子抽样和读目录索引的那几个标志都在缓存之外现做。"""+ state = state if state_predicate(state) else ""+ scope = PRESENT_ASSET_CLAUSE + (JAV_ASSET_CLAUSE if jav else "") + state_clause(state)+ folder_params = []+ if filters and filters.get('folder'):+ conditions, folder_params = catalog_filter(contract, filters)+ scope += ' AND ' + ' AND '.join(conditions)+ base = (+ "SELECT e.id,e.canonical_name,count(DISTINCT ae.asset_id) n,"+ "(SELECT a2.id FROM asset_entity ae2 JOIN asset a2 ON a2.id=ae2.asset_id "+ " WHERE ae2.entity_id=e.id AND a2.medium='video' AND a2.snapshot_path IS NOT NULL "+ " AND (e.kind<>'performer' OR " + solo_performer_clause("a2.id", "e.id") + ") "+ " ORDER BY (a2.play_count IS NULL),a2.size DESC LIMIT 1) rep "+ "FROM asset_entity ae JOIN entity e ON e.id=ae.entity_id "+ "JOIN asset a ON a.id=ae.asset_id "+ "WHERE a.medium='video' AND e.kind=? " + scope ++ "GROUP BY e.id,e.canonical_name ORDER BY n DESC LIMIT ? OFFSET ?"+ )+ first_page_span = n * TOPS_POOL_FACTOR if seed else n++ def read(kind, limit, skip):+ def compute():+ with contract.read_connection() as c:+ return [{"id": entity_id, "k": k, "n": cnt, "rep": representative}+ for entity_id, k, cnt, representative+ in c.execute(base, (kind, *folder_params, limit, skip))]+ # 目录筛选的条件已在上面按目录索引展开成 SQL,键里带上它,口径就完整了。+ key = repr(("tops-pool", kind, jav, state, scope, tuple(folder_params), limit, skip))+ rows = contract.cached_until_changed(key, compute, tables=TOPS_TABLES)+ # 下面还要往每行补目录索引的标志,不能写进缓存里那一份。+ return [dict(row) for row in rows]++ def pick(kind):+ """按数量取候选池,再按种子确定性抽样。种子为空时退回严格前 N。"""+ if page:+ return read(kind, n, first_page_span + (page - 1) * n)+ pool = read(kind, first_page_span, 0)+ if not seed or len(pool) <= n:+ return pool[:n]+ # 同一个种子必须给出同一批人:翻页和重绘之间不能抖动。+ digest = hashlib.blake2b(f"{seed}:{kind}".encode(), digest_size=8).digest()+ rng = random.Random(int.from_bytes(digest, "big"))+ chosen = rng.sample(pool, n)+ # 抽完仍按数量排序,免得常见身份被排到末尾。+ return sorted(chosen, key=lambda row: -row["n"])++ out = {}+ out["performers"] = pick("performer")+ out["studios"] = pick("studio")# 顶栏那排厂牌小圆片据此决定要不要输出 `<img>`:没装标识就直接首字母垫底。# 判定在库连接之外做,它读的是目录索引而不是账本。for studio in out["studios"]:@@ -1279,6 +1292,12 @@ def q_tops(contract: WebContract, n=28, jav=False, seed="", state="", page=0, fi+#: 筛选项读到的账本表(不含实体范围与搜索词那几条分支,它们不走按版本的缓存):+#: 作品与实体、标签隐藏偏好、「已标记」「稍后看」两种状态,以及在线卡片的关注标签。+FACETS_TABLES = GROUP_TABLES + ("asset_tag_preference", "asset_preference", "watch_queue",+ "follow_item", "follow_source")++def q_facets(contract: WebContract,jav: bool = False,diff --git a/src/peach/web_entity.py b/src/peach/web_entity.pyindex f3b830a43..74ab5aa88 100644--- a/src/peach/web_entity.py+++ b/src/peach/web_entity.py@@ -641,8 +641,34 @@ def _attach_index_favorites(connection, rows: list[dict]) -> None:row["favorite"] = row.get("entity_id") in favorites+#: 索引页账本那一段读到的表:计数与代表作、分类、事务所成员与官网、片商旗下 label、+#: 订阅状态,以及收藏(存在 `profile` 里,按别名与重定向解析成规范实体)。+INDEX_TABLES = ("asset", "asset_entity", "asset_tag", "asset_tag_preference", "entity",+ "entity_alias", "entity_redirect", "entity_classification", "entity_external_ref",+ "entity_identity_link", "entity_link", "entity_membership", "label_maker",+ "feed_source", "follow_source", "profile")++def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category=""):- """全部艺人 / 创作者 / 厂牌 / 事务所 / 标签的索引页数据。"""+ """全部艺人 / 创作者 / 厂牌 / 事务所 / 标签的索引页数据。++ 账本那一段十来条 SQL,名册页合计三四百毫秒;没有搜索词时按 `INDEX_TABLES` 的版本缓存。+ 搜索词的键空间不封闭,带搜索词照旧现算。读目录索引的头像与标识标志在缓存之外现做。+ """+ def read():+ return _index_rows(contract, kind, q, limit, offset, category)+ if q or kind not in {"agencies", "tags", *INDEX_ENTITY_KINDS}:+ rows, has_more, category_counts = read()+ else:+ rows, has_more, category_counts = contract.cached_until_changed(+ repr(("index", kind, limit, offset, category)), read, tables=INDEX_TABLES)+ # 下面还要往每行补目录索引的标志,不能写进缓存里那一份。+ rows = [dict(row) for row in rows]+ return _decorate_index(contract, kind, rows, has_more, category_counts)+++def _index_rows(contract: WebContract, kind, q, limit, offset, category):+ category_counts = Nonewith contract.read_connection() as c:if kind == "agencies":# 事务所自己不挂作品,所以它排的是人:一家有多少艺人是它的规模,作品数是@@ -735,6 +761,10 @@ def q_index(contract: WebContract, kind, q="", limit=600, offset=0, category="")rows = all_rows[offset:offset + limit]has_more = offset + limit < len(all_rows)_attach_index_favorites(c, rows)+ return rows, has_more, category_counts+++def _decorate_index(contract: WebContract, kind, rows, has_more, category_counts):if kind in INDEX_ENTITY_KINDS:entity_kind = INDEX_ENTITY_KINDS[kind]# 索引页一屏几十个圆头像,走的是和顶栏那排同一条两级链:规范实体图优先,diff --git a/src/peach/web_router.py b/src/peach/web_router.pyindex 0f1c0632d..402fd40b7 100644--- a/src/peach/web_router.py+++ b/src/peach/web_router.py@@ -10,6 +10,7 @@"""from __future__ import annotations+from . import media_libraries, settings_filefrom .follow_discovery import MAX_SUGGESTIONS, MAX_TERM_LENGTHfrom .review_csv import candidate_root_versionfrom .web_activity import (@@ -24,6 +25,7 @@ from .web_batch import q_ads, q_duplicates, w_batch, w_empty_trashfrom .web_tags import q_tag_management, w_tag_management, w_tag_previewfrom .taste_history import history_source_countfrom .web_catalog import (+ FACETS_TABLES,catalog_filter,q_editions,q_facets,@@ -142,7 +144,8 @@ def _get_index(contract, args):def _get_stats(contract, _args):- return contract.cached("stats", lambda: q_stats(contract))+ # 账本那一段在 `q_stats` 里按版本缓存,存储卷每次现量。+ return q_stats(contract)def _get_tops(contract, args):@@ -183,6 +186,11 @@ def _get_related(contract, args):f"related:{asset_id}:{limit}", lambda: q_related(contract, asset_id, limit))+#: 按账本版本缓存的筛选项口径:状态页与取值有限的几组筛选。+FACET_STATES = frozenset({"", "fresh", "played", "flagged", "later"})+FACET_ENUM_FILTERS = frozenset({"loc", "len", "orient", "region", "exclude_vertical", "thumb", "library"})++def _get_facets(contract, args):jav = args.get("jav") == "1"scope_kind = str(args.get("scope_kind", ""))@@ -196,14 +204,20 @@ def _get_facets(contract, args):'library', 'folder', 'folder_recursive',) if args.get(key)}scope_key += repr(sorted(filters.items()))- return contract.cached(- f"facets{'-jav' if jav else ''}:{scope_key}",- lambda: q_facets(- contract,- jav=jav, scope_kind=scope_kind, scope_name=scope_name, asset_id=asset_id,- state=state, filters=filters or None,- ),+ compute = lambda: q_facets( # noqa: E731+ contract,+ jav=jav, scope_kind=scope_kind, scope_name=scope_name, asset_id=asset_id,+ state=state, filters=filters or None,)+ # 首页与侧栏几组枚举筛选(来源、时长、画幅、产地、媒体库)的组合有限,按账本版本缓存;+ # 实体、详情、搜索词、标签与时长区间的键空间不封闭,照旧走 TTL 缓存。+ if (not (scope_kind or scope_name or asset_id is not None) and state in FACET_STATES+ and set(filters) <= FACET_ENUM_FILTERS):+ library = (repr(media_libraries.predicate(settings_file.active(), filters['library']))+ if 'library' in filters else '')+ return contract.cached_until_changed(+ f"facets{'-jav' if jav else ''}:{scope_key}", compute, library, tables=FACETS_TABLES)+ return contract.cached(f"facets{'-jav' if jav else ''}:{scope_key}", compute)def _get_suggest(contract, args):diff --git a/src/peach/web_stats.py b/src/peach/web_stats.pyindex 052eaf3a7..2a4b160e7 100644--- a/src/peach/web_stats.py+++ b/src/peach/web_stats.py@@ -348,8 +348,30 @@ def _replays(c, has_follow: bool) -> list[dict[str, int]]:return [{"k": plays, "n": n} for plays, n in sorted(counts.items())]+#: 统计页账本那一段读到的表。`tag_not_hidden` 读标签偏好,`tag_is_not_a_performer_name` 读实体,+#: 在线播放读关注三张表。+STATS_TABLES = ("asset", "asset_entity", "entity", "asset_tag", "asset_tag_preference",+ "asset_preference", "follow_playback", "follow_item", "follow_source")++def q_stats(contract: WebContract):- """统计页:库存 / 归属 / 标签 / 本地与在线播放 / 各存储卷。"""+ """统计页:库存 / 归属 / 标签 / 本地与在线播放 / 各存储卷。++ 账本那一段三十多条聚合 SQL 合计一秒多,按 `STATS_TABLES` 的版本缓存;媒体库划分取自设置,+ 热力图按本机时区分桶,两样作为输入进版本。存储卷读的是磁盘余量,与账本无关,按时间过期。+ """+ config = settings_file.active()+ libraries = [(library, media_libraries.predicate(config, library["id"]))+ for library in media_libraries.libraries(config)]+ out = dict(contract.cached_until_changed(+ "stats-ledger", lambda: _ledger_stats(contract, libraries),+ repr(libraries), _utc_offset(datetime.now().astimezone()), tables=STATS_TABLES))+ # 判定在线要读一次各挂载根的首条目录项,网盘挂载上不便宜,沿用 TTL 缓存。+ out.update(contract.cached("stats-storage", _storage_stats))+ return out+++def _ledger_stats(contract: WebContract, libraries) -> dict:with contract.read_connection() as c:out = {}out["by_loc"] = [dict(r) for r in c.execute(@@ -361,10 +383,8 @@ def q_stats(contract: WebContract):f"FROM asset WHERE {PRESENT} GROUP BY medium ORDER BY bytes DESC")]out["by_length"] = _bands(c, "ctx_length", LENGTH_BANDS)out["by_quality"] = _bands(c, "ctx_quality", QUALITY_BANDS)- config = settings_file.active()out["by_library"] = []- for library in media_libraries.libraries(config):- clause, params = media_libraries.predicate(config, library["id"])+ for library, (clause, params) in libraries:counts = c.execute("SELECT count(*) videos,COALESCE(sum(a.size),0) bytes FROM asset a "f"WHERE a.medium='video' AND {PRESENT_A} AND " + clause, params,@@ -454,7 +474,11 @@ def q_stats(contract: WebContract):)[:12]out["play_activity"] = _play_activity(c, has_follow)out["replays"] = _replays(c, has_follow)- out["storage_volumes"] = _storage_volumes()+ return out+++def _storage_stats() -> dict:+ out = {"storage_volumes": _storage_volumes()}measured = [row for row in out["storage_volumes"] if row["total"] is not None]out["storage_summary"] = {"volumes": len(out["storage_volumes"]),diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex 275239255..555499b5c 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -126,6 +126,36 @@ class WebDataTests(unittest.TestCase):con.close()return row+ def test_home_aggregates_recompute_only_when_the_tables_they_read_change(self):+ """顶栏候选池、统计、名册、筛选项各按自己读的表缓存:换种子、搜一次不重算,作品变了就重算。"""+ def entries():+ return {key: id(entry) for key, entry in self.contract.cache.items()+ if key == "stats-ledger" or key.startswith(("('tops-pool'", "('index'", "facets:"))}++ def load(seed):+ return (rm_web.q_tops(self.contract, 28, seed=seed),+ rm_web.dispatch_api_get(self.contract, "/api/stats", {}),+ rm_web.dispatch_api_get(self.contract, "/api/index", {"kind": "performers"}),+ rm_web.dispatch_api_get(self.contract, "/api/facets", {"loc": "local,115"}))++ load("first")+ cached = entries()+ # 两排候选池、统计、名册、筛选项各一份。+ self.assertEqual(len(cached), 5)+ rm_web.w_search_history(self.contract, {"query": "Alice"})+ load("second")+ self.assertEqual(entries(), cached)+ with self.contract.write_transaction() as connection:+ connection.execute("UPDATE asset SET o_count=3 WHERE id=1")+ connection.execute("INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) "+ "VALUES(2,11,'performer','test',1.0)")+ tops, stats, index, facets = load("second")+ self.assertFalse(set(entries().items()) & set(cached.items()))+ self.assertEqual(stats["consumption"]["o_total"], 3)+ self.assertEqual([(row["k"], row["n"]) for row in tops["performers"]], [("Canonical Alice", 2)])+ self.assertEqual(next(row["n"] for row in index["items"] if row["k"] == "Canonical Alice"), 2)+ self.assertEqual([(row["k"], row["n"]) for row in facets["tagperformers"]], [("Canonical Alice", 2)])+def test_creator_card_and_detail_share_available_entity_image(self):(self.avatars / f"{entity_image_key('creator', 12)}.img").write_bytes(b"image")row = rm_web.q_items(self.contract, {"limit": "10"})["items"][0]