Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(vision): 人脸检出改用 YuNet,取景第一次真正生效

longmeidao1d164f151a88
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 5d9e17c8e..0580752e8 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -58,7 +58,7 @@
| 生成产物跨机同步 | Syncthing 2.1.x,Windows send-only → Mac receive-only | 目录划分、忽略规则、方向固定与「Mac 不发布正式产物」的边界 |
| Windows 托盘 | pystray 0.19.5(LGPLv3)、Pillow、Win32 Per-Monitor V2 DPI | Peach 服务归属、后台更新检查、菜单动作、品牌图标 |
| macOS 菜单栏 | `pyobjc-framework-Cocoa==12.2.2`(MIT)提供 AppKit / PyObjCTools / objc | 附件应用策略、18 pt template 图、服务归属与菜单动作 |
-| 人脸取景 | `opencv-python-headless==5.0.0.93`(Apache-2.0)Haar cascade;MetaTube SDK `6a5e6128c725187aeaf921d48ed7d9cd9f30671b` 的主脸聚类只作算法参考 | 头像/封面离线脚本、最大脸选择、归一化焦点与 sidecar;Pigo v1.4.6(MIT)在 512 张真实头像无写入 POC 中检出 488 张、现有 OpenCV 检出 313 张,但 Pigo-only 抽样存在无脸误报且无 Python 部署优势,故不引入;下一轮只 POC 当前 OpenCV YuNet 与多脸主簇,不先替换运行时 |
+| 人脸取景 | `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。**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 部署优势,仍不引入。 |
| 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_avatar_faces.py b/scripts/detect_avatar_faces.py
index 06154d698..9ce7c48bc 100644
--- a/scripts/detect_avatar_faces.py
+++ b/scripts/detect_avatar_faces.py
@@ -20,26 +20,24 @@ from pathlib import Path
import cv2
from peach.config import GENERATED_DIR
+from peach.face_detect import FaceDetector, FaceModelUnavailable
from peach.web_contract import face_focus
-def detect(path: Path, cascade) -> dict | None:
+def detect(path: Path, detector: FaceDetector) -> 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)))
+ faces = detector.detect(image)
record: dict = {"ratio": ratio, "face": None}
- if len(faces) == 0:
+ if not faces:
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)}
+ best = faces[0]
+ cx, cy = best.cx, best.cy
+ record["face"] = {"cx": cx, "cy": cy, "score": best.score}
focus = face_focus(ratio, cx, cy)
if focus:
record["focus"] = focus
@@ -56,10 +54,10 @@ def build_parser() -> argparse.ArgumentParser:
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")
+ try:
+ detector = FaceDetector()
+ except FaceModelUnavailable as error:
+ raise SystemExit(str(error))
images = sorted(args.avatars.glob("*.img"))
todo = [p for p in images
@@ -70,7 +68,7 @@ def run(args: argparse.Namespace) -> int:
stats = {"focus": 0, "face": 0, "none": 0, "unreadable": 0}
for index, path in enumerate(todo, 1):
- result = detect(path, cascade)
+ result = detect(path, detector)
if result is None:
stats["unreadable"] += 1
print(f"[{index}/{len(todo)}] 读图失败 {path.name}", flush=True)
diff --git a/scripts/detect_cover_faces.py b/scripts/detect_cover_faces.py
index 600c9b311..730180717 100644
--- a/scripts/detect_cover_faces.py
+++ b/scripts/detect_cover_faces.py
@@ -27,6 +27,7 @@ from pathlib import Path
import cv2
from peach.config import COVER_DIR
+from peach.face_detect import FaceDetector, FaceModelUnavailable
#: 长封套的宽高比下限。低于它按竖版正封处理(整张就是正封,没有剧照区)。
SLEEVE_RATIO_MIN = 1.2
@@ -37,32 +38,24 @@ FRONT_START = 0.468
MIN_Y, MAX_Y = 0.05, 0.60
-def detect(path: Path, cascade) -> dict | None:
+def detect(path: Path, detector: FaceDetector) -> 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:
+ faces = detector.detect(image)
+ # 长封套左半边是剧照拼贴,那里的脸不是正封主体。这条仍然保留:它挡的不是
+ # 假阳性(YuNet 给的是真脸),而是「拼贴里的另一个人」——按面积取最大在
+ # `ABW-232` 这类图上已经落在右侧正封,但拼贴里偶尔会有更大的一张。
+ if SLEEVE_RATIO_MIN <= ratio < SLEEVE_RATIO_MAX:
+ faces = [face for face in faces if face.cx >= FRONT_START]
+ faces = [face for face in faces if MIN_Y <= face.cy <= MAX_Y]
+ if not faces:
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 SLEEVE_RATIO_MIN <= ratio < SLEEVE_RATIO_MAX 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)}}
+ best = max(faces, key=lambda face: face.area)
+ return {"ratio": round(ratio, 3),
+ "face": {"cx": best.cx, "cy": best.cy, "score": best.score}}
def build_parser() -> argparse.ArgumentParser:
@@ -74,10 +67,10 @@ def build_parser() -> argparse.ArgumentParser:
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")
+ try:
+ detector = FaceDetector()
+ except FaceModelUnavailable as error:
+ raise SystemExit(str(error))
covers = sorted(args.covers.glob("*.jpg"))
todo = [p for p in covers
@@ -88,7 +81,7 @@ def run(args: argparse.Namespace) -> int:
stats = {"face": 0, "none": 0, "unreadable": 0}
for index, path in enumerate(todo, 1):
- result = detect(path, cascade)
+ result = detect(path, detector)
if result is None:
stats["unreadable"] += 1
print(f"[{index}/{len(todo)}] 读图失败 {path.name}", flush=True)
diff --git a/scripts/test_runner.py b/scripts/test_runner.py
index 776613db1..661f63017 100644
--- a/scripts/test_runner.py
+++ b/scripts/test_runner.py
@@ -31,7 +31,7 @@ SCOPES: dict[str, tuple[str, ...]] = {
"test_review_mirror.py"),
"metadata": ("test_metadata*.py", "test_fc2*.py", "test_babepedia_match.py",
"test_jav*.py", "test_code_creators.py", "test_logo_provider.py",
- "test_avatar_provider.py", "test_performer*.py",
+ "test_avatar_provider.py", "test_face_detect.py", "test_performer*.py",
"test_series_localization.py",
"test_duplicate_identity_merge.py", "test_entity_merge.py",
"test_stash_entity_import.py", "test_migrations.py",
diff --git a/src/peach/face_detect.py b/src/peach/face_detect.py
new file mode 100644
index 000000000..8588833c6
--- /dev/null
+++ b/src/peach/face_detect.py
@@ -0,0 +1,154 @@
+r"""人脸检出:OpenCV 的 YuNet,取代已经跑不起来的 Haar 级联。
+
+**先说清一件常被混淆的事:YuNet 不是 OpenCV 的替代品,它就是 OpenCV 的一部分。**
+`cv2.FaceDetectorYN` 是 OpenCV 的 API,YuNet 是它跑的那个模型。解码、色彩转换、
+缩放仍然要 OpenCV。这里换掉的只是「检出器」这一层:
+
+- Haar 级联:2001 年的算法,模型是随 wheel 分发的 XML。
+- YuNet:2021 年的小型 CNN,模型是一个 232 KB 的 ONNX,走 OpenCV 的 DNN 模块。
+
+换的直接原因是旧路径已经跑不起来。`pyproject.toml` 钉的是
+`opencv-python-headless==5.0.0.93`,而 OpenCV 5 把 Haar 级联移出了 Python wheel:
+`cv2.CascadeClassifier` 不存在,`cv2/data/` 只剩 `__init__.py`。两个取景脚本因此
+直接抛 `AttributeError`,954 张封面一个 sidecar 都没有,「人脸取景」从来没生效过。
+
+换的第二个原因是召回。`docs/REUSE.md` 记过一次实测:512 张头像 Haar 检出 313;
+封面脚本自己的注释也写着 46 张检出 24。也就是漏掉三分之一以上,还得靠额外规则
+丢掉假阳性(`278GYAN-017` 检到画面最左的剧照拼贴,`KAVR-428` 一张图检出 7 个框)。
+YuNet 给的是框 + 5 个关键点 + 置信度,可以按分数卡,不必靠位置猜。
+
+模型不进 Git:它是二进制资产,和 ffmpeg 一样放 `peach-data/tools/`。首次运行按
+固定 URL 取一次并校验 sha256——版本要能复现,不能「取到什么算什么」。
+"""
+from __future__ import annotations
+
+import hashlib
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path
+
+from .config import TOOLS_DIR
+
+#: opencv_zoo 的 YuNet 定版模型。走 media. 域名是因为仓库用 Git LFS,
+#: raw. 域名只会回一个 131 字节的指针文件。
+MODEL_URL = (
+ "https://media.githubusercontent.com/media/opencv/opencv_zoo/main/"
+ "models/face_detection_yunet/face_detection_yunet_2023mar.onnx"
+)
+MODEL_SHA256 = "8f2383e4dd3cfbb4553ea8718107fc0423210dc964f9f4280604804ed2552fa4"
+MODEL_BYTES = 232589
+MODEL_PATH = TOOLS_DIR / "yunet" / "face_detection_yunet_2023mar.onnx"
+
+#: 低于这个分数的检出不算数。YuNet 会给出置信度,不必再靠「落在左半边就是假阳性」
+#: 这类位置规则去猜——那条规则只在长封套上成立,换个版式就不成立。
+DEFAULT_SCORE = 0.6
+#: NMS 阈值沿用 opencv_zoo 示例的默认值。
+DEFAULT_NMS = 0.3
+#: 送进网络前的长边上限。YuNet 是定尺寸输入,超大图先缩再检更快且不掉召回;
+#: 坐标按缩放比还原回原图。
+MAX_SIDE = 1280
+
+
+class FaceModelUnavailable(RuntimeError):
+ """模型取不到。调用方据此决定是跳过还是整轮停下,不要静默当成「没有脸」。"""
+
+
+@dataclass(frozen=True)
+class Face:
+ """一张脸在原图里的归一化位置。`score` 是模型给的置信度。"""
+
+ cx: float
+ cy: float
+ width: float
+ height: float
+ score: float
+
+ @property
+ def area(self) -> float:
+ return self.width * self.height
+
+
+def ensure_model(path: Path | None = None, *, allow_download: bool = True) -> Path:
+ """返回可用的模型路径;本地没有且允许联网时取一次。
+
+ 校验 sha256 而不是只看文件在不在:半个下载同样留下一个文件,而它会让
+ `FaceDetectorYN_create` 抛一个和网络毫无关系的错。
+ """
+ target = Path(path) if path is not None else MODEL_PATH
+ if target.is_file() and _digest(target) == MODEL_SHA256:
+ return target
+ if target.is_file():
+ target.unlink()
+ if not allow_download:
+ raise FaceModelUnavailable(f"缺少人脸模型:{target}")
+ target.parent.mkdir(parents=True, exist_ok=True)
+ temporary = target.with_suffix(".part")
+ try:
+ with urllib.request.urlopen(MODEL_URL, timeout=60) as response:
+ payload = response.read()
+ except OSError as error:
+ raise FaceModelUnavailable(f"取人脸模型失败:{error}") from error
+ digest = hashlib.sha256(payload).hexdigest()
+ if digest != MODEL_SHA256:
+ raise FaceModelUnavailable(
+ f"人脸模型校验不符:期望 {MODEL_SHA256},实际 {digest}")
+ temporary.write_bytes(payload)
+ temporary.replace(target)
+ return target
+
+
+def _digest(path: Path) -> str:
+ return hashlib.sha256(path.read_bytes()).hexdigest()
+
+
+class FaceDetector:
+ """YuNet 检出器。一次构造反复使用,输入尺寸每张图现设。"""
+
+ def __init__(self, model: Path | None = None, *, score: float = DEFAULT_SCORE,
+ nms: float = DEFAULT_NMS, allow_download: bool = True) -> None:
+ import cv2
+
+ self._cv2 = cv2
+ self.score = score
+ self.model_path = ensure_model(model, allow_download=allow_download)
+ create = getattr(cv2, "FaceDetectorYN_create", None)
+ if create is None: # pragma: no cover - 依赖版本兜底
+ raise FaceModelUnavailable(
+ "当前 OpenCV 没有 FaceDetectorYN;需要 4.5.4 以上")
+ self._detector = create(str(self.model_path), "", (320, 320), score, nms, 5000)
+
+ def detect(self, image) -> list[Face]:
+ """返回归一化坐标的人脸,按面积从大到小。
+
+ 送进网络前按长边缩到 `MAX_SIDE`:YuNet 的输入尺寸是现设的,超大图直接喂
+ 既慢又不涨召回。坐标先在缩放图上算,再按同一个比例还原——归一化之后
+ 缩放比自然抵消,所以只要保证宽高用的是同一张图的。
+ """
+ cv2 = self._cv2
+ height, width = image.shape[:2]
+ if not height or not width:
+ return []
+ scale = min(1.0, MAX_SIDE / max(height, width))
+ source = (cv2.resize(image, (max(1, int(width * scale)),
+ max(1, int(height * scale))))
+ if scale < 1.0 else image)
+ rows, cols = source.shape[:2]
+ self._detector.setInputSize((cols, rows))
+ _, raw = self._detector.detect(source)
+ if raw is None:
+ return []
+ faces = []
+ for row in raw:
+ x, y, w, h, *_rest = row.tolist()
+ confidence = float(row[-1])
+ if confidence < self.score or w <= 0 or h <= 0:
+ continue
+ faces.append(Face(
+ cx=round(min(1.0, max(0.0, (x + w / 2) / cols)), 3),
+ cy=round(min(1.0, max(0.0, (y + h / 2) / rows)), 3),
+ width=round(min(1.0, w / cols), 3),
+ height=round(min(1.0, h / rows), 3),
+ score=round(confidence, 3),
+ ))
+ faces.sort(key=lambda face: face.area, reverse=True)
+ return faces
diff --git a/tests/test_face_detect.py b/tests/test_face_detect.py
new file mode 100644
index 000000000..932b236bc
--- /dev/null
+++ b/tests/test_face_detect.py
@@ -0,0 +1,92 @@
+import hashlib
+import tempfile
+import unittest
+from pathlib import Path
+from unittest.mock import patch
+
+from peach import face_detect
+from peach.face_detect import (
+ MODEL_SHA256,
+ FaceModelUnavailable,
+ ensure_model,
+)
+
+
+class EnsureModelTests(unittest.TestCase):
+ """模型是二进制资产,不进 Git;取一次就得能复现同一份。"""
+
+ def test_a_matching_local_model_is_reused_without_network(self):
+ with tempfile.TemporaryDirectory() as temp:
+ target = Path(temp).resolve() / "yunet.onnx"
+ payload = b"model-bytes"
+ target.write_bytes(payload)
+ with patch.object(face_detect, "MODEL_SHA256",
+ hashlib.sha256(payload).hexdigest()), \
+ patch.object(face_detect.urllib.request, "urlopen") as opener:
+ self.assertEqual(ensure_model(target), target)
+ opener.assert_not_called()
+
+ def test_a_half_written_model_is_replaced_not_trusted(self):
+ """半个下载同样留下一个文件。
+
+ 只看「文件在不在」的话,下一步 `FaceDetectorYN_create` 会抛一个和网络
+ 毫无关系的错,排查会从模型格式开始找——而真正的原因是上一次没下完。
+ """
+ with tempfile.TemporaryDirectory() as temp:
+ target = Path(temp).resolve() / "yunet.onnx"
+ target.write_bytes(b"half")
+ with self.assertRaises(FaceModelUnavailable):
+ ensure_model(target, allow_download=False)
+ self.assertFalse(target.exists(), "校验不过的文件必须删掉,不能留着下次再骗一次")
+
+ def test_a_download_whose_digest_differs_is_refused(self):
+ class _Response:
+ def read(self):
+ return b"not-the-model"
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *_exc):
+ return False
+
+ with tempfile.TemporaryDirectory() as temp:
+ target = Path(temp).resolve() / "yunet.onnx"
+ with patch.object(face_detect.urllib.request, "urlopen",
+ return_value=_Response()):
+ with self.assertRaises(FaceModelUnavailable) as caught:
+ ensure_model(target)
+ self.assertIn("校验不符", str(caught.exception))
+ self.assertFalse(target.exists())
+
+ def test_the_pinned_digest_is_a_real_sha256(self):
+ # 定版是这条复用记录的全部意义:URL 指向 main 分支,内容可能变。
+ self.assertEqual(len(MODEL_SHA256), 64)
+ self.assertTrue(all(ch in "0123456789abcdef" for ch in MODEL_SHA256))
+ self.assertIn("media.githubusercontent.com", face_detect.MODEL_URL,
+ "opencv_zoo 用 Git LFS,raw 域名只会回一个指针文件")
+
+
+class DetectorContractTests(unittest.TestCase):
+ def test_scripts_no_longer_reach_for_the_removed_cascade_api(self):
+ """OpenCV 5 的 wheel 里没有 `CascadeClassifier`,也没有级联 XML。
+
+ 两个脚本此前一起门都进不去,954 张封面 0 个 sidecar——「人脸取景没生效」
+ 的成因就在这里,不在取景公式上。
+ """
+ root = Path(__file__).resolve().parents[1]
+ for name in ("detect_cover_faces.py", "detect_avatar_faces.py"):
+ source = (root / "scripts" / name).read_text(encoding="utf-8")
+ self.assertNotIn("CascadeClassifier", source, name)
+ self.assertNotIn("haarcascades", source, name)
+ self.assertIn("FaceDetector()", source, name)
+
+ def test_normalised_face_is_clamped_into_the_frame(self):
+ detector = face_detect.FaceDetector.__new__(face_detect.FaceDetector)
+ face = face_detect.Face(cx=0.8, cy=0.2, width=0.25, height=0.3, score=0.9)
+ self.assertAlmostEqual(face.area, 0.075, places=6)
+ self.assertIsInstance(detector, face_detect.FaceDetector)
+
+
+if __name__ == "__main__":
+ unittest.main()