Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat: frame entity avatars on detected face centers

longmeidaofbf5837ccf32
diff --git a/docs/STATUS.md b/docs/STATUS.md
index 4188fa996..e0ad5fb17 100644
--- a/docs/STATUS.md
+++ b/docs/STATUS.md
@@ -74,6 +74,7 @@
- 详情中的本地来源图标已补齐 `stroke: currentColor` 和 `fill: none`,不再因 SVG 默认黑色而不可见。标签添加使用弹窗完成搜索、最近使用、全部标签、已选状态和键盘操作;侧栏入口简化为「艺人」「标签」,并删除装饰性分隔线。
- 首页创作者头像已移除常驻黑框,只在 hover/选中时显示状态描边。女优/厂牌/创作者/系列资料页打开后隐藏首页人物、厂牌和筛选栏;资料区取消巨型外框,桌面头像为 160 px,并在资料下展示真实标签与关联艺人。厂牌资料优先使用 Logo,只有缺失时才使用实体图,不再用代表作品截图冒充厂牌头像。
- 实体资料页标签只筛选当前实体作品,不再跳回首页做全局筛选;当前标签写入资料页查询参数,便于返回和分享。首页状态标签已精简为「全部、没看过、稍后看、已标记」,与右侧内容标签之间恢复语义分隔线。搜索框显示随机推荐关键词,不加「试试:」;空输入聚焦后按 Enter 会直接搜索当前推荐词。
+- 资料页圆头像按检出的人脸取景(2026-08-22):512 张实体图多为竖版,几何居中裁切会切掉头顶;`scripts/detect_avatar_faces.py` 用与封面同一套 Haar 离线检出 313 张,283 张有取景余量,sidecar `<kind>-<id>.face.json` 存归一化脸心与换算好的 object-position,换算公式只有一份(`web_contract.face_focus`)。`/api/entity` 以 `avatar_focus` 下发,未检出或未算过的实体维持几何居中;详情图回落代表作截图时会先摘掉内联取景。新增头像后重跑一次脚本即可补齐。
- 大结果集不再按总数一次构建:实体页每批 48、首页 60、艺人索引 120、标签索引 180、疑似广告 DOM 每批 60。实体与首页第二页起跳过全量总数统计;无限滚动有单请求锁,快速切换会丢弃迟到响应,顶部聚合复用 30 秒会话缓存。
- 详情播放器使用本地固定版本 Video.js 8.23.9,提供 ±10 秒、画中画和播放统计。远端原生 MP4 优先走 HLS 片段,HLS 失败仍回退标准 HTTP Range;不再把浏览器的开放区间伪截成 32 MiB。item 29297 的权威总时长固定为 28,639.916 秒(`7:57:19`),不再随缓存增长。
- 详情全屏覆盖播放器的 `76vh`/固定比例限制,视频按播放器尺寸渲染;加载或等待时显示基于 VHS/媒体请求的实际速度估算。沉浸模式横屏使用全视口 `object-fit:cover`,竖屏根据媒体真实宽高切到 `contain`,避免桌面宽屏裁掉上下画面;初次加载和切换下一条时显示 spinner 与速度,按钮采用 Shorts 取证的 tonal 圆角层级。
diff --git a/scripts/detect_avatar_faces.py b/scripts/detect_avatar_faces.py
new file mode 100644
index 000000000..06154d698
--- /dev/null
+++ b/scripts/detect_avatar_faces.py
@@ -0,0 +1,94 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+r"""给已落盘的实体图算人脸位置,供圆形头像取景用。
+
+实体图多为竖版人像(当前 512 张里 458 张竖版),圆框按几何中心裁切会切掉头顶、
+把脸压到下半圈。这里用与封面同一套 Haar 级联检出最大的人脸,把归一化中心和换算
+好的 object-position 写进 sidecar(`<kind>-<id>.face.json`);取景公式只有一份,
+在 `peach.web_contract.face_focus`,契约层读 sidecar 原样下发。
+
+结果写成每张图一个 sidecar,不写单一索引文件,理由与封面相同:导入任务可能并发
+写同目录。脚本可反复运行,已算过的默认跳过;新增头像后重跑一次即可补齐。未检出
+的写 `"face": null` 且省略 `focus`,页面维持几何居中。
+"""
+from __future__ import annotations
+
+import argparse
+import json
+from pathlib import Path
+
+import cv2
+
+from peach.config import GENERATED_DIR
+from peach.web_contract import face_focus
+
+
+def detect(path: Path, cascade) -> dict | None:
+ image = cv2.imread(str(path))
+ if image is None:
+ return None
+ height, width = image.shape[:2]
+ ratio = round(width / height, 3) 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)))
+ record: dict = {"ratio": ratio, "face": None}
+ if len(faces) == 0:
+ return record
+ # 多张脸时取最大的:实体图的主角通常占画面最大,其余是拼贴或背景人物。
+ x, y, w, h = max(faces, key=lambda box: box[2] * box[3])
+ cx, cy = (x + w / 2) / width, (y + h / 2) / height
+ record["face"] = {"cx": round(float(cx), 3), "cy": round(float(cy), 3)}
+ focus = face_focus(ratio, cx, cy)
+ if focus:
+ record["focus"] = focus
+ return record
+
+
+def build_parser() -> argparse.ArgumentParser:
+ parser = argparse.ArgumentParser(description="给实体图算人脸位置,供圆头像取景")
+ parser.add_argument("--avatars", type=Path, default=GENERATED_DIR / "avatars",
+ help="实体图目录(默认 generated/avatars)")
+ 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")
+
+ images = sorted(args.avatars.glob("*.img"))
+ todo = [p for p in images
+ if args.redo or not p.with_suffix(".face.json").is_file()]
+ if args.limit:
+ todo = todo[:args.limit]
+ print(f"实体图 {len(images)} 张,待处理 {len(todo)} 张")
+
+ stats = {"focus": 0, "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
+ if result.get("focus"):
+ stats["focus"] += 1
+ path.with_suffix(".face.json").write_text(
+ json.dumps(result, ensure_ascii=False), encoding="utf-8")
+ print(f"\n检出 {stats['face']}(其中可取景 {stats['focus']}),"
+ f"未检出 {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 ac8f866bb..033e65ee5 100644
--- a/src/peach/web_contract.py
+++ b/src/peach/web_contract.py
@@ -93,16 +93,44 @@ def is_jav_code(code: str | None) -> bool:
or _CODE_DATE.match(value))
+def face_focus(ratio: float, cx: float, cy: float) -> dict | None:
+ """把归一化人脸中心换算成圆框 object-position 的取景提示。
+
+ 竖图(ratio=宽/高 < 1)的取景余量在纵向、横图在横向,脸放在余量轴的中心;
+ 换算式由 cover 取景的同一几何关系推出:可见窗口在余量轴上的起点是
+ `(余量) × pos%`,令窗口中心等于脸心即可解出 pos。接近正方时 cover 几乎
+ 裁不掉东西,返回 None 维持几何居中;脸太靠边、几何上无法完整居中时
+ 夹取到边缘,保证不会比现在更差。
+ """
+ try:
+ ratio = float(ratio)
+ cx = float(cx)
+ cy = float(cy)
+ except (TypeError, ValueError):
+ return None
+ if ratio <= 0 or abs(1.0 - ratio) <= 0.05:
+ return None
+ if ratio < 1.0:
+ pos = (cy - ratio / 2) / (1 - ratio)
+ else:
+ pos = (ratio * cx - 0.5) / (ratio - 1)
+ pct = int(round(min(1.0, max(0.0, pos)) * 100))
+ axis = "y" if ratio < 1.0 else "x"
+ return {"axis": axis, "pct": pct}
+
+
class WebContract:
"""单个应用实例的数据库、写锁和聚合缓存;不共享模块级可变状态。"""
def __init__(self, db_path: Path, snapshot_root: Path | None = None,
legacy_snapshot_roots: Sequence[Path] = (),
candidate_root: Path | None = None,
- cover_root: Path | None = None):
+ cover_root: Path | None = None,
+ avatar_root: Path | None = None):
# 候选 CSV 的目录做成实例属性而不是模块常量,复核层才能在临时目录里被测试。
self.candidate_root = Path(candidate_root) if candidate_root is not None else GENERATED_DIR
self.cover_root = Path(cover_root) if cover_root is not None else COVER_DIR
+ self.avatar_root = Path(avatar_root) if avatar_root is not None else GENERATED_DIR / "avatars"
self.db_path = Path(db_path)
self.snapshot_root = Path(snapshot_root) if snapshot_root is not None else None
self.legacy_snapshot_roots = tuple(Path(path) for path in legacy_snapshot_roots)
@@ -175,6 +203,28 @@ class WebContract:
face = data.get("face")
return {"cy": face["cy"]} if isinstance(face, dict) and "cy" in face else None
+ def avatar_focus(self, kind: str, entity_id: int) -> dict | None:
+ """实体图的取景提示:人脸中心换算成的 object-position。
+
+ sidecar 由 `scripts/detect_avatar_faces.py` 离线写入,与封面取景同一
+ 约定;没算过、读不出或没检出都返回 None,页面维持几何居中。
+ """
+ path = self.avatar_root / f"{kind}-{int(entity_id)}.face.json"
+ if not path.is_file():
+ return None
+ try:
+ data = json.loads(path.read_text(encoding="utf-8"))
+ except (OSError, ValueError):
+ return None
+ focus = data.get("focus") if isinstance(data, dict) else None
+ if not isinstance(focus, dict):
+ return None
+ axis = focus.get("axis")
+ pct = focus.get("pct")
+ if axis not in {"x", "y"} or not isinstance(pct, (int, float)):
+ return None
+ return {"axis": axis, "pct": int(pct)}
+
def has_fts(self) -> bool:
if self._fts_available is None:
connection = self.db()
@@ -758,6 +808,7 @@ def q_entity(contract: WebContract, args):
).fetchone()
d["asset_count"] = count
d["representative_asset_id"] = rep
+ d["avatar_focus"] = contract.avatar_focus(kind, d["id"])
d["tags"] = [dict(r) for r in c.execute(
"SELECT tag.id,tag.canonical_name k,count(DISTINCT scope.asset_id) n "
"FROM asset_entity scope "
diff --git a/tests/test_rm_web.py b/tests/test_rm_web.py
index 5dc8a7d6f..ef6070c8e 100644
--- a/tests/test_rm_web.py
+++ b/tests/test_rm_web.py
@@ -1079,6 +1079,88 @@ class JavModeAndCoverTests(unittest.TestCase):
+class FaceFocusMathTests(unittest.TestCase):
+ """人脸中心 → 圆框 object-position 的换算。"""
+
+ def test_a_portrait_centers_the_face_vertically(self):
+ # 640x960(ratio 2/3)、脸心在 cy=0.45:窗口应从余量的 35% 处开始。
+ self.assertEqual(rm_web.face_focus(0.667, 0.5, 0.45),
+ {"axis": "y", "pct": 35})
+
+ def test_the_centered_face_keeps_the_default_position(self):
+ self.assertEqual(rm_web.face_focus(2 / 3, 0.5, 0.5),
+ {"axis": "y", "pct": 50})
+
+ def test_faces_too_close_to_an_edge_clamp_instead_of_overflowing(self):
+ self.assertEqual(rm_web.face_focus(0.667, 0.5, 0.0),
+ {"axis": "y", "pct": 0})
+ self.assertEqual(rm_web.face_focus(0.667, 0.5, 1.0),
+ {"axis": "y", "pct": 100})
+
+ def test_a_landscape_image_takes_its_margin_horizontally(self):
+ # 1500x1000、脸心在 cx=0.6:窗口应从余量的 80% 处开始。
+ self.assertEqual(rm_web.face_focus(1.5, 0.6, 0.4),
+ {"axis": "x", "pct": 80})
+ # 脸太靠右时夹取到边缘,不越界。
+ self.assertEqual(rm_web.face_focus(1.5, 0.9, 0.4),
+ {"axis": "x", "pct": 100})
+
+ def test_near_square_images_have_no_margin_to_reframe(self):
+ self.assertIsNone(rm_web.face_focus(1.0, 0.5, 0.3))
+ self.assertIsNone(rm_web.face_focus(1.03, 0.5, 0.3))
+
+ def test_unreadable_numbers_return_none_not_an_exception(self):
+ self.assertIsNone(rm_web.face_focus(None, 0.5, 0.3))
+ self.assertIsNone(rm_web.face_focus("x", 0.5, 0.3))
+ self.assertIsNone(rm_web.face_focus(-1, 0.5, 0.3))
+
+
+class AvatarFocusTests(unittest.TestCase):
+ """资料页实体图的人脸取景 sidecar。"""
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ root = Path(self.tmp.name)
+ self.avatars = root / "avatars"
+ self.avatars.mkdir()
+ self.contract = rm_web.WebContract(
+ Path(str(root / "ledger.db")), avatar_root=self.avatars)
+
+ def test_the_sidecar_focus_is_passed_through(self):
+ (self.avatars / "performer-7900.img").write_bytes(b"x")
+ (self.avatars / "performer-7900.face.json").write_text(
+ '{"ratio":0.667,"face":{"cx":0.5,"cy":0.45},'
+ '"focus":{"axis":"y","pct":35}}', encoding="utf-8")
+ self.assertEqual(self.contract.avatar_focus("performer", 7900),
+ {"axis": "y", "pct": 35})
+
+ def test_no_sidecar_falls_back_silently(self):
+ (self.avatars / "performer-7900.img").write_bytes(b"x")
+ self.assertIsNone(self.contract.avatar_focus("performer", 7900))
+
+ def test_a_sidecar_without_a_detection_is_not_a_focus(self):
+ # Haar 对侧脸、低头会漏检,没检出是常态而不是错误——必须安静回落。
+ (self.avatars / "performer-7900.img").write_bytes(b"x")
+ (self.avatars / "performer-7900.face.json").write_text(
+ '{"ratio":0.667,"face":null}', encoding="utf-8")
+ self.assertIsNone(self.contract.avatar_focus("performer", 7900))
+
+ def test_a_corrupt_sidecar_never_breaks_the_page(self):
+ (self.avatars / "performer-7900.img").write_bytes(b"x")
+ (self.avatars / "performer-7900.face.json").write_text(
+ "{not json", encoding="utf-8")
+ self.assertIsNone(self.contract.avatar_focus("performer", 7900))
+
+ def test_a_malformed_focus_is_rejected(self):
+ (self.avatars / "performer-7900.face.json").write_text(
+ '{"focus":{"axis":"z","pct":50}}', encoding="utf-8")
+ (self.avatars / "studio-12.face.json").write_text(
+ '{"focus":{"axis":"y","pct":"high"}}', encoding="utf-8")
+ self.assertIsNone(self.contract.avatar_focus("performer", 7900))
+ self.assertIsNone(self.contract.avatar_focus("studio", 12))
+
+
class DuplicateDetectionTests(unittest.TestCase):
"""同番号不等于重复:合集、分卷和混入的广告都会共用一个 code。"""
diff --git a/tests/test_web_ui.py b/tests/test_web_ui.py
index 0a9586ff1..6241f0ed4 100644
--- a/tests/test_web_ui.py
+++ b/tests/test_web_ui.py
@@ -58,6 +58,13 @@ class WebUiSourceTests(unittest.TestCase):
self.assertPageContains("`/entity-image?kind=performer&id=${ref.id}`")
self.assertPageContains("this.onerror=null;this.src='/avatar?id=${repId}'")
+ def test_entity_hero_avatar_frames_the_detected_face(self):
+ # 资料页圆框按检出的人脸取景;换回落图时必须先摘掉内联 object-position——
+ # 回落图是另一张照片,脸不在同一位置。
+ self.assertPageContains("function facePos(f)")
+ self.assertPageContains('"${facePos(d.avatar_focus)}')
+ self.assertPageContains("onerror=\"this.removeAttribute('style')")
+
def test_detail_identity_groups_by_kind_with_the_label_on_top(self):
# 逐行一个名字在共演作品上会把整个侧栏撑满,左侧还重复一列标签。
self.assertPageContains("const idGroup=(label,kind,list,extra='')=>list.length")
diff --git a/web/app.js b/web/app.js
index e77f3fe6d..b7d569117 100644
--- a/web/app.js
+++ b/web/app.js
@@ -413,6 +413,14 @@ function avatarInner(name,ref,repId){
return `<span class="ini">${esc((name||'?').slice(0,1))}</span>`+
(src?`<img src="${src}" alt="" loading="lazy" onerror="${fallback}">`:'');
}
+/* 人脸取景:资料页圆框按检出的人脸中心取景(/api/entity 的 avatar_focus)。
+ 没检出或没算过返回空串维持几何居中;换回落图时必须撤掉——那是另一张照片,
+ 脸不在同一位置,见 entityhero img 的 onerror。 */
+function facePos(f){
+ return f&&f.axis==='x'?` style="object-position:${f.pct}% 50%"`
+ :f&&f.axis==='y'?` style="object-position:50% ${f.pct}%"`
+ :'';
+}
/* 官方封套有两种形态,实测过:整张封套约 1.48(左侧是剧照拼贴,右侧才是正封),
竖版正封约 0.70(本身就是正封,没有左半边可裁)。所以取景不能写死「取右边」,
得等图片加载后按它自己的宽高比分流——服务端没存这个比例,也不该为此再存一份。 */
@@ -1178,8 +1186,8 @@ async function openEntity(kind,name,push=true,requestedTag){
const image=d.id?(kind==='studio'
? `<img src="/logo?studio=${encodeURIComponent(d.canonical_name)}" alt="${esc(d.canonical_name)}"
onerror="if(!this.dataset.f){this.dataset.f='1';this.src='/entity-image?kind=studio&id=${d.id}'}else{this.remove()}">`
- : `<img src="/entity-image?kind=${kind}&id=${d.id}" alt="${esc(d.canonical_name)}"
- onerror="${d.representative_asset_id?`this.onerror=null;this.src='/avatar?id=${d.representative_asset_id}'`:`this.remove()`}">`):'';
+ : `<img src="/entity-image?kind=${kind}&id=${d.id}" alt="${esc(d.canonical_name)}"${facePos(d.avatar_focus)}
+ onerror="this.removeAttribute('style');${d.representative_asset_id?`this.onerror=null;this.src='/avatar?id=${d.representative_asset_id}'`:`this.remove()`}">`):'';
const links=(d.links||[]).map(x=>x.clickable&&/^https?:\/\//i.test(x.url||'')
? `<a href="${esc(x.url)}" target="_blank" rel="noreferrer"><span class="entitylinkicon">${icon('globe')}<img class="entityfavicon" src="${esc(faviconUrl(x.url))}" data-studio="${kind==='studio'?esc(d.canonical_name):''}" alt=""></span><span class="entitylinklabel">${esc(x.label)}</span><span class="entitylinkarrow" aria-hidden="true">↗</span></a>`
: `<span class="private" title="私人馆藏来源记录,不直接打开下载页"><span class="entitylinkicon">${icon('globe')}</span><span class="entitylinklabel">来源 · ${esc(x.label||x.hostname||'已记录')}</span></span>`).join('');