Skip to content

armgit / peach

Public Imported from GitHub
0

Peach: Local-first video metadata scraper and media manager.

perf(related): MMR 的冗余项改增量维护,/api/related 从 6.2 秒降到 0.48 秒

longmeidaod520c624e326
diff --git a/src/peach/related.py b/src/peach/related.py
index cb9a0cd96..7cfd3ed33 100644
--- a/src/peach/related.py
+++ b/src/peach/related.py
@@ -4,6 +4,7 @@ from __future__ import annotations
import hashlib
import math
from collections.abc import Iterable, Mapping
+from dataclasses import dataclass
KINDS = ("creator", "performer", "series", "studio", "tag")
@@ -39,17 +40,22 @@ def _weighted_jaccard(left: set[int], right: set[int], weights: Mapping[int, flo
)
-def _closeness(left: Mapping, right: Mapping, weights: Mapping[int, float]) -> float:
- a, b = _sets(left), _sets(right)
+def _feature(item: Mapping):
+ """打分只用得到这三样。抽出来是因为 MMR 会对同一条候选反复算 closeness,
+ 每次都从 `entities` 重建五个集合的话,集合构造本身就成了主要开销。"""
+ return _sets(item), item.get("year"), item.get("duration")
+
+
+def _closeness_features(left, right, weights: Mapping[int, float]) -> float:
+ a, left_year, left_duration = left
+ b, right_year, right_duration = right
score = 0.55 * _weighted_jaccard(a["tag"], b["tag"], weights)
score += 0.45 if a["creator"] & b["creator"] else 0.0
score += 0.24 if a["series"] & b["series"] else 0.0
score += 0.18 if a["performer"] & b["performer"] else 0.0
score += 0.12 if a["studio"] & b["studio"] else 0.0
- left_year, right_year = left.get("year"), right.get("year")
if left_year and right_year:
score += max(0.0, 0.04 - 0.01 * abs(int(left_year) - int(right_year)))
- left_duration, right_duration = left.get("duration"), right.get("duration")
if left_duration and right_duration:
ratio = min(float(left_duration), float(right_duration)) / max(
float(left_duration), float(right_duration)
@@ -58,45 +64,74 @@ def _closeness(left: Mapping, right: Mapping, weights: Mapping[int, float]) -> f
return score
-def _reasons(source: Mapping, candidate: Mapping) -> list[str]:
- a, b = _sets(source), _sets(candidate)
- reasons = []
- for kind, label in (
+def _closeness(left: Mapping, right: Mapping, weights: Mapping[int, float]) -> float:
+ return _closeness_features(_feature(left), _feature(right), weights)
+
+
+def _reasons_features(a: Mapping[str, set[int]], b: Mapping[str, set[int]]) -> list[str]:
+ return [label for kind, label in (
("creator", "同创作者"), ("series", "同系列"),
("performer", "同出演者"), ("tag", "标签接近"), ("studio", "同厂牌"),
- ):
- if a[kind] & b[kind]:
- reasons.append(label)
- return reasons
+ ) if a[kind] & b[kind]]
+
+
+def _reasons(source: Mapping, candidate: Mapping) -> list[str]:
+ return _reasons_features(_sets(source), _sets(candidate))
+
+
+@dataclass(slots=True)
+class _Entry:
+ row: dict
+ feature: tuple
+ relevance: float
+ key: str
+ redundancy: float = 0.0
def rank_related(source: Mapping, candidates: Iterable[Mapping], limit: int,
*, seed: str | None = None, diversity: float = 0.22) -> list[dict]:
- """以 IDF 加权相关度选片,再用 MMR 抑制连续出现的近重复作品。"""
+ """以 IDF 加权相关度选片,再用 MMR 抑制连续出现的近重复作品。
+
+ MMR 的代价原本是 O(limit² × 候选池):每选中一条,都要把整池和**全部**已选重算一遍
+ closeness。候选池上限 4000,生产实测 limit=20 要 3.2 秒、limit=28 要 6.2 秒、
+ limit=60 要 28 秒——`/api/related` 的耗时几乎全在这里,不在 SQL。
+ 「候选对已选集的最大 closeness」可以增量维护:新选中一条时只和这一条比一次,取较大值。
+ 这是等价变换,选出来的结果逐条不变,代价降到 O(limit × 候选池)。
+ """
+ want = max(0, int(limit))
+ source_id = int(source["id"])
pool = [dict(candidate) for candidate in candidates
- if int(candidate["id"]) != int(source["id"])]
+ if int(candidate["id"]) != source_id]
weights = _idf([source, *pool])
+ source_feature = _feature(source)
+ stable_seed = seed or str(source_id)
+
+ entries: list[_Entry] = []
for candidate in pool:
- candidate["_relevance"] = _closeness(source, candidate, weights)
- candidate["_reasons"] = _reasons(source, candidate)
- pool = [candidate for candidate in pool
- if candidate["_relevance"] > 0 and candidate["_reasons"]]
+ feature = _feature(candidate)
+ relevance = _closeness_features(source_feature, feature, weights)
+ if relevance <= 0:
+ continue
+ reasons = _reasons_features(source_feature[0], feature[0])
+ if not reasons:
+ continue
+ candidate["why"] = " · ".join(reasons[:2])
+ candidate["related_score"] = round(relevance, 4)
+ entries.append(_Entry(candidate, feature, relevance,
+ _stable_key(stable_seed, int(candidate["id"]))))
+
selected: list[dict] = []
- stable_seed = seed or str(source["id"])
- while pool and len(selected) < max(0, int(limit)):
- def key(candidate: Mapping):
- redundancy = max(
- (_closeness(candidate, prior, weights) for prior in selected),
- default=0.0,
- )
- mmr = float(candidate["_relevance"]) - diversity * redundancy
- return (-mmr, _stable_key(stable_seed, int(candidate["id"])))
-
- choice = min(pool, key=key)
- pool.remove(choice)
- reasons = choice.pop("_reasons")
- relevance = choice.pop("_relevance")
- choice["why"] = " · ".join(reasons[:2])
- choice["related_score"] = round(relevance, 4)
- selected.append(choice)
+ while entries and len(selected) < want:
+ best = min(range(len(entries)), key=lambda index: (
+ -(entries[index].relevance - diversity * entries[index].redundancy),
+ entries[index].key,
+ ))
+ chosen = entries.pop(best)
+ selected.append(chosen.row)
+ if len(selected) >= want:
+ break
+ for entry in entries:
+ closeness = _closeness_features(entry.feature, chosen.feature, weights)
+ if closeness > entry.redundancy:
+ entry.redundancy = closeness
return selected
diff --git a/tests/test_related.py b/tests/test_related.py
index 227e5f916..330392e3f 100644
--- a/tests/test_related.py
+++ b/tests/test_related.py
@@ -1,8 +1,75 @@
import unittest
+from peach import related
from peach.related import rank_related
+def _naive_rank(source, candidates, limit, *, seed=None, diversity=0.22):
+ """优化前的朴素 MMR:每选一条,就把整池和**全部**已选重算一遍 closeness。
+
+ 它留在测试里只有一个用途:当基准。增量维护「候选对已选集的最大
+ closeness」是等价变换,一旦哪天有人把它改成不等价的写法(比如改成只和
+ 最后一条比、或者改成平均值),推荐顺序会静静地变,而不会报错。
+ """
+ pool = [dict(candidate) for candidate in candidates
+ if int(candidate["id"]) != int(source["id"])]
+ weights = related._idf([source, *pool])
+ for candidate in pool:
+ candidate["_relevance"] = related._closeness(source, candidate, weights)
+ candidate["_reasons"] = related._reasons(source, candidate)
+ pool = [candidate for candidate in pool
+ if candidate["_relevance"] > 0 and candidate["_reasons"]]
+ selected = []
+ stable_seed = seed or str(source["id"])
+ while pool and len(selected) < max(0, int(limit)):
+ def key(candidate):
+ redundancy = max(
+ (related._closeness(candidate, prior, weights) for prior in selected),
+ default=0.0,
+ )
+ mmr = float(candidate["_relevance"]) - diversity * redundancy
+ return (-mmr, related._stable_key(stable_seed, int(candidate["id"])))
+
+ choice = min(pool, key=key)
+ pool.remove(choice)
+ reasons = choice.pop("_reasons")
+ relevance = choice.pop("_relevance")
+ choice["why"] = " · ".join(reasons[:2])
+ choice["related_score"] = round(relevance, 4)
+ selected.append(choice)
+ return selected
+
+
+def _corpus(size=120):
+ """往每个维度都撑出重叠的候选池。模数互质,于是同创作者、同厂牌、
+ 标签重叠和时长接近会交错出现,MMR 的冗余惩罚才真的会改变名次。"""
+ rows = []
+ for asset_id in range(2, 2 + size):
+ rows.append({
+ "id": asset_id,
+ "entities": {
+ "tag": {10 + asset_id % 7, 20 + asset_id % 5, 30 + asset_id % 11},
+ "creator": {40 + asset_id % 3} if asset_id % 4 else set(),
+ "performer": {50 + asset_id % 6},
+ "studio": {60 + asset_id % 2},
+ "series": {70} if asset_id % 9 == 0 else set(),
+ },
+ "year": 2010 + asset_id % 12,
+ "duration": 600 + 37 * (asset_id % 20),
+ })
+ return rows
+
+
+def _corpus_source():
+ return {
+ "id": 1,
+ "entities": {"tag": {10, 20, 30}, "creator": {40}, "performer": {50},
+ "studio": {60}, "series": {70}},
+ "year": 2016,
+ "duration": 1200,
+ }
+
+
class RelatedRankerTests(unittest.TestCase):
def test_rare_shared_tag_beats_common_shared_tag(self):
source = {"id": 1, "entities": {"tag": {10, 20}}}
@@ -34,5 +101,48 @@ class RelatedRankerTests(unittest.TestCase):
self.assertEqual(ranked, [])
+ def test_incremental_mmr_picks_exactly_what_the_naive_loop_picks(self):
+ """这次优化只能改代价,不能改结果。
+
+ 逐条对整个返回字典,不只对 id:`why` 和 `related_score` 同样是契约,
+ 它们直接显示在“接着看”和 Mix 队列里。diversity=0 把 MMR 退化成纯排序,
+ 0.6 则让冗余惩罚大到足以改变名次;两端都要对得上才算等价。
+ """
+ source, corpus = _corpus_source(), _corpus()
+ for limit in (0, 1, 3, 8, 25, 200):
+ for diversity in (0.0, 0.22, 0.6):
+ with self.subTest(limit=limit, diversity=diversity):
+ expected = _naive_rank(source, corpus, limit,
+ seed="fixed", diversity=diversity)
+ actual = rank_related(source, corpus, limit,
+ seed="fixed", diversity=diversity)
+ self.assertEqual(actual, expected)
+
+ def test_mmr_cost_is_linear_in_limit(self):
+ """守住优化的实际目的:代价对 limit 是线性,不是二次。
+
+ 旧写法在真实候选池(上限 4000)上 limit=28 要 6.2 秒、limit=60 要 28 秒,
+ 而悬浮 Mix 卡片和详情页“接着看”都卡在这一步。上界取 池×(limit+2):
+ 增量实现宽松成立,任何「每轮重算全部已选」的写法当场超出。
+ """
+ source, corpus = _corpus_source(), _corpus()
+ calls = 0
+ original = related._closeness_features
+
+ def counting(left, right, weights):
+ nonlocal calls
+ calls += 1
+ return original(left, right, weights)
+
+ related._closeness_features = counting
+ try:
+ picked = rank_related(source, corpus, 16, seed="fixed")
+ finally:
+ related._closeness_features = original
+ self.assertEqual(len(picked), 16)
+ self.assertLessEqual(calls, len(corpus) * 18,
+ f"closeness 调用 {calls} 次,已超出线性上界")
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 01853d518..551c3541a 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -1668,6 +1668,9 @@ class WebUiSourceTests(unittest.TestCase):
"el.addEventListener('mouseleave',stop);" + chr(10)
+ " el._stopHover=stop;")
self.assertPageContains("const mixRelatedCache=new Map();")
+ # 第一张不能等满一个完整间隔:那会把「鼠标停下到有反应」拉到两秒。
+ self.assertPageContains(
+ "lead=setTimeout(()=>{step();cycle=setInterval(step,MIX_FLIP_MS)},MIX_FLIP_LEAD_MS);")
self.assertPageContains(
"Promise.all([api('/api/item?id='+seedId),mixRelated(seedId)])")
# 队列长度不能被悬浮预取剪短:两边用同一个 limit。
diff --git a/web/app.js b/web/app.js
index b3dcb7463..069b3de86 100644
--- a/web/app.js
+++ b/web/app.js
@@ -1408,16 +1408,18 @@ function mixRelated(seedId){
return mixRelatedCache.get(seedId);
}
const MIX_FLIP_MS=1100; // 一张停多久再翻走
-const MIX_FLIP_FACES=5; // 最多预渲染几张,一次悬浮不拉一整批封面
+const MIX_FLIP_LEAD_MS=420; // 面板建好到第一次翻动。直接用 1.1 秒间隔等第一张,鼠标停下到有反应要接近两秒
+const MIX_FLIP_FACES=9; // 最多预渲染几张,一次悬浮不拉一整批封面
const reduceMotion=()=>matchMedia('(prefers-reduced-motion:reduce)').matches;
/* 悬浮 Mix 卡片时把它里面的前几部作品逐张翻走,说明它是一叠相似作品而不是
某一个视频。门槛和悬停预览一致:多选、遮挡、滞后动画偏好和滚动中都不启动,
离开即停并还原静止封面;`_stopHover` 让 releaseHoverPreviews 能连它一起收掉。 */
function wireMixFlip(el,seedId){
const box=el.querySelector('[data-mix-faces]');if(!box)return;
- let armed=null,cycle=null,faces=[],index=0,live=false;
+ let armed=null,lead=null,cycle=null,faces=[],index=0,live=false;
const stop=()=>{
- live=false;clearTimeout(armed);armed=null;clearInterval(cycle);cycle=null;
+ live=false;clearTimeout(armed);armed=null;clearTimeout(lead);lead=null;
+ clearInterval(cycle);cycle=null;
box.hidden=true;box.innerHTML='';faces=[];index=0;
};
const step=()=>{
@@ -1440,7 +1442,7 @@ function wireMixFlip(el,seedId){
if(pool.length<2)return;
box.innerHTML=pool.map((x,i)=>`<div class="mixface${i?'':' on'}">${mixFacePoster(x,layout,true)}</div>`).join('');
faces=[...box.children];index=0;box.hidden=false;
- cycle=setInterval(step,MIX_FLIP_MS);
+ lead=setTimeout(()=>{step();cycle=setInterval(step,MIX_FLIP_MS)},MIX_FLIP_LEAD_MS);
};
el.addEventListener('mouseenter',()=>{clearTimeout(armed);armed=setTimeout(start,340)});
el.addEventListener('mouseleave',stop);