Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: nudge cover framing vertically with detected face position

Peach local maintenance1cb73388f048
diff --git a/scripts/detect_cover_faces.py b/scripts/detect_cover_faces.py
new file mode 100644
index 000000000..3afe26f7d
--- /dev/null
+++ b/scripts/detect_cover_faces.py
@@ -0,0 +1,108 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+r"""给已落盘的封面算人脸位置,供 4:3 版式取景用。
+
+固定取景(右侧 53%、纵向 22%)在多数封套上够用,但人物在画面里的高低差别很大,
+写死的纵向位置会把一部分作品裁掉下巴或留出大片空白。人脸只用来做**纵向微调**,
+横向仍由版式决定——横向靠几何规则已经稳定,没必要交给检出结果。
+
+判据来自 46 张真实封面的实测:
+
+- Haar 正脸检出 24/46。检出率不高,所以这是「锦上添花」而不是取景的前提,
+ 取不到就退回固定值。
+- 21/24 个检出落在 x 68~90%、y 12~33%,正是长封套右侧正封上的人脸位置。
+- 剩下 3 个是假阳性:`278GYAN-017` 检到 x=2.9%(封套最左的剧照拼贴),
+ `KAVR-428` 一张图检出 7 个框。所以**长封套上落在左半边的检出一律丢弃**——
+ 那必然是剧照区,不是正封。
+
+结果写成每张封面一个 sidecar(`<番号>.face.json`),不写单一索引文件:抓取器
+可能正在并发写同目录,单文件会互相覆盖。脚本可反复运行,已算过的默认跳过。
+"""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import cv2
+
+from peach.config import COVER_DIR
+
+#: 长封套的宽高比下限。低于它按竖版正封处理(整张就是正封,没有剧照区)。
+SLEEVE_RATIO = 1.2
+#: 长封套上正封的起始横向位置。左边是剧照拼贴,检出必然是假阳性。
+FRONT_START = 0.468
+#: 纵向取景的合理区间。超出这个范围的检出多半不是主体人物。
+MIN_Y, MAX_Y = 0.05, 0.60
+
+
+def detect(path: Path, cascade) -> dict | None:
+ image = cv2.imread(str(path))
+ if image is None:
+ return None
+ height, width = image.shape[:2]
+ ratio = width / height if height else 0
+ grey = cv2.equalizeHist(cv2.cvtColor(image, cv2.COLOR_BGR2GRAY))
+ faces = cascade.detectMultiScale(
+ grey, scaleFactor=1.08, minNeighbors=6,
+ minSize=(max(40, width // 25), max(40, height // 25)))
+ if len(faces) == 0:
+ return {"ratio": round(ratio, 3), "face": None}
+
+ usable = []
+ for x, y, w, h in faces:
+ cx, cy = (x + w / 2) / width, (y + h / 2) / height
+ # 长封套左半边是剧照拼贴,那里的「人脸」不是正封主体。
+ if ratio >= SLEEVE_RATIO and cx < FRONT_START:
+ continue
+ if not (MIN_Y <= cy <= MAX_Y):
+ continue
+ usable.append((w * h, cx, cy))
+ if not usable:
+ return {"ratio": round(ratio, 3), "face": None}
+ _, cx, cy = max(usable, key=lambda item: item[0])
+ return {"ratio": round(ratio, 3), "face": {"cx": round(cx, 3), "cy": round(cy, 3)}}
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="给封面算人脸位置,供取景用")
+ parser.add_argument("--covers", type=Path, default=COVER_DIR)
+ parser.add_argument("--redo", action="store_true", help="重算已有的 sidecar")
+ parser.add_argument("--limit", type=int, default=0)
+ return parser
+
+
+def run(args: argparse.Namespace) -> int:
+ cascade = cv2.CascadeClassifier(
+ cv2.data.haarcascades + "haarcascade_frontalface_alt2.xml")
+ if cascade.empty():
+ raise SystemExit("级联文件不可用:opencv-python-headless 需为 4.x")
+
+ covers = sorted(args.covers.glob("*.jpg"))
+ todo = [p for p in covers
+ if args.redo or not p.with_suffix(".face.json").is_file()]
+ if args.limit:
+ todo = todo[:args.limit]
+ print(f"封面 {len(covers)} 张,待处理 {len(todo)} 张")
+
+ stats = {"face": 0, "none": 0, "unreadable": 0}
+ for index, path in enumerate(todo, 1):
+ result = detect(path, cascade)
+ if result is None:
+ stats["unreadable"] += 1
+ print(f"[{index}/{len(todo)}] 读图失败 {path.name}", flush=True)
+ continue
+ stats["face" if result["face"] else "none"] += 1
+ path.with_suffix(".face.json").write_text(
+ json.dumps(result, ensure_ascii=False), encoding="utf-8")
+ print(f"\n检出 {stats['face']},未检出 {stats['none']},读图失败 {stats['unreadable']}")
+ print("未检出的会退回固定取景,不影响显示。")
+ 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/web_contract.py b/src/peach/web_contract.py
index 4716da12d..5c194340a 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -151,6 +151,25 @@ class WebContract:
def has_cover(self, code: str | None) -> bool:
return self.cover_path(code) is not None
+ def cover_frame(self, code: str | None) -> dict | None:
+ """封面的取景提示:宽高比和人脸中心。没算过或没检出就返回 None。
+
+ 只用来做纵向微调,横向仍由版式决定——横向靠几何规则已经稳定。
+ 取不到时前端退回固定取景,不影响显示。
+ """
+ path = self.cover_path(code)
+ if path is None:
+ return None
+ sidecar = path.with_suffix(".face.json")
+ if not sidecar.is_file():
+ return None
+ try:
+ data = json.loads(sidecar.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ face = data.get("face")
+ return {"cy": face["cy"]} if isinstance(face, dict) and "cy" in face else None
+
def has_fts(self) -> bool:
if self._fts_available is None:
connection = self.db()
@@ -333,6 +352,8 @@ def q_items(contract: WebContract, args):
r["cost"] = COST.get(r["location"], "metered")
r["has_thumb"] = contract.has_snapshot(r["snapshot_path"])
r["has_cover"] = contract.has_cover(r.get("code"))
+ if r["has_cover"]:
+ r["cover_frame"] = contract.cover_frame(r.get("code"))
r.pop("snapshot_path", None)
r.pop("path", None) # 路径不外发,串流走 id
return {"total": cnt, "items": rows, "has_more": has_more}
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index ae14c1894..9f61d5aad 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -877,6 +877,30 @@ class JavModeAndCoverTests(unittest.TestCase):
self.assertIsNone(self.contract.cover_path("ABW-232"))
self.assertIsNone(self.contract.cover_path(None))
+ def test_cover_frame_reads_the_face_sidecar(self):
+ (self.covers / "ABW-232.jpg").write_bytes(b"x")
+ (self.covers / "ABW-232.face.json").write_text(
+ '{"ratio":1.49,"face":{"cx":0.82,"cy":0.19}}', encoding="utf-8")
+ self.assertEqual(self.contract.cover_frame("ABW-232"), {"cy": 0.19})
+
+ def test_a_cover_without_a_sidecar_falls_back_silently(self):
+ (self.covers / "ABW-232.jpg").write_bytes(b"x")
+ self.assertIsNone(self.contract.cover_frame("ABW-232"))
+
+ def test_a_sidecar_reporting_no_face_is_not_a_frame(self):
+ # 检出率约 48%,没检出是常态而不是错误——必须安静回落。
+ (self.covers / "ABW-232.jpg").write_bytes(b"x")
+ (self.covers / "ABW-232.face.json").write_text(
+ '{"ratio":1.49,"face":null}', encoding="utf-8")
+ self.assertIsNone(self.contract.cover_frame("ABW-232"))
+
+ def test_a_corrupt_sidecar_never_breaks_the_card(self):
+ (self.covers / "ABW-232.jpg").write_bytes(b"x")
+ (self.covers / "ABW-232.face.json").write_text("{not json", encoding="utf-8")
+ self.assertIsNone(self.contract.cover_frame("ABW-232"))
+
+
+
class DuplicateDetectionTests(unittest.TestCase):
"""同番号不等于重复:合集、分卷和混入的广告都会共用一个 code。"""
diff --git a/web/app.css b/web/app.css
index 3c92aa367..c0634056e 100644
--- a/web/app.css
+++ b/web/app.css
@@ -863,8 +863,9 @@ body.drawer-open .edge{opacity:0;pointer-events:none} /* 展开时窄栏让位
/* 取景:正封模式下,整张封套要把镜头推到右半边;本身就是竖版正封的则整张用。
判据是图片自己的宽高比,由 onload 写进 data-frame。 */
.poster.cover{width:100%;height:100%;object-fit:cover;display:block}
-.poster.cover.front[data-frame="sleeve"]{object-position:82% 22%}
-.poster.cover.front[data-frame="front"]{object-position:50% 22%}
+/* --cover-y 由人脸检出写入;没检出时回落到 22%,那是 46 张实测里的常见位置。 */
+.poster.cover.front[data-frame="sleeve"]{object-position:82% var(--cover-y,22%)}
+.poster.cover.front[data-frame="front"]{object-position:50% var(--cover-y,22%)}
.poster.cover.whole{object-fit:contain;background:#000;object-position:50% 50%}
diff --git a/web/app.js b/web/app.js
index 50eea1d73..5e37ac9f2 100644
--- a/web/app.js
+++ b/web/app.js
@@ -335,9 +335,13 @@ function avatarInner(name,ref,repId){
const COVER_FRAME=`onload="const r=this.naturalWidth/this.naturalHeight;this.dataset.frame=r>1.2?'sleeve':'front'"`;
function coverImage(it,layout){
const src=`/cover?code=${encodeURIComponent(it.code||'')}`;
+ // 人脸只做纵向微调:人物在画面里的高低差别很大,写死的纵向位置会把一部分
+ // 作品裁掉下巴或留出大片空白。检出率约 48%,取不到就退回固定值。
+ const cy=it.cover_frame&&it.cover_frame.cy;
+ const y=cy!=null?`--cover-y:${Math.round(Math.min(0.6,Math.max(0.05,cy))*100)}%`:'';
// 封套模式看整张(含剧照拼贴),正封模式只取右侧那半。
return `<img class="poster cover ${layout==='sleeve'?'whole':'front'}" src="${src}"
- alt="" loading="lazy" ${COVER_FRAME} onerror="this.remove()">`;
+ alt="" loading="lazy"${y?` style="${y}"`:''} ${COVER_FRAME} onerror="this.remove()">`;
}
function cardHtml(it,cls){
const jav=javActive(),layout=javLayout();