Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(avatars): 头像候选按脸的像素宽挑选

longmeidao65f9c93ccb6b
diff --git a/docs/SOURCING.md b/docs/SOURCING.md
index 249347e9f..969e30ae9 100644
--- a/docs/SOURCING.md
+++ b/docs/SOURCING.md
@@ -319,6 +319,13 @@ Windows 空数据预览的项目 CA HTTPS、合成 Cookie 保存/撤销、DMM
`_200x200`(8068 B vs 12302 B)。所以一律从无后缀原图起、按 `peach.social_links.twimg_tiers` 的档位往下
退(旧头像有过只剩缩略图的),`resolved_url` 记实际取到的那一档,全档缺失才算取图失败。厂牌 Logo
(`fetch_studio_avatar_candidates.py`)与演员社媒头像(`harvest_social_avatars.py`)共用这一份判据。
+- **头像候选按脸的像素宽挑,画布只是它没得比时的退路。** 头像最终落在 64–160 px 的圆框里,认不认得出
+ 是谁取决于那张脸有多少像素,与这张图多大无关。`performer-8711` 是实测反例:装着的 640×960 全身站姿
+ 照脸只有 67 px 宽,同一个人另有一张 540×810 半身照、画布小 15% 而脸有 160 px 上下——按画布挑,赢的
+ 是唯一看不清脸的那张。判据在 `harvest_social_avatars.rank_key`,脸宽由 `peach.face_detect` 的 YuNet 量
+ (同 SHA 只量一次),并写进候选 CSV 的 `face_width` 列供复核的人直接看。检不出脸记 0,排在任何量得
+ 到的候选之后;整批都是 0(模型缺席、清一色侧脸)时排序原样落回画布口径,并在运行统计里说明本轮是
+ 按画布挑的。单人作品封面这条退路走同一把尺:JAV 双联封面右半幅剧照里的脸常常只有几十像素。
- 能解析不等于是对的品牌:`@bazooka` 确实存在且能取到 400×400 头像,但那是 2007 年注册的通用账号,
不是这个 AV 厂牌。所以 handle 必须逐个取证确认,脚本默认不猜,`--guess-handles` 的产出一律标
`needs_confirmation` 且不自动采纳,查不到就留空。
diff --git a/scripts/harvest_social_avatars.py b/scripts/harvest_social_avatars.py
index 6e7d3bbee..2d8c4f68d 100644
--- a/scripts/harvest_social_avatars.py
+++ b/scripts/harvest_social_avatars.py
@@ -134,7 +134,7 @@ LINK_FIELDS = ("entity_id", "kind", "name", "link_kind", "label", "url", "eviden
CANDIDATE_FIELDS = (
"entity_id", "current_name", "matched_name", "name_source", "provider",
"source_kind", "source_url", "external_id", "gfriends_category",
- "gfriends_file", "width", "height", "mime_type", "sha256", "cache_path",
+ "gfriends_file", "width", "height", "face_width", "mime_type", "sha256", "cache_path",
"provenance_path", "policy_version", "verdict", "avatar_url", "evidence",
)
@@ -554,8 +554,13 @@ def harvest_entity(record: dict, http: HttpTransport, limiter: HostLimiter,
def cover_fallback(connection, record: dict, cache: AvatarCandidateCache,
- cover_root: Path = COVER_DIR) -> dict | None:
- """仅使用已关联的单人作品封面,保留完整大图和来源。"""
+ cover_root: Path = COVER_DIR, face_width=None) -> dict | None:
+ """仅使用已关联的单人作品封面,保留完整大图和来源。
+
+ 封面是这条链路上脸最容易被画布口径坑到的一档:JAV 封面普遍是 800×538 的双联版式,
+ 右半幅整幅剧照里那张脸常常只有几十像素,而左半幅的文字块一个像素也不给脸。挑封面
+ 和挑社媒头像用同一把尺——先看脸有多少像素。
+ """
if record["kind"] != "performer":
return None
candidates = []
@@ -582,13 +587,88 @@ def cover_fallback(connection, record: dict, cache: AvatarCandidateCache,
sha256=inspected.sha256, object_path=stored,
matched=record['canonical'], name_source='ledger-performer',
evidence=f'单人作品 {code} 完整封面'))
- return max(candidates, key=lambda r: r['width'] * r['height']) if candidates else None
+ if not candidates:
+ return None
+ if face_width is not None:
+ measure_faces(candidates, face_width)
+ return max(candidates, key=rank_key)
-def select_winner(candidates: list[dict]) -> tuple[dict | None, list[dict]]:
- """同图去重(SHA-256 相同 = 同一张图的不同档位/不同平台),取最大的最清晰的。
+class FaceWidth:
+ """一枚候选里那张脸有多少像素宽。检不出脸就是 0。
- 「大」的口径:先比短边再比长边——竖构图人像与方图头像用同一把尺会偏袒长边。
+ 模型按需构造,与 `harvest_studio_icons.FaceGate` 同一条理由:一趟里一个候选都
+ 没走到就不必去下 232 KB 的 ONNX,而取不到模型也不能让整轮停下——那会把「今天
+ 没网」变成「所有人都没有头像」。取不到就退回画布口径,并把原因记进统计。
+ """
+
+ 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` 要回答的是「装进圆框后看不看得清这张脸」,
+ 而那取决于脸有多少像素可用,与画布多大无关。
+ """
+ seen: dict[str, int] = {}
+ 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]
+
+
+def rank_key(row: dict) -> tuple[int, int, int, int]:
+ """挑图的唯一判据:脸的像素宽先说话,画布只是它没得比时的退路。
+
+ 检不出脸的候选脸宽是 0,自然排到有脸的后面;全都检不出(侧脸、低头、模型缺席)
+ 时整批都是 0,排序原样落回画布口径:先比短边再比长边——竖构图人像与方图头像
+ 用同一把尺会偏袒长边。
+ """
+ return (row.get("face_width") or 0,
+ min(row["width"], row["height"]),
+ max(row["width"], row["height"]),
+ row["width"] * row["height"])
+
+
+def select_winner(candidates: list[dict]) -> tuple[dict | None, list[dict]]:
+ """同图去重(SHA-256 相同 = 同一张图的不同档位/不同平台),取脸最清楚的那一张。
+
+ **脸的像素数先说话,画布只是它没得比时的退路。** 头像最终显示在一个 64–160 px
+ 的圆框里,能不能认出是谁,取决于那张脸有多少像素,不取决于这张图有多大。
+ 实测 `performer-8711`:装着的是 640×960 的全身站姿照,脸只有 67 px 宽,在资料页
+ 圆框里放到源图 1:1 也只占两成;同一个人另有一张 540×810 的半身照,画布小了 15%,
+ 脸却有 160 px 上下——按画布挑,赢的是前者,而它是两张里唯一看不清脸的。
+ 判据本身见 `rank_key`。
"""
by_sha: dict[str, dict] = {}
for candidate in candidates:
@@ -603,10 +683,7 @@ def select_winner(candidates: list[dict]) -> tuple[dict | None, list[dict]]:
by_sha[candidate["sha256"]] = larger
if not by_sha:
return None, []
- ranked = sorted(by_sha.values(),
- key=lambda row: (min(row["width"], row["height"]),
- max(row["width"], row["height"]),
- row["width"] * row["height"]))
+ ranked = sorted(by_sha.values(), key=rank_key)
return ranked[-1], ranked[:-1]
@@ -724,6 +801,7 @@ def run(args) -> int:
install_rows: list[dict] = []
review_rows: list[dict] = []
installed = 0
+ face_width = FaceWidth()
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)
@@ -760,10 +838,13 @@ def run(args) -> int:
row.update(verdict="需人工确认", reason="名字闸门未过")
review_rows.append(row)
+ # 先量脸再挑:赢家由脸的像素数定,画布只是没得比时的退路。
+ measure_faces(result["candidates"], face_width)
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'])
+ fallback = cover_fallback(connection, record, caches['cover'],
+ face_width=face_width)
if fallback:
if winner:
runners_up.append(winner)
@@ -792,7 +873,7 @@ def run(args) -> int:
elif is_winner:
note = "竞选赢家但身份未核实;先核链接再装"
else:
- note = "竞选落选(同图或更小);留档备查"
+ note = "竞选落选(同图或脸更小);留档备查"
candidate_rows.append({
"entity_id": entity_id, "current_name": record["canonical"],
"matched_name": candidate.get("matched") or "",
@@ -803,6 +884,8 @@ def run(args) -> int:
"external_id": candidate["external_id"],
"gfriends_category": "", "gfriends_file": "",
"width": candidate["width"], "height": candidate["height"],
+ # 复核的人据此一眼看出「这张脸够不够大」,比画布尺寸有用得多。
+ "face_width": candidate.get("face_width") or 0,
"mime_type": candidate["mime_type"],
"sha256": candidate["sha256"],
"cache_path": candidate["object_path"].name,
@@ -825,9 +908,15 @@ 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:
+ # 说清这一轮是按什么挑的。不说的话,一次「今天没网下不到 ONNX」会静悄悄地
+ # 把整批退回画布口径,产出看着完全正常,脸却全挑小了。
+ print(f"人脸检测未取得({face_width.unavailable}):本轮按画布尺寸挑图,"
+ "face_width 一列全是 0;模型可用后加 --force 重跑该批。")
if not args.apply:
print("空跑:以上一张头像都没落盘;确认候选无误后加 --apply 重跑。")
print({"候选": len(candidate_rows), "自动安装": installed,
+ "带脸候选": 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),
"复核链接 CSV": str(args.review_links)})
diff --git a/tests/test_social_avatar_harvest.py b/tests/test_social_avatar_harvest.py
index 0b55113de..f6ae1488d 100644
--- a/tests/test_social_avatar_harvest.py
+++ b/tests/test_social_avatar_harvest.py
@@ -6,6 +6,7 @@ import sqlite3
import sys
import tempfile
import unittest
+import unittest.mock
from pathlib import Path
from PIL import Image
@@ -48,6 +49,34 @@ class CoverFallbackTests(unittest.TestCase):
self.assertIsNone(module.cover_fallback(con, record, cache, root))
con.close()
+ def test_the_cover_with_the_bigger_face_wins_over_the_bigger_canvas(self):
+ """JAV 封面普遍是双联版式,右半幅剧照里那张脸常常只有几十像素。挑封面
+ 和挑社媒头像用同一把尺:先看脸有多少像素。"""
+ module = load_module()
+ with tempfile.TemporaryDirectory() as tmp:
+ root = Path(tmp).resolve()
+ big = jpeg(1600, 1076, (10, 20, 30))
+ small = jpeg(800, 538, (30, 20, 10))
+ (root / 'AAA-001.jpg').write_bytes(big)
+ (root / 'BBB-002.jpg').write_bytes(small)
+ con = sqlite3.connect(':memory:')
+ con.executescript("CREATE TABLE asset(id,code,disposal);"
+ "CREATE TABLE asset_entity(asset_id,entity_id,role);"
+ "INSERT INTO asset VALUES(1,'AAA-001',NULL);"
+ "INSERT INTO asset VALUES(2,'BBB-002',NULL);"
+ "INSERT INTO asset_entity VALUES(1,5,'performer');"
+ "INSERT INTO asset_entity VALUES(2,5,'performer');")
+ record = dict(kind='performer', entity_id=5, canonical='风见步')
+ 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()])
+ self.assertEqual(result['external_id'], 'BBB-002')
+ con.close()
+
X_BASE = "https://pbs.twimg.com/profile_images/2033362507679850496/4wvXoOFw"
@@ -186,12 +215,69 @@ class SelectionTests(unittest.TestCase):
self.module = load_module()
@staticmethod
- def candidate(width, height, sha, evidence="图"):
- return {"provider": "social-web", "source_kind": "official_profile",
- "source_url": "https://example.invalid/a.jpg", "external_id": "x",
- "width": width, "height": height, "mime_type": "image/jpeg",
- "sha256": sha, "object_path": Path("/tmp/x"), "matched": "釈アリス",
- "name_source": "social_identity_gate", "evidence": evidence}
+ def candidate(width, height, sha, evidence="图", face_width=None):
+ row = {"provider": "social-web", "source_kind": "official_profile",
+ "source_url": "https://example.invalid/a.jpg", "external_id": "x",
+ "width": width, "height": height, "mime_type": "image/jpeg",
+ "sha256": sha, "object_path": Path("/tmp/x"), "matched": "釈アリス",
+ "name_source": "social_identity_gate", "evidence": evidence}
+ if face_width is not None:
+ row["face_width"] = face_width
+ return row
+
+ def test_the_bigger_canvas_loses_to_the_bigger_face(self):
+ """`performer-8711` 的真实两张:640×960 的全身照画布更大,脸只有 67 px;
+ 540×810 的半身照画布小 15%,脸有 160 px。头像圆框里认不认得出人,看的是
+ 后者。"""
+ standing = self.candidate(640, 960, hashlib.sha256(b"stand").hexdigest(),
+ face_width=67)
+ bust = self.candidate(540, 810, hashlib.sha256(b"bust").hexdigest(),
+ face_width=160)
+ winner, runners_up = self.module.select_winner([standing, bust])
+ self.assertEqual((winner["width"], winner["height"]), (540, 810))
+ self.assertEqual([r["width"] for r in runners_up], [640])
+
+ def test_a_face_that_was_not_detected_ranks_below_any_detected_face(self):
+ """侧脸、低头、戴口罩都会检不出。检不出的记 0,让位给量得到的那张。"""
+ huge = self.candidate(1500, 1500, hashlib.sha256(b"huge").hexdigest(),
+ face_width=0)
+ small = self.candidate(400, 400, hashlib.sha256(b"small").hexdigest(),
+ face_width=90)
+ winner, _ = self.module.select_winner([huge, small])
+ self.assertEqual(winner["width"], 400)
+
+ def test_a_batch_with_no_measurable_face_ranks_by_canvas(self):
+ """模型缺席或整批都检不出脸时,脸宽全是 0,判据原样落回画布口径。"""
+ rows = [self.candidate(500, 1500, hashlib.sha256(b"t").hexdigest(), face_width=0),
+ self.candidate(600, 600, hashlib.sha256(b"s").hexdigest(), face_width=0)]
+ winner, _ = self.module.select_winner(rows)
+ self.assertEqual((winner["width"], winner["height"]), (600, 600))
+
+ def test_the_same_image_is_measured_once_and_lands_in_the_review_csv(self):
+ """脸宽是 CSV 的一列:复核的人据此判断这张脸够不够大。同图只量一次——
+ 一个人的 X、lit.link、Instagram 三处常常挂着同一张图。"""
+ self.assertIn("face_width", self.module.CANDIDATE_FIELDS)
+ sha = hashlib.sha256(b"one").hexdigest()
+ rows = [self.candidate(400, 400, sha), self.candidate(400, 400, sha),
+ self.candidate(400, 400, hashlib.sha256(b"two").hexdigest())]
+ calls = []
+
+ def fake(path):
+ calls.append(path)
+ return 88
+
+ 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)
def test_same_image_on_two_platforms_collapses_and_merges_evidence(self):
sha = hashlib.sha256(b"same").hexdigest()