Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(follow): 跨作者合集只数画面作者,阈值收到 3

longmeidaodf205805eb48
diff --git a/docs/OPERATIONS.md b/docs/OPERATIONS.md
index a2b3d3ed6..a5311db7a 100644
--- a/docs/OPERATIONS.md
+++ b/docs/OPERATIONS.md
@@ -246,6 +246,7 @@ curl -s --noproxy '*' -o /dev/null -w '%{http_code}\n' https://peach.local/healt
- 备份自带保留:`ledger.pre-*.db` 由 `peach.ledger_backups` 按「最近 5 份、24 小时内、比 `ledger.db` 更新」三类全留、其余连同 `-wal`/`-shm` 清退;Windows 托盘每次启动自动执行,`scripts/prune_ledger_backups.py` 手动跑缺省只列计划、`--apply` 才删,账本 `integrity_check` 不是 ok 时拒绝清退并以退出码 2 报出。每份备份一百多 MB,5 天不清就是 7 GB。
- 已应用的迁移文件不得修改,任何后续变更必须新增版本:`0007` 曾在应用后被改写格式导致校验和漂移,只能用迁移前备份重放、逐条比对差异为 0 后才校正 `schema_migration`。
- 导入运维脚本不得触发文件、网络或数据库副作用;`scrape_codes.py` 默认写可续跑复核 CSV,`clean_names.py` 先预览,`--apply` 必须同时给出 `--backup <路径>`,备份落盘后当场校验完整性(`peach.scripting.open_for_write`)。
+- 追更的合集判据只作用于新抓到的候选,收紧阈值后跑 `scripts/prune_follow_compilations.py` 扫存量:缺省只列清单并落一份复核 CSV,`--apply` 先备份成 `ledger.pre-follow-compilations-*.db` 再删,已保存成 asset 的条目一律不动。没探过详情页的旧行拿不到署名,判据数不到它们。
- 文件名只按 ledger 已确认的番号规范化,不从名称重新猜番号;大小写单改走同目录临时名,去广告后撞名用 `(2)` 起的后缀保留两份媒体。
- `generated/cover-fetch-log.csv` 是来源、尺寸和结果证据,不随图片清理;图片丢失时用 `scripts/fetch_jav_covers.py --restore-successes` 按成功记录的原 URL 恢复并原子替换,失败保留为失败,不拿缩略图冒充封面。
- 封面候选必须限定在当前作品的主封面节点:作品页混有数百张关联作品、剧照和演员头像,禁止对整页图片 URL 逐张量尺寸。
diff --git a/docs/reference-snapshots/rule34-follow-tags-and-collections.md b/docs/reference-snapshots/rule34-follow-tags-and-collections.md
index b30126fbe..b72bafe65 100644
--- a/docs/reference-snapshots/rule34-follow-tags-and-collections.md
+++ b/docs/reference-snapshots/rule34-follow-tags-and-collections.md
@@ -1,8 +1,8 @@
-# Rule34 追更标签与超大合集证据
+# Rule34 追更标签与跨作者合集证据
-- 取证日期:2026-08-27
+- 取证日期:2026-08-27(选择器与字段)、2026-09-08(署名里的角色标注与阈值)
- 取证通道:Python HTTPX 直接读取公开 HTML/CSS;浏览器加载详情页 45 秒超时,视觉与实时 DOM 为**未取得**。
-- 用途:Rule34Video 详情补全、超大跨作者合集排除、关注页标签类型配色。
+- 用途:Rule34Video 详情补全、跨作者合集排除、关注页标签类型配色。
## Rule34Video 详情页
@@ -22,9 +22,28 @@ URL:`https://rule34video.com/video/4533145/…/`
| 作品分类 | `a.video_meta_pill[href*="/categories/"]`,本页 3 个 |
| 署名作者 | `a.video_meta_pill[href*="/models/"]`,本页 54 位 |
-同一作者页抽取的 8 个普通作品均只有 1 位署名作者,内容标签为 3–11 个。因此 Peach 以
-`model_count > 20` 识别超大跨作者合集;详情取不到时保留候选,不用一次网络失败删更新。
-已有的 4533145 行只在读取时隐藏,不删除 ledger。
+同一作者页抽取的 8 个普通作品均只有 1 位署名作者,内容标签为 3–11 个。
+
+### 署名里的角色标注(2026-09-08)
+
+站点把配音与音效记在同一份 `Artist` 名单里,角色写在名字末尾的括号中:
+`Oolay-Tiger (VA)`、`HentAudio (Audio)`、`Huntress___ (Audio/SFX)`、
+`Squish The Succubus (sound)`。当日抓取的 16 个详情页与库内 623 条记录中,
+后缀出现 `va` 126 次、`audio` 54 次、`sound` 5 次、`audio/sfx` 3 次、`voice` 1 次。
+
+判跨作者打包只数剔掉这些角色之后的画面作者,阈值 `> 3`:
+
+| 条目 | 名单 | 画面作者 |
+| --- | --- | --- |
+| `Yunara Showing Ahri Some Discipline` | 5 | 1 |
+| `The Rite of Loss` | 6 | 1 |
+| `Max Feetfuck [Regina3D]` | 4 | 2 |
+| `Fuck Track / Futa PMV` | 13 | 13 |
+| `ON AND ON \| HMV / PMV` | 17 | 17 |
+
+同一批 623 条里超过阈值的共 12 条。`Uploaded by` 不是判据:抽样 16 条无一由署名
+作者本人上传,站内几乎全是搬运号。详情取不到时保留候选,不用一次网络失败删更新。
+4533145 没探过详情页、拿不到署名,它单独按 id 在读取时隐藏。
## Rule34.xxx 标签类型
diff --git a/docs/reference-sources.json b/docs/reference-sources.json
index a9bfcb4b1..ad24aabe4 100644
--- a/docs/reference-sources.json
+++ b/docs/reference-sources.json
@@ -68,9 +68,9 @@
"name": "Rule34 标签类型与 Rule34Video 合集证据",
"url": "https://rule34.xxx/css/desktop.css?46",
"snapshot": "docs/reference-snapshots/rule34-follow-tags-and-collections.md",
- "checked_on": "2026-09-01",
- "sha256": "3761d28313ca7970c31fbb1c56f469adcaf3d762b5205ad32d3c82a4517defa6",
- "role": "关注页标签类型配色、Rule34Video 内容标签补全与超大跨作者合集排除证据。",
+ "checked_on": "2026-09-08",
+ "sha256": "ecb09c351d934ac18f1cb8f335d4e20102a3e4f57a7922c58e157b8cc8f70197",
+ "role": "关注页标签类型配色、Rule34Video 内容标签补全与跨作者合集排除证据。",
"consumers": [
"src/peach/follow_sources.py",
"src/peach/web_follow.py",
diff --git a/scripts/prune_follow_compilations.py b/scripts/prune_follow_compilations.py
new file mode 100644
index 000000000..3bc2a969c
--- /dev/null
+++ b/scripts/prune_follow_compilations.py
@@ -0,0 +1,74 @@
+"""清退已入库的跨作者合集条目。默认只列清单,`--apply` 才删。
+
+抓取那一侧按画面作者数拦截新候选(`Rule34VideoConnector.MAX_COLLECTION_MODELS`),
+判据收紧之前入库的行还在库里,这个脚本按同一个判据扫一遍存量。删除不可逆,
+`--apply` 先把账本备份成 `ledger.pre-follow-compilations-<时间戳>.db`,
+清单同时落盘成 CSV 复核产物。已经保存成 asset 的条目一律不动。
+"""
+from __future__ import annotations
+
+import argparse
+import json
+import sqlite3
+import sys
+from datetime import datetime, timezone
+from pathlib import Path
+
+sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
+
+from peach.config import DATABASE_PATH, GENERATED_DIR # noqa: E402
+from peach.follow_store import FollowStore # noqa: E402
+from peach.migrations import sqlite_backup # noqa: E402
+from peach.review_csv import write_rows # noqa: E402
+
+FIELDS = ("item_id", "external_id", "source_ref", "status", "credited", "visual", "title")
+
+
+def main(argv: list[str] | None = None) -> int:
+ parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
+ parser.add_argument("--db", type=Path, default=DATABASE_PATH, help="当前账本路径")
+ parser.add_argument("--review", type=Path, help="复核 CSV 的落盘位置")
+ parser.add_argument("--apply", action="store_true", help="真的删除;缺省只列清单")
+ parser.add_argument("--json", action="store_true", help="机器可读输出")
+ args = parser.parse_args(argv)
+
+ db = args.db.resolve()
+ stamp = datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S")
+ connection = sqlite3.connect(db)
+ try:
+ rows = FollowStore(lambda: connection).collected_compilations()
+ review = args.review or GENERATED_DIR / f"follow-compilations-{stamp}.csv"
+ write_rows(review, FIELDS,
+ [{field: getattr(row, field) for field in FIELDS} for row in rows])
+ backup = None
+ if args.apply and rows:
+ connection.close()
+ backup = db.with_name(f"{db.stem}.pre-follow-compilations-{stamp}{db.suffix}")
+ sqlite_backup(db, backup)
+ connection = sqlite3.connect(db)
+ store = FollowStore(lambda: connection)
+ with connection:
+ removed = store.purge_compilations(rows, confirm=True)
+ else:
+ removed = 0
+ finally:
+ connection.close()
+
+ if args.json:
+ print(json.dumps({
+ "db": str(db), "found": len(rows), "removed": removed,
+ "backup": str(backup) if backup else None, "review": str(review),
+ }, ensure_ascii=False, indent=2))
+ else:
+ for row in rows:
+ print(f"{row.visual:>2} 位画面作者(名单 {row.credited:>2} 位)"
+ f" {row.source_ref} {row.title[:52]}")
+ verb = "已删除" if args.apply else "将删除"
+ print(f"{verb} {len(rows)} 条,复核清单 {review}")
+ if backup:
+ print(f"账本备份 {backup}")
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/src/peach/follow_providers.py b/src/peach/follow_providers.py
index dd4ded458..eca64b505 100644
--- a/src/peach/follow_providers.py
+++ b/src/peach/follow_providers.py
@@ -83,8 +83,8 @@ PROVIDERS: dict[str, ProviderSpec] = {
hosts=("coomer.st",), url_hosts=("coomer.st",),
priority=20, backfill=True),
# 标签/模特站。
- # `excluded_external_ids` 是用户明确点名的那个既有超大合集。连接器现在按
- # 详情页署名作者数拦截同类条目;这一条只让已经入库的旧候选立即从浏览面消失。
+ # `excluded_external_ids` 是用户明确点名的那条,它没探过详情页、拿不到署名。
+ # 同类条目由连接器按详情页的画面作者数拦截;这一条只管让它从浏览面消失。
ProviderSpec("rule34video", "Rule34Video",
source_url="https://rule34video.com/models/{ref}/",
# 正片不在站内:详情页给的 `/get_file/…` 会 302 到 `*.boomio-cdn.com`
diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.py
index 2fd8aab21..3c2408ea9 100644
--- a/src/peach/follow_sources.py
+++ b/src/peach/follow_sources.py
@@ -159,7 +159,7 @@ class SourceFetch:
#: 这次抓取里被判为「不是 release」而丢掉的条数。必须报出来:用户看到的条目数
#: 比站点上少的时候,他得能分清少的是被过滤掉的,还是根本没抓到。
skipped: int = 0
- #: `skipped` 里有多少条是来源详情确认的超大跨作者合集。单列出来让界面能说清
+ #: `skipped` 里有多少条是来源详情确认的跨作者合集。单列出来让界面能说清
#: 「主动不收」而不是把它误报成「没有资源」。
skipped_compilations: int = 0
#: 列表判不出来、额外抓了详情页的条数。这是唯一会放大请求数的路径,
@@ -959,9 +959,13 @@ class Rule34VideoConnector(_BaseConnector):
HISTORY_END_STATUSES = (404,)
_SLUG_RE = re.compile(r"^[a-z0-9][a-z0-9_\-]{0,80}$")
_VIDEO_RE = re.compile(r"^https://rule34video\.com/video/(\d+)/")
- #: 详情页的署名作者通常只有 1 位;用户给出的超大合集实测有 54 位。20 以上只会
- #: 排除这种跨作者打包,不影响普通合作作品。
- MAX_COLLECTION_MODELS = 20
+ #: 站点把配音和音效也记在同一份 Artist 名单里,角色写在名字末尾的括号中
+ #: (`Oolay-Tiger (VA)`、`HentAudio (Audio)`、`Huntress___ (Audio/SFX)`)。
+ #: 判跨作者打包只数画面作者:2026-09-08 复核库内 623 条,普通作品剔掉配音后
+ #: 剩 1 到 2 位,PMV 与合辑剩 7 到 17 位,超过 3 位的一共 12 条。
+ _CREDIT_ROLE_RE = re.compile(
+ r"\((?:va|audio|audio/sfx|sfx|sound|voice|music)\)\s*$", re.IGNORECASE)
+ MAX_COLLECTION_MODELS = 3
DEFAULT_MAX_PROBES = 24
@classmethod
@@ -1025,8 +1029,8 @@ class Rule34VideoConnector(_BaseConnector):
if probed < self.max_probes and candidate.url:
probed += 1
enriched = self._probe_detail(candidate)
- model_count = int(enriched.extra.get("model_count") or 0)
- if model_count > self.max_collection_models:
+ visual = int(enriched.extra.get("visual_model_count") or 0)
+ if visual > self.max_collection_models:
skipped_compilations += 1
continue
candidates.append(enriched)
@@ -1093,8 +1097,8 @@ class Rule34VideoConnector(_BaseConnector):
extra=extra,
)
- @staticmethod
- def _detail(body: bytes) -> dict[str, object]:
+ @classmethod
+ def _detail(cls, body: bytes) -> dict[str, object]:
soup = BeautifulSoup(body, "html.parser")
video = {}
for node in soup.find_all("script", attrs={"type": "application/ld+json"}):
@@ -1114,6 +1118,8 @@ class Rule34VideoConnector(_BaseConnector):
tags = list(dict.fromkeys(value for value in tags if value))
categories = list(dict.fromkeys(value for value in categories if value))
models = list(dict.fromkeys(value for value in models if value))
+ visual_models = [value for value in models
+ if not cls._CREDIT_ROLE_RE.search(value)]
if not video and not tags and not categories and not models:
return {}
tag_types = {tag: "general" for tag in tags}
@@ -1138,6 +1144,7 @@ class Rule34VideoConnector(_BaseConnector):
"categories": categories,
"models": models,
"model_count": len(models),
+ "visual_model_count": len(visual_models),
"tag_types": tag_types,
},
}
diff --git a/src/peach/follow_store.py b/src/peach/follow_store.py
index 2e4d2ee72..887154582 100644
--- a/src/peach/follow_store.py
+++ b/src/peach/follow_store.py
@@ -20,7 +20,8 @@ from pathlib import Path
from . import follow_providers
from .follow import FollowSourceError, write_immutable
from .follow_sources import (
- FollowCandidate, SourceFetch, canonical_source_ref, official_profile_handle,
+ FollowCandidate, Rule34VideoConnector, SourceFetch, canonical_source_ref,
+ official_profile_handle,
)
from .follow_variants import classify, group_duplicates
@@ -778,6 +779,68 @@ class FollowStore:
(asset_id, item_id))
return asset_id
+ # ---- 跨作者合集的存量清退 -------------------------------------------
+
+ def collected_compilations(self) -> tuple["CompilationRow", ...]:
+ """已入库、按当前判据算跨作者打包的条目。
+
+ 抓取那一侧只过滤新拿到的候选,判据收紧之前入库的行还在库里。已经保存成
+ asset 的不在结果里:那条 asset 是真相,留不留由它自己那一侧决定。
+ """
+ connection = self._connect()
+ rows = connection.execute(
+ "SELECT i.id,i.external_id,i.title,i.status,s.ref,i.metadata_json"
+ " FROM follow_item i JOIN follow_source s ON s.id=i.source_id"
+ " WHERE s.provider='rule34video' AND i.asset_id IS NULL"
+ ).fetchall()
+ found = []
+ for item_id, external_id, title, status, ref, payload in rows:
+ try:
+ credits = json.loads(payload or "{}").get("models") or []
+ except json.JSONDecodeError:
+ continue
+ visual = [name for name in credits
+ if not Rule34VideoConnector._CREDIT_ROLE_RE.search(str(name))]
+ if len(visual) <= Rule34VideoConnector.MAX_COLLECTION_MODELS:
+ continue
+ found.append(CompilationRow(
+ item_id=int(item_id), external_id=str(external_id), title=str(title),
+ status=str(status), source_ref=str(ref),
+ credited=len(credits), visual=len(visual)))
+ return tuple(sorted(found, key=lambda row: -row.visual))
+
+ def purge_compilations(self, rows, *, confirm: bool = False) -> int:
+ """删掉这些条目,连同它们的播放记录。不可逆,要显式 `confirm=True`。
+
+ 播放记录先删:`PRAGMA foreign_keys` 默认是 OFF,指望表上那条
+ `ON DELETE CASCADE` 会留下认不出主人的孤儿行。
+ """
+ if not confirm:
+ raise FollowSourceError("删 ledger 行需要显式 confirm=True")
+ connection = self._connect()
+ removed = 0
+ for row in rows:
+ connection.execute("DELETE FROM follow_playback WHERE follow_item_id=?",
+ (row.item_id,))
+ removed += connection.execute(
+ "DELETE FROM follow_item WHERE id=?", (row.item_id,)).rowcount
+ return removed
+
+
+@dataclass(frozen=True)
+class CompilationRow:
+ """一条按画面作者数判为跨作者打包的存量条目。"""
+
+ item_id: int
+ external_id: str
+ title: str
+ status: str
+ source_ref: str
+ #: 站点 Artist 名单的长度,配音和音效都算在里面。
+ credited: int
+ #: 剔掉配音与音效之后的画面作者数,判据看的是这个。
+ visual: int
+
def _medium_for(item: FollowItemRow) -> str:
if item.duration:
diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.py
index a02cf514d..4a023d104 100644
--- a/tests/test_follow_sources.py
+++ b/tests/test_follow_sources.py
@@ -881,22 +881,43 @@ class Rule34VideoConnectorTests(unittest.TestCase):
self.assertTrue(first.thumb_url.endswith("/preview.jpg"))
self.assertIn("4542721_360.mp4", first.media_url)
- def test_detail_with_many_credited_models_is_not_collected(self):
- models = "".join(
- f'<a class="item btn_link video_meta_pill" href="https://rule34video.com/models/m{n}/">M{n}</a>'
- for n in range(21)
+ def _detail_with_credits(self, names):
+ credits = "".join(
+ f'<a class="item btn_link video_meta_pill"'
+ f' href="https://rule34video.com/models/m{n}/">{name}</a>'
+ for n, name in enumerate(names)
).encode()
- detail = RULE34VIDEO_DETAIL_HTML.replace(b"</body>", models + b"</body>")
+ detail = RULE34VIDEO_DETAIL_HTML.replace(b"</body>", credits + b"</body>")
def transport(request, timeout, max_bytes):
return HttpResponse(200, {},
RULE34VIDEO_HTML if "/models/" in request.url else detail)
- result = Rule34VideoConnector(transport=transport).fetch("lazyprocrastinator")
+ return Rule34VideoConnector(transport=transport).fetch("lazyprocrastinator")
+
+ def test_detail_with_many_credited_models_is_not_collected(self):
+ # 样本自带 LazyProcrastinator 一位,这里再添三位就是四位画面作者。
+ result = self._detail_with_credits(["M1", "M2", "M3"])
self.assertEqual(result.candidates, ())
self.assertEqual(result.skipped, 2)
self.assertEqual(result.skipped_compilations, 2)
+ def test_voice_and_audio_credits_do_not_make_a_work_a_collection(self):
+ """配音和音效不算画面作者。
+
+ 站点把它们记在同一份 Artist 名单里,角色写在名字末尾的括号中。三位配音
+ 加一位音效的单人作品在名单上是五位,画面作者只有一位;数满名单会把
+ `Yunara Showing Ahri Some Discipline`、`The Rite of Loss` 这类作品
+ 误判成合辑。
+ """
+ result = self._detail_with_credits(
+ ["Adaline (VA)", "GeminiStarsign1 (VA)", "Cinderdryadva (va)",
+ "Huntress___ (Audio/SFX)", "HentAudio (Audio)"])
+ self.assertEqual(result.skipped_compilations, 0)
+ first = result.candidates[0]
+ self.assertEqual(first.extra["model_count"], 6)
+ self.assertEqual(first.extra["visual_model_count"], 1)
+
class PagingBackTests(unittest.TestCase):
"""各站往回翻的地址形状。都是 2026-08-27 实测过的端点。"""
diff --git a/tests/test_follow_store.py b/tests/test_follow_store.py
index ce5fb3a04..7e6875e10 100644
--- a/tests/test_follow_store.py
+++ b/tests/test_follow_store.py
@@ -788,5 +788,56 @@ class EnrichedMarkTests(_StoreCase):
self.store.enriched_external_ids(source_id, "whatever")
+class StoredCompilationTests(_StoreCase):
+ """判据收紧之前入库的跨作者打包,按同一判据清退。"""
+
+ def _record(self, external_id, title, models):
+ source_id = self._source()
+ self.store.record(source_id, _fetch([
+ _candidate(external_id, title, extra={"models": list(models),
+ "model_count": len(models)}),
+ ]), moment=MOMENT)
+ return self.store.items()[0]
+
+ def test_voice_and_audio_credits_keep_a_single_creator_work_out_of_the_list(self):
+ self._record("1", "Yunara Showing Ahri Some Discipline",
+ ["Iidssm", "Adaline (VA)", "GeminiStarsign1 (VA)",
+ "Huntress___ (Audio/SFX)", "HentAudio (Audio)"])
+ self.assertEqual(self.store.collected_compilations(), ())
+
+ def test_a_cross_artist_pack_is_listed_with_both_counts(self):
+ self._record("2", "Fuck Track / Futa PMV", [f"M{n}" for n in range(13)])
+ listed = self.store.collected_compilations()
+ self.assertEqual(len(listed), 1)
+ self.assertEqual((listed[0].credited, listed[0].visual), (13, 13))
+ self.assertEqual(listed[0].external_id, "2")
+
+ def test_an_item_already_saved_as_an_asset_is_left_alone(self):
+ item = self._record("3", "ON AND ON | HMV / PMV", [f"M{n}" for n in range(17)])
+ self.connection.execute("UPDATE follow_item SET url=? WHERE id=?",
+ ("https://rule34video.com/video/3/x/", item.id))
+ self.store.save_asset(item.id, confirm=True, moment=MOMENT)
+ self.assertEqual(self.store.collected_compilations(), ())
+
+ def test_purging_requires_explicit_confirmation(self):
+ self._record("4", "Resident Evil - The Fallen Saga",
+ [f"M{n}" for n in range(14)])
+ listed = self.store.collected_compilations()
+ with self.assertRaises(FollowSourceError):
+ self.store.purge_compilations(listed)
+ self.assertEqual(self.connection.execute(
+ "SELECT count(*) FROM follow_item").fetchone()[0], 1)
+
+ def test_a_confirmed_purge_takes_the_playback_rows_with_it(self):
+ item = self._record("5", "triss blacked censored", [f"M{n}" for n in range(13)])
+ self.store.record_playback(item.id)
+ listed = self.store.collected_compilations()
+ self.assertEqual(self.store.purge_compilations(listed, confirm=True), 1)
+ self.assertEqual(self.connection.execute(
+ "SELECT count(*) FROM follow_item").fetchone()[0], 0)
+ self.assertEqual(self.connection.execute(
+ "SELECT count(*) FROM follow_playback").fetchone()[0], 0)
+
+
if __name__ == "__main__":
unittest.main()