Peach: Local-first video metadata scraper and media manager.
fix(follow): 封面先查盘再分组,poster 失败短时记住
longmeidao4093bdc01634
diff --git a/src/peach/follow_covers.py b/src/peach/follow_covers.pyindex 2f3648f5e..3dc1486bc 100644--- a/src/peach/follow_covers.py+++ b/src/peach/follow_covers.py@@ -13,6 +13,7 @@ import osimport subprocessimport threadingimport time+from collections.abc import Callable, Iterablefrom pathlib import Pathimport httpx@@ -82,13 +83,20 @@ class FollowCoverService:# 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)+ # poster 只是几张静态小图的 GET,另占一组槽:上游删了片、8 个地址挨个超时的+ # 那几张卡,不该把 fanbox 和 paheal 的抽帧也堵在后面。+ self._poster_slots = threading.BoundedSemaphore(4)+ self._poster_misses: dict[str, float] = {}def cover(self, item: FollowItemRow, media: int | None = None, *,- alternatives: tuple[str, ...] = ()) -> Path:+ alternatives: Callable[[], Iterable[str]] | Iterable[str] = ()) -> Path:"""条目的视频封面;`media` 点名 fanbox 帖子里的某一个视频,缺省是第一个。卡面要的是第一个视频,详情里的多媒体清单每个视频各要一张。第一个视频不论是否点名都落在同一份缓存上,卡面和清单里那一格共用一次抽帧。++ `alternatives` 是同一作品其他版本的 poster 地址,只有 rule34video 用;给可调用+ 对象时只在磁盘缓存未命中后才调用,命中的请求不碰账本。"""if item.provider == "rule34video" and media is None:return self._poster(item, alternatives)@@ -162,49 +170,100 @@ class FollowCoverService:stale.unlink(missing_ok=True)return destination- def _poster(self, item: FollowItemRow, alternatives: tuple[str, ...]) -> Path:- """缓存来源 poster;失效时取同一作品其他版本的封面,只请求静态图片。"""- urls = tuple(url for url in dict.fromkeys((item.thumb_url or "", *alternatives))+ #: 一组 poster 地址全部取不到后,多久内不再重试。上游删片是长期状态,这里只挡住+ #: 同一屏每次渲染都把 8 个地址重新挨个请求一遍。+ POSTER_MISS_TTL = 300.0++ def _poster(self, item: FollowItemRow,+ alternatives: Callable[[], Iterable[str]] | Iterable[str]) -> Path:+ """缓存来源 poster;失效时取同一作品其他版本的封面,只请求静态图片。++ 缓存文件按条目自己的 poster 地址命名:同作品别的版本增减不改名,命中时不用+ 先去账本里找同组版本。+ """+ poster_key = hashlib.sha256(+ f"poster\0{item.thumb_url or ''}".encode("utf-8")).hexdigest()[:16]+ destination = self.root / f"{item.id}-poster-{poster_key}.jpg"+ if destination.is_file():+ return destination+ others = alternatives() if callable(alternatives) else alternatives+ urls = tuple(url for url in dict.fromkeys((item.thumb_url or "", *others))if proxyable("rule34video", url))[:8]if not urls:raise FollowCoverUnavailable("该作品没有可用的封面地址")- fingerprint = hashlib.sha256("\0".join(urls).encode("utf-8")).hexdigest()[:16]- destination = self.root / f"{item.id}-poster-{fingerprint}.jpg"- if destination.is_file():- return destination- with self._lock_for(destination.name), self._slots:+ miss_key = hashlib.sha256("\0".join(urls).encode("utf-8")).hexdigest()+ if self._recent_miss(miss_key):+ raise FollowCoverUnavailable("该作品的封面未取得")+ with self._lock_for(destination.name):if destination.is_file():return destination- deadline = time.monotonic() + self.timeout- self.root.mkdir(parents=True, exist_ok=True)- temporary = destination.with_name(- f"{destination.stem}.{os.getpid()}.{threading.get_ident()}.tmp.jpg")- try:- for url in urls:- remaining = deadline - time.monotonic()- if remaining <= 0:- break- try:- response = self.media_resolver.transport(HttpRequest("GET", url, {- "User-Agent": USER_AGENT, "Accept": "image/*", "Referer": item.url or "",- }), min(8.0, remaining), 4_000_000)- if response.status != 200 or len(response.body) > 4_000_000:- continue- if response.url and not proxyable("rule34video", response.url):- continue- with Image.open(io.BytesIO(response.body)) as image:- if image.width * image.height > 16_000_000:- continue- image.seek(0)- image.thumbnail((1280, 1280))- image.convert("RGB").save(temporary, "JPEG", quality=90)- os.replace(temporary, destination)- return destination- except (OSError, ValueError, httpx.HTTPError, UnidentifiedImageError, Image.DecompressionBombError):+ if self._recent_miss(miss_key):+ raise FollowCoverUnavailable("该作品的封面未取得")+ with self._poster_slots:+ fetched = self._fetch_poster(item, urls, destination)+ if not fetched:+ self._remember_miss(miss_key)+ raise FollowCoverUnavailable("该作品的封面未取得")+ # 自己的 poster 地址变了才会换名;同一条目只留当前这一份。+ for stale in self.root.glob(f"{item.id}-poster-*.jpg"):+ if stale != destination and not stale.name.endswith(".tmp.jpg"):+ stale.unlink(missing_ok=True)+ return destination++ def _recent_miss(self, key: str) -> bool:+ with self._guard:+ missed = self._poster_misses.get(key)+ if missed is None:+ return False+ if time.monotonic() - missed < self.POSTER_MISS_TTL:+ return True+ del self._poster_misses[key]+ return False++ def _remember_miss(self, key: str) -> None:+ with self._guard:+ if len(self._poster_misses) >= self.MAX_TRACKED_LOCKS:+ now = time.monotonic()+ for name, missed in list(self._poster_misses.items()):+ if now - missed >= self.POSTER_MISS_TTL:+ del self._poster_misses[name]+ while len(self._poster_misses) >= self.MAX_TRACKED_LOCKS:+ del self._poster_misses[next(iter(self._poster_misses))]+ self._poster_misses[key] = time.monotonic()++ def _fetch_poster(self, item: FollowItemRow, urls: tuple[str, ...],+ destination: Path) -> bool:+ """按次序取第一张能解码的 poster,转成 JPEG 原子落到 `destination`。"""+ deadline = time.monotonic() + self.timeout+ self.root.mkdir(parents=True, exist_ok=True)+ temporary = destination.with_name(+ f"{destination.stem}.{os.getpid()}.{threading.get_ident()}.tmp.jpg")+ try:+ for url in urls:+ remaining = deadline - time.monotonic()+ if remaining <= 0:+ break+ try:+ response = self.media_resolver.transport(HttpRequest("GET", url, {+ "User-Agent": USER_AGENT, "Accept": "image/*", "Referer": item.url or "",+ }), min(8.0, remaining), 4_000_000)+ if response.status != 200 or len(response.body) > 4_000_000:continue- finally:- temporary.unlink(missing_ok=True)- raise FollowCoverUnavailable("该作品的封面未取得")+ if response.url and not proxyable("rule34video", response.url):+ continue+ with Image.open(io.BytesIO(response.body)) as image:+ if image.width * image.height > 16_000_000:+ continue+ image.seek(0)+ image.thumbnail((1280, 1280))+ image.convert("RGB").save(temporary, "JPEG", quality=90)+ os.replace(temporary, destination)+ return True+ except (OSError, ValueError, httpx.HTTPError, UnidentifiedImageError, Image.DecompressionBombError):+ continue+ finally:+ temporary.unlink(missing_ok=True)+ return False#: 同时追踪多少把生成锁。键是带指纹的缓存文件名,条目一多、URL 一变就再加一条,#: 只增不减的话,进程活多久它就长多久。超过上限就丢掉当前没人持有的键——丢锁最diff --git a/src/peach/routes_media.py b/src/peach/routes_media.pyindex 65ec653c6..9f66dfc0e 100644--- a/src/peach/routes_media.py+++ b/src/peach/routes_media.py@@ -944,8 +944,9 @@ def follow_cover(request: Request, id: int, media: int | None = None,return JSONResponse({"error": "no such follow item"}, status_code=404)try:if item.provider == "rule34video":+ # 同作品别的版本只在磁盘缓存未命中时才去查:命中的请求不该先算一遍整库分组。path = state.follow_cover_service.cover(- item, media, alternatives=web_follow.cover_alternatives(state.web_contract, item.id))+ item, media, alternatives=lambda: web_follow.cover_alternatives(state.web_contract, item.id))else:path = state.follow_cover_service.cover(item, media)except FollowCoverUnavailable:diff --git a/src/peach/web_follow.py b/src/peach/web_follow.pyindex 99c0b2f1d..c00b3be76 100644--- a/src/peach/web_follow.py+++ b/src/peach/web_follow.py@@ -865,8 +865,20 @@ def _thumb_url(item) -> str | None:return _unhide_thumb(item, display_thumb_url(item))+#: 账本一变,冷缓存下同时到的一屏封面请求只让一个去算整库分组,其余等它算完直接命中。+_COVER_INDEX_LOCK = threading.Lock()++def cover_alternatives(contract, item_id: int) -> tuple[str, ...]:"""同一作品其他版本的 Rule34Video 封面;来源地址只在服务端使用。"""+ with _COVER_INDEX_LOCK:+ index = contract.cached_until_changed(+ "follow-cover-alternatives", lambda: _cover_alternative_index(contract))+ return index.get(item_id, ())+++def _cover_alternative_index(contract) -> dict[int, tuple[str, ...]]:+ """每条 Rule34Video 条目 → 同组其他 Rule34Video 版本的 poster 地址,整库分组一次建好。"""with contract.database.read_connection() as connection:store = _store(contract, connection)sources = store.sources()@@ -875,15 +887,16 @@ def cover_alternatives(contract, item_id: int) -> tuple[str, ...]:everything = contract.cached_until_changed("follow-items:None", lambda: tuple(item for item in store.items(limit=_ALL_ITEMS)if item.source_id in enabled and not _excluded_item(item)))- groups = contract.cached_until_changed(- "follow-cover-groups", lambda: store.group(everything, group_authors(sources, aliases)))- for group in groups:- members = (group.primary, *group.variants, *group.duplicates)- if any(member.id == item_id for member in members):- return tuple(dict.fromkeys(member.thumb_url for member in members- if member.id != item_id and member.provider == "rule34video"- and member.thumb_url))- return ()+ index: dict[int, tuple[str, ...]] = {}+ for group in store.group(everything, group_authors(sources, aliases)):+ members = [member for member in (group.primary, *group.variants, *group.duplicates)+ if member.provider == "rule34video"]+ for member in members:+ others = tuple(dict.fromkeys(other.thumb_url for other in members+ if other.id != member.id and other.thumb_url))+ if others:+ index[member.id] = others+ return indexdef _fanbox_card_thumb(item) -> str | None:diff --git a/tests/test_follow_covers.py b/tests/test_follow_covers.pyindex d4236c040..e16c3c5a1 100644--- a/tests/test_follow_covers.py+++ b/tests/test_follow_covers.py@@ -71,6 +71,62 @@ class FollowCoverServiceTests(unittest.TestCase):self.assertEqual(self.media.transport.call_count, 1)self.assertEqual(list(self.root.glob("*.jpg")), [])+ def _poster_transport(self, failing=()):+ image = io.BytesIO()+ Image.new("RGB", (32, 18), "red").save(image, "PNG")+ self.media.transport = mock.Mock(side_effect=lambda request, timeout, limit: HttpResponse(+ 404 if request.url in failing else 200, {"content-type": "image/png"}, image.getvalue()))+ item = self._item("rule34video")+ item.url = "https://rule34video.com/video/7/movie/"+ item.thumb_url = "https://rule34video.com/poster.jpg"+ return item++ def test_rule34video_cache_hit_skips_the_work_lookup(self):+ """命中磁盘缓存的请求不去问同作品还有哪些版本:那一问要整库分组。"""+ item = self._poster_transport()+ lookup = mock.Mock(return_value=("https://rule34video.com/other.jpg",))+ path = self.service.cover(item, alternatives=lookup)+ self.assertEqual(lookup.call_count, 1)+ self.assertEqual(self.service.cover(item, alternatives=lookup), path)+ self.assertEqual(lookup.call_count, 1)+ self.assertEqual(self.media.transport.call_count, 1)++ def test_rule34video_missing_posters_are_not_retried_within_the_ttl(self):+ item = self._poster_transport(failing={"https://rule34video.com/poster.jpg",+ "https://rule34video.com/other.jpg"})+ clock = [1000.0]+ alternatives = ("https://rule34video.com/other.jpg",)+ with mock.patch("peach.follow_covers.time.monotonic", side_effect=lambda: clock[0]):+ with self.assertRaises(FollowCoverUnavailable):+ self.service.cover(item, alternatives=alternatives)+ self.assertEqual(self.media.transport.call_count, 2)+ clock[0] += self.service.POSTER_MISS_TTL - 1+ with self.assertRaises(FollowCoverUnavailable):+ self.service.cover(item, alternatives=alternatives)+ self.assertEqual(self.media.transport.call_count, 2)+ clock[0] += 2+ with self.assertRaises(FollowCoverUnavailable):+ self.service.cover(item, alternatives=alternatives)+ self.assertEqual(self.media.transport.call_count, 4)++ def test_rule34video_posters_do_not_wait_for_ffmpeg_slots(self):+ item = self._poster_transport()+ for _ in range(2):+ self.assertTrue(self.service._slots.acquire(blocking=False))+ self.addCleanup(self.service._slots.release)+ self.assertTrue(self.service.cover(item).is_file())++ def test_rule34video_poster_replaces_its_older_cached_files(self):+ item = self._poster_transport()+ stale = self.root / "7-poster-0123456789abcdef.jpg"+ working = self.root / "7-poster-0123456789abcdef.1.2.tmp.jpg"+ other = self.root / "8-poster-0123456789abcdef.jpg"+ for path in (stale, working, other):+ path.write_bytes(b"jpeg")+ current = self.service.cover(item)+ self.assertFalse(stale.exists())+ self.assertTrue(working.exists() and other.exists() and current.is_file())+def test_rule34video_network_failures_leave_no_cached_file(self):self.media.transport = mock.Mock(side_effect=httpx.ReadTimeout("offline"))item = self._item("rule34video")diff --git a/tests/test_follow_web.py b/tests/test_follow_web.pyindex 16b300e80..8de8cf320 100644--- a/tests/test_follow_web.py+++ b/tests/test_follow_web.py@@ -1869,6 +1869,38 @@ class FollowContractTests(unittest.TestCase):self._post('/api/follow/source', {"action": "enabled", "id": member["source_id"], "enabled": False})self.assertEqual(web_follow.cover_alternatives(self.contract, member["id"]), ())+ def test_concurrent_cover_lookups_group_the_library_once(self):+ """账本刚变时一屏封面请求同时到:整库分组只算一次,其余等它算完直接查表。"""+ self._seed(candidates=(+ FollowCandidate(provider="rule34video", external_id="1", title="Evening Movie (4K60fps)",+ thumb_url="https://rule34video.com/4k.jpg"),+ FollowCandidate(provider="rule34video", external_id="2", title="Evening Movie (60fps)",+ thumb_url="https://rule34video.com/60.jpg"),+ ))+ group = next(group for group in self._get()["groups"] if group["stack"])+ ids = [row["id"] for row in (group["primary"], *group["variants"])]+ self.contract.cache_bust()+ original = FollowStore.group+ entered = threading.Event()++ def slow_group(store, *args, **kwargs):+ entered.set()+ threading.Event().wait(0.2)+ return original(store, *args, **kwargs)++ results = {}+ with mock.patch.object(FollowStore, "group", autospec=True, side_effect=slow_group) as grouped:+ workers = [threading.Thread(target=lambda item=item: results.__setitem__(+ item, web_follow.cover_alternatives(self.contract, item))) for item in ids * 3]+ for worker in workers:+ worker.start()+ for worker in workers:+ worker.join(10)+ self.assertTrue(entered.is_set())+ self.assertEqual(grouped.call_count, 1)+ self.assertEqual(set(results.values()), {("https://rule34video.com/60.jpg",),+ ("https://rule34video.com/4k.jpg",)})+def test_archive_copies_of_one_file_count_as_one_medium_without_thumbnails(self):"""归档站视频没有缩略图,计数按已存地址里的内容哈希认同一个文件,不发请求。"""digest = "58739e4717810cf6b2d4b4a0c1b5f79a0e2f1e3d4c5b6a79881726354a5b6c7d"