Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(avatar): 个人博主按两部作品互证从接触印相截脸

longmeidao5231a4a79088
diff --git a/src/peach/avatar_cover_face.py b/src/peach/avatar_cover_face.py
index ccfb0a121..aed6e7f8e 100644
--- a/src/peach/avatar_cover_face.py
+++ b/src/peach/avatar_cover_face.py
@@ -12,10 +12,14 @@
只看单人作品:一部片挂着两个演员时,封面上那张脸是谁机器答不出来。单人作品也只是
「多半是她」,不是核实过的身份,所以来源记录标 `identity_verified: false`,这张图
永远排在图库与名录人像之后,出现那一档就被换掉(`avatar_followup`)。
+
+个人博主(过 `work_portrait_predicate` 的发布账号)走 `sheet_faces`:作品没有番号封面,
+画面取自接触印相九格,截法与来源记录同上(ADR-0096)。
"""
from __future__ import annotations
import json
+from collections.abc import Callable
from dataclasses import dataclass
from pathlib import Path
@@ -31,6 +35,10 @@ WHOLE_COVER_PROVIDERS = ("cover", "cover-fallback", "poster-fallback")
#: 方框边长是脸宽的几倍。YuNet 的框只框到额头和下巴,放到 2.4 倍才装得下头发和下巴
#: 下面一点;圆框再切掉四角,脸不贴边。
FACE_SPAN = 2.4
+#: 接触印相是三行三列(`PreviewService.poster` 按同一个网格切格)。
+SHEET_GRID = 3
+#: 个人博主一次最多看这么多部作品的印相:一部九格,每格检两次脸。
+MAX_SHEET_WORKS = 24
@dataclass(frozen=True)
@@ -43,21 +51,29 @@ class CoverFace:
width: int
height: int
record: dict
+ #: 接触印相的第几格(`sheet_faces`);封面上截的是 None。
+ cell: int | None = None
@property
def face_px(self) -> int:
return face_px_width(self.record)
-def single_performer_works(connection, entity_id: int) -> list[tuple[int, str]]:
- """这个人名下只有她一个演员的作品,`(asset_id, 番号)`,回收站里的不算。"""
- return [(int(asset_id), str(code or '')) for asset_id, code in connection.execute(
- "SELECT a.id,a.code FROM asset a JOIN asset_entity ae ON ae.asset_id=a.id "
- "WHERE ae.entity_id=? AND ae.role='performer' "
+def single_works(connection, entity_id: int,
+ role: str = "performer") -> list[tuple[int, str, str]]:
+ """这个人以 `role` 独占的作品,`(asset_id, 番号, 接触印相路径)`,回收站里的不算。
+
+ 女优按 `performer` 取,同一部片不挂别的演员;个人博主按 `creator` 取,同一部片不挂
+ 别的发布账号。
+ """
+ return [(int(asset_id), str(code or ''), str(snapshot or ''))
+ for asset_id, code, snapshot in connection.execute(
+ "SELECT a.id,a.code,a.snapshot_path FROM asset a JOIN asset_entity ae ON ae.asset_id=a.id "
+ "WHERE ae.entity_id=? AND ae.role=? "
"AND a.disposal IS NULL "
"AND NOT EXISTS(SELECT 1 FROM asset_entity other WHERE other.asset_id=a.id "
- "AND other.role='performer' AND other.entity_id<>ae.entity_id) "
- "ORDER BY a.id", (int(entity_id),))]
+ "AND other.role=ae.role AND other.entity_id<>ae.entity_id) "
+ "ORDER BY a.id", (int(entity_id), role))]
def faces(connection, cover_root: Path, entity_id: int, probe) -> list[CoverFace]:
@@ -77,7 +93,7 @@ def faces(connection, cover_root: Path, entity_id: int, probe) -> list[CoverFace
"""
found: list[CoverFace] = []
seen: set[str] = set()
- for asset_id, code in single_performer_works(connection, entity_id):
+ for asset_id, code, _snapshot in single_works(connection, entity_id):
key = artwork_key(asset_id, code)
if not key or key in seen:
continue
@@ -98,6 +114,72 @@ def faces(connection, cover_root: Path, entity_id: int, probe) -> list[CoverFace
return found
+def sheet_cells(body: bytes) -> list[tuple[int, bytes]]:
+ """接触印相切成九格,`(格号, 字节)`。格号与 `/poster` 的 `cell` 同一个编号:行优先,0 起。"""
+ size = images.measure_image_size(body)
+ if size is None:
+ return []
+ width, height = size
+ cells = []
+ for cell in range(SHEET_GRID * SHEET_GRID):
+ col, row = cell % SHEET_GRID, cell // SHEET_GRID
+ box = (width * col // SHEET_GRID, height * row // SHEET_GRID,
+ width * (col + 1) // SHEET_GRID, height * (row + 1) // SHEET_GRID)
+ if (piece := images.crop_to_box(body, box)) is not None:
+ cells.append((cell, piece))
+ return cells
+
+
+def sheet_faces(connection, cover_root: Path, entity_id: int, probe,
+ snapshot_file: Callable[[str], Path | None], *,
+ role: str = "creator") -> list[CoverFace]:
+ """个人博主独占的作品里检得出脸的那些画面,一部作品一张,脸最宽的在前。
+
+ 博主作品大多没有番号,封面目录里没有它们的封面(`artwork_key` 落到 `ASSET-ID-<id>`,
+ 多数没有那张图);画面来自接触印相的九格,有封面的作品封面也算一格。每部作品只留
+ 脸最宽、截出来还检得出脸的那一格:互证数的是作品,同一部片的两格不算两份证据。
+
+ `snapshot_file` 把账本里的印相路径换成本机文件,取不到是 None(`WebContract.snapshot_file`)。
+ 最多看 `MAX_SHEET_WORKS` 部作品。
+ """
+ found: list[CoverFace] = []
+ seen: set[str] = set()
+ for asset_id, code, snapshot in single_works(connection, entity_id, role):
+ if len(seen) >= MAX_SHEET_WORKS:
+ break
+ key = artwork_key(asset_id, code)
+ if key in seen:
+ continue
+ pictures: list[tuple[int | None, bytes]] = []
+ cover = Path(cover_root) / f"{key}.jpg"
+ if artwork_cast_size(cover, 1) <= 1:
+ try:
+ pictures.append((None, cover.read_bytes()))
+ except OSError:
+ pass
+ sheet = snapshot_file(snapshot) if snapshot else None
+ if sheet is not None:
+ try:
+ pictures += sheet_cells(sheet.read_bytes())
+ except OSError:
+ pass
+ if not pictures:
+ continue
+ seen.add(key)
+ best: CoverFace | None = None
+ for cell, body in pictures:
+ record = probe.on_bytes(body) or {}
+ px = record.get("px") or [0, 0]
+ candidate = CoverFace(asset_id, key, body, int(px[0]), int(px[1]), record, cell)
+ if (candidate.face_px > (best.face_px if best else 0)
+ and readable_cut(candidate, probe)):
+ best = candidate
+ if best is not None:
+ found.append(best)
+ found.sort(key=lambda face: (face.face_px, face.width * face.height), reverse=True)
+ return found
+
+
def face_square(record: dict | None, width: int, height: int) -> tuple[int, int, int, int] | None:
"""一份人脸记录在 `width`×`height` 那张图上框出的方图;没有脸,或记录说的是另一张图,
就是 None。
@@ -130,12 +212,13 @@ def cut(face: CoverFace) -> tuple[bytes, dict] | None:
body = images.crop_to_box(face.body, box)
if body is None:
return None
+ sheet = {"sheet_cell": face.cell} if face.cell is not None else {}
return body, {"source": "cover face", "provider": PROVIDER, "source_kind": SOURCE_KIND,
"external_id": face.code, "upstream_url": f"peach:cover-face/{face.code}",
"asset_id": face.asset_id,
"asset_code": face.code, "crop_box": list(box),
"crop_source_px": [face.width, face.height],
- "face_px": face.face_px, "identity_verified": False}
+ "face_px": face.face_px, "identity_verified": False, **sheet}
def _has_face(probe, body: bytes | None) -> bool:
diff --git a/src/peach/avatar_followup.py b/src/peach/avatar_followup.py
index 4aa4c19b1..71d05cd63 100644
--- a/src/peach/avatar_followup.py
+++ b/src/peach/avatar_followup.py
@@ -23,6 +23,10 @@
* 两档都落空、图库里只有没过尺寸门槛的小图时,装认得准的那张小图(ADR-0066):只有一张
就装它,好几张照同一套互证判据挑,认定的几张里挑像素最大的。小图同样可以在上面几档里
作证,只是不当那张被装上的图。这一档装的图之后有了过门槛的图或封面人脸就换掉。
+* **个人博主**(过 `work_portrait_predicate` 的发布账号)不查图库,只从自己独占作品的
+ 画面上截脸(`avatar_cover_face.sheet_faces`,接触印相九格加有封面的那张):两部不同作品
+ 截出的脸互相过线才装,判据与馆外单人作品封面同一条(ADR-0074、ADR-0096)。情侣号、
+ 多人号的两部作品对不上同一张脸就不装。装上的和封面截脸同一档。没过判据的账号不派。
* **厂牌**不走这条:官网和标识由补厂牌后继(`studio_followup`)按厂牌那套判据补。
这条后继是幂等的(ADR-0040 第六条要求):第一件事就是看盘上有没有那张图,有就当场返回。
@@ -46,7 +50,8 @@ TASK_KEY = "entity-avatar"
TASK_LABEL = "补实体头像"
#: 会被派后继的实体种类。厂牌的图是标识,归 `studio_followup`;系列、标签没有头像位。
-KINDS = ("performer",)
+#: 发布账号只派过 `work_portrait_predicate` 的那些(`_candidates`)。
+KINDS = ("performer", "creator")
#: 一次刮削最多为这么多个新实体派后继。上限本身由 `task_runs.MAX_FOLLOWUPS` 判,
#: 这里先按作品数排好序再交出去:截断真的发生时,留下的该是库里出现得最多的那些。
@@ -67,6 +72,9 @@ MAX_MATCH_CANDIDATES = 24
NEAR_DUPLICATE = 0.9
#: 小图兜底那一档装上的图,头像边车里记的 `source_kind`。
SMALL_SOURCE_KIND = "gallery_small"
+#: 派出之后账号分类被改、不再过 `work_portrait_predicate` 时的结论。它取决于分类而不是作品,
+#: 不记进 `Attempts`:分类改回来时照常再派。
+NO_IDENTITY = "账号没有本人身份依据"
def followup_key(kind: str, entity_id: int) -> str:
@@ -93,11 +101,12 @@ def plan(connection: sqlite3.Connection, avatar_root, *,
`covered_asset_ids` 是这一轮换上了新封面的作品。它们的女优也派一条:没头像的现在
可能截得出脸了,头像是从封面截的那些可能换得到更清楚的一张。
"""
+ wanted = _candidates(connection)
rows = connection.execute(
"SELECT e.id,e.kind,e.canonical_name,"
" (SELECT count(DISTINCT ae.asset_id) FROM asset_entity ae"
" WHERE ae.entity_id=e.id) AS assets"
- " FROM entity e WHERE e.id>? AND e.kind='performer' ORDER BY e.id",
+ f" FROM entity e WHERE e.id>? AND {wanted} ORDER BY e.id",
(int(since_entity_id),)).fetchall()
covered = [int(asset_id) for asset_id in covered_asset_ids]
if covered:
@@ -107,7 +116,7 @@ def plan(connection: sqlite3.Connection, avatar_root, *,
"SELECT e.id,e.kind,e.canonical_name,"
" (SELECT count(DISTINCT ae.asset_id) FROM asset_entity ae"
" WHERE ae.entity_id=e.id) AS assets"
- " FROM entity e WHERE e.kind='performer' AND e.id IN"
+ f" FROM entity e WHERE {wanted} AND e.id IN"
f" (SELECT entity_id FROM asset_entity WHERE asset_id IN ({marks}))"
" ORDER BY e.id", covered).fetchall() if int(row["id"]) not in known]
found = []
@@ -123,6 +132,23 @@ def plan(connection: sqlite3.Connection, avatar_root, *,
for _assets, entity_id, kind, name in found]
+def _candidates(connection: sqlite3.Connection) -> str:
+ """派后继的实体:女优,加作品画面能当本人头像的发布账号。"""
+ from .entity_classification import work_portrait_predicate
+
+ return ("(e.kind='performer' OR (e.kind='creator' AND "
+ f"{work_portrait_predicate(connection)}))")
+
+
+def _portrait_account(connection: sqlite3.Connection, entity_id: int) -> bool:
+ """这个发布账号此刻过不过 `work_portrait_predicate`。派出与跑之间分类可能被改过。"""
+ from .entity_classification import work_portrait_predicate
+
+ return connection.execute(
+ f"SELECT 1 FROM entity e WHERE e.id=? AND {work_portrait_predicate(connection)}",
+ (int(entity_id),)).fetchone() is not None
+
+
def needs_avatar(avatar_root, kind: str, entity_id: int) -> bool:
"""没有头像,或者装着的是封面截的、小图兜底的那一档(还可能换到更清楚的)。"""
return (not avatar_picker.installed_digest(avatar_root, kind, entity_id)
@@ -142,7 +168,11 @@ def _installed_small(avatar_root, kind: str, entity_id: int) -> bool:
return isinstance(record, dict) and record.get("source_kind") == SMALL_SOURCE_KIND
-#: 指纹里的量:别名数与 avwikidb 编号数。SQL 与 `stock` 那条共用。
+#: 指纹里的量:作品数、别名数与 avwikidb 编号数。SQL 与 `stock` 那条共用。发布账号的
+#: 作品只数铺过接触印相的:印相是它唯一的画面来源,后补的印相要让它再派一次。
+_WORK_COUNT = ("(SELECT count(DISTINCT ae.asset_id) FROM asset_entity ae"
+ " JOIN asset a ON a.id=ae.asset_id WHERE ae.entity_id=e.id"
+ " AND (e.kind<>'creator' OR coalesce(a.snapshot_path,'')<>''))")
_ALIAS_COUNT = "(SELECT count(*) FROM entity_alias al WHERE al.entity_id=e.id)"
_OFFSITE_COUNT = ("(SELECT count(*) FROM entity_external_ref x WHERE x.entity_id=e.id"
" AND x.provider='avwikidb' AND x.external_kind='performer')")
@@ -165,15 +195,14 @@ def fingerprint(connection: sqlite3.Connection, entity_id: int) -> str:
馆外单人作品的封面才有路可走;判据换了,同一份证据也可能认得出。
"""
row = connection.execute(
- "SELECT (SELECT count(DISTINCT asset_id) FROM asset_entity WHERE entity_id=e.id),"
- f" {_ALIAS_COUNT}, {_OFFSITE_COUNT} FROM entity e WHERE e.id=?",
+ f"SELECT {_WORK_COUNT}, {_ALIAS_COUNT}, {_OFFSITE_COUNT} FROM entity e WHERE e.id=?",
(int(entity_id),)).fetchone()
return _fingerprint(*(row if row else (0, 0, 0)))
def stock(connection: sqlite3.Connection, avatar_root, attempts, *, limit: int,
skip=()) -> list[Followup]:
- """库里早就登记、至今缺头像的女优,作品多的在前,最多 `limit` 条(ADR-0053)。
+ """库里早就登记、至今缺头像的女优与个人博主,作品多的在前,最多 `limit` 条(ADR-0053)。
跑过一次、指纹也没变的不再派(`attempts`):作品和别名都没变,封面和图库命中也不会变。
"""
@@ -182,10 +211,11 @@ def stock(connection: sqlite3.Connection, avatar_root, attempts, *, limit: int,
skip = set(skip)
found = []
for row in connection.execute(
- "SELECT e.id,e.kind,e.canonical_name,count(DISTINCT ae.asset_id) AS assets,"
+ f"SELECT e.id,e.kind,e.canonical_name,{_WORK_COUNT} AS assets,"
f" {_ALIAS_COUNT} AS aliases, {_OFFSITE_COUNT} AS offsite"
- " FROM entity e JOIN asset_entity ae ON ae.entity_id=e.id"
- " WHERE e.kind='performer' GROUP BY e.id ORDER BY assets DESC, e.id"):
+ f" FROM entity e WHERE {_candidates(connection)}"
+ " AND EXISTS(SELECT 1 FROM asset_entity ae WHERE ae.entity_id=e.id)"
+ " ORDER BY assets DESC, e.id"):
entity_id, kind = int(row["id"]), str(row["kind"])
key = followup_key(kind, entity_id)
current = _fingerprint(row["assets"], row["aliases"], row["offsite"])
@@ -204,10 +234,12 @@ def run(contract, key: str, handle) -> dict:
"""跑一条补头像后继,再把实体当时的指纹记进 `Attempts`,存量补派按它判。
该比对却取不到比对模型、或 avwikidb 正在冷却的那一次不记:结论取决于那天有没有网,
- 不取决于她的作品和名字,记下来就要等到她多一部作品才会再试。
+ 不取决于她的作品和名字,记下来就要等到她多一部作品才会再试。账号此刻没有本人身份
+ 依据的那一次(`NO_IDENTITY`)同样不记。
"""
summary = _run(contract, key, handle)
- if summary.get("face_match_unavailable") or summary.get("source_unavailable"):
+ if (summary.get("face_match_unavailable") or summary.get("source_unavailable")
+ or summary.get("outcome") == NO_IDENTITY):
return summary
_kind, entity_id = parse_key(key)
with contract.database.read_connection() as connection:
@@ -240,6 +272,10 @@ def _run(contract, key: str, handle) -> dict:
# 实体被合并或删掉了。这不是失败:那件事已经不存在了。
return {"outcome": "实体已不存在"}
name = str(row[0] or "")
+ if kind == "creator":
+ handle.progress(label=f"{TASK_LABEL}:{name}", throttle=0)
+ return _install_account_face(contract, connection, providers_root, avatar_root,
+ entity_id, name, cropped_px)
# 图库索引只读本地缓存,这一步不联网;联网只发生在要量、要比、要装那几张的时候。
listing = avatar_picker.choices(connection, providers_root, avatar_root,
kind, entity_id)
@@ -658,6 +694,59 @@ def _install_offsite(contract, connection, providers_root, avatar_root, kind: st
f"({len(outcome.evidence['codes'])} 部互证)"}
+def _install_account_face(contract, connection, providers_root, avatar_root, entity_id: int,
+ name: str, cropped_px: int | None) -> dict:
+ """个人博主:两部独占作品的画面截出同一张脸才装(ADR-0074 的互证,ADR-0096)。
+
+ 一部作品只出一张脸(`sheet_faces`),互证数的是作品。没对上的脸照样截好留进候选缓存,
+ 挑图弹层里能点。装上的来源记 `cover-face`、`identity_verified: false`,和封面截脸同一档。
+ """
+ from . import avatar_offsite_cover_face as offsite
+ from .avatar_face import FaceProbe
+
+ summary = {"name": name, "matched": 0}
+ if not _portrait_account(connection, entity_id):
+ return {**summary, "outcome": NO_IDENTITY}
+ probe = FaceProbe()
+ faces = avatar_cover_face.sheet_faces(connection, contract.cover_root, entity_id, probe,
+ contract.snapshot_file)
+ if probe.unavailable:
+ return {**summary, "outcome": f"探针不可用:{probe.unavailable}",
+ "face_match_unavailable": True}
+ if not faces:
+ return {**summary, "outcome": "作品画面上没有能截的脸"}
+ matcher = face_match.FaceMatcher()
+ agreed, scores = offsite.agreeing(faces, matcher)
+ if matcher.unavailable:
+ return {**summary, "outcome": f"比对模型不可用:{matcher.unavailable}",
+ "face_match_unavailable": True}
+ winner = agreed[0] if len({face.code for face in agreed}) >= offsite.AGREE_WORKS else None
+ kept = 0
+ for face in faces[:MAX_KEPT_FACES]:
+ if face is not winner and (extra := avatar_cover_face.cut(face)) is not None:
+ avatar_picker.keep(providers_root, entity_id, *extra)
+ kept += 1
+ summary = {**summary, **({"kept": kept} if kept else {})}
+ if winner is None:
+ return {**summary, "outcome": f"作品画面截到 {len(faces)} 张脸,凑不齐两部互证"}
+ if cropped_px and not avatar_cover_face.installed_face_readable(avatar_root, "creator",
+ entity_id, probe):
+ cropped_px = 0
+ if cropped_px is not None and winner.face_px <= cropped_px:
+ return {**summary, "outcome": "已是最清楚的作品画面人脸", "source": winner.code}
+ cut = avatar_cover_face.cut(winner)
+ if cut is None:
+ return {**summary, "outcome": "画面截不出这一块", "source": winner.code}
+ body, origin = cut
+ evidence = {"codes": [face.code for face in agreed], "scores": scores}
+ inspected = avatar_picker.install(providers_root, avatar_root, "creator", entity_id, body,
+ {**origin, "face_match": evidence})
+ contract.cache_bust()
+ return {**summary, "outcome": "已装上",
+ "size": f"{inspected['width']}×{inspected['height']}",
+ "source": f"作品画面 {winner.code}({len(evidence['codes'])} 部互证)"}
+
+
#: 不写账本:这条后继只往 `avatar_root` 与候选缓存里写文件。它照样一次只跑一条——
#: 通道按 task_key 分,同一种后继本来就共用一条。
TYPE = register(FollowupType(task_key=TASK_KEY, label=TASK_LABEL,
diff --git a/src/peach/web_state.py b/src/peach/web_state.py
index 272cbae9c..07d9abfdd 100644
--- a/src/peach/web_state.py
+++ b/src/peach/web_state.py
@@ -342,10 +342,14 @@ class WebContract:
return self.database.write_transaction()
def has_snapshot(self, raw_path: str | None) -> bool:
+ return self.snapshot_file(raw_path) is not None
+
+ def snapshot_file(self, raw_path: str | None) -> Path | None:
+ """账本里那条接触印相路径在本机的文件;不在盘上是 None。"""
if not raw_path:
- return False
+ return None
path = normalized_path(raw_path) if self.snapshot_root is not None else Path(raw_path)
- return path.is_file()
+ return path if path.is_file() else None
def cover_path(self, code: str | None) -> Path | None:
"""封面按归一番号存一份,多个文件共用同一张;没有就返回 None。"""
diff --git a/tests/test_followups.py b/tests/test_followups.py
index a534a1329..95a65581c 100644
--- a/tests/test_followups.py
+++ b/tests/test_followups.py
@@ -1070,6 +1070,147 @@ class OffsiteCoverFaceTests(FaceStubCase):
self.assertEqual(planned(), [key])
+class AccountFaceFollowupTests(FaceStubCase):
+ """个人博主从自己独占作品的接触印相上截脸,两部作品互证才装(ADR-0074、ADR-0096)。"""
+
+ def setUp(self):
+ super().setUp()
+ self.account = self.entity("creator", "博主")
+ self.identify(self.account)
+
+ def identify(self, entity_id: int) -> None:
+ from peach.entity_classification import write_claim
+
+ with self.database.write_transaction(notify=False) as connection:
+ write_claim(connection, entity_id=entity_id, facet="identity", value="person",
+ source="user:identity-review", evidence="本人出镜", status="approved",
+ confidence=1)
+
+ def sheet(self, asset_id: int, colour) -> Path:
+ """九格同一个人的接触印相:每格上半截黑、下半截是这个人的颜色。"""
+ import io
+
+ from PIL import Image
+ sheet = Image.new("RGB", (900, 600))
+ cell = Image.open(io.BytesIO(self.picture((300, 200), colour)))
+ for index in range(9):
+ sheet.paste(cell, (index % 3 * 300, index // 3 * 200))
+ path = self.root / "snapshots" / f"{asset_id}.jpg"
+ path.parent.mkdir(exist_ok=True)
+ sheet.save(path, format="JPEG", quality=95)
+ return path
+
+ def post(self, asset_id: int, colour, *, owners: tuple[int, ...] = (),
+ snapshot: bool = True) -> None:
+ """账号名下一部没有番号的作品;`colour` 为 None 时没有印相。"""
+ path = self.sheet(asset_id, colour) if snapshot and colour is not None else None
+ with self.database.write_transaction(notify=False) as connection:
+ connection.execute(
+ "INSERT INTO asset(id,location,path,name,medium,size,snapshot_path) "
+ "VALUES(?,'R:',?,?,'video',100,?)",
+ (asset_id, f"R:\\media\\{asset_id}.mp4", f"{asset_id}.mp4",
+ str(path) if path else None))
+ for entity_id in owners or (self.account,):
+ connection.execute(
+ "INSERT INTO asset_entity(asset_id,entity_id,role,source) "
+ "VALUES(?,?,'creator','test')", (asset_id, entity_id))
+
+ def contract(self):
+ def snapshot_file(raw):
+ path = Path(raw) if raw else None
+ return path if path is not None and path.is_file() else None
+
+ return SimpleNamespace(
+ avatar_root=self.avatars, candidate_root=self.root / "generated",
+ cover_root=self.covers, database=self.database, task_runs=self.store,
+ cache_bust=lambda: None, snapshot_file=snapshot_file)
+
+ def run_followup(self) -> dict:
+ from peach.avatar_followup import run as avatar_run
+
+ return avatar_run(self.contract(), followup_key("creator", self.account), mock.Mock())
+
+ def provenance(self) -> dict:
+ return json.loads((self.avatars / f"creator-{self.account}.img.provenance.json")
+ .read_text(encoding="utf-8"))
+
+ def test_the_key_round_trips_for_an_account(self):
+ self.assertEqual(parse_key(followup_key("creator", 9553)), ("creator", 9553))
+
+ def test_two_works_agreeing_install_the_face(self):
+ self.post(1, self.HER)
+ self.post(2, self.HER_AGAIN)
+ summary = self.run_followup()
+ self.assertEqual((summary["outcome"], summary["source"]),
+ ("已装上", "作品画面 ASSET-ID-1(2 部互证)"))
+ record = self.provenance()
+ self.assertEqual((record["provider"], record["identity_verified"], record["sheet_cell"]),
+ ("cover-face", False, 0))
+ self.assertEqual(sorted(record["face_match"]["codes"]), ["ASSET-ID-1", "ASSET-ID-2"])
+
+ def test_two_different_people_install_nothing(self):
+ """情侣号、多人号:两部作品截出的脸对不上同一个人。"""
+ self.post(1, self.HER)
+ self.post(2, self.STRANGER)
+ summary = self.run_followup()
+ self.assertIn("凑不齐两部互证", summary["outcome"])
+ self.assertEqual(summary["kept"], 2)
+ self.assertFalse((self.avatars / f"creator-{self.account}.img").exists())
+
+ def test_nine_cells_of_one_work_are_one_piece_of_evidence(self):
+ self.post(1, self.HER)
+ self.assertIn("凑不齐两部互证", self.run_followup()["outcome"])
+ self.assertFalse((self.avatars / f"creator-{self.account}.img").exists())
+
+ def test_works_shared_with_another_account_are_not_read(self):
+ other = self.entity("creator", "另一个号")
+ self.post(1, self.HER)
+ self.post(2, self.HER_AGAIN, owners=(self.account, other))
+ self.assertIn("凑不齐两部互证", self.run_followup()["outcome"])
+
+ def test_an_account_without_identity_is_neither_planned_nor_recorded(self):
+ from peach.avatar_followup import NO_IDENTITY, fingerprint, stock
+ from peach.followups import Attempts, attempts_root
+
+ unknown = self.entity("creator", "未核实的号")
+ self.post(1, self.HER, owners=(self.account, unknown))
+ attempts = Attempts(attempts_root(self.root / "generated"))
+ with self.database.read_connection() as connection:
+ planned = [item.key for item in plan(connection, self.avatars, since_entity_id=0)]
+ stocked = [item.key for item in stock(connection, self.avatars, attempts, limit=10)]
+ for keys in (planned, stocked):
+ self.assertIn(followup_key("creator", self.account), keys)
+ self.assertNotIn(followup_key("creator", unknown), keys)
+ from peach.avatar_followup import run as avatar_run
+
+ key = followup_key("creator", unknown)
+ self.assertEqual(avatar_run(self.contract(), key, mock.Mock())["outcome"], NO_IDENTITY)
+ with self.database.read_connection() as connection:
+ current = fingerprint(connection, unknown)
+ self.assertFalse(attempts.settled(key, current))
+
+ def test_a_new_contact_sheet_queues_the_account_again(self):
+ from peach.avatar_followup import stock
+ from peach.followups import Attempts, attempts_root
+
+ attempts = Attempts(attempts_root(self.root / "generated"))
+ key = followup_key("creator", self.account)
+
+ def planned():
+ with self.database.read_connection() as connection:
+ return [item.key for item in stock(connection, self.avatars, attempts, limit=10)]
+
+ self.post(1, self.HER)
+ self.post(2, None)
+ self.run_followup()
+ self.assertEqual(planned(), [])
+ path = self.sheet(2, self.HER_AGAIN)
+ with self.database.write_transaction(notify=False) as connection:
+ connection.execute("UPDATE asset SET snapshot_path=? WHERE id=2", (str(path),))
+ self.assertEqual(planned(), [key])
+ self.assertEqual(self.run_followup()["outcome"], "已装上")
+
+
class ProcessLibraryTests(LedgerTestCase):
"""一整条链走通:刮削登记新女优 → 声明后继 → 派出 → 真的跑完。