Peach: Local-first video metadata scraper and media manager.
feat(metadata): JAV 横版封面的 2:3 竖海报取景框
longmeidao81512c646f0e
diff --git a/.claude/skills/peach-jav-cover-workflow/SKILL.md b/.claude/skills/peach-jav-cover-workflow/SKILL.mdindex cf6c81534..9a9636d80 100644--- a/.claude/skills/peach-jav-cover-workflow/SKILL.md+++ b/.claude/skills/peach-jav-cover-workflow/SKILL.md@@ -3,7 +3,7 @@ name: peach-jav-cover-workflowdescription: 在用户说 JAV 封面、高清封面、缺封面、封面刮削、重探、来源比较或继续抓取时使用。----最后复核:2026-09-03+最后复核:2026-09-11证据来源:`scripts/fetch_jav_covers.py`、`scripts/detect_cover_faces.py`、`tests/test_jav_covers.py`、`docs/REUSE.md` 与 ABW-232 官方来源实测。# JAV 封面获取流程@@ -59,9 +59,21 @@ description: 在用户说 JAV 封面、高清封面、缺封面、封面刮削- 已算过的默认跳过,`--redo` 才重算;954 张实测检出 885 张,未检出的页面居中。- sidecar 的 `cx` 和 `cy` 都要留着。用哪个轴由容器比例决定:`object-fit:cover`一次只裁一个轴,16:9 官方剧照在大图版式里裁的是横向,纵向锚点在那里不生效。-- 版式判据(1.2 / 1.65 两个分界)在脚本和 `web/app.js` 的 `coverAnchor` 里各有- 一份,改一处必须改两处:对不上就会出现「脚本按封套丢掉左半边的脸、页面按剧照- 用那张脸取景」。+- 版式判据(1.2 / 1.65 两个分界)的真相在 `peach.jav_poster_crop`,`web/app.js`+ 的 `coverAnchor` 里另有一份,改一处必须改两处:对不上就会出现「脚本按封套丢掉+ 左半边的脸、页面按剧照用那张脸取景」。++竖海报要的是另一样东西——横版封套里 2:3 那一块的坐标,同目录写 `<番号>.poster.json`:++```powershell+& .\.venv\Scripts\python.exe .\scripts\poster_crop_boxes.py+& .\.venv\Scripts\python.exe .\scripts\poster_crop_boxes.py --apply+```++- 判据在 `peach.jav_poster_crop`:Sobel 列梯度找书脊折痕,找不到退回右半居中,+ HEYZO/FC2/六位日期/韩国 MIB/16:9 剧照不裁。原图一个字节都不动。+- 默认只算边车缺失、算法版本落后或源图尺寸对不上的封面,所以重探换上更大的图之后+ 再跑一遍就会重算;`--redo` 才无条件全算。## 正式批次diff --git a/docs/REUSE.md b/docs/REUSE.mdindex 4181a0505..4a67e10e8 100644--- a/docs/REUSE.md+++ b/docs/REUSE.md@@ -250,6 +250,7 @@ CloudDrive 为外部应用,本项目不捆绑其二进制或依赖其管理 AP| macOS 菜单栏 | `pyobjc-framework-Cocoa==12.2.2`(MIT)提供 AppKit / PyObjCTools / objc | 附件应用策略、18 pt template 图、服务归属与菜单动作 || 人脸取景 | `opencv-python-headless==5.0.0.93`(Apache-2.0)的 `cv2.FaceDetectorYN` + opencv_zoo 定版模型 `face_detection_yunet_2023mar.onnx`(sha256 `8f2383e4…52fa4`,232 KB,放 `peach-data/tools/yunet/`,不进 Git);MetaTube SDK `6a5e6128c725187aeaf921d48ed7d9cd9f30671b` 的主脸聚类只作算法参考 | 头像/封面离线脚本共用 `peach.face_detect`,主脸选择、归一化焦点与 sidecar。**主脸不是最大的那张**:`main_face` 先筛掉分数落后最好那张 0.1 以上的框,再在剩下的里取最大。只按面积挑会被「大而勉强」的误检抢走(`performer-8218` 那张 600×1000 人像上,罩在胸口的框 0.427×0.313 分 0.798 压过 0.202×0.170 分 0.928 的脸,圆头像于是取景在胸口);只按分数挑会被背景里那张小而清晰的脸抢走(`performer-8540` 右上角 0.066×0.052 分 0.925)。954 张封面按这条重算,47 张换了主脸,每一张的新框分数都更高(`451HHH-029` 从画面中缝的 0.813 换到左上主体的 0.925)。**Haar 级联已不可用**:OpenCV 5 把它移出了 Python wheel(`cv2.CascadeClassifier` 不存在、`cv2/data/` 只剩 `__init__.py`),两个脚本一直抛 AttributeError,954 张封面 0 个 sidecar,取景从未生效。YuNet 同属 OpenCV,不是替代品,换掉的只是检出器这一层:Haar 在 512 张头像上检出 313、46 张封面上检出 24,YuNet 首轮 12 张封面检出 11,且带置信度,不必再靠位置规则丢假阳性。Pigo v1.4.6(MIT)512 张检出 488,但存在无脸误报且无 Python 部署优势,仍不引入。 || 头像水印检出 | `opencv-python-headless==5.0.0.93`(Apache-2.0)的 `cv2.dnn.TextDetectionModel_DB` + opencv_zoo 定版模型 `text_detection_en_ppocrv3_2023may.onnx`(sha256 `03f550c6…66587`,2.4 MB,放 `peach-data/tools/ppocr/`,不进 Git) | `peach.avatar_watermark` 检出站点水印,`scripts/scrub_avatar_watermarks.py` 复核与移除。**先自己写过一版启发式,实测不够用**:MSER 加几何、字高一致与明暗同向过滤,干净图上假阳性能压到零,那 14 张里总共抓到 1 处水印,半透明的一个字符都抓不到——头发和织物纹理产出的字符状连通块跟真文字在单张图上无从分辨。换 DB 模型后同一批图 6 处实心水印全中、零假阳性。**门槛按实测数据定**:真水印分数几乎都在 0.97 以上(`PRIVATE.com` 0.994、`TEAMSKEET.COM` 0.986),衣服花纹上的假阳性 0.71 到 0.81,`MIN_SCORE` 卡在两群中间的 0.9;再加框宽占图宽 ≥ 4% 挡掉碎块,加「框要整体落在距边 15% 带内」的位置先验挡掉裙子花纹和脸上的框。**半透明水印它给不出框**(`NUBILES.NET`、`MATTIEDOLL.DEVIANTART.COM`),这一层补不上,所以流程是半自动的:检出是候选,人看标注图确认,漏的自己补框。移除优先裁边不 inpaint——620 张实测 16 张纯裁切、1 张裁切加修补、6 张只能修补,裁切不伪造任何像素。 |+| 竖海报取景 | `opencv-python-headless==5.0.0.93`(Apache-2.0)的 `cv2.Sobel` 求列向梯度;NeoAVDC `c7a430c64013c97a0213cd8a57e2ff5696793a86`(MIT)的封套几何与 sakuramediabe `7e40ef87c7518c1dc2b6c8c299170ad7395fec6d`(GPL-3.0,只作算法边界参考,不引入代码与运行时)的切点接受条件 | `peach.jav_poster_crop` 给出 2:3 竖海报的取景框,`scripts/poster_crop_boxes.py` 批量落边车。**产物是坐标不是图片**:封面原样保存(`jav_cover_fetch` 的约定),框写进 `<番号>.poster.json`,和人脸取景的 `.face.json` 同目录、同命名风格。**两份外部先验都采信,各挡一类失败**:NeoAVDC 量 DMM/JavBus 封套得出折痕在全宽约 52.5%,sakuramediabe 的接受条件是「左右两峰关于中线对称」或「右峰离中线约 20 像素」——那 20 像素是在 800×539 的低清封套上量的,正好是 2.5% 宽,所以 Peach 把它写成宽度比例,否则 2184 像素宽的高清图上同一道折痕离中线 55 像素,会被全判成没有折痕。再加一道「峰值要到全图最强列梯度的 35%」挡住平缓横图。**本机 1014 张封面实测**:命中折痕 577 张,折痕相对位置中位数 0.5253(最小 0.500、最大 0.5875),与 NeoAVDC 的 52.5% 对上;回退右半居中 106 张;不裁 331 张(韩国 MIB 90、FC2 130、16:9 官方剧照 111)。欧美片的编号和厂牌番号同形,番号那一关拦不住,靠宽高比这一关拦下。 || 115 文件清单 | `p115client==0.0.9.6.5.1`(MIT) | 只在显式 SHA-1 对账脚本中安装,Peach 负责 ledger 事务、备份与写入门槛 || 智能体用量/配额 | Provider 官方配额接口;T3 Code/CodexBar 提供本地历史 | 任务路由、脱敏、过期快照标记 || 视频出处/片尾证据 | 现有 FFmpeg 抽帧 + Windows.Media.Ocr WinRT Provider(Windows PowerShell 5.1 固定适配器) | 有界首尾采样、缓存、来源/Full version 分类、健康统计与人工复核 |diff --git a/scripts/detect_cover_faces.py b/scripts/detect_cover_faces.pyindex 1635651b8..751f87cde 100644--- a/scripts/detect_cover_faces.py+++ b/scripts/detect_cover_faces.py@@ -34,12 +34,11 @@ if str(SRC_DIR) not in sys.path:from peach.config import COVER_DIRfrom peach.face_detect import FaceDetector, FaceModelUnavailable, main_face+#: 长封套的宽高比区间。判据只有一份,住在 `peach.jav_poster_crop`:竖海报取景框、+#: 这里的左半剧照剔除、`web/app.js` 的 `coverAnchor` 都按同一对值分档,各写一份+#: 就会出现「脚本按封套丢掉左半边的脸、页面按剧照用那张脸取景」。+from peach.jav_poster_crop import SLEEVE_RATIO_MAX, SLEEVE_RATIO_MIN-#: 长封套的宽高比下限。低于它按竖版正封处理(整张就是正封,没有剧照区)。-SLEEVE_RATIO_MIN = 1.2-#: 上限之外是 16:9 官方剧照。这个值和 `web/app.js` 的 `coverAnchor` 必须是同一个,-#: 否则脚本按封套丢掉左半边的脸,页面却拿这张图当剧照按人脸取景,两边对不上。-SLEEVE_RATIO_MAX = 1.65#: 长封套上正封的起始横向位置。左边是剧照拼贴,检出必然是假阳性。FRONT_START = 0.468#: 纵向取景的合理区间。超出这个范围的检出多半不是主体人物。diff --git a/scripts/poster_crop_boxes.py b/scripts/poster_crop_boxes.pynew file mode 100644index 000000000..e49d18b98--- /dev/null+++ b/scripts/poster_crop_boxes.py@@ -0,0 +1,127 @@+#!/usr/bin/env python3+# -*- coding: utf-8 -*-+r"""给已落盘的封面算 2:3 竖海报的取景框,写进边车。++用法(默认只看不写):++ python scripts/poster_crop_boxes.py+ python scripts/poster_crop_boxes.py --apply+ python scripts/poster_crop_boxes.py --apply --redo++判据全在 `peach.jav_poster_crop`:番号形态决定该不该裁,Sobel 列梯度决定书脊折痕+在哪,找不到折痕就退回右半居中。这里只负责遍历、统计和落盘。++**原图一个字节都不动。** 产物是 `<番号>.poster.json`,和人脸取景的+`<番号>.face.json` 同目录、同命名风格,各描述一件事。++可重入:默认只处理边车缺失、算法版本落后或源图尺寸对不上的封面,所以中断之后再跑+一遍就是续跑。封面被更大的那张替换过(`fetch_jav_covers.py --upgrade-existing`+只升不降)时尺寸对不上,同样会重算。`--redo` 无条件全部重算。++失败不写成正常值:图读不出来只计进 `unreadable` 并跳过,不留一个按零尺寸算出来的+框——那种框在页面上和真框看不出区别。+"""+from __future__ import annotations++import argparse+import sys+from pathlib import Path++sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))++from peach import jav_poster_crop # noqa: E402+from peach.config import COVER_DIR # noqa: E402++#: 每处理这么多张报一次进度。封面目录是千张量级,一张一行会把日志淹掉。+PROGRESS_EVERY = 100+#: 每一档在报告里带几个样例路径,供人抽查。+SAMPLES = 3+++def image_size(path: Path) -> tuple[int, int] | None:+ """封面的像素尺寸;读不出来返回 None。只读图头,不解全图。"""+ try:+ from PIL import Image+ except ImportError: # pragma: no cover - 基础依赖+ return None+ try:+ with Image.open(path) as image:+ return image.size+ except Exception:+ return None+++def pending(covers: list[Path], redo: bool) -> list[tuple[Path, tuple[int, int]]]:+ """待处理的封面加它们的尺寸。读不出尺寸的留给主循环去计数。"""+ todo: list[tuple[Path, tuple[int, int]]] = []+ for path in covers:+ size = image_size(path)+ if size is None:+ todo.append((path, (0, 0)))+ continue+ if redo or not jav_poster_crop.is_current(+ jav_poster_crop.read_sidecar(path), *size):+ todo.append((path, size))+ return todo+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(description="给封面算 2:3 竖海报取景框")+ parser.add_argument("--covers", type=Path, default=COVER_DIR)+ parser.add_argument("--redo", action="store_true",+ help="无条件重算,不看边车是否还作数")+ parser.add_argument("--limit", type=int, default=0)+ parser.add_argument("--apply", action="store_true", help="真的写边车")+ return parser+++def run(args: argparse.Namespace) -> int:+ covers = sorted(args.covers.glob("*.jpg")) if args.covers.is_dir() else []+ todo = pending(covers, args.redo)+ if args.limit:+ todo = todo[:args.limit]+ print(f"封面 {len(covers)} 张,待处理 {len(todo)} 张"+ f"({'写入边车' if args.apply else '只看不写'})", flush=True)++ counts = {jav_poster_crop.FOLD: 0, jav_poster_crop.RATIO: 0,+ jav_poster_crop.NONE: 0, "unreadable": 0}+ samples: dict[str, list[str]] = {}+ for index, (path, size) in enumerate(todo, 1):+ width, height = size+ if not width or not height:+ counts["unreadable"] += 1+ print(f"[{index}/{len(todo)}] 读图失败 {path.name}", flush=True)+ continue+ record = jav_poster_crop.crop_record(+ path.stem, width, height, jav_poster_crop.file_gradient(path))+ method = record["box"]["method"]+ counts[method] += 1+ bucket = samples.setdefault(method, [])+ if len(bucket) < SAMPLES:+ bucket.append(f"{path.name} {width}×{height} → "+ + " ".join(f"{key}={record['box'][key]}"+ for key in ("x0", "y0", "x1", "y1")))+ if args.apply:+ jav_poster_crop.write_sidecar(path, record)+ if index % PROGRESS_EVERY == 0:+ print(f"[{index}/{len(todo)}] "+ + ",".join(f"{key} {value}" for key, value in counts.items()),+ flush=True)++ print("\n折痕 {fold},右半居中 {ratio},不裁 {none},读图失败 {unreadable}".format(+ fold=counts[jav_poster_crop.FOLD], ratio=counts[jav_poster_crop.RATIO],+ none=counts[jav_poster_crop.NONE], unreadable=counts["unreadable"]))+ for method in (jav_poster_crop.FOLD, jav_poster_crop.RATIO, jav_poster_crop.NONE):+ for line in samples.get(method, []):+ print(f" {method}: {line}")+ if not args.apply:+ print("只看不写。加 --apply 才写边车;原图任何一档都不改。")+ return 0+++def main(argv: list[str] | None = None) -> int:+ return run(build_parser().parse_args(argv))+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/src/peach/jav_poster_crop.py b/src/peach/jav_poster_crop.pynew file mode 100644index 000000000..96529e8c6--- /dev/null+++ b/src/peach/jav_poster_crop.py@@ -0,0 +1,270 @@+# -*- coding: utf-8 -*-+r"""横版封套里那块 2:3 竖海报的取景框。++JAV 的官方封套是「背面 | 书脊 | 正面」拼成的一整张横图,正面在右侧。Peach 原样+保存这张图(`jav_cover_fetch` 的约定),所以竖海报不是一张新图片,而是一组坐标:+算出来的框写进 sidecar,页面按它取景。原图一个字节都不动。++三种取景方式,写在框的 `method` 里:++- `fold`:Sobel 找到了书脊折痕那道竖直峭壁,正面从折痕右侧开始。+- `ratio`:没找到折痕,退回「右半居中」——正面占右半是封套版式的先验。+- `none`:这张图不该裁。整图框原样返回,页面维持现有的封面取景。++折痕位置的先验来自两份外部实现的实测值,登记在 `docs/REUSE.md`:++- NeoAVDC `c7a430c64013c97a0213cd8a57e2ff5696793a86`(MIT)量 DMM/JavBus 封套,+ 折痕落在全宽约 52.5%,也就是中线右侧 2.5% 宽处;它的 `right` 模式先取右半再+ 居中取 2:3。+- sakuramediabe `7e40ef87c7518c1dc2b6c8c299170ad7395fec6d`(GPL-3.0,只作算法边界+ 参考,不引入代码与运行时)用列向 Sobel 梯度找切点,接受条件是「左右两个峰关于+ 中线对称」或「右峰离中线约 20 像素」。++那个 20 像素是在 800×539 的 DMM 低清封套上量的,换算过来正是 2.5% 宽。所以这里+把它写成宽度比例而不是像素常数:在 2184×1464 的高清图上,同一道折痕离中线 55 像素,+拿 20 像素去卡只会把高清图全判成没有折痕。++OpenCV 不在(`vision` 是可选依赖组)或图读不出来时直接走 `ratio`:取景退化成先验+几何,仍然给得出框,不会让整批停下。+"""+from __future__ import annotations++import json+from collections.abc import Callable, Sequence+from pathlib import Path++from .catalog_rules import (+ is_jav_code,+ is_korean_mib_code,+ is_uncensored_code,+ normalise_code_key,+)++#: 竖海报的宽高比。三处共用:框的形状、`ratio` 回退、越界收缩。+POSTER_ASPECT = 2 / 3++#: 封套的宽高比下限。低于它按竖版正封处理:整张就是正封,没有可裁的横向余量。+#: 这个数和 `SLEEVE_RATIO_MAX` 是 `scripts/detect_cover_faces.py` 与 `web/app.js`+#: 的 `coverAnchor` 共用的同一对判据,三处必须是同一对值,由+#: `tests/test_web_ui.py` 的 `CoverSleeveThresholdTests` 守住。+SLEEVE_RATIO_MIN = 1.2+#: 上限之外是 16:9 官方剧照。整幅都是画面,没有「正面那一块」可推,右半居中会裁出+#: 半张背景,所以这一档不给框。NeoAVDC 对 HEYZO、FC2 与欧美片标 `posterNoCrop`+#: 是同一条判据的另一面:那些封面本身就是成品横版剧照。+SLEEVE_RATIO_MAX = 1.65++#: 找折痕的宽度带。折痕在中线附近,带的右边界放宽到 65% 是为了容纳正面偏窄的封套。+FOLD_BAND = (0.40, 0.65)+#: 折痕相对中线的先验偏移,占全宽的比例(全宽 52.5% 处减去中线 50%)。+SPINE_OFFSET_RATIO = 0.025+#: 偏移与对称两项判据共用的容差,占全宽的比例。在 800 像素宽的封套上等于 10 像素。+FOLD_TOLERANCE_RATIO = 0.0125+#: 峰值要达到全图最强列梯度的这个比例才算一道峭壁。挡住的是平缓横图:那种图在带里+#: 照样有一个最大值,但它只是噪声的最高点,按它切会把画面拦腰截断。+FOLD_MIN_STRENGTH = 0.35+#: 没有折痕时正面的起始位置,占全宽的比例。+RIGHT_HALF = 0.5++FOLD = "fold"+RATIO = "ratio"+NONE = "none"++#: 算法版本号。sidecar 记着它,落后的重算。改动判据、常数或框的形状都要进位。+ALGORITHM_VERSION = "poster-crop-v1"+#: sidecar 与封面同名换后缀:`ABW-232.jpg` → `ABW-232.poster.json`。人脸取景是+#: `.face.json`,两者同目录、同命名风格,各描述一件事:一个是脸在哪,一个是竖框在哪。+SIDECAR_SUFFIX = ".poster.json"++#: 列梯度的来源:一条长度等于图宽的序列,或一个返回它的可调用对象,或 None。+#: 收可调用对象是为了惰性:番号形态或宽高比就能定下 `none` 的图不必解码。+GradientSource = Sequence[float] | Callable[[], Sequence[float] | None] | None+++def crops_to_portrait(code: str | None) -> bool:+ """这个番号的封面是横版封套吗。++ 判据全部走 `catalog_rules` 现有函数,不在这里另立一套番号形态:++ - 不是 JAV 番号的(欧美片目录名、转载站水印)没有封套版式可言;+ - FC2 是个人投稿,封面是投稿者自选的一张横图;+ - HEYZO 与六位日期式的无码番号(`is_uncensored_code`)走成品横版剧照;+ - 韩国 MIB 不是 JAV,发行物的封面版式另算。+ """+ key = normalise_code_key(code)+ if not key or not is_jav_code(key):+ return False+ if key.startswith("FC2"):+ return False+ return not (is_uncensored_code(key) or is_korean_mib_code(key))+++def column_gradient(image) -> list[float] | None:+ """一张 BGR 图按列求和的横向 Sobel 梯度,归一化到 0~1;量不出来返回 None。++ 竖直的折痕在横向梯度上是一整列的强响应,按列求和之后它是一根尖峰;横向的构图+ 边界(地平线、色带)在横向梯度上几乎没有响应,不会混进来。+ """+ try:+ import cv2+ import numpy+ except ImportError: # pragma: no cover - 缺 vision 依赖组+ return None+ if image is None or not getattr(image, "size", 0):+ return None+ gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)+ columns = numpy.abs(cv2.Sobel(gray, cv2.CV_64F, 1, 0, ksize=3)).sum(axis=0)+ peak = float(columns.max()) if columns.size else 0.0+ if peak <= 0:+ return None+ return (columns / peak).tolist()+++def file_gradient(path: Path | str) -> Callable[[], list[float] | None]:+ """把一张封面包成惰性的列梯度来源:真要用到时才解码。"""+ def source() -> list[float] | None:+ try:+ import cv2+ except ImportError: # pragma: no cover - 缺 vision 依赖组+ return None+ return column_gradient(cv2.imread(str(path)))+ return source+++def portrait_crop_box(width: int, height: int,+ gradient_source: GradientSource = None) -> dict:+ """源图尺寸加列梯度 → 2:3 竖海报的取景框。纯函数,不碰文件也不碰 OpenCV。++ 返回 `{"x0", "y0", "x1", "y1", "method"}`,坐标是源图像素,右下开区间。+ `method` 为 `none` 时框是整张图:没有可裁的形状,调用方照原图处理。++ 框严格 2:3——边长按 `(2k, 3k)` 取整,所以比例是精确的而不是四舍五入出来的。+ `k` 取「高度」与「正面宽度」两者允许的较小值,框因此只会向内收,不会探出源图,+ 也不会探出正面那一块。+ """+ width, height = int(width or 0), int(height or 0)+ if width <= 0 or height <= 0:+ return {"x0": 0, "y0": 0, "x1": 0, "y1": 0, "method": NONE}+ ratio = width / height+ if not SLEEVE_RATIO_MIN <= ratio < SLEEVE_RATIO_MAX:+ return _whole(width, height)+ fold = fold_column(width, gradient_source)+ start = fold if fold is not None else round(width * RIGHT_HALF)+ return _fit(width, height, start, FOLD if fold is not None else RATIO)+++def fold_column(width: int, gradient_source: GradientSource = None) -> int | None:+ """列梯度里那道书脊折痕所在的列;不成立返回 None。++ 带内中线两侧各取一个最大值:右峰是折痕本体的候选,左峰用来判对称。两条判据+ 任一成立就采信——折痕压在中线上时两侧峰离中线一样远(折痕有两条边),折痕落在+ 先验位置时右峰离中线约 `SPINE_OFFSET_RATIO` 宽。都不成立说明带里那个最大值只是+ 画面内容,按它切会切进正面。+ """+ profile = gradient_source() if callable(gradient_source) else gradient_source+ if profile is None:+ return None+ profile = list(profile)+ if len(profile) != int(width) or not profile:+ return None+ peak = max(profile)+ if peak <= 0:+ return None+ center = int(width) // 2+ low = max(0, int(width * FOLD_BAND[0]))+ high = min(int(width), int(width * FOLD_BAND[1]))+ left_span = range(low, center)+ right_span = range(center, high)+ if not left_span or not right_span:+ return None+ left_point = max(left_span, key=profile.__getitem__)+ right_point = max(right_span, key=profile.__getitem__)+ if profile[right_point] < peak * FOLD_MIN_STRENGTH:+ return None+ tolerance = int(width) * FOLD_TOLERANCE_RATIO+ symmetric = abs((center - left_point) - (right_point - center)) <= tolerance+ at_spine = abs((right_point - center) - int(width) * SPINE_OFFSET_RATIO) <= tolerance+ return right_point if symmetric or at_spine else None+++def _whole(width: int, height: int) -> dict:+ return {"x0": 0, "y0": 0, "x1": width, "y1": height, "method": NONE}+++def _fit(width: int, height: int, start: int, method: str) -> dict:+ """在 `[start, width)` 这一段里放下最大的 2:3 框,居中,越界就收缩。"""+ start = max(0, min(int(start), width))+ panel = width - start+ unit = min(height // 3, panel // 2)+ if unit <= 0:+ return _whole(width, height)+ box_width, box_height = unit * 2, unit * 3+ x0 = start + (panel - box_width) // 2+ y0 = (height - box_height) // 2+ return {"x0": x0, "y0": y0, "x1": x0 + box_width, "y1": y0 + box_height,+ "method": method}+++def crop_record(code: str | None, width: int, height: int,+ gradient_source: GradientSource = None) -> dict:+ """可直接落盘的 sidecar 内容:算法版本、源图尺寸、框。++ 番号形态先判:不该裁的图连梯度都不算,`gradient_source` 是惰性的就一次都不解码。+ """+ width, height = int(width or 0), int(height or 0)+ box = (portrait_crop_box(width, height, gradient_source)+ if crops_to_portrait(code) else _whole(width, height))+ return {"version": ALGORITHM_VERSION, "px": [width, height], "box": box}+++def sidecar_path(image_path: Path | str) -> Path:+ return Path(image_path).with_suffix(SIDECAR_SUFFIX)+++def read_sidecar(image_path: Path | str) -> dict | None:+ try:+ data = json.loads(sidecar_path(image_path).read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+ return data if isinstance(data, dict) else None+++def write_sidecar(image_path: Path | str, record: dict) -> Path:+ path = sidecar_path(image_path)+ path.write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8")+ return path+++def is_current(record: dict | None, width: int, height: int) -> bool:+ """这份 sidecar 还作数吗:版本要对得上,源图尺寸也要对得上。++ 尺寸也要对,是因为封面会被更大的那张原子替换(`jav_cover_fetch` 只升不降)。+ 版本没变而图换了的话,框仍然是按旧尺寸算的,落在新图上是一块错位的区域——+ 而错位在页面上和「这张图本来就该这么取景」看不出区别。+ """+ if not isinstance(record, dict) or record.get("version") != ALGORITHM_VERSION:+ return False+ return list(record.get("px") or []) == [int(width), int(height)]+++def projection(record: dict | None) -> dict | None:+ """sidecar → API 的 `poster_box` 字段;不该裁、算不出、读不出都是 None。++ 给出源图像素坐标加源图尺寸 `px`,消费方据此自己换算:竖框容器用+ `object-fit: cover` 时,横向 `object-position` 的百分比是 `x0 / (px[0] - 框宽)`。+ """+ if not isinstance(record, dict) or record.get("version") != ALGORITHM_VERSION:+ return None+ box = record.get("box")+ size = record.get("px")+ if not isinstance(box, dict) or box.get("method") in (None, NONE):+ return None+ try:+ edges = {name: int(box[name]) for name in ("x0", "y0", "x1", "y1")}+ width, height = int(size[0]), int(size[1])+ except (KeyError, IndexError, TypeError, ValueError):+ return None+ if edges["x1"] <= edges["x0"] or edges["y1"] <= edges["y0"]:+ return None+ if edges["x1"] > width or edges["y1"] > height:+ return None+ return {**edges, "method": str(box["method"]), "px": [width, height]}diff --git a/src/peach/web_catalog.py b/src/peach/web_catalog.pyindex fc3362650..e5d874646 100644--- a/src/peach/web_catalog.py+++ b/src/peach/web_catalog.py@@ -352,6 +352,9 @@ def q_items(contract: WebContract, args):attach_jav_display_fields(r, r.get("tags", ()), r.pop("_entity_kinds", ()))if r["has_cover"]:r["cover_frame"] = contract.cover_frame(r.get("code"))+ # 竖版位置要的是一个框,不是锚点:横版封套里 2:3 那一块由离线脚本算好+ # 写在边车里,没算过或本来就不该裁就是 null,版式退回整张封面。+ r["poster_box"] = contract.poster_box(r.get("code"))r.pop("snapshot_path", None)r.pop("path", None) # 路径不外发,串流走 idattach_saved_follow_cards(contract, rows)@@ -835,6 +838,7 @@ def q_related(contract: WebContract, aid, limit=24):)if d["has_cover"]:d["cover_frame"] = contract.cover_frame(d.get("code"))+ d["poster_box"] = contract.poster_box(d.get("code"))d.pop("release_date", None)d.pop("snapshot_path", None)return {"items": picked[:limit]}diff --git a/src/peach/web_contract.py b/src/peach/web_contract.pyindex 022803d88..b8c923f68 100644--- a/src/peach/web_contract.py+++ b/src/peach/web_contract.py@@ -28,6 +28,11 @@ from .catalog_rules import (part_marker,)from .entities import normalize_entity_name+# 卡片上的 `poster_box` 字段由这两个名字定形:框由 `portrait_crop_box` 算,+# 端点侧由 `WebContract.poster_box` 从边车读出来。字段的形状写在+# `jav_poster_crop.projection` 的文档串里——源图像素坐标加源图尺寸,+# 不该裁、没算过与读不出一律 null。+from .jav_poster_crop import POSTER_ASPECT, portrait_crop_box# 这几个处理器本来就住在别的域模块里,旧 `web_contract` 只是把它们又摊了一遍。# tests 里三十多处按 `web_contract.X` 调用,所以再导出留着;新代码请直接 import 那边。from .web_activity import (@@ -118,6 +123,7 @@ from .web_stats import ()__all__ = [+ "POSTER_ASPECT", "portrait_crop_box","AD_DIRPACK", "AD_DOMAIN", "ASSET_REFERENCE_TABLES", "BUNDLE_DIR_ASSETS", "CACHE_TTL","CARD_PERFORMERS", "CONTENT_BYTES", "COST", "ContractRouteNotFound", "EDITION_ORDER","FAVICON",diff --git a/src/peach/web_resource_sync.py b/src/peach/web_resource_sync.pyindex 841d6ca1f..25aedf07f 100644--- a/src/peach/web_resource_sync.py+++ b/src/peach/web_resource_sync.py@@ -16,6 +16,7 @@ from concurrent.futures import ThreadPoolExecutorfrom pathlib import Pathfrom typing import Callable, Protocol, Sequence+from . import jav_poster_cropfrom .catalog_rules import dir_expr, normalise_code_key, photo_set_titlefrom .config import LOCATION_ROOT_DECLARATIONSfrom .jobs import BackgroundJob@@ -256,9 +257,13 @@ def _resource_orphan_plan(contract: ResourceSyncContract, excluded_ids: Sequenceand contract.cover_root.is_dir()):for path in contract.cover_root.iterdir():key = ""- if path.name.endswith(".face.json"):- key = path.name[:-10]- elif path.suffix.lower() == ".jpg":+ # 边车跟着它描述的那张封面一起走,否则封面被清掉之后目录里会留下一批+ # 指向不存在的图的框和脸。+ for suffix in (".face.json", jav_poster_crop.SIDECAR_SUFFIX):+ if path.name.endswith(suffix):+ key = path.name[:-len(suffix)]+ break+ if not key and path.suffix.lower() == ".jpg":key = path.stemif key and normalise_code_key(key) not in active_codes and path.is_file():_cache_file(path, "covers", files)diff --git a/src/peach/web_state.py b/src/peach/web_state.pyindex 9c6f147b6..07ebac631 100644--- a/src/peach/web_state.py+++ b/src/peach/web_state.py@@ -32,6 +32,7 @@ from .config import (STATE_DIR,)from . import brand_marks+from . import jav_poster_cropfrom .jobs import BackgroundJobfrom .media import normalized_path# `previews` 是取图那一侧,不是 web 域处理器:依赖方向仍然只有一个走法。落盘名的@@ -280,8 +281,12 @@ class WebContract:path = self.cover_root / f"{key}.jpg"return path if path.is_file() else None- def cover_index(self) -> dict[str, dict | None]:- """封面目录扫一遍的索引:casefold(归一番号) → 取景 `{"cx": …, "cy": …}` 或 None。+ def cover_index(self) -> dict[str, dict]:+ """封面目录扫一遍的索引:casefold(归一番号) → 两份取景提示。++ 值的形状是 `{"frame": 人脸中心或 None, "poster": 竖海报框或 None}`。两份+ 边车各描述一件事,一次目录扫描一起收齐:`.face.json` 说脸在哪,+ `.poster.json` 说 2:3 竖框在哪。卡片列表逐行问「有封面吗」「取景是多少」,一页 60 行就是 120+ 次 stat 加读文件;封面目录一次 scandir 就覆盖全部番号,结果走 `cached()` 的 TTL。@@ -292,16 +297,20 @@ class WebContract:"""return self.cached("cover-index", self._scan_cover_root)- def _scan_cover_root(self) -> dict[str, dict | None]:- """一次目录扫描同时收集封面存在性和 sidecar 取景。目录不存在就是空索引。"""- scanned: dict[str, dict | None] = {}+ def _scan_cover_root(self) -> dict[str, dict]:+ """一次目录扫描同时收集封面存在性和两份 sidecar。目录不存在就是空索引。"""+ scanned: dict[str, dict] = {}try:with os.scandir(self.cover_root) as entries:for entry in entries:if not entry.name.endswith(".jpg"):continue- scanned[entry.name[:-len(".jpg")].casefold()] = self._cover_focus(- entry.path[:-len(".jpg")] + ".face.json")+ stem = entry.path[:-len(".jpg")]+ scanned[entry.name[:-len(".jpg")].casefold()] = {+ "frame": self._cover_focus(stem + ".face.json"),+ "poster": self._poster_box(+ stem + jav_poster_crop.SIDECAR_SUFFIX),+ }except OSError:return {}return scanned@@ -323,6 +332,19 @@ class WebContract:focus = {axis: face[axis] for axis in ("cx", "cy") if axis in face}return focus or None+ @staticmethod+ def _poster_box(sidecar: str) -> dict | None:+ """sidecar 里那个 2:3 竖海报框。算法版本落后、判定为不裁、读不出都是 None。++ 校验和形状判据都在 `jav_poster_crop.projection` 一处,这里只负责把文件读+ 进来:页面拿到的框必须和算它的那份代码是同一套判据。+ """+ try:+ with open(sidecar, encoding="utf-8") as handle:+ return jav_poster_crop.projection(json.load(handle))+ except (OSError, ValueError):+ return None+def has_cover(self, code: str | None) -> bool:key = normalise_code_key(code)# 索引的键是 casefold 过的:`is_file()` 在 Windows 与 macOS 的默认文件系统上@@ -461,6 +483,17 @@ class WebContract:横向只用在 16:9 官方剧照上——那种图在大图容器里只会横向裁,写死的居中会把偏在一侧的人整个切掉。取不到时前端退回固定取景,不影响显示。"""+ return (self._cover_entry(code) or {}).get("frame")++ def poster_box(self, code: str | None) -> dict | None:+ """封面里那块 2:3 竖海报的取景框,源图像素坐标加源图尺寸。++ 没算过、算法版本落后、或这个番号的封面本来就不该裁(`jav_poster_crop`+ 的 `none` 一档)都返回 None,竖版位置退回整张封面。+ """+ return (self._cover_entry(code) or {}).get("poster")++ def _cover_entry(self, code: str | None) -> dict | None:key = normalise_code_key(code)return self.cover_index().get(key.casefold()) if key else Nonediff --git a/tests/test_jav_poster_crop.py b/tests/test_jav_poster_crop.pynew file mode 100644index 000000000..dcc1f057e--- /dev/null+++ b/tests/test_jav_poster_crop.py@@ -0,0 +1,338 @@+# -*- coding: utf-8 -*-+"""横版封套里那块 2:3 竖海报取景框的判据。++图都是 Pillow 当场合成的,不依赖真实封面:折痕是一条画上去的竖线,位置已知,+所以「找到的那一列对不对」有确定答案可比。+"""+from __future__ import annotations++import functools+import io+import json+import tempfile+import unittest+from pathlib import Path++from PIL import Image++from peach import jav_poster_crop+from peach.jav_poster_crop import FOLD, NONE, RATIO+++def sleeve(width: int, height: int, fold: int | None) -> Image.Image:+ """一张封套:左边是背面,右边是正面,中间可选一条书脊折痕。"""+ image = Image.new("RGB", (width, height), (200, 200, 200))+ if fold is None:+ return image+ for x in range(fold, min(fold + 3, width)):+ for y in range(height):+ image.putpixel((x, y), (0, 0, 0))+ for x in range(min(fold + 3, width), width):+ for y in range(height):+ image.putpixel((x, y), (150, 150, 150))+ return image+++def edge_left(width: int, height: int) -> Image.Image:+ """折痕带之外有一条强边,带内平整:这张图没有可采信的折痕。"""+ image = Image.new("RGB", (width, height), (200, 200, 200))+ for x in range(0, int(width * 0.1)):+ for y in range(height):+ image.putpixel((x, y), (10, 10, 10))+ return image+++def gradient_of(image: Image.Image):+ import cv2+ import numpy++ array = cv2.cvtColor(numpy.array(image), cv2.COLOR_RGB2BGR)+ return jav_poster_crop.column_gradient(array)+++def opencv_available() -> bool:+ try:+ import cv2 # noqa: F401+ import numpy # noqa: F401+ except ImportError:+ return False+ return True++[email protected]_cache(maxsize=1)+def batch_script():+ """把 `scripts/poster_crop_boxes.py` 当模块载入,按文件路径而不是包名。"""+ import importlib.util++ root = Path(__file__).resolve().parents[1]+ spec = importlib.util.spec_from_file_location(+ "poster_crop_boxes", root / "scripts" / "poster_crop_boxes.py")+ module = importlib.util.module_from_spec(spec)+ spec.loader.exec_module(module)+ return module+++class CropShapeTests(unittest.TestCase):+ """框的形状:严格 2:3,落在源图里,不越出正面那一块。"""++ def assert_two_by_three(self, box: dict, width: int, height: int):+ self.assertEqual((box["x1"] - box["x0"]) * 3, (box["y1"] - box["y0"]) * 2,+ f"框不是 2:3:{box}")+ self.assertGreaterEqual(box["x0"], 0)+ self.assertGreaterEqual(box["y0"], 0)+ self.assertLessEqual(box["x1"], width)+ self.assertLessEqual(box["y1"], height)++ def test_the_box_stays_exactly_two_by_three_at_every_sleeve_size(self):+ for width, height in ((800, 539), (2184, 1464), (1000, 674), (760, 600)):+ with self.subTest(size=(width, height)):+ box = jav_poster_crop.portrait_crop_box(width, height)+ self.assertEqual(box["method"], RATIO)+ self.assert_two_by_three(box, width, height)++ def test_the_box_shrinks_instead_of_reaching_past_the_front_panel(self):+ """正面窄到放不下满高的 2:3 时,框按正面宽度收,不往折痕左边借。"""+ box = jav_poster_crop.portrait_crop_box(1000, 700, [0.0] * 1000)+ self.assertGreaterEqual(box["x0"], 500)+ self.assert_two_by_three(box, 1000, 700)++ def test_a_degenerate_size_gives_an_empty_box_and_no_method(self):+ self.assertEqual(jav_poster_crop.portrait_crop_box(0, 0),+ {"x0": 0, "y0": 0, "x1": 0, "y1": 0, "method": NONE})+++class MethodTests(unittest.TestCase):+ """三档各自的触发条件。"""++ @unittest.skipUnless(opencv_available(), "缺 vision 依赖组")+ def test_a_visible_spine_is_found_and_the_front_starts_there(self):+ width, height, fold = 800, 540, 420+ profile = gradient_of(sleeve(width, height, fold))+ self.assertIsNotNone(profile)+ found = jav_poster_crop.fold_column(width, profile)+ self.assertIsNotNone(found, "画上去的折痕没被找到")+ self.assertLessEqual(abs(found - fold), 2, found)+ box = jav_poster_crop.portrait_crop_box(width, height, profile)+ self.assertEqual(box["method"], FOLD)+ self.assertGreaterEqual(box["x0"], fold)+ self.assertEqual((box["x1"] - box["x0"]) * 3, (box["y1"] - box["y0"]) * 2)++ @unittest.skipUnless(opencv_available(), "缺 vision 依赖组")+ def test_without_a_spine_the_front_falls_back_to_the_right_half(self):+ width, height = 800, 540+ profile = gradient_of(edge_left(width, height))+ self.assertIsNone(jav_poster_crop.fold_column(width, profile))+ box = jav_poster_crop.portrait_crop_box(width, height, profile)+ self.assertEqual(box["method"], RATIO)+ self.assertGreaterEqual(box["x0"], width // 2)++ def test_a_missing_gradient_falls_back_to_the_right_half(self):+ """OpenCV 不在时取景仍然给得出框,只是退化成先验几何。"""+ box = jav_poster_crop.portrait_crop_box(800, 540, None)+ self.assertEqual(box["method"], RATIO)++ def test_a_portrait_or_square_image_is_not_cropped(self):+ for width, height in ((600, 900), (800, 800), (900, 800)):+ with self.subTest(size=(width, height)):+ box = jav_poster_crop.portrait_crop_box(width, height)+ self.assertEqual(box, {"x0": 0, "y0": 0, "x1": width, "y1": height,+ "method": NONE})++ def test_a_sixteen_by_nine_still_is_not_cropped(self):+ """整幅都是画面的官方剧照没有「正面那一块」,右半居中会裁出半张背景。"""+ box = jav_poster_crop.portrait_crop_box(1920, 1080)+ self.assertEqual(box["method"], NONE)++ def test_the_band_peak_must_be_a_real_cliff(self):+ """带里总有一个最大值,它不够陡就只是噪声的最高点,按它切会切进画面。"""+ profile = [0.0] * 800+ profile[80] = 1.0+ profile[425] = 0.1+ self.assertIsNone(jav_poster_crop.fold_column(800, profile))+ profile[425] = 0.9+ self.assertEqual(jav_poster_crop.fold_column(800, profile), 425)++ def test_a_symmetric_pair_around_the_centre_is_accepted(self):+ """折痕压在中线上时两条边离中线一样远,这是另一条采信路径。"""+ profile = [0.0] * 800+ profile[396] = 1.0+ profile[404] = 1.0+ self.assertEqual(jav_poster_crop.fold_column(800, profile), 404)++ def test_a_peak_far_from_both_priors_is_rejected(self):+ profile = [0.0] * 800+ profile[330] = 1.0+ profile[510] = 1.0+ self.assertIsNone(jav_poster_crop.fold_column(800, profile))++ def test_the_spine_prior_scales_with_width(self):+ """先验偏移是全宽的 2.5%,在高清封套上是五十多像素而不是二十像素。"""+ for width in (800, 2184):+ with self.subTest(width=width):+ profile = [0.0] * width+ profile[round(width * 0.525)] = 1.0+ self.assertEqual(jav_poster_crop.fold_column(width, profile),+ round(width * 0.525))++ def test_a_profile_that_does_not_match_the_image_is_ignored(self):+ self.assertIsNone(jav_poster_crop.fold_column(800, [1.0] * 400))+++class CodeShapeTests(unittest.TestCase):+ """哪些番号的封面是横版封套。判据全部走 `catalog_rules` 现有函数。"""++ def test_studio_and_amateur_codes_are_sleeves(self):+ for code in ("ABW-232", "abw-232", "278GYAN-017", "259LUXU-1475"):+ with self.subTest(code=code):+ self.assertTrue(jav_poster_crop.crops_to_portrait(code))++ def test_finished_landscape_artwork_is_not_cropped(self):+ for code in ("HEYZO-1380", "FC2-PPV-1812235", "FC2-1812235",+ "040221-001", "092620-001"):+ with self.subTest(code=code):+ self.assertFalse(jav_poster_crop.crops_to_portrait(code))++ def test_non_jav_and_korean_codes_are_not_cropped(self):+ for code in ("", None, "20211103_JENNIFERMENDEZ", "HHD800",+ "AR-101", "NOAH-101"):+ with self.subTest(code=code):+ self.assertFalse(jav_poster_crop.crops_to_portrait(code))++ def test_a_western_release_is_stopped_by_the_shape_of_its_artwork(self):+ """欧美片的编号和厂牌番号同形,番号这一关拦不住它,宽高比这一关拦得住。++ 它们的封面是成品横版剧照,落在 16:9 一档,所以走的是 `none`。+ """+ self.assertTrue(jav_poster_crop.crops_to_portrait("BLACKED-2021"))+ self.assertEqual(+ jav_poster_crop.crop_record("BLACKED-2021", 1920, 1080)["box"]["method"],+ NONE)+++class RecordTests(unittest.TestCase):+ """边车的内容、读写与失效判定。"""++ def setUp(self):+ self.root = Path(tempfile.mkdtemp()).resolve()+ self.cover = self.root / "ABW-232.jpg"+ sleeve(800, 540, 420).save(self.cover)++ def test_a_shape_that_is_not_cropped_never_touches_the_gradient(self):+ """番号形态先判:不该裁的图连解码都不做。"""+ calls = []++ def source():+ calls.append(1)+ return [0.0] * 800++ record = jav_poster_crop.crop_record("HEYZO-1380", 800, 540, source)+ self.assertEqual(record["box"]["method"], NONE)+ self.assertEqual(calls, [])++ def test_the_record_carries_the_version_the_size_and_the_box(self):+ record = jav_poster_crop.crop_record("ABW-232", 800, 540, [0.0] * 800)+ self.assertEqual(record["version"], jav_poster_crop.ALGORITHM_VERSION)+ self.assertEqual(record["px"], [800, 540])+ self.assertEqual(record["box"]["method"], RATIO)++ def test_the_sidecar_sits_beside_the_cover_and_round_trips(self):+ record = jav_poster_crop.crop_record("ABW-232", 800, 540, [0.0] * 800)+ path = jav_poster_crop.write_sidecar(self.cover, record)+ self.assertEqual(path.name, "ABW-232.poster.json")+ self.assertEqual(jav_poster_crop.read_sidecar(self.cover), record)+ self.assertTrue(jav_poster_crop.is_current(record, 800, 540))++ def test_an_outdated_version_or_a_replaced_cover_forces_a_recount(self):+ record = jav_poster_crop.crop_record("ABW-232", 800, 540, [0.0] * 800)+ self.assertFalse(jav_poster_crop.is_current(record, 2184, 1464),+ "封面被更大的那张换掉之后,旧框落在新图上是一块错位的区域")+ stale = dict(record, version="poster-crop-v0")+ self.assertFalse(jav_poster_crop.is_current(stale, 800, 540))+ self.assertFalse(jav_poster_crop.is_current(None, 800, 540))++ def test_a_broken_sidecar_reads_as_missing(self):+ jav_poster_crop.sidecar_path(self.cover).write_text("{not json",+ encoding="utf-8")+ self.assertIsNone(jav_poster_crop.read_sidecar(self.cover))+++class ProjectionTests(unittest.TestCase):+ """API 字段的投影:只有真的算出框的那一档才给值。"""++ def test_a_real_box_projects_with_the_source_size(self):+ record = jav_poster_crop.crop_record("ABW-232", 800, 540, [0.0] * 800)+ projected = jav_poster_crop.projection(record)+ self.assertEqual(projected["px"], [800, 540])+ self.assertEqual(projected["method"], RATIO)+ self.assertEqual((projected["x1"] - projected["x0"]) * 3,+ (projected["y1"] - projected["y0"]) * 2)++ def test_everything_unusable_projects_to_none(self):+ for record in (None, {}, {"version": "poster-crop-v0"},+ jav_poster_crop.crop_record("HEYZO-1380", 800, 540),+ {"version": jav_poster_crop.ALGORITHM_VERSION,+ "px": [800, 540], "box": {"x0": 0, "x1": 0, "y0": 0,+ "y1": 0, "method": RATIO}},+ {"version": jav_poster_crop.ALGORITHM_VERSION,+ "px": [800, 540], "box": {"x0": 0, "x1": 900, "y0": 0,+ "y1": 540, "method": RATIO}}):+ with self.subTest(record=record):+ self.assertIsNone(jav_poster_crop.projection(record))+++class BatchScriptTests(unittest.TestCase):+ """批处理只写边车、只处理该处理的那些图。"""++ def setUp(self):+ self.script = batch_script()+ self.root = Path(tempfile.mkdtemp()).resolve()+ self.cover = self.root / "ABW-232.jpg"+ sleeve(800, 540, 420).save(self.cover)+ self.before = self.cover.read_bytes()++ def run_script(self, *argv):+ return self.script.main([*argv, "--covers", str(self.root)])++ def test_a_dry_run_writes_nothing(self):+ self.assertEqual(self.run_script(), 0)+ self.assertFalse(jav_poster_crop.sidecar_path(self.cover).exists())++ def test_apply_writes_the_sidecar_and_leaves_the_image_untouched(self):+ self.assertEqual(self.run_script("--apply"), 0)+ record = json.loads(+ jav_poster_crop.sidecar_path(self.cover).read_text(encoding="utf-8"))+ self.assertEqual(record["px"], [800, 540])+ self.assertIn(record["box"]["method"], (FOLD, RATIO))+ self.assertEqual(self.cover.read_bytes(), self.before,+ "取景是边车元数据,原图一个字节都不动")++ def test_a_current_sidecar_is_skipped_and_a_stale_one_is_redone(self):+ self.run_script("--apply")+ self.assertEqual(self.script.pending([self.cover], False), [])+ stale = jav_poster_crop.read_sidecar(self.cover)+ jav_poster_crop.write_sidecar(self.cover, dict(stale, version="poster-crop-v0"))+ self.assertEqual(self.script.pending([self.cover], False),+ [(self.cover, (800, 540))])++ def test_an_unreadable_cover_is_counted_and_never_given_a_box(self):+ broken = self.root / "BAD-001.jpg"+ broken.write_bytes(b"not an image")+ self.assertEqual(self.run_script("--apply"), 0)+ self.assertFalse(jav_poster_crop.sidecar_path(broken).exists())+++class ImageSizeTests(unittest.TestCase):+ def test_the_size_probe_reports_none_for_junk(self):+ root = Path(tempfile.mkdtemp()).resolve()+ broken = root / "x.jpg"+ broken.write_bytes(b"nope")+ self.assertIsNone(batch_script().image_size(broken))+ good = root / "y.jpg"+ buffer = io.BytesIO()+ Image.new("RGB", (40, 30)).save(buffer, "JPEG")+ good.write_bytes(buffer.getvalue())+ self.assertEqual(batch_script().image_size(good), (40, 30))+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_rm_web.py b/tests/test_rm_web.pyindex ad50f1c51..3464ef77b 100644--- a/tests/test_rm_web.py+++ b/tests/test_rm_web.py@@ -12,7 +12,7 @@ from dataclasses import replacefrom pathlib import Pathfrom unittest import mock-from peach import catalog_rules, web_batch, web_catalog, web_stats+from peach import catalog_rules, jav_poster_crop, web_batch, web_catalog, web_statsfrom peach import web_contract as rm_webfrom peach.previews import entity_image_key, logo_keyfrom support.ledger import fresh_ledger@@ -2065,6 +2065,54 @@ class JavModeAndCoverTests(unittest.TestCase):(self.covers / "ABW-232.face.json").write_text("{not json", encoding="utf-8")self.assertIsNone(self.contract.cover_frame("ABW-232"))+ def install_poster_sidecar(self, method: str = "fold") -> None:+ (self.covers / "ABW-232.jpg").write_bytes(b"x")+ (self.covers / "ABW-232.poster.json").write_text(json.dumps({+ "version": jav_poster_crop.ALGORITHM_VERSION, "px": [800, 540],+ "box": {"x0": 429, "y0": 0, "x1": 789, "y1": 540, "method": method},+ }), encoding="utf-8")+ self.contract.cache_bust()++ def test_the_card_carries_the_portrait_crop_box_when_it_has_been_computed(self):+ """竖版位置要的是一个框,不是锚点:2:3 那一块由离线脚本算好写在边车里。"""+ self.install_poster_sidecar()+ self.assertEqual(self.contract.poster_box("ABW-232"),+ {"x0": 429, "y0": 0, "x1": 789, "y1": 540,+ "method": "fold", "px": [800, 540]})+ rows = {row["id"]: row for row in+ rm_web.q_items(self.contract, {"jav": "1", "limit": "20"})["items"]}+ self.assertEqual(rows[1]["poster_box"]["method"], "fold")++ def test_a_cover_that_should_not_be_cropped_reports_no_box(self):+ """不该裁的那一档也会落边车,但它不是一个可用的框,字段给 null。"""+ self.install_poster_sidecar(method="none")+ self.assertIsNone(self.contract.poster_box("ABW-232"))+ rows = {row["id"]: row for row in+ rm_web.q_items(self.contract, {"jav": "1", "limit": "20"})["items"]}+ self.assertIsNone(rows[1]["poster_box"])++ def test_a_stale_or_corrupt_poster_sidecar_is_ignored(self):+ (self.covers / "ABW-232.jpg").write_bytes(b"x")+ (self.covers / "ABW-232.poster.json").write_text("{not json", encoding="utf-8")+ self.assertIsNone(self.contract.poster_box("ABW-232"))+ (self.covers / "ABW-232.poster.json").write_text(json.dumps({+ "version": "poster-crop-v0", "px": [800, 540],+ "box": {"x0": 429, "y0": 0, "x1": 789, "y1": 540, "method": "fold"},+ }), encoding="utf-8")+ self.contract.cache_bust()+ self.assertIsNone(self.contract.poster_box("ABW-232"))++ def test_the_two_cover_sidecars_do_not_shadow_each_other(self):+ """脸和竖框各描述一件事,同一次目录扫描一起收齐,缺一份不影响另一份。"""+ self.install_poster_sidecar()+ (self.covers / "ABW-232.face.json").write_text(+ '{"ratio":1.49,"face":{"cx":0.82,"cy":0.19}}', encoding="utf-8")+ self.contract.cache_bust()+ self.assertEqual(self.contract.cover_frame("ABW-232"),+ {"cx": 0.82, "cy": 0.19})+ self.assertEqual(self.contract.poster_box("ABW-232")["x0"], 429)+ self.assertTrue(self.contract.has_cover("ABW-232"))+diff --git a/tests/test_web_ui.py b/tests/test_web_ui.pyindex a50c11ae8..028008c32 100644--- a/tests/test_web_ui.py+++ b/tests/test_web_ui.py@@ -10467,10 +10467,10 @@ class IndexHtmlTagBalanceTests(unittest.TestCase):class CoverSleeveThresholdTests(unittest.TestCase):- def test_the_page_and_the_face_script_share_the_sleeve_thresholds(self):- """脚本按封套丢掉左半边的脸,页面按同一对阈值决定取景;两边的数必须是同一对。"""+ def test_the_page_and_the_module_share_the_sleeve_thresholds(self):+ """页面按这对阈值决定取景,模块按它分档竖海报;两边的数必须是同一对。"""root = Path(__file__).resolve().parents[1]- source = (root / "scripts" / "detect_cover_faces.py").read_text(encoding="utf-8")+ source = (root / "src" / "peach" / "jav_poster_crop.py").read_text(encoding="utf-8")low = float(re.search(r"^SLEEVE_RATIO_MIN = ([\d.]+)", source, re.M).group(1))high = float(re.search(r"^SLEEVE_RATIO_MAX = ([\d.]+)", source, re.M).group(1))page = (root / "web" / "app.js").read_text(encoding="utf-8")@@ -10479,6 +10479,15 @@ class CoverSleeveThresholdTests(unittest.TestCase):self.assertEqual((low, high), (float(anchor.group(2)), float(anchor.group(1))))self.assertLess(low, high)+ def test_the_face_script_takes_the_thresholds_from_the_module(self):+ """脚本按封套丢掉左半边的脸,用的必须是模块里那一份,不是自己抄的一份。"""+ root = Path(__file__).resolve().parents[1]+ source = (root / "scripts" / "detect_cover_faces.py").read_text(encoding="utf-8")+ self.assertIn(+ "from peach.jav_poster_crop import SLEEVE_RATIO_MAX, SLEEVE_RATIO_MIN", source)+ self.assertIsNone(re.search(r"^SLEEVE_RATIO_M(?:IN|AX) = ", source, re.M),+ "阈值抄成第二份就会和页面漂开")+class BoardStyleIsolationTests(unittest.TestCase):def test_the_board_layer_is_the_only_interface_and_ships_unconditionally(self):