Peach: Local-first video metadata scraper and media manager.
feat(follow): rule34video 连传的一包短片按角色归成一张卡
longmeidaoe0c0e3641bd1
diff --git a/docs/adr/0045-follow-upload-packs-fold-per-character.md b/docs/adr/0045-follow-upload-packs-fold-per-character.mdnew file mode 100644index 000000000..cd4cece91--- /dev/null+++ b/docs/adr/0045-follow-upload-packs-fold-per-character.md@@ -0,0 +1,63 @@+# ADR-0045:关注页把同一批连传的短片按角色归成一包++- 状态:Accepted+- 日期:2026-09-23+- 关系:与 [ADR-0028](0028-follow-groups-fold-within-an-author.md)、+ [ADR-0044](0044-follow-booru-bursts-fold-into-one-work.md) 同为读时计算++## 背景++rule34video 上有一类作品是「一包」:同一个工程导出好几条长度相同的短片,一次连着传上去。+LazyProcrastinator 的一段 KOF 沙滩动画就是 7 条 20 秒的片子,`Angel-handjob`、+`Angel-missionary`、`Mai-blowjob`、`Mai-doggy` 等。标题各不相同,站点不给出处,+发布时间也只有「1 周前」这种天级精度,现有判据没有一条能把它们连起来。++它们的共同点是站内视频 id:这是全站递增的上传序号,这 7 条的 id 只差 4 到 20。++## 决策++来源登记 `sequential_upload_ids=True` 的站点(当前只有 rule34video),五个条件同时成立的+条目归成一组:++1. 同一个来源。+2. 标题开头的角色名相同:取第一个分隔符(` - `、`-`、`[`、`(` 等)之前、不超过 3 个词的部分;+ 没有分隔符就取第一个词,跳过冠词和含数字的词(日期、序号)。+3. 按站内 id 排开,相邻两条相差不超过 30。+4. 时长相差不超过 1 秒。+5. 作品分类(`copyright`)有交集。++两条都带 `名字 (作品)` 形式的 general 标签、但一个都对不上时拆开。标题开头是系列名、+角色写在后面的(`Summer Fantasy – Cindy & Lunafreya` 与 `– Tifa & Aerith`)靠这一条分开。+artist 类里同样形式的 `Chloeangelva (VA)` 是配音演员,不算角色。++**不同角色分开,是用户定下的边界。** 同一包里的 Angel 与 Mai 是两组,不是一组。++归组按键合并:一条并进来,和它同键的别站副本一起跟过来。实现是+`follow_store._align_upload_packs`。++同一次改动里,`origin_group_key` 给缺协议头的出处补上 https 再解析,`group_hint` 在读时按+出处重算。实测 rule34.xxx 上同一条推文,一帖写 `https://x.com/…`、另一帖只写 `x.com/…`,+不补协议头就认不出后一帖的出处,两帖会分成两张卡。++## 依据++2026-09-23 在真实 ledger 上只读试算,16324 条可见条目,分组数从 11916 降到 11765,新并出+84 组。++| 判据 | rule34video 归并组 | 减少的卡片 | 抽查结论 |+| --- | --- | --- | --- |+| 只看 id 连号(相差不超过 100) | 139 | 487 | 不采用:一口气补传几十部旧作,id 同样连着,一组 23 条横跨数月 |+| 连号 + 时长相同 + 分类有交集 | 123 | 277 | 不采用:同一包里的不同角色并在一起(Madam M、Jihl、Rinoa) |+| **再加角色名与角色标签(采用)** | 84 | 约 150 | 抽查 28 组未见不同角色并组 |++## 拒绝方案++- 只按 id 连号归组。上传者补传旧作时 id 同样连着。+- 同一包里不同角色合成一张卡。用户明确要求分开。+- 从 general 标签里猜角色。rule34video 不区分角色标签与动作标签,只有 `名字 (作品)`+ 这一种写法能认出来,且只作拆开的依据,不作合并的依据。++## 后果++同一角色的一包短片合成一张卡,角标写「N 个视频」。误并的代价是同一角色、同一天、+同样长度的两部作品落在一张卡里;发现误并时收紧 id 间隔或时长容差。diff --git a/src/peach/follow_providers.py b/src/peach/follow_providers.pyindex 9942436aa..8de72b1a4 100644--- a/src/peach/follow_providers.py+++ b/src/peach/follow_providers.py@@ -41,6 +41,9 @@ class ProviderSpec:#: 这个来源的每个条目都是一次独立发布,即使标题相同。#: F95 的线程标题只是容器名,每个带资源的楼层各自成组。release_key_per_post: bool = False+ #: 站内 id 是全站递增的上传序号,同一作者一次连传的几条 id 相距很近。+ #: 关注页据此把同一批导出的短片认成一包(ADR-0045)。+ sequential_upload_ids: bool = False#: 直链媒体可以落在任意公网主机。给帖子里贴的第三方图床用:图站有几十家、还在#: 换,白名单追不上;而这类媒体本来就不带凭据取,代理到哪个公网主机都泄露不了#: 什么。安全边界改由 `follow_stream` 守:明文 http、IP 字面量、本机与局域网专用@@ -95,7 +98,7 @@ PROVIDERS: dict[str, ProviderSpec] = {# 整站的视频一条都放不出来。hosts=("rule34video.com", "boomio-cdn.com"),url_hosts=("rule34video.com",),- priority=30, backfill=True,+ priority=30, backfill=True, sequential_upload_ids=True,excluded_external_ids=("4533145",)),ProviderSpec("rule34xxx", "Rule34.xxx",source_url="https://rule34.xxx/index.php?page=post&s=list&tags={ref}",@@ -182,6 +185,12 @@ def release_key_per_post() -> frozenset[str]:if spec.release_key_per_post)+def sequential_upload_providers() -> frozenset[str]:+ """站内 id 是全站递增上传序号的来源。"""+ return frozenset(key for key, spec in PROVIDERS.items()+ if spec.sequential_upload_ids)++def excluded_external_ids() -> dict[str, frozenset[str]]:"""按来源列出要从浏览面隐藏的既有条目。没有要隐藏的来源不出现在结果里。"""return {key: frozenset(spec.excluded_external_ids)diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex a6aebd7a8..4ab6b7ddb 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -327,12 +327,16 @@ def origin_group_key(source_url: str | None) -> str | None:实测(2026-08-25)同一个 fanbox 帖在 rule34.xxx 上有两种写法——`lazyprocrast.fanbox.cc/posts/12304831` 和`www.fanbox.cc/@lazyprocrast/posts/12304831`——必须归一到同一个键,- 而那串数字正是 kemono 上同一帖子的 post id。+ 而那串数字正是 kemono 上同一帖子的 post id。出处常常省掉协议头+ (`x.com/vileclipse/status/…`),缺了就按 https 补上再解析。"""if not source_url or not isinstance(source_url, str):return None+ text = source_url.strip()+ if "://" not in text and not text.startswith("//"):+ text = "https://" + text.lstrip("/")try:- parsed = urllib.parse.urlsplit(source_url.strip())+ parsed = urllib.parse.urlsplit(text)except ValueError:return Nonehost = (parsed.hostname or "").lower()diff --git a/src/peach/follow_store.py b/src/peach/follow_store.pyindex df76c2dba..eea6c7455 100644--- a/src/peach/follow_store.py+++ b/src/peach/follow_store.py@@ -22,7 +22,7 @@ from .follow import FollowSourceError, write_immutablefrom .follow_image_dims import positive_dimsfrom .follow_sources import (FollowCandidate, Rule34VideoConnector, SourceFetch, canonical_source_ref,- official_profile_handle, profile_link_identity,+ official_profile_handle, origin_group_key, profile_link_identity,)from .follow_variants import classify, group_duplicates@@ -107,6 +107,7 @@ _OFFICIAL_IDENTITY_PROVIDERS = follow_providers.official_identity_providers()#: 每个条目都是一次独立发布的来源。论坛线程的标题只是容器名,同一线程里每个带#: 资源的楼层各自成组;这条口径登记在 `follow_providers`,不在这里点名站点。_RELEASE_KEY_PER_POST = follow_providers.release_key_per_post()+_SEQUENTIAL_UPLOADS = follow_providers.sequential_upload_providers()#: 完整候选(列表 + 详情都取到了)更新已有行时用的 SET 子句。_FULL_UPDATE = (@@ -698,7 +699,8 @@ class FollowStore:先按来源自带的 `group_hint` 合并(booru 的 `parent_id` 比标题可靠),再按标题推出的 `release_key` 合并,最后同一组里选主条目。booru 上没有标题也- 没有出处的帖子,按角色、上传时间与标签重合度认出同一作品的连发(ADR-0044)。+ 没有出处的帖子,按角色、上传时间与标签重合度认出同一作品的连发(ADR-0044);+ 站内 id 连号上传的同一批短片按角色认成一包(ADR-0045)。`authors` 把来源 id 映射到(作者键, 这位作者的全部名字写法)。给了它,标题里夹着的作者名在分组前剥掉,相似标题的版本也跨同一作者的各个来源去对。@@ -713,12 +715,13 @@ class FollowStore:if item.provider in _RELEASE_KEY_PER_POSTand not item.release_key.endswith(f"\u0000{item.external_id}")else item- for item in items+ for item in map(_with_origin_hint, items))stripped = _strip_author_names(split_posts, authors or {})linked = _hint_linked(stripped)- aligned = _align_by_group_hint(_align_tag_bursts(_align_title_families(- _split_ambiguous_works(stripped, linked), authors), linked))+ aligned = _align_by_group_hint(_align_upload_packs(_align_tag_bursts(+ _align_title_families(_split_ambiguous_works(stripped, linked), authors),+ linked)))primaries = group_duplicates(aligned)buckets: dict[int, tuple[FollowItemRow, list[FollowItemRow]]] = {}for item, primary in zip(aligned, primaries):@@ -1349,6 +1352,99 @@ def _overlap(left: frozenset[str], right: frozenset[str]) -> float:return len(left & right) / len(union) if union else 0.0+#: 一包短片的边界:相邻两条站内 id 至多差多少、时长至多差几秒,以及标题开头的+#: 角色名至多几个词。+_PACK_ID_GAP = 30+_PACK_DURATION_SLACK = 1.0+_PACK_NAME_MAX_WORDS = 3+_PACK_NAME_SEPARATOR_RE = re.compile(r"\s+[-–—|:]\s+|[-–—]|[\[(『【|:]")+_PACK_LEADING_ARTICLES = frozenset({"the", "a", "an"})+_PACK_CHARACTER_TAG_RE = re.compile(r"\S.*\s\(.+\)$")+++def _pack_name(title: str) -> str:+ """标题开头的角色名:`Angel-handjob` 是 `angel`,`Barney's Mom - Paizuri` 是+ `barney's mom`,`Luna Doggy` 是 `luna`。含数字的词(日期、序号)不算名字。"""+ def words(text: str) -> list[str]:+ cleaned = (word.strip(".,!?&\"'’").lower() for word in text.split()+ if not any(char.isdigit() for char in word))+ return [word for word in cleaned if word]++ match = _PACK_NAME_SEPARATOR_RE.search(title or "")+ head = words(title[:match.start()]) if match else []+ if 1 <= len(head) <= _PACK_NAME_MAX_WORDS:+ return " ".join(head)+ rest = [word for word in words(title or "") if word not in _PACK_LEADING_ARTICLES]+ return rest[0] if rest else ""+++def _align_upload_packs(items: tuple[FollowItemRow, ...]) -> tuple[FollowItemRow, ...]:+ """站内 id 连号上传的同一批短片、同一个角色的几条归到一个键下。++ rule34video 的视频 id 是全站递增的上传序号。LazyProcrastinator 把一段 KOF 沙滩+ 动画导出成 7 条 20 秒的短片连着传(`Angel-handjob`、`Mai-blowjob` ……),id 只差+ 4 到 20,标题各不相同,站点也不给出处。只看连号太宽:有人一口气补传几十部旧作,+ id 同样连着。所以五个条件同时成立才归组:同一来源;标题开头的角色名相同+ (Angel 与 Mai 是两组);按 id 排开相邻两条相差不超过 `_PACK_ID_GAP`;时长相差不超过+ `_PACK_DURATION_SLACK` 秒(同一个工程导出的一批长度一样);作品分类有交集。两条都带+ `名字 (作品)` 形式的角色标签却对不上时也拆开。++ 归组按键合并:一条并进来,和它同键的别站副本也一起跟过来。+ """+ buckets: dict[tuple[int, str], list[tuple[int, FollowItemRow, frozenset[str],+ frozenset[str]]]] = {}+ for item in items:+ if (item.provider not in _SEQUENTIAL_UPLOADS or not item.release_key+ or not str(item.external_id).isdigit() or not item.duration):+ continue+ name = _pack_name(item.title)+ tag_types = (item.metadata or {}).get("tag_types")+ if not name or not isinstance(tag_types, dict):+ continue+ works = frozenset(tag for tag, kind in tag_types.items() if kind == "copyright")+ # 角色在 rule34video 上归 general;artist 类里的 `Chloeangelva (VA)` 是配音演员。+ characters = frozenset(tag.lower() for tag, kind in tag_types.items()+ if kind == "general" and _PACK_CHARACTER_TAG_RE.fullmatch(tag))+ buckets.setdefault((item.source_id, name), []).append(+ (int(item.external_id), item, works, characters))+ parent: dict[str, str] = {}++ def root(key: str) -> str:+ while parent.get(key, key) != key:+ key = parent[key]+ return key++ for members in buckets.values():+ members.sort(key=lambda entry: entry[0])+ for previous, current in zip(members, members[1:]):+ if (current[0] - previous[0] <= _PACK_ID_GAP+ and abs(current[1].duration - previous[1].duration) <= _PACK_DURATION_SLACK+ and current[2] & previous[2]+ and not (current[3] and previous[3] and not current[3] & previous[3])):+ left, right = root(previous[1].release_key), root(current[1].release_key)+ if left != right:+ parent[max(left, right)] = min(left, right)+ if not parent:+ return items+ return tuple(+ FollowItemRow(**{**item.__dict__, "release_key": root(item.release_key)})+ if item.release_key and root(item.release_key) != item.release_key else item+ for item in items+ )+++def _with_origin_hint(item: FollowItemRow) -> FollowItemRow:+ """按条目记下的出处重算 `group_hint`。++ 落库的 `group_hint` 是抓取那一刻按出处算的。读时按当前的 `origin_group_key` 重算,+ 归一规则认出的新写法(例如缺协议头的 `x.com/…`)不必重抓就能生效。+ """+ origin = origin_group_key((item.metadata or {}).get("source"))+ if origin is None or origin == item.group_hint:+ return item+ return FollowItemRow(**{**item.__dict__, "group_hint": origin})++def _align_by_group_hint(items: tuple[FollowItemRow, ...]) -> tuple[FollowItemRow, ...]:"""让来源声明为同组的条目共用一个 `release_key`。diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex 8dce651f5..d86ea2512 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -1765,6 +1765,13 @@ class OriginGroupKeyTests(unittest.TestCase):self.assertEqual(origin_group_key("https://lazyprocrast.fanbox.cc/posts/12304831"),origin_group_key("https://www.fanbox.cc/@lazyprocrast/posts/12304831"))+ def test_a_source_without_a_scheme_still_normalizes(self):+ # rule34.xxx 实测:同一条推文,一帖写 `https://x.com/…`,另一帖只写 `x.com/…`。+ self.assertEqual(origin_group_key("x.com/vileclipse/status/2101310844021928089"),+ "x:2101310844021928089")+ self.assertEqual(origin_group_key("lazyprocrast.fanbox.cc/posts/12304831"),+ origin_group_key("https://www.fanbox.cc/@lazyprocrast/posts/12304831"))+def test_known_platforms_get_their_own_prefix(self):self.assertEqual(origin_group_key("https://x.com/a/status/20861277667730761"),"x:20861277667730761")diff --git a/tests/test_follow_store.py b/tests/test_follow_store.pyindex 827aced4e..e4a8a1955 100644--- a/tests/test_follow_store.py+++ b/tests/test_follow_store.py@@ -3,6 +3,7 @@ import jsonimport sqlite3import tempfileimport unittest+from dataclasses import replacefrom datetime import datetime, timedelta, timezonefrom pathlib import Path@@ -478,6 +479,57 @@ class GroupingTests(_StoreCase):self._booru_post("2", 1, source="https://www.fanbox.cc/@lazy/posts/1"))self.assertEqual(len(groups), 2)+ def test_a_stored_hint_is_recomputed_from_the_recorded_source(self):+ # 落库时缺协议头的出处没认出来,键退回了帖子自己的 id;读时按出处重算后并组。+ stale = self._booru_post("2", 1, character="ahri",+ source="x.com/vileclipse/status/2101310844021928089")+ groups = self._record_booru(+ self._booru_post("1", 0, source="https://x.com/vileclipse/status/2101310844021928089"),+ replace(stale, group_hint="rule34xxx:post:2"))+ self.assertEqual(len(groups), 1)++ def _clip(self, video_id, title, *, duration=20.0, character="angel (kof)",+ work="King of Fighters", **extra_tags):+ tag_types = {"beach": "general", character: "general", work: "copyright",+ "LazyProcrastinator": "artist", **extra_tags}+ return FollowCandidate(provider="rule34video", external_id=str(video_id),+ title=title, duration=duration,+ extra={"tag_types": tag_types})++ def _record_clips(self, *clips):+ source_id = self._source(provider="rule34video", ref="lazyprocrastinator")+ self.store.record(source_id, _fetch(clips), moment=MOMENT)+ return sorted(sorted(m.title for m in (g.primary, *g.variants, *g.duplicates))+ for g in self.store.group(self.store.items()))++ def test_a_batch_of_clips_folds_per_character(self):+ # 同一段 KOF 动画导出成几条 20 秒短片连着传;Angel 与 Mai 是两个角色,分成两组。+ mai = "mai shiranui (dead or alive)"+ groups = self._record_clips(+ self._clip(4608755, "Angel-riding hugging"), self._clip(4608759, "Angel-missionary"),+ self._clip(4608779, "Angel-handjob"), self._clip(4608787, "Mai-blowjob", character=mai),+ self._clip(4608795, "Mai-doggy", character=mai))+ self.assertEqual(groups, [["Angel-handjob", "Angel-missionary", "Angel-riding hugging"],+ ["Mai-blowjob", "Mai-doggy"]])++ def test_clips_far_apart_or_of_another_length_stay_apart(self):+ groups = self._record_clips(+ self._clip(4608755, "Angel-riding hugging"), self._clip(4609755, "Angel-missionary"),+ self._clip(4609759, "Angel-handjob", duration=45.0))+ self.assertEqual(len(groups), 3)++ def test_a_series_title_does_not_fold_different_characters(self):+ # 标题开头是系列名,角色在后半截;带括号的角色标签对不上就拆开。配音演员+ # `Chloeangelva (VA)` 两边都有,但它归 artist,不算角色。+ groups = self._record_clips(+ self._clip(4454645, "Summer Fantasy – Cindy & Lunafreya", duration=97.0,+ character="cindy aurum (final fantasy)", work="Final Fantasy",+ **{"Chloeangelva (VA)": "artist"}),+ self._clip(4454649, "Summer Fantasy – Tifa & Aerith", duration=97.0,+ character="tifa lockhart (final fantasy)", work="Final Fantasy",+ **{"Chloeangelva (VA)": "artist"}))+ self.assertEqual(len(groups), 2)+def test_wip_is_surfaced_on_the_group(self):source_id = self._source()self.store.record(source_id, _fetch([