Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(metadata): 封面来源部分连不上时不记成一周没有封面

longmeidaob4cefe1b18f6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 1b9d50094..73feaa84a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -32,6 +32,7 @@ Removed / Fixed / Security。
### 修复
+- **采集**:封面来源只是部分连不上时(如 JavBus 断线、javdb 照常答上),不再记成「外部来源没有这部片的封面,7 天内不再问」;这类作品下次采集或点重试会照常再问,来源恢复后就能取到封面(如 `ABF-047`)。只有来源都明确答复没有、图都下载到却不能用或对不上时,才记 7 天。
- **采集**:云下载入库后的整理不再因为一个资料站限流或拒绝访问就整条失败、文件留在云下载目录:其余资料已经取到时照常整理,任务详情写明哪项等来源恢复后再采集。有码作品在片商官网已经给出标签时,JavDB 拒绝访问也不再算问题,先用官方标签(如 `MIAB-086`)。用户脚本可以直接重试失败的整理。
- **采集**:用户脚本浮卡标题的人物头像,在素人作品入库后不再变成两个人:馆藏里已经按资料站记下真名(如 `390JAC-059` 的夏希栗)时,详情页上的店铺艺名(れいか)不再另算一人;只有馆藏和资料都没有人物时才用页面上的出演者名。
- **桌面**:本机代理、加速器或安全软件改写了请求地址,或浏览器发出空来源时,首次设置不再报「请从 Peach 设置页提交」,配置页的保存也不再报「请从 Peach 配置页提交」;判断改以浏览器自己标注的同源信息为准,别的网站发来的提交照旧拒收。仍被拒绝时,诊断包会记下来源对不上的方式、浏览器标识、系统代理开关和默认浏览器,便于定位。
diff --git a/src/peach/community_catalog.py b/src/peach/community_catalog.py
index 50e0a3908..422b9211b 100644
--- a/src/peach/community_catalog.py
+++ b/src/peach/community_catalog.py
@@ -164,63 +164,81 @@ def same_scene(data: bytes, other: bytes) -> bool:
return mask is not None and int(mask.sum()) >= SCENE_INLIERS
-def _download(transport, candidate: Candidate, *, deadline: float | None) -> tuple[Picture | None, bool]:
- """一张候选图:下载得到、宽度够小图门槛的静态图,再报下载到没有。"""
+def _download(transport, candidate: Candidate, *, deadline: float | None) -> tuple[Picture | None, str]:
+ """一张候选图:下载得到、宽度够小图门槛的静态图,再报这一张的下落:`fetched` 下载到了,
+ `paused` 来源正在冷却,`failed` 断在连接、5xx 或 404 上。"""
try:
data = _fetch(transport, candidate.url, referer=candidate.referer, limit=IMAGE_LIMIT, deadline=deadline)
- except (NotFound, Unavailable, SourcePaused, httpx.TransportError, OSError):
- return None, False
+ except SourcePaused:
+ return None, "paused"
+ except (NotFound, Unavailable, httpx.TransportError, OSError):
+ return None, "failed"
try:
found = picture(candidate, data)
except (OSError, ValueError, Image.DecompressionBombError):
- return None, True
- return (found if found.size[0] >= SMALL_MIN_WIDTH else None), True
+ return None, "fetched"
+ return (found if found.size[0] >= SMALL_MIN_WIDTH else None), "fetched"
def _pictures(transport, urls: dict[str, Candidate], reference, siblings: tuple[Candidate, ...], *,
- deadline: float | None) -> tuple[list[Picture], int, int]:
- """官方小图与它的同页图(有的话)加上社区来源里能用的图;再报社区来源下载到了几张、能用几张。
+ deadline: float | None) -> tuple[list[Picture], int, int, list[str]]:
+ """官方小图与它的同页图(有的话)加上社区来源里能用的图;再报社区来源下载到了几张、能用几张,
+ 以及没下载到的那几张各是什么下落(`_download`)。
下载到了却不能用(动图、太窄)和没下载到是两回事:前者再问一遍还是这几张。
"""
pool = [picture(reference[0], reference[2])] if reference is not None else []
seen = {pool[0].candidate.url} if pool else set()
+ missed = []
for candidate in siblings:
if candidate.url not in seen and candidate.url not in urls:
seen.add(candidate.url)
- found, _ = _download(transport, candidate, deadline=deadline)
+ found, outcome = _download(transport, candidate, deadline=deadline)
pool += [found] if found else []
+ missed += [outcome] if outcome != "fetched" else []
official = len(pool)
fetched = 0
for url, candidate in urls.items():
if url in seen:
continue
- found, downloaded = _download(transport, candidate, deadline=deadline)
- fetched += downloaded
+ found, outcome = _download(transport, candidate, deadline=deadline)
+ fetched += outcome == "fetched"
pool += [found] if found else []
- return pool, fetched, len(pool) - official
+ missed += [outcome] if outcome != "fetched" else []
+ return pool, fetched, len(pool) - official, missed
-def _unverified(pool: list[Picture], usable: int,
- fetched: int) -> tuple[Candidate, tuple[int, int], bytes, tuple[str, ...]]:
+def _unverified(pool: list[Picture], usable: int, fetched: int,
+ missed: list[str]) -> tuple[Candidate, tuple[int, int], bytes, tuple[str, ...]]:
"""没有两个图源对得上时的退路:图全出自一个图源就取最大那张,印证图源留空。
- `usable` 是池子里社区来源那几张,不算官方小图与它的同页图。"""
+ `usable` 是池子里社区来源那几张,不算官方小图与它的同页图。`missed` 是没下载到的那几张的下落
+ (`_download`),交给 `_settled` 决定落空是不是确定答复。"""
if not usable:
if fetched:
- raise NotFound("社区来源给的封面都是动图或太小")
+ raise _settled("社区来源给的封面都是动图或太小", missed)
raise Unavailable("社区来源的封面下载失败")
origins = sorted({one.origin for one in pool})
if len(origins) > 1:
# 几家都答了、图都下到了,只是互相对不上:再问还是这几张,交 `NotFound` 让采集任务记住。
- raise NotFound(f"{'、'.join(origins)} 给的封面不是同一张图,无法互相印证")
+ raise _settled(f"{'、'.join(origins)} 给的封面不是同一张图,无法互相印证", missed)
allowed = [one for one in pool if not is_javdb_image(one.candidate.url)]
if not allowed:
- raise NotFound('未取得无 JavDB 水印的封面')
+ raise _settled('未取得无 JavDB 水印的封面', missed)
largest = max(allowed, key=lambda one: one.pixels)
return largest.candidate, largest.size, largest.data, ()
+def _settled(message: str, missed: list[str]) -> Exception:
+ """图都下载到了才交 `NotFound`。有图没下载到时不下「没有」的结论(#342):那一张可能正是能印证的、
+ 或不带 JavDB 水印的那张,下次再问答案可能就变了,交 `NotFound` 会被采集任务记成一周不问。
+ 没下到的全在冷却就是本趟没轮到(`SourcePaused`)。"""
+ if not missed:
+ return NotFound(message)
+ kind = SourcePaused if all(outcome == "paused" for outcome in missed) else Unavailable
+ return kind(f"{message};另有 {len(missed)} 张封面没下载到")
+
+
def verified_cover(transport, code: str, works: list[tuple[str, dict]], *,
reference: tuple[Candidate, tuple[int, int], bytes] | None = None,
siblings: tuple[Candidate, ...] = (),
@@ -239,7 +257,7 @@ def verified_cover(transport, code: str, works: list[tuple[str, dict]], *,
if not urls:
raise NotFound("社区来源没有这部片的封面")
siblings = tuple(one for one in siblings if not is_cross_product_cover(code, one.url))
- pool, fetched, usable = _pictures(transport, urls, reference, siblings, deadline=deadline)
+ pool, fetched, usable, missed = _pictures(transport, urls, reference, siblings, deadline=deadline)
best = None
for one in pool:
if is_javdb_image(one.candidate.url):
@@ -248,5 +266,5 @@ def verified_cover(transport, code: str, works: list[tuple[str, dict]], *,
if len(origins) >= 2 and (best is None or one.pixels > best[0].pixels):
best = (one, tuple(sorted(origins)))
if best is None:
- return _unverified(pool, usable, fetched)
+ return _unverified(pool, usable, fetched, missed)
return best[0].candidate, best[0].size, best[0].data, best[1]
diff --git a/src/peach/library_processing.py b/src/peach/library_processing.py
index 4af812118..769bc2f74 100644
--- a/src/peach/library_processing.py
+++ b/src/peach/library_processing.py
@@ -475,11 +475,17 @@ class LibraryMetadataProvider:
raise _again(cache[code])
return [*have.items(), *((source, payload) for source, payload in cache[code] if source not in have)]
+ def community_problems(self, code):
+ """`community` 问这个番号时没问成的几家 `[(原因, 是否冷却)]`,别的几家照常答上时也留着。
+
+ 封面那一步据此不下「没有」的结论(#342):JavBus 断线、javdb 答上时,只剩 javdb 带水印的那张,
+ 印证不了也用不了,可 JavBus 那张下次可能就取到了。"""
+ return list(self.__dict__.get('_community_problems', {}).get(code, ()))
+
def _ask_community(self, code, sources, deadline, received):
"""逐家问 `sources`,交出答上的 `[(来源, 资料)]`,或一个待缓存再抛的异常(见 `community`)。"""
- from .jav_cover_fetch import Unavailable
- from .scraping_access import SourcePaused
- found, problems, said_no, held = [], [], [], 0
+ found, problems, said_no = [], [], []
+ self.__dict__.setdefault('_community_problems', {})[code] = problems
for source in sources:
try:
payload = self.site(source, code, deadline=deadline)
@@ -492,15 +498,15 @@ class LibraryMetadataProvider:
if is_missing(error):
said_no.append(source)
continue
- held += source_paused(error)
text = describe_failure(error)
- problems.append(text if text.startswith(SOURCE_LABELS[source]) else f'{SOURCE_LABELS[source]}:{text}')
+ problems.append((text if text.startswith(SOURCE_LABELS[source]) else f'{SOURCE_LABELS[source]}:{text}',
+ source_paused(error)))
continue
found.append((source, payload))
received([(source, payload)])
if found or not problems:
return found or _said_no('社区来源都没有这个番号', said_no)
- return (SourcePaused if held == len(problems) else Unavailable)(';'.join(problems))
+ return _unreached(problems)
def fc2(self, code, *, deadline=None, route=None, covers=False, required=(), known=(), received=lambda found: None):
"""FC2 自己那一页,下架了就依次问几个存档站;返回沿路答上的每一档 `[(来源, 资料)]`。
@@ -694,6 +700,7 @@ class LibraryMetadataProvider:
answers = self.community(code, deadline=_extended(deadline, self.excused - mark), absent=absent,
known=[(name, payload) for name, payload in snapshots
if name in metadata_routes.COMMUNITY_STAGE])
+ problems += self.community_problems(code)
*picked, verified_by = verified_cover(self.transport, code, answers,
reference=official, siblings=siblings if official else (),
deadline=_extended(deadline, self.excused - mark))
diff --git a/tests/test_community_catalog.py b/tests/test_community_catalog.py
index b4dc5ac83..b00119741 100644
--- a/tests/test_community_catalog.py
+++ b/tests/test_community_catalog.py
@@ -1,13 +1,18 @@
"""社区来源的解析与封面比对:AVBase、JavBus、javdb 各自的页面形状,以及图源印证与只有一个图源时的退路。"""
import io
import json
+import tempfile
import unittest
+from pathlib import Path
+from unittest.mock import patch
+import httpx
from PIL import Image
from peach.community_catalog import COMMUNITY_SOURCES, IMAGE_LIMIT, community_sources_for, verified_cover
from peach.http import HttpResponse
from peach.jav_cover_fetch import Candidate, NotFound, Unavailable, _fetch
+from peach.scraping_access import SourcePaused
from peach.sources import (SITE_SOURCES, AVBaseSource, FailureReason, JavBusSource, JavDBSource, Page, Session,
SourceFailure)
from peach.sources.javdb import actresses as javdb_actresses
@@ -313,6 +318,61 @@ class VerifiedCoverTests(unittest.TestCase):
with self.assertRaisesRegex(NotFound, '无 JavDB 水印'):
verified_cover(serve({JAVDB_COVER: gradient(800, 534)}), "IPX-060", works)
+ def test_a_picture_cut_off_on_the_network_keeps_the_answer_retryable(self):
+ """#342:JavBus 那张断在连接、5xx 或冷却上时,剩下的 javdb 图凑不成答复,不能当「没有」记一周。"""
+ works = [("javbus", {"cover_urls": [JAVBUS_COVER]}), ("javdb", {"cover_urls": [JAVDB_COVER]})]
+ pages = {JAVBUS_COVER: gradient(800, 538), JAVDB_COVER: gradient(800, 534)}
+
+ def failing(failure, pages=pages):
+ def call(request, timeout, limit):
+ if request.url == JAVBUS_COVER:
+ if isinstance(failure, int):
+ return HttpResponse(failure, {}, b"", request.url)
+ raise failure
+ return serve(pages)(request, timeout, limit)
+ return call
+
+ conflicting = {**pages, JAVBUS_COVER: gradient(800, 538, rising=False),
+ DMM_COVER: gradient(800, 538, rising=False)}
+ failures = ((httpx.ConnectError("proxy down"), Unavailable), (httpx.ReadTimeout("read timeout"), Unavailable),
+ (503, Unavailable), (404, Unavailable), (SourcePaused("来源正在冷却"), SourcePaused))
+ for failure, expected in failures:
+ with self.subTest(failure=failure), patch("peach.jav_cover_fetch.time.sleep"):
+ # 只剩 javdb 带水印的那张;或另两家各给一张对不上:没下到的 JavBus 那张都可能改变结论。
+ for served, answered, reason in (
+ (pages, works, "^未取得无 JavDB 水印的封面"),
+ (conflicting, [*works, ("avbase", {"cover_urls": [DMM_COVER]})], "^dmm、javdb 给的封面不是同一张图")):
+ with self.assertRaisesRegex(expected, reason + ".*;另有 1 张封面没下载到$") as caught:
+ verified_cover(failing(failure, served), "ABW-358", answered)
+ self.assertNotIsInstance(caught.exception, NotFound)
+ # 下到的图全出自一个图源时照旧用它:别家那张没下到不挡已经能用的封面。
+ candidate, _size, _data, origins = verified_cover(
+ failing(failure, {DMM_COVER: gradient(800, 538)}), "ABW-358",
+ [works[0], ("avbase", {"cover_urls": [DMM_COVER]})])
+ self.assertEqual((candidate.url, origins), (DMM_COVER, ()))
+ with self.assertRaisesRegex(NotFound, "无 JavDB 水印"):
+ verified_cover(serve(pages), "ABW-358", [("javbus", {"cover_urls": []}), works[1]])
+
+ def test_a_site_cut_off_while_another_answers_keeps_the_cover_retryable(self):
+ """#342:JavBus 作品页断线、AVBase 说没有、javdb 答上;只剩 javdb 带水印的图,不是「来源没有封面」。"""
+ from peach.library_processing import LibraryMetadataProvider
+ pages = {JAVDB_SEARCH: JAVDB_RESULTS, JAVDB_DETAIL: JAVDB_PAGE, JAVDB_COVER: gradient(800, 534)}
+
+ def transport(request, timeout, limit):
+ if request.url == JAVBUS_WORK:
+ raise httpx.ConnectError("proxy down")
+ return serve(pages)(request, timeout, limit)
+
+ provider = LibraryMetadataProvider.__new__(LibraryMetadataProvider)
+ provider.transport = transport
+ covers = Path(self.enterContext(tempfile.TemporaryDirectory()))
+ with patch("peach.jav_cover_fetch.time.sleep"), \
+ patch("peach.jav_cover_fetch.best_cover", side_effect=NotFound("所有渠道都没有候选")), \
+ self.assertRaisesRegex(Unavailable, "JavBus") as caught:
+ provider.cover("ABW-358", covers)
+ self.assertNotIsInstance(caught.exception, NotFound)
+ self.assertFalse((covers / "ABW-358.jpg").exists())
+
def test_a_small_official_cover_counts_as_the_second_origin(self):
works = [("javdb", {"cover_urls": [JAVDB_COVER]})]
small = Candidate("image.mgstage.com", "https://image.mgstage.com/images/x/pf_o1_x.jpg")