Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(related): 接着看的推荐理由带出共同标签

longmeidaoe7d444c86fbc
diff --git a/src/peach/related.py b/src/peach/related.py
index f58831800..126390461 100644
--- a/src/peach/related.py
+++ b/src/peach/related.py
@@ -65,10 +65,13 @@ def _closeness_features(left, right, weights: Mapping[int, float]) -> float:
return score
+TAG_REASON = "标签接近"
+
+
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", "同厂牌"),
+ ("performer", "同出演者"), ("tag", TAG_REASON), ("studio", "同厂牌"),
) if a[kind] & b[kind]]
@@ -111,6 +114,9 @@ def rank_related(source: Mapping, candidates: Iterable[Mapping], limit: int,
if not reasons and not relevance_for:
continue
candidate["why"] = " · ".join(reasons[:2])
+ # 「标签接近」本身说不出接近在哪:共同标签按 IDF 从稀有到常见交出去,由调用方换成名字。
+ candidate["shared_tags"] = sorted(source_feature[0]["tag"] & feature[0]["tag"],
+ key=lambda tag: (-weights.get(tag, 1.0), tag))
candidate["related_score"] = round(relevance, 4)
entries.append(_Entry(candidate, feature, relevance,
_stable_key(stable_seed, int(candidate["id"]))))
diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.py
index 575c42cb5..9ea30aacd 100644
--- a/src/peach/web_catalog.py
+++ b/src/peach/web_catalog.py
@@ -1109,6 +1109,30 @@ def _one_card_per_release(contract: WebContract, source_code, rows: list[dict])
kept.append(row)
return kept
+def _name_shared_tags(contract: WebContract, aid, picked, related_tags) -> None:
+ """「标签接近」换成共同标签本身(`why_tags`,稀有的在前)。
+
+ 只留两边都看得见的标签:排序用的是实体关联,被用户隐藏的标签也在里面。一个都不剩时
+ 照旧写「标签接近」。"""
+ from peach.related import TAG_REASON
+
+ ids = sorted({tag for row in picked for tag in row.get("shared_tags", ())})
+ names: dict[int, str] = {}
+ if ids:
+ with contract.read_connection() as c:
+ names = dict(c.execute(
+ f"SELECT id,canonical_name FROM entity WHERE id IN ({','.join('?' * len(ids))})",
+ ids,
+ ))
+ source_tags = {tag for _asset_id, tag in con_tags(contract, [aid], "?")}
+ for row in picked:
+ visible = source_tags & set(related_tags.get(row["id"], ()))
+ shared = [names[tag] for tag in row.pop("shared_tags", ()) if names.get(tag) in visible]
+ if shared:
+ row["why_tags"] = shared[:6]
+ row["why"] = " · ".join(reason for reason in row["why"].split(" · ") if reason != TAG_REASON)
+
+
def q_related(contract: WebContract, aid, limit=24):
"""接着看:IDF 抑制泛标签,MMR 避免近重复连续占满列表。"""
from peach.related import rank_related
@@ -1179,6 +1203,7 @@ def q_related(contract: WebContract, aid, limit=24):
marks = ",".join("?" * len(related_ids))
for asset_id, tag in con_tags(contract, related_ids, marks):
related_tags.setdefault(asset_id, []).append(tag)
+ _name_shared_tags(contract, aid, picked, related_tags)
for d in picked:
d["cost"] = cost_for(d['location'], d.get('path'))
d["has_thumb"] = contract.has_snapshot(d["snapshot_path"])
diff --git a/tests/test_related.py b/tests/test_related.py
index dbfda19bb..4ece1eae0 100644
--- a/tests/test_related.py
+++ b/tests/test_related.py
@@ -44,6 +44,8 @@ def _naive_rank(source, candidates, limit, *, seed=None, diversity=0.22):
reasons = choice.pop("_reasons")
relevance = choice.pop("_relevance")
choice["why"] = " · ".join(reasons[:2])
+ choice["shared_tags"] = sorted(related._sets(source)["tag"] & related._sets(choice)["tag"],
+ key=lambda tag: (-weights.get(tag, 1.0), tag))
choice["related_score"] = round(relevance, 4)
selected.append(choice)
return selected
@@ -107,6 +109,14 @@ class RelatedRankerTests(unittest.TestCase):
self.assertEqual(ranked[0]["id"], 3)
self.assertEqual(ranked[0]["why"], "标签接近")
+ def test_shared_tags_come_rarest_first(self):
+ source = {"id": 1, "entities": {"tag": {10, 20, 30}}}
+ both = {"id": 2, "entities": {"tag": {10, 20, 30}}}
+ background = [{"id": asset_id, "entities": {"tag": {10, 30} if asset_id % 2 else {10}}}
+ for asset_id in range(3, 13)]
+ ranked = rank_related(source, [both, *background], 1, seed="fixed")
+ self.assertEqual(ranked[0]["shared_tags"], [20, 30, 10])
+
def test_result_is_stable_and_mmr_adds_variety(self):
source = {"id": 1, "entities": {"creator": {7}, "tag": {10, 11}}}
candidates = [
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 4679989f6..4bff95298 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -2136,6 +2136,27 @@ class WebDataTests(unittest.TestCase):
with self.assertRaises(ValueError):
rm_web.w_batch(self.contract, {"ids": list(range(201)), "operation": "seen"})
+ def test_related_reason_names_shared_tags_the_user_can_see(self):
+ con = sqlite3.connect(self.db_path)
+ con.execute("INSERT INTO entity(id,kind,canonical_name,normalized_name,created_at,updated_at) "
+ "VALUES(14,'tag','痴女','痴女','2026-01-01','2026-01-01')")
+ con.executemany("INSERT INTO asset_tag(asset_id,tag,source) VALUES(?,?,?)",
+ [(1, "痴女", "name"), (2, "足交", "name"), (2, "痴女", "name")])
+ con.executemany("INSERT INTO asset_entity(asset_id,entity_id,role,source,confidence) "
+ "VALUES(?,?,'tag','test',1.0)", [(1, 14), (2, 10), (2, 14)])
+ con.commit()
+ con.close()
+
+ first = rm_web.q_related(self.contract, 1, 10)["items"][0]
+ self.assertEqual((first["why"], first["why_tags"]), ("同创作者", ["足交", "痴女"]))
+ # 用户在对面那部上隐藏的标签不拿来当理由;一个都不剩时退回「标签接近」。
+ rm_web.w_item_tag(self.contract, {"id": 2, "operation": "remove", "tag": "足交"})
+ first = rm_web.q_related(self.contract, 1, 10)["items"][0]
+ self.assertEqual(first["why_tags"], ["痴女"])
+ rm_web.w_item_tag(self.contract, {"id": 2, "operation": "remove", "tag": "痴女"})
+ first = rm_web.q_related(self.contract, 1, 10)["items"][0]
+ self.assertEqual((first["why"], "why_tags" in first), ("同创作者 · 标签接近", False))
+
def test_top_lists_and_related_items_use_canonical_entities(self):
tops = rm_web.q_tops(self.contract, 10)
self.assertEqual(tops["performers"][0]["k"], "Canonical Alice")