Peach: Local-first video metadata scraper and media manager.
fix(avatars): 装头像前先量盘上那张,脸没更大就不覆盖
longmeidao9b9eff6f3077
diff --git a/docs/SOURCING.md b/docs/SOURCING.mdindex d79e80af3..21b505c8e 100644--- a/docs/SOURCING.md+++ b/docs/SOURCING.md@@ -354,6 +354,17 @@ Windows 空数据预览的项目 CA HTTPS、合成 Cookie 保存/撤销、DMM(同 SHA 只量一次),并写进候选 CSV 的 `face_width` 列供复核的人直接看。检不出脸记 0,排在任何量得到的候选之后;整批都是 0(模型缺席、清一色侧脸)时排序原样落回画布口径,并在运行统计里说明本轮是按画布挑的。单人作品封面这条退路走同一把尺:JAV 双联封面右半幅剧照里的脸常常只有几十像素。+- **头像目录是几条管线共用的,`--apply` 只往好里换。** `--force` 的语义是「已有头像也参加竞选」,+ 它覆盖的却是**所有**已装头像,包括别的管线装的,而 `harvest_social_avatars.py` 的候选池(X 的+ 400×400、jae 的 320×500、作品封面)比 `verified-photo-page` 那类整版人像差一大截。2026-09-06 实测+ 一趟 `--force --apply`:换掉 350 张,其中 282 张脸变小,脸宽中位数从 262 px 掉到 139 px,风见步的+ 640×960 半身照被换成 JBS-023 的双联封面。现在落盘前先按同一把 `rank_key` 量一次盘上那张,脸没有+ 更大就不覆盖,运行统计里报「在位的更好未覆盖」多少张。在位那张的脸宽优先读现成的取景 sidecar,+ 没有才真检一遍。+- **换图必须换 sidecar**。取景 sidecar 与选图判据同出一次 YuNet 检出(`peach.avatar_face`),装头像时+ 一并写出;给不出新记录就把旧的删掉。留着上一张图的脸框,页面会拿它给这一张取景、放大到一个空+ 位置上,而这在界面上与「这张图本来就该这么显示」看不出区别。`scripts/detect_avatar_faces.py` 从+ 批量生成入口退成补齐入口,检测与形状都不再由它自己定义。- 能解析不等于是对的品牌:`@bazooka` 确实存在且能取到 400×400 头像,但那是 2007 年注册的通用账号,不是这个 AV 厂牌。所以 handle 必须逐个取证确认,脚本默认不猜,`--guess-handles` 的产出一律标`needs_confirmation` 且不自动采纳,查不到就留空。diff --git a/scripts/detect_avatar_faces.py b/scripts/detect_avatar_faces.pyindex b910be7aa..3ca54e862 100644--- a/scripts/detect_avatar_faces.py+++ b/scripts/detect_avatar_faces.py@@ -12,48 +12,23 @@ r"""给已落盘的实体图算人脸位置,供圆形头像取景用。倍数本身由页面按框的实际尺寸和设备像素比算,判据在 `web/js/face-frame.js`。结果写成每张图一个 sidecar,不写单一索引文件,理由与封面相同:导入任务可能并发-写同目录。脚本可反复运行,已算过的默认跳过;新增头像后重跑一次即可补齐。未检出-的写 `"face": null` 且省略 `focus`,页面维持几何居中。+写同目录。脚本可反复运行,已算过的默认跳过。检测与 sidecar 形状都在+`peach.avatar_face`,采集脚本装头像时就地写同一份,这里是补齐用的批量入口。"""from __future__ import annotationsimport argparse-import jsonimport sysfrom pathlib import Path-import cv2-PROJECT_ROOT = Path(__file__).resolve().parent.parentSRC_DIR = PROJECT_ROOT / "src"if str(SRC_DIR) not in sys.path:sys.path.insert(0, str(SRC_DIR))+from peach.avatar_face import face_record, sidecar_path, write_sidecarfrom peach.config import GENERATED_DIR-from peach.face_detect import FaceDetector, FaceModelUnavailable, main_face-from peach.web_contract import face_focus---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- faces = detector.detect(image)- record: dict = {"ratio": ratio, "px": [width, height], "face": None}- if not faces:- return record- # 多张脸时挑主角:先卡分数再取最大,判据在 peach.face_detect.main_face。- best = main_face(faces)- cx, cy = best.cx, best.cy- # `w`/`h` 是归一化的脸框,配上 `px` 才还得出像素数——放大到几倍还清楚问的是像素。- record["face"] = {"cx": cx, "cy": cy, "w": best.width, "h": best.height,- "score": best.score}- focus = face_focus(ratio, cx, cy)- if focus:- record["focus"] = focus- return record+from peach.face_detect import FaceDetector, FaceModelUnavailabledef build_parser() -> argparse.ArgumentParser:@@ -72,15 +47,14 @@ def run(args: argparse.Namespace) -> int:raise SystemExit(str(error))images = sorted(args.avatars.glob("*.img"))- todo = [p for p in images- if args.redo or not p.with_suffix(".face.json").is_file()]+ todo = [p for p in images if args.redo or not sidecar_path(p).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, detector)+ result = face_record(path, detector)if result is None:stats["unreadable"] += 1print(f"[{index}/{len(todo)}] 读图失败 {path.name}", flush=True)@@ -88,8 +62,7 @@ def run(args: argparse.Namespace) -> int:stats["face" if result["face"] else "none"] += 1if result.get("focus"):stats["focus"] += 1- path.with_suffix(".face.json").write_text(- json.dumps(result, ensure_ascii=False), encoding="utf-8")+ write_sidecar(path, result)print(f"\n检出 {stats['face']}(其中可取景 {stats['focus']}),"f"未检出 {stats['none']},读图失败 {stats['unreadable']}")print("未检出的维持几何居中,不影响显示。")diff --git a/scripts/harvest_social_avatars.py b/scripts/harvest_social_avatars.pyindex 2d8c4f68d..948c7a455 100644--- a/scripts/harvest_social_avatars.py+++ b/scripts/harvest_social_avatars.py@@ -23,6 +23,9 @@ r"""社媒存在感扩张:从已核实的 X 账号走到集链页,扩张全队列存在的理由(KRONE 那次「人对、页面错」就是这一类),所以本脚本和仓库里其余写入脚本一样,写盘必须显式 `--apply`。+`--apply` 只往好里换:落盘前先按同一把尺(`rank_key`)量一次盘上那张,脸没有更大就+不覆盖。头像目录是几条管线共用的,本脚本的候选池未必比别人装的强。+头像源(登出可取;取不到的只记链接,不产头像):X profile_images 原图(无尺寸后缀),失败退 _400x400 / _200x200lit.link creators/<uuid>/icons/<uuid>.jpe@@ -52,6 +55,9 @@ from pathlib import Pathsys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))+from peach.avatar_face import ( # noqa: E402+ FaceProbe, drop_sidecar, face_px_width, read_sidecar, write_sidecar,+)from peach.avatar_provider import ( # noqa: E402POLICY_VERSION,AvatarCandidateCache,@@ -554,7 +560,7 @@ def harvest_entity(record: dict, http: HttpTransport, limiter: HostLimiter,def cover_fallback(connection, record: dict, cache: AvatarCandidateCache,- cover_root: Path = COVER_DIR, face_width=None) -> dict | None:+ cover_root: Path = COVER_DIR, probe=None) -> dict | None:"""仅使用已关联的单人作品封面,保留完整大图和来源。封面是这条链路上脸最容易被画布口径坑到的一档:JAV 封面普遍是 800×538 的双联版式,@@ -589,62 +595,28 @@ def cover_fallback(connection, record: dict, cache: AvatarCandidateCache,evidence=f'单人作品 {code} 完整封面'))if not candidates:return None- if face_width is not None:- measure_faces(candidates, face_width)+ if probe is not None:+ measure_faces(candidates, probe)return max(candidates, key=rank_key)-class FaceWidth:- """一枚候选里那张脸有多少像素宽。检不出脸就是 0。-- 模型按需构造,与 `harvest_studio_icons.FaceGate` 同一条理由:一趟里一个候选都- 没走到就不必去下 232 KB 的 ONNX,而取不到模型也不能让整轮停下——那会把「今天- 没网」变成「所有人都没有头像」。取不到就退回画布口径,并把原因记进统计。- """+def measure_faces(candidates: list[dict], probe) -> None:+ """就地给每枚候选检一次脸。同一张图(SHA 相同)只检一次。- def __init__(self):- self._detector = None- self._unavailable = ""-- @property- def unavailable(self) -> str:- return self._unavailable-- def __call__(self, path: Path) -> int:- if self._unavailable:- return 0- if self._detector is None:- try:- from peach.face_detect import FaceDetector- self._detector = FaceDetector()- except Exception as error: # 缺模型、缺 OpenCV、下载失败- self._unavailable = str(error)- return 0- try:- import cv2- from peach.face_detect import main_face- image = cv2.imread(str(path))- if image is None:- return 0- face = main_face(self._detector.detect(image))- return round(face.width * image.shape[1]) if face else 0- except Exception: # 单张图解不开不该拖垮整轮- return 0---def measure_faces(candidates: list[dict], face_width) -> None:- """就地给每枚候选量一次脸宽。同一张图(SHA 相同)只量一次。-- 量的是像素不是比例:`select_winner` 要回答的是「装进圆框后看不看得清这张脸」,- 而那取决于脸有多少像素可用,与画布多大无关。+ 落在候选上的是两样东西:`face_width` 是选图判据——量的是像素不是比例,因为+ `rank_key` 要回答的是「装进圆框后看不看得清这张脸」,而那取决于脸有多少像素可用,+ 与画布多大无关;`face_record` 是赢家落盘时一并写出的取景 sidecar,同一次检出直接+ 复用,不让页面读的脸框和挑图用的脸框来自两次不同的检测。"""- seen: dict[str, int] = {}+ seen: dict[str, dict | None] = {}for candidate in candidates:digest = candidate.get("sha256", "")if digest not in seen:path = candidate.get("object_path")- seen[digest] = face_width(path) if path else 0- candidate["face_width"] = seen[digest]+ seen[digest] = probe(path) if path else None+ record = seen[digest]+ candidate["face_record"] = record+ candidate["face_width"] = face_px_width(record)def rank_key(row: dict) -> tuple[int, int, int, int]:@@ -687,8 +659,42 @@ def select_winner(candidates: list[dict]) -> tuple[dict | None, list[dict]]:return ranked[-1], ranked[:-1]+def incumbent_row(destination: Path, probe) -> dict | None:+ """盘上那张的选图口径,用来和赢家比。没有图、读不出都返回 None。++ 先用现成的取景 sidecar,那本来就是同一次 YuNet 检出的结果;没有 sidecar 才真去+ 检一遍。525 张头像各检一次要好几分钟,而绝大多数的 sidecar 早就算好了。+ """+ if not destination.is_file():+ return None+ record = read_sidecar(destination)+ if not (record and record.get("px")):+ record = probe(destination)+ if not (record and record.get("px")):+ return None+ width, height = record["px"][0], record["px"][1]+ if not (width > 0 and height > 0):+ return None+ return {"width": width, "height": height,+ "face_width": face_px_width(record), "face_record": record}+++def outranks_incumbent(winner: dict, incumbent: dict | None) -> bool:+ """赢家值不值得覆盖盘上那张。用的是同一把尺 `rank_key`。++ 这道闸门是 `--force` 的安全带。`--force` 的语义是「已有头像也重跑」,覆盖的却是+ **所有**已装头像,包括别的管线装的——而本脚本的候选池(X 的 400×400、jae 的+ 320×500、作品封面)比 `verified-photo-page` 那类整版人像差一大截。2026-09-06 实测:+ 一趟 `--force --apply` 换掉 350 张,其中 282 张脸变小,脸宽中位数从 262 px 掉到+ 139 px。缺头像时这道闸门是空操作,只在真要覆盖时才拦。+ """+ if incumbent is None:+ return True+ return rank_key(winner) > rank_key(incumbent)++def install_avatar(avatar_dir: Path, kind: str, entity_id: int, winner: dict) -> Path:- """赢家直接落盘到 /entity-image 真正读的目录,带 .ct 与 provenance。"""+ """赢家直接落盘到 /entity-image 真正读的目录,带 .ct、provenance 与取景 sidecar。"""destination = avatar_dir / f"{kind}-{entity_id}.img"avatar_dir.mkdir(parents=True, exist_ok=True)data = winner["object_path"].read_bytes()@@ -712,6 +718,13 @@ def install_avatar(avatar_dir: Path, kind: str, entity_id: int, winner: dict) ->"imported_at": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),"purpose": "local performer identity cache",}, ensure_ascii=False, indent=2), encoding="utf-8")+ # sidecar 必须跟着图一起换。留着上一张图的脸框,页面会拿它给这一张取景、放大到+ # 一个空位置上,而这在界面上与「这张图本来就该这么显示」看不出区别。+ record = winner.get("face_record")+ if record:+ write_sidecar(destination, record)+ else:+ drop_sidecar(destination)return destination@@ -775,7 +788,7 @@ def build_parser() -> argparse.ArgumentParser:parser.add_argument("--entities", type=str, default="",help="逗号分隔的 entity id;缺省跑全部缺头像且有路线的人")parser.add_argument("--force", action="store_true",- help="已有头像也重跑并覆盖(默认跳过)")+ help="已有头像也参加竞选(默认跳过);只有脸更大才覆盖")parser.add_argument("--apply", action="store_true",help="把过线的赢家头像落盘到 --avatars;缺省只产 CSV 不写盘")parser.add_argument("--timeout", type=float, default=25.0)@@ -801,7 +814,8 @@ def run(args) -> int:install_rows: list[dict] = []review_rows: list[dict] = []installed = 0- face_width = FaceWidth()+ kept = 0+ probe = FaceProbe()try:entities = [int(v) for v in str(args.entities).split(",") if v.strip().isdigit()]targets = load_targets(connection, args.avatars, entities, args.force, include_cover_targets=True)@@ -839,16 +853,18 @@ def run(args) -> int:review_rows.append(row)# 先量脸再挑:赢家由脸的像素数定,画布只是没得比时的退路。- measure_faces(result["candidates"], face_width)+ measure_faces(result["candidates"], probe)winner, runners_up = select_winner(result["candidates"])if (winner is None or not winner.get('matched')or not passes_auto_bar(winner['width'], winner['height'])):fallback = cover_fallback(connection, record, caches['cover'],- face_width=face_width)+ probe=probe)if fallback:if winner:runners_up.append(winner)winner = fallback+ # 盘上那张只量一次,赢家拿它当门槛:新的没有更好就不动它。+ incumbent = incumbent_row(args.avatars / f"{kind}-{entity_id}.img", probe)for candidate in ([winner] if winner else []) + runners_up:cache = caches[PROVIDER_CACHES[candidate["provider"]]]provenance_path = cache.store_provenance(@@ -865,6 +881,10 @@ def run(args) -> int:note += ",未达自动安装线,待复核"elif not args.apply:note += ",已过自动安装线;加 --apply 才落盘"+ elif not outranks_incumbent(candidate, incumbent):+ note += (f",盘上那张的脸更大({incumbent['face_width']} px "+ f"vs {candidate.get('face_width') or 0} px),不覆盖")+ kept += 1else:destination = install_avatar(args.avatars, kind, entity_id,candidate)@@ -908,14 +928,14 @@ def run(args) -> int:write_rows(args.candidates, CANDIDATE_FIELDS, candidate_rows, atomic=True)write_rows(args.out_links, LINK_FIELDS, install_rows, atomic=True)write_rows(args.review_links, LINK_FIELDS, review_rows, atomic=True)- if face_width.unavailable:+ if probe.unavailable:# 说清这一轮是按什么挑的。不说的话,一次「今天没网下不到 ONNX」会静悄悄地# 把整批退回画布口径,产出看着完全正常,脸却全挑小了。- print(f"人脸检测未取得({face_width.unavailable}):本轮按画布尺寸挑图,"+ print(f"人脸检测未取得({probe.unavailable}):本轮按画布尺寸挑图,""face_width 一列全是 0;模型可用后加 --force 重跑该批。")if not args.apply:print("空跑:以上一张头像都没落盘;确认候选无误后加 --apply 重跑。")- print({"候选": len(candidate_rows), "自动安装": installed,+ print({"候选": len(candidate_rows), "自动安装": installed, "在位的更好未覆盖": kept,"带脸候选": sum(1 for r in candidate_rows if int(r.get("face_width") or 0) > 0),"链接待装": len(install_rows), "链接待复核": len(review_rows),"候选 CSV": str(args.candidates), "链接 CSV": str(args.out_links),diff --git a/scripts/test_runner.py b/scripts/test_runner.pyindex 78abc03ac..b65a052e1 100644--- a/scripts/test_runner.py+++ b/scripts/test_runner.py@@ -31,6 +31,7 @@ SCOPES: dict[str, tuple[str, ...]] = {"test_review_mirror.py", "test_rm_ledger.py", "test_rm_web.py","test_entity_link_install.py", "test_web_links.py","test_link_marks.py", "test_site_icons.py", "test_site_logos.py",+ "test_avatar_face.py","test_studio_icon_variants.py","test_review_csv.py", "test_related.py","test_jav_code_domain.py",@@ -47,7 +48,8 @@ SCOPES: dict[str, tuple[str, ...]] = {"metadata": ("test_scraping_access.py", "test_metadata*.py", "test_genre_taxonomy.py", "test_fc2*.py","test_babepedia_match.py","test_jav*.py", "test_code_creators.py", "test_logo_provider.py",- "test_avatar_provider.py", "test_face_detect.py", "test_performer*.py",+ "test_avatar_provider.py", "test_avatar_face.py",+ "test_face_detect.py", "test_performer*.py","test_social_avatar_harvest.py","test_series_localization.py","test_duplicate_identity_merge.py", "test_entity_merge.py",diff --git a/src/peach/avatar_face.py b/src/peach/avatar_face.pynew file mode 100644index 000000000..e669efef5--- /dev/null+++ b/src/peach/avatar_face.py@@ -0,0 +1,115 @@+# -*- coding: utf-8 -*-+r"""实体图的人脸记录:一张图检一次,两处用。++同一次 YuNet 检出既是圆头像的取景依据(`<kind>-<id>.face.json` sidecar),也是选图+时「这张脸有多少像素」的判据。两处分头各检一遍不只是浪费,还会给出互相矛盾的答案:+`harvest_social_avatars.py` 按脸挑赢家、`detect_avatar_faces.py` 另算一份 sidecar,+中间隔着一次落盘,两边看到的可以是不同的图。++sidecar 的形状是契约的一部分,读它的是 `peach.web_state.avatar_focus`:`px` 给源图+像素,归一化的 `face` 配上它才还得出脸的像素数——放大到几倍还清楚问的是像素。未检出+写 `"face": null` 并省略 `focus`,页面维持几何居中。+"""+from __future__ import annotations++import json+from pathlib import Path++from peach.catalog_rules import face_focus+from peach.face_detect import FaceDetector, main_face++#: sidecar 与实体图同名,换后缀。`performer-8711.img` → `performer-8711.face.json`。+SIDECAR_SUFFIX = ".face.json"+++def sidecar_path(image_path: Path) -> Path:+ return Path(image_path).with_suffix(SIDECAR_SUFFIX)+++def face_record(image_path: Path, detector: FaceDetector) -> dict | None:+ """检一张图,返回可直接落盘的 sidecar 内容;读不出图返回 None。"""+ import cv2++ image = cv2.imread(str(image_path))+ if image is None:+ return None+ height, width = image.shape[:2]+ ratio = round(width / height, 3) if height else 0+ record: dict = {"ratio": ratio, "px": [width, height], "face": None}+ faces = detector.detect(image)+ if not faces:+ return record+ # 多张脸时挑主角:先卡分数再取最大,判据在 peach.face_detect.main_face。+ best = main_face(faces)+ record["face"] = {"cx": best.cx, "cy": best.cy, "w": best.width,+ "h": best.height, "score": best.score}+ focus = face_focus(ratio, best.cx, best.cy)+ if focus:+ record["focus"] = focus+ return record+++def face_px_width(record: dict | None) -> int:+ """记录里那张脸有多少像素宽。没有脸、没有记录都是 0。"""+ if not record:+ return 0+ face = record.get("face") or {}+ px = record.get("px") or [0, 0]+ try:+ return round(float(face["w"]) * float(px[0]))+ except (KeyError, TypeError, ValueError, IndexError):+ return 0+++def write_sidecar(image_path: Path, record: dict) -> Path:+ path = sidecar_path(image_path)+ path.write_text(json.dumps(record, ensure_ascii=False), encoding="utf-8")+ return path+++def read_sidecar(image_path: Path) -> dict | None:+ path = sidecar_path(image_path)+ try:+ return json.loads(path.read_text(encoding="utf-8"))+ except (OSError, ValueError):+ return None+++def drop_sidecar(image_path: Path) -> None:+ """换了图又给不出新记录时,宁可没有 sidecar。++ 留着旧的比没有更糟:页面会拿上一张图的脸框去给这一张取景,放大到一个空位置上,+ 而这在界面上与「这张图本来就该这么显示」看不出区别。+ """+ sidecar_path(image_path).unlink(missing_ok=True)+++class FaceProbe:+ """按需构造模型的人脸探针,检不出与检不了分得开。++ 模型是懒构造的:这一趟一个候选都没走到就不必去下 232 KB 的 ONNX。取不到模型也不+ 让整轮停下——那会把「今天没网」变成「所有人都没有头像」——但要把原因记进 `unavailable`+ 让调用方报出来,不然一次下载失败会静悄悄地把整批退回不看脸的旧判据。+ """++ def __init__(self):+ self._detector: FaceDetector | None = None+ self._unavailable = ""++ @property+ def unavailable(self) -> str:+ return self._unavailable++ def __call__(self, image_path: Path) -> dict | None:+ if self._unavailable:+ return None+ if self._detector is None:+ try:+ self._detector = FaceDetector()+ except Exception as error: # 缺模型、缺 OpenCV、下载失败+ self._unavailable = str(error)+ return None+ try:+ return face_record(Path(image_path), self._detector)+ except Exception: # 单张图解不开不该拖垮整轮+ return Nonediff --git a/tests/test_avatar_face.py b/tests/test_avatar_face.pynew file mode 100644index 000000000..323a10b44--- /dev/null+++ b/tests/test_avatar_face.py@@ -0,0 +1,93 @@+# -*- coding: utf-8 -*-+"""实体图人脸记录:sidecar 形状、像素换算与探针的降级行为。"""+import json+import tempfile+import unittest+import unittest.mock+from pathlib import Path++from peach.avatar_face import (+ FaceProbe, drop_sidecar, face_px_width, read_sidecar, sidecar_path,+ write_sidecar,+)+++def record(width=640, height=960, face_w=0.105):+ return {"ratio": round(width / height, 3), "px": [width, height],+ "face": {"cx": 0.439, "cy": 0.224, "w": face_w, "h": 0.095,+ "score": 0.934}}+++class SidecarTests(unittest.TestCase):+ def test_the_sidecar_sits_beside_the_image_under_a_swapped_suffix(self):+ self.assertEqual(sidecar_path(Path("/x/performer-8711.img")).name,+ "performer-8711.face.json")++ def test_a_written_sidecar_reads_back_unchanged(self):+ with tempfile.TemporaryDirectory() as tmp:+ image = Path(tmp).resolve() / "performer-1.img"+ payload = record()+ written = write_sidecar(image, payload)+ self.assertEqual(json.loads(written.read_text(encoding="utf-8")), payload)+ self.assertEqual(read_sidecar(image), payload)++ def test_a_missing_or_broken_sidecar_reads_as_nothing(self):+ with tempfile.TemporaryDirectory() as tmp:+ image = Path(tmp).resolve() / "performer-1.img"+ self.assertIsNone(read_sidecar(image))+ sidecar_path(image).write_text("{ not json", encoding="utf-8")+ self.assertIsNone(read_sidecar(image))++ def test_dropping_is_safe_to_repeat(self):+ with tempfile.TemporaryDirectory() as tmp:+ image = Path(tmp).resolve() / "performer-1.img"+ write_sidecar(image, record())+ drop_sidecar(image)+ drop_sidecar(image)+ self.assertFalse(sidecar_path(image).exists())+++class FacePixelWidthTests(unittest.TestCase):+ def test_the_normalized_box_becomes_pixels_against_the_source_width(self):+ """归一化值给得出比例,给不出像素——放大到几倍还清楚问的是像素。"""+ self.assertEqual(face_px_width(record(640, 960, 0.105)), 67)++ def test_everything_unmeasurable_is_zero(self):+ for payload in (None, {}, {"px": [640, 960], "face": None},+ {"face": {"w": 0.1}}, {"px": [], "face": {"w": 0.1}},+ {"px": [640, 960], "face": {"w": "大"}}):+ with self.subTest(payload=payload):+ self.assertEqual(face_px_width(payload), 0)+++class FaceProbeTests(unittest.TestCase):+ def test_the_model_is_built_once_and_only_when_something_needs_it(self):+ """一趟里一个候选都没走到就不必去下 232 KB 的 ONNX。"""+ probe = FaceProbe()+ with unittest.mock.patch("peach.avatar_face.FaceDetector") as detector:+ self.assertEqual(detector.call_count, 0)+ with unittest.mock.patch("peach.avatar_face.face_record",+ return_value=record()):+ probe(Path("/tmp/a.img"))+ probe(Path("/tmp/b.img"))+ self.assertEqual(detector.call_count, 1)++ def test_an_unavailable_model_is_reported_instead_of_stopping_the_run(self):+ """取不到模型会把「今天没网」变成「所有人都没有头像」,所以只记原因。"""+ probe = FaceProbe()+ with unittest.mock.patch("peach.avatar_face.FaceDetector",+ side_effect=RuntimeError("模型未取得")):+ self.assertIsNone(probe(Path("/tmp/a.img")))+ self.assertEqual(probe.unavailable, "模型未取得")++ def test_one_undecodable_image_does_not_take_down_the_batch(self):+ probe = FaceProbe()+ with unittest.mock.patch("peach.avatar_face.FaceDetector"):+ with unittest.mock.patch("peach.avatar_face.face_record",+ side_effect=ValueError("解不开")):+ self.assertIsNone(probe(Path("/tmp/a.img")))+ self.assertEqual(probe.unavailable, "")+++if __name__ == "__main__":+ unittest.main()diff --git a/tests/test_social_avatar_harvest.py b/tests/test_social_avatar_harvest.pyindex f6ae1488d..747860173 100644--- a/tests/test_social_avatar_harvest.py+++ b/tests/test_social_avatar_harvest.py@@ -2,6 +2,7 @@import hashlibimport importlib.utilimport io+import jsonimport sqlite3import sysimport tempfile@@ -70,10 +71,16 @@ class CoverFallbackTests(unittest.TestCase):cache = module.AvatarCandidateCache(root / 'cache')faces = {hashlib.sha256(big).hexdigest(): 40,hashlib.sha256(small).hexdigest(): 220}- result = module.cover_fallback(- con, record, cache, root,- face_width=lambda path: faces[- hashlib.sha256(Path(path).read_bytes()).hexdigest()])++ def probe(path):+ payload = Path(path).read_bytes()+ width = 1600 if payload == big else 800+ digest = hashlib.sha256(payload).hexdigest()+ return {"ratio": 1.5, "px": [width, 1],+ "face": {"cx": 0.5, "cy": 0.4, "w": faces[digest] / width,+ "h": 0.2, "score": 0.9}}++ result = module.cover_fallback(con, record, cache, root, probe=probe)self.assertEqual(result['external_id'], 'BBB-002')con.close()@@ -254,7 +261,7 @@ class SelectionTests(unittest.TestCase):self.assertEqual((winner["width"], winner["height"]), (600, 600))def test_the_same_image_is_measured_once_and_lands_in_the_review_csv(self):- """脸宽是 CSV 的一列:复核的人据此判断这张脸够不够大。同图只量一次——+ """脸宽是 CSV 的一列:复核的人据此判断这张脸够不够大。同图只检一次——一个人的 X、lit.link、Instagram 三处常常挂着同一张图。"""self.assertIn("face_width", self.module.CANDIDATE_FIELDS)sha = hashlib.sha256(b"one").hexdigest()@@ -264,20 +271,15 @@ class SelectionTests(unittest.TestCase):def fake(path):calls.append(path)- return 88+ return {"ratio": 1.0, "px": [400, 400],+ "face": {"cx": 0.5, "cy": 0.4, "w": 0.22, "h": 0.2, "score": 0.9}}self.module.measure_faces(rows, fake)self.assertEqual(len(calls), 2)self.assertEqual([row["face_width"] for row in rows], [88, 88, 88])-- def test_a_missing_face_model_records_the_reason_instead_of_raising(self):- """下不到 ONNX 不该把「今天没网」变成「所有人都没有头像」。"""- measure = self.module.FaceWidth()- measure._detector = None- with unittest.mock.patch.dict(- sys.modules, {"peach.face_detect": None}):- self.assertEqual(measure(Path("/tmp/nope.jpg")), 0)- self.assertTrue(measure.unavailable)+ # 同一次检出既定判据也写 sidecar,页面读的脸框和挑图用的脸框不会来自两次检测。+ self.assertEqual([row["face_record"]["px"] for row in rows],+ [[400, 400]] * 3)def test_same_image_on_two_platforms_collapses_and_merges_evidence(self):sha = hashlib.sha256(b"same").hexdigest()@@ -306,6 +308,104 @@ class SelectionTests(unittest.TestCase):self.assertFalse(module.passes_auto_bar(200, 200))+class InstallGateTests(unittest.TestCase):+ """`--force` 的安全带:只有脸更大才覆盖盘上那张。"""++ def setUp(self):+ self.module = load_module()++ @staticmethod+ def record(width, height, face_w):+ return {"ratio": round(width / height, 3), "px": [width, height],+ "face": {"cx": 0.5, "cy": 0.4, "w": face_w / width, "h": 0.2,+ "score": 0.9}}++ def install(self, directory, name, payload, record):+ (directory / name).write_bytes(payload)+ if record is not None:+ (directory / name).with_suffix(".face.json").write_text(+ json.dumps(record), encoding="utf-8")++ def winner(self, directory, payload, face_record):+ cached = directory / "cached.jpg"+ cached.write_bytes(payload)+ return {"object_path": cached, "sha256": hashlib.sha256(payload).hexdigest(),+ "mime_type": "image/jpeg", "provider": "social-web",+ "source_url": "https://example.invalid/a.jpg", "external_id": "x",+ "width": 400, "height": 400, "face_record": face_record}++ def test_an_empty_slot_takes_anything_that_won(self):+ """缺头像时这道闸门是空操作。"""+ with tempfile.TemporaryDirectory() as tmp:+ missing = Path(tmp).resolve() / "performer-1.img"+ self.assertIsNone(self.module.incumbent_row(missing, lambda p: None))+ self.assertTrue(self.module.outranks_incumbent(+ {"width": 400, "height": 400, "face_width": 10}, None))++ def test_a_smaller_face_never_overwrites_the_installed_one(self):+ """2026-09-06 实测:一趟 --force 换掉 350 张,282 张脸更小。本脚本的候选池+ (X 的 400×400、jae 的 320×500、作品封面)未必比别的管线装的强。"""+ winner = {"width": 400, "height": 400, "face_width": 137}+ incumbent = {"width": 2880, "height": 1800, "face_width": 786}+ self.assertFalse(self.module.outranks_incumbent(winner, incumbent))+ self.assertTrue(self.module.outranks_incumbent(incumbent, winner))++ def test_the_installed_face_comes_from_the_sidecar_instead_of_a_second_detection(self):+ """525 张各检一遍要好几分钟,而 sidecar 本来就是同一次检出的结果。"""+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp).resolve()+ self.install(root, "performer-1.img", jpeg(640, 960),+ self.record(640, 960, 300))+ calls = []+ row = self.module.incumbent_row(root / "performer-1.img",+ lambda path: calls.append(path))+ self.assertEqual(calls, [])+ self.assertEqual((row["width"], row["height"], row["face_width"]),+ (640, 960, 300))++ def test_an_installed_image_without_a_sidecar_is_detected_once(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp).resolve()+ self.install(root, "performer-1.img", jpeg(640, 960), None)+ row = self.module.incumbent_row(+ root / "performer-1.img", lambda path: self.record(640, 960, 210))+ self.assertEqual(row["face_width"], 210)++ def test_installing_replaces_the_sidecar_so_the_page_never_frames_the_old_face(self):+ """留着上一张图的脸框,页面会拿它给这一张取景、放大到一个空位置上,而这在+ 界面上与「这张图本来就该这么显示」看不出区别。"""+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp).resolve()+ self.install(root, "performer-1.img", jpeg(640, 960),+ self.record(640, 960, 300))+ self.module.install_avatar(root, "performer", 1, self.winner(+ root, jpeg(400, 400, (9, 9, 9)), self.record(400, 400, 120)))+ written = json.loads(+ (root / "performer-1.face.json").read_text(encoding="utf-8"))+ self.assertEqual(written["px"], [400, 400])++ def test_a_winner_with_no_face_record_drops_the_stale_sidecar(self):+ with tempfile.TemporaryDirectory() as tmp:+ root = Path(tmp).resolve()+ self.install(root, "performer-1.img", jpeg(640, 960),+ self.record(640, 960, 300))+ self.module.install_avatar(root, "performer", 1, self.winner(+ root, jpeg(400, 400, (9, 9, 9)), None))+ self.assertFalse((root / "performer-1.face.json").exists())++ def test_a_missing_face_model_records_the_reason_instead_of_raising(self):+ """下不到 ONNX 不该把「今天没网」变成「所有人都没有头像」。"""+ from peach.avatar_face import FaceProbe+ probe = FaceProbe()+ with unittest.mock.patch("peach.avatar_face.FaceDetector",+ side_effect=RuntimeError("模型未取得")):+ self.assertIsNone(probe(Path("/tmp/nope.jpg")))+ self.assertEqual(probe.unavailable, "模型未取得")+ # 记住之后不再反复重试,也不再抛。+ self.assertIsNone(probe(Path("/tmp/nope.jpg")))+++class HarvestTests(unittest.TestCase):def setUp(self):self.module = load_module()