Peach: Local-first video metadata scraper and media manager.
fix: use clear covers for Rule34 sources
longmeidaoecfff8b9a3bc
diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 4989c7e2c..320bd0b6f 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -94,6 +94,7 @@| `taste_history.py` 自写 Chrome/Firefox/Zen/Safari SQLite 解析 | **已替换为 `browserexport==0.4.4`** | Python 3.14 依赖解析通过;审计 POC 在本机 7 个 Chrome/Firefox/Zen profile 上与 Peach 逐库计数完全一致,macOS 的 Safari/Zen/Firefox/Chrome 路径发现有独立测试。首个消费者是 `/taste` 的本机读取与导出导入;Peach 保留 SQLite backup、Takeout、私有原始存储、域名分析和 candidate 生成,并在 Windows 自己关闭只读连接以避开依赖的文件句柄滞留。跨主机同步不由该依赖提供,仍须显式导出、传输和按来源去重合并。 || `jobs.PidFileLock` | **优先替换为 `portalocker==4.3.0` 的 `PidFileLock`** | Python 3.14 解析通过,现成覆盖 PID 写入、锁持有者、原子替换、陈旧文件与释放清理。Peach 只保留任务归属和错误文案映射。 || Rule34Video 媒体页解析 | **部分替换为 `yt-dlp==2026.8.19`** | 对真实视频 4533145 无写入提取成功,取得 4 个格式、31 个标签、缩略图与时间。Peach 仍负责作者分页、合集/超多 model 排除、来源分组和跨站去重。 |+| Rule34.xxx / Paheal 高清封面 | **固定参考 gallery-dl `86047cf67a12bdb6ff1085774f8ad9fc347e8da9`,运行时复用现有 FFmpeg** | gallery-dl(GPL-2.0)只作协议行为证据,不引入或复制为运行时:booru URL 明确支持 `sample_url`/`preview_url`/`file_url` 回退,Paheal 抽取器只取得原始 `file_url`。真实 POC 中 Rule34.xxx 历史 preview 为 250×141、同哈希 sample 为 1920×1080;Paheal 页面只有低清 poster/og:image,原视频首帧可在约 2.3 秒生成 1280×720 JPEG。Peach 负责 URL 白名单、同源代理、按需双并发抽帧、缓存与低清失败回退,不新增依赖、不改 ledger。 || FANBOX 正文解析 | **已采用 PixivUtil2 `v20251112` / `e537e96` 的公开正文模型** | Peach 的独立规范化 DTO 已覆盖 image/text/file/article/video/entry、`fileMap`、`embedMap`、`urlEmbedMap` 和旧 HTML 正文,并保留正文顺序、稳定去重、可播放媒体与文件页边界;BSD-2-Clause 依据写在实现头部。PixivUtil2 是完整下载器而非可嵌入解析库,因此不引入整套依赖;传输继续固定 `curl_cffi==0.16.2`。真实公开帖 12228983 只读 POC 得到 article、6 图和 Gofile `OS2Qz9`。 || `mp4index.py` 有界 MP4 关键帧索引 | **保留自研** | PyAV 需要 demux,`pymp4` 依赖旧 Construct,Bento4 是额外二进制;都不能证明在云盘文件上保留“只读 moov/stss/stts、避免整片流量”的约束。 || `certs.py` 固定项目 CA 与短期叶证书 | **保留自研 policy,继续调用 OpenSSL** | mkcert 会接管本机 CA 安装/私钥,不能保持跨设备固定项目 CA;cryptography 只替换证书编码且增加原生依赖,不能删除 Peach 的 Apple 398 天与 CA 生命周期策略。 |diff --git a/src/peach/__init__.py b/src/peach/__init__.pyindex 2392673b5..5268c26ef 100644--- a/src/peach/__init__.py+++ b/src/peach/__init__.py@@ -1,3 +1,3 @@"""Peach application package."""-__version__ = "0.7.6"+__version__ = "0.7.7"diff --git a/src/peach/api.py b/src/peach/api.pyindex aa5652377..210217bb5 100644--- a/src/peach/api.py+++ b/src/peach/api.py@@ -29,6 +29,7 @@ from .ffmpeg import FFmpegResolverfrom .follow import FollowSourceErrorfrom .follow_scheduler import FollowUpdateSchedulerfrom .follow_avatar import resolve_official_avatar+from .follow_covers import FollowCoverService, FollowCoverUnavailablefrom .follow_store import FollowStorefrom .follow_stream import FollowMediaResolver, FollowMediaUnavailablefrom .http import HttpxTransport@@ -147,6 +148,8 @@ def create_app(http_transport = HttpxTransport()follow_media_resolver = FollowMediaResolver(http_transport).with_credential_loader(lambda provider: web_follow._credential_store(contract).load(provider))+ follow_cover_service = FollowCoverService(+ resolver, follow_media_resolver, settings.poster_root / "follow")filesystem = FilesystemBackend(settings.allowed_media_roots,settings.snapshot_root,@@ -233,6 +236,7 @@ def create_app(app.state.review_mirror = review_mirrorapp.state.http_transport = http_transportapp.state.follow_media_resolver = follow_media_resolver+ app.state.follow_cover_service = follow_cover_serviceapp.state.follow_scheduler = follow_schedulerstream_sessions = StreamSessionRegistry()app.state.stream_sessions = stream_sessions@@ -748,6 +752,28 @@ def create_app(body(), status_code=upstream.status_code, headers=forwarded,)+ @app.api_route("/follow-cover", methods=["GET", "HEAD"])+ def follow_cover(request: Request, id: int):+ """Return a cached clear still for a follow video; keep its URL server-side."""+ args = _first_query_values(request)+ if not _authorized(request, settings.token, args):+ return JSONResponse({"error": "unauthorized"}, status_code=401)+ with database.read_connection() as connection:+ item = FollowStore(lambda: connection).item(id)+ if item is None:+ return JSONResponse({"error": "no such follow item"}, status_code=404)+ try:+ path = request.app.state.follow_cover_service.cover(item)+ except FollowCoverUnavailable:+ # Paheal itself only has this low-resolution fallback. A temporary FFmpeg or+ # network failure should degrade to the old cover instead of leaving a hole.+ if str(item.thumb_url or "").startswith("https://"):+ return RedirectResponse(str(item.thumb_url), status_code=307)+ return JSONResponse({"error": "follow cover unavailable"}, status_code=404)+ response = FileResponse(path, media_type="image/jpeg")+ response.headers["Cache-Control"] = "public, max-age=86400"+ return response+@app.api_route("/logo", methods=["GET", "HEAD"])def logo(request: Request, studio: str = ""):args = _first_query_values(request)diff --git a/src/peach/follow_covers.py b/src/peach/follow_covers.pynew file mode 100644index 000000000..435f94aee--- /dev/null+++ b/src/peach/follow_covers.py@@ -0,0 +1,92 @@+"""Generate cached high-resolution covers for remote follow videos.++Paheal exposes the original video and a 150/250px thumbnail, but no larger still.+The card therefore extracts the first decodable frame once and serves the cached JPEG.+"""+from __future__ import annotations++import hashlib+import os+import subprocess+import threading+from pathlib import Path++from .ffmpeg import FFmpegResolver+from .follow_store import FollowItemRow+from .follow_stream import FollowMediaResolver, FollowMediaUnavailable+++class FollowCoverUnavailable(RuntimeError):+ pass+++class FollowCoverService:+ """Create a bounded, cached still without exposing the upstream media URL."""++ def __init__(self, resolver: FFmpegResolver, media_resolver: FollowMediaResolver,+ root: Path, *, timeout: float = 30.0):+ self.resolver = resolver+ self.media_resolver = media_resolver+ self.root = Path(root).resolve()+ self.timeout = timeout+ self._guard = threading.Lock()+ self._locks: dict[str, threading.Lock] = {}+ # A visible grid can ask for several lazy images together. Two workers keep the+ # first screen responsive without turning the source CDN into a batch job.+ self._slots = threading.BoundedSemaphore(2)++ def cover(self, item: FollowItemRow) -> Path:+ if (item.provider != "rule34paheal"+ or str(item.metadata.get("media_kind") or "") != "video"):+ raise FollowCoverUnavailable("该条目不需要生成视频封面")+ try:+ target = self.media_resolver.resolve(item)+ except FollowMediaUnavailable as exc:+ raise FollowCoverUnavailable(str(exc)) from exc+ choice = self.resolver.ffmpeg()+ if choice is None:+ raise FollowCoverUnavailable("ffmpeg 不可用")++ fingerprint = hashlib.sha256(target.url.encode("utf-8")).hexdigest()[:16]+ destination = self.root / f"{item.id}-{fingerprint}.jpg"+ if destination.is_file():+ return destination+ lock = self._lock_for(destination.name)+ with lock:+ if destination.is_file():+ return destination+ self.root.mkdir(parents=True, exist_ok=True)+ temporary = destination.with_name(+ f"{destination.stem}.{os.getpid()}.{threading.get_ident()}.tmp.jpg")+ command = [+ str(choice.path), "-y", "-v", "error",+ "-rw_timeout", "15000000", "-user_agent", "Peach follow cover",+ ]+ if target.referer:+ command.extend(("-referer", target.referer))+ command.extend((+ "-i", target.url, "-frames:v", "1",+ "-vf", "scale='min(1280,iw)':-2", "-update", "1",+ "-q:v", "4", str(temporary),+ ))+ try:+ with self._slots:+ result = subprocess.run(+ command, capture_output=True, timeout=self.timeout, check=False)+ if (result.returncode != 0 or not temporary.is_file()+ or temporary.stat().st_size == 0):+ raise FollowCoverUnavailable("视频封面生成失败")+ os.replace(temporary, destination)+ except (OSError, subprocess.TimeoutExpired) as exc:+ raise FollowCoverUnavailable("视频封面生成失败") from exc+ finally:+ temporary.unlink(missing_ok=True)+ # URL 变化时留下旧帧没有价值;只清理同一条目的旧缓存。+ for stale in self.root.glob(f"{item.id}-*.jpg"):+ if stale != destination:+ stale.unlink(missing_ok=True)+ return destination++ def _lock_for(self, key: str) -> threading.Lock:+ with self._guard:+ return self._locks.setdefault(key, threading.Lock())diff --git a/src/peach/follow_sources.py b/src/peach/follow_sources.pyindex 9a3870a9b..98a952ebd 100644--- a/src/peach/follow_sources.py+++ b/src/peach/follow_sources.py@@ -884,12 +884,16 @@ class Rule34XxxConnector(_BaseConnector):url=f"https://rule34.xxx/index.php?page=post&s=view&id={post_id}"if post_id else None,media_url=str(post.get("file_url")) if post.get("file_url") else None,- thumb_url=str(post.get("preview_url")) if post.get("preview_url") else None,+ # dapi 的 preview_url 只有约 250px;sample_url 对视频是同帧 JPEG,+ # 对图片则是站点选定的样图。gallery-dl 的 booru 抽取器也把这三层+ # 作为可配置回退链,不能把最小 preview 固定成 Peach 封面。+ thumb_url=str(post.get("sample_url") or post.get("preview_url") or "") or None,published_at=_iso_from_epoch(post.get("change")),group_hint=hint,title_is_name=title_is_name,extra={"tag": tag, "tags": tags, "score": post.get("score"),- "source": source, "title_from": title_from},+ "source": source, "title_from": title_from,+ "preview_url": post.get("preview_url")},)@classmethoddiff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex ca3df1e92..9dc5d4743 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -67,6 +67,9 @@ LOW_VALUE_FOLLOW_TAGS = frozenset({_IMAGE_MEDIA_RE = re.compile(r"\.(?:avif|gif|jpe?g|png|webp)(?:$|[?#])", re.I)_VIDEO_MEDIA_RE = re.compile(r"\.(?:m4v|mov|mp4|og[gv]|webm)(?:/)?(?:$|[?#])", re.I)+_RULE34XXX_PREVIEW_RE = re.compile(+ r"^https://api-cdn\.rule34\.xxx/thumbnails/(\d+)/thumbnail_"+ r"([0-9a-f]{32})\.jpg(?:[?#].*)?$", re.I)def _item_tags(item) -> list[str]:@@ -149,6 +152,21 @@ def _media_items(item) -> list[dict]:def _thumb_url(item) -> str | None:+ # rule34.xxx 的历史行存的是 250px preview。官方 dapi 的 sample_url 与它使用+ # 同一 bucket/hash;2026-08-28 对生产历史行实测推导后为 1920x1080。+ if item.provider == "rule34xxx" and item.thumb_url:+ matched = _RULE34XXX_PREVIEW_RE.match(str(item.thumb_url))+ if matched:+ return ("https://api-cdn.rule34.xxx/images/"+ f"{matched.group(1)}/{matched.group(2)}.jpg")+ # Paheal 图片直接经现有同源代理读原图;视频站点没有高清 poster,改由+ # /follow-cover 抽首帧并缓存。两条路径都不把原始媒体 URL放进公共 JSON。+ if item.provider == "rule34paheal" and item.media_url:+ kind = _media_kind(item)+ if kind == "image":+ return f"/follow-stream?id={item.id}"+ if kind == "video":+ return f"/follow-cover?id={item.id}"if item.thumb_url:return item.thumb_url# 旧的 Kemono/Pawchive 行在封面修复前已入库:media_url 是图片,但 thumb_urldiff --git a/tests/test_fastapi_api.py b/tests/test_fastapi_api.pyindex 7f814b5e8..c83a338e3 100644--- a/tests/test_fastapi_api.py+++ b/tests/test_fastapi_api.py@@ -718,6 +718,53 @@ class FastApiContractTests(unittest.IsolatedAsyncioTestCase):self.assertEqual(response.headers["content-range"], "bytes 2-5/10")self.assertNotIn("img.kemono.cr", response.text)+ async def test_follow_cover_serves_cached_frame_and_falls_back_to_source_thumb(self):+ connection = sqlite3.connect(self.db)+ connection.executescript((ROOT / "migrations" / "0018_online_follow.sql").read_text(+ encoding="utf-8"))+ connection.execute(+ "INSERT INTO follow_source(id,provider,ref,label,url,semantics,created_at,updated_at)"+ " VALUES(1,'rule34paheal','artist','Artist','https://rule34.paheal.net/u',"+ "'work','x','x')"+ )+ connection.execute(+ "INSERT INTO follow_item(id,source_id,external_id,title,url,media_url,thumb_url,"+ "release_key,metadata_json,first_seen_at,last_seen_at) VALUES(7,1,'7','Remote',"+ "'https://rule34.paheal.net/post/view/7',"+ "'https://r34i.paheal-cdn.net/ab/cd/video',"+ "'https://r34t.paheal.net/ab/cd/video','remote',"+ "'{\"media_kind\":\"video\"}','x','x')"+ )+ connection.commit()+ connection.close()+ frame = self.root / "clear.jpg"+ frame.write_bytes(b"clear-jpeg")++ class Cover:+ def __init__(self):+ self.fail = False++ def cover(self, _item):+ if self.fail:+ from peach.follow_covers import FollowCoverUnavailable+ raise FollowCoverUnavailable("test")+ return frame++ cover = Cover()+ self.app.state.follow_cover_service = cover+ denied = await self.client.get("/follow-cover?id=7")+ response = await self.client.get("/follow-cover?id=7&t=secret")+ self.assertEqual(denied.status_code, 401)+ self.assertEqual(response.status_code, 200)+ self.assertEqual(response.content, b"clear-jpeg")+ self.assertEqual(response.headers["cache-control"], "public, max-age=86400")+ cover.fail = True+ fallback = await self.client.get(+ "/follow-cover?id=7&t=secret", follow_redirects=False)+ self.assertEqual(fallback.status_code, 307)+ self.assertEqual(fallback.headers["location"],+ "https://r34t.paheal.net/ab/cd/video")+async def test_stream_session_cancel_is_authenticated_and_tombstoned(self):denied = await self.client.post("/api/stream-cancel?session=detail-1")self.assertEqual(denied.status_code, 401)diff --git a/tests/test_follow_covers.py b/tests/test_follow_covers.pynew file mode 100644index 000000000..d434f9f2b--- /dev/null+++ b/tests/test_follow_covers.py@@ -0,0 +1,64 @@+import subprocess+import tempfile+import unittest+from pathlib import Path+from types import SimpleNamespace+from unittest import mock++from peach.ffmpeg import BinaryChoice+from peach.follow_covers import FollowCoverService, FollowCoverUnavailable+from peach.follow_stream import ResolvedFollowMedia+++class _FFmpeg:+ def ffmpeg(self):+ return BinaryChoice(Path("ffmpeg"), "test")+++class _Media:+ def __init__(self):+ self.calls = 0++ def resolve(self, item):+ self.calls += 1+ return ResolvedFollowMedia(+ "https://r34i.paheal-cdn.net/ab/cd/video", item.url)+++class FollowCoverServiceTests(unittest.TestCase):+ def setUp(self):+ self.temporary = tempfile.TemporaryDirectory()+ self.addCleanup(self.temporary.cleanup)+ self.root = Path(self.temporary.name)+ self.media = _Media()+ self.service = FollowCoverService(_FFmpeg(), self.media, self.root)++ @staticmethod+ def _item(provider="rule34paheal", kind="video"):+ return SimpleNamespace(+ id=7, provider=provider, metadata={"media_kind": kind},+ url="https://rule34.paheal.net/post/view/7")++ def test_first_frame_is_generated_once_and_cached(self):+ commands = []++ def run(command, **kwargs):+ commands.append(command)+ Path(command[-1]).write_bytes(b"jpeg")+ return subprocess.CompletedProcess(command, 0, b"", b"")++ with mock.patch("peach.follow_covers.subprocess.run", side_effect=run):+ first = self.service.cover(self._item())+ second = self.service.cover(self._item())+ self.assertEqual(first, second)+ self.assertEqual(first.read_bytes(), b"jpeg")+ self.assertEqual(len(commands), 1)+ self.assertIn("-frames:v", commands[0])+ self.assertIn("scale='min(1280,iw)':-2", commands[0])++ def test_only_paheal_videos_enter_the_generator(self):+ for provider, kind in (("rule34xxx", "video"),+ ("rule34paheal", "image")):+ with self.subTest(provider=provider, kind=kind):+ with self.assertRaises(FollowCoverUnavailable):+ self.service.cover(self._item(provider, kind))diff --git a/tests/test_follow_sources.py b/tests/test_follow_sources.pyindex 8d1a4dc26..379d67786 100644--- a/tests/test_follow_sources.py+++ b/tests/test_follow_sources.py@@ -305,6 +305,7 @@ RULE34XXX_JSON = json.dumps([{"id": 18534395, "image": "3df1cbc67e072d6144588d6c80e490ea.mp4", "parent_id": 0,"tags": "lazyprocrastinator fiona blush video sound", "change": 1787445373,"file_url": "https://api-cdn-mp4.rule34.xxx/images/1232/3df1.mp4",+ "sample_url": "https://api-cdn.rule34.xxx/images/1232/3df1.jpg","preview_url": "https://api-cdn.rule34.xxx/thumbnails/1232/t_3df1.jpg","score": 72, "source": "https://lazyprocrast.fanbox.cc/posts/12304831"},{"id": 18534396, "image": "3bda1572c365b223d8b287c538a38956.mp4", "parent_id": 0,@@ -883,6 +884,14 @@ class Rule34XxxConnectorTests(unittest.TestCase):self.assertIn("fiona", first.title)self.assertEqual(first.published_at, "2026-08-23T00:36:13Z")+ def test_sample_image_is_preferred_over_the_small_preview(self):+ first = self._connector().fetch("lazyprocrastinator").candidates[0]+ self.assertEqual(+ first.thumb_url, "https://api-cdn.rule34.xxx/images/1232/3df1.jpg")+ self.assertEqual(+ first.extra["preview_url"],+ "https://api-cdn.rule34.xxx/thumbnails/1232/t_3df1.jpg")+def test_a_readable_filename_is_still_preferred_and_counts_as_a_name(self):last = self._connector().fetch("lazyprocrastinator").candidates[3]self.assertEqual(last.title, "fiona paizuri nude")diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 677f23490..f0da5eb07 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -253,6 +253,43 @@ class FollowContractTests(unittest.TestCase):self.assertEqual(item["media_kind"], "image")self.assertTrue(item["playable"])+ def test_old_rule34xxx_previews_are_upgraded_without_rewriting_the_ledger(self):+ self._seed(candidates=(FollowCandidate(+ provider="rule34xxx", external_id="1", title="Remote video",+ url="https://rule34.xxx/index.php?page=post&s=view&id=1",+ media_url="https://api-cdn-mp4.rule34.xxx/images/42/"+ "0123456789abcdef0123456789abcdef.mp4",+ thumb_url="https://api-cdn.rule34.xxx/thumbnails/42/"+ "thumbnail_0123456789abcdef0123456789abcdef.jpg",+ extra={"media_kind": "video"},+ ),), provider="rule34xxx", ref="artist")+ item = self._get()["groups"][0]["primary"]+ self.assertEqual(+ item["thumb_url"],+ "https://api-cdn.rule34.xxx/images/42/"+ "0123456789abcdef0123456789abcdef.jpg")++ def test_paheal_cards_use_same_origin_clear_cover_routes(self):+ self._seed(candidates=(+ FollowCandidate(+ provider="rule34paheal", external_id="video", title="Video",+ media_url="https://r34i.paheal-cdn.net/ab/cd/video",+ thumb_url="https://r34t.paheal.net/ab/cd/video",+ extra={"media_kind": "video"}),+ FollowCandidate(+ provider="rule34paheal", external_id="image", title="Image",+ media_url="https://r34i.paheal-cdn.net/ab/cd/image",+ thumb_url="https://r34t.paheal.net/ab/cd/image",+ extra={"media_kind": "image"}),+ ), provider="rule34paheal", ref="artist")+ items = {group["primary"]["external_id"]: group["primary"]+ for group in self._get()["groups"]}+ self.assertEqual(items["video"]["thumb_url"],+ f"/follow-cover?id={items['video']['id']}")+ self.assertEqual(items["image"]["thumb_url"],+ f"/follow-stream?id={items['image']['id']}")+ self.assertNotIn("r34i.paheal-cdn.net", json.dumps(items))+def test_named_large_collection_is_hidden_but_not_deleted(self):self._seed(candidates=(FollowCandidate(provider="rule34video", external_id="4533145", title="Large collection",