Skip to content

armgit / peach

Public Imported from GitHub
0

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

fix(western): 西方头像比脸后才装,官方封面按批次可撤回

longmeidao5bfee502e0c5
diff --git a/docs/REUSE.md b/docs/REUSE.md
index 746534195..42269785d 100644
--- a/docs/REUSE.md
+++ b/docs/REUSE.md
@@ -10,17 +10,17 @@
Babepedia 主图库和 Vixen 网络公开 GraphQL 的字段核对 [Stash CommunityScrapers](https://github.com/stashapp/CommunityScrapers/tree/d0f75013e09a0469b70365fef3294ca915edcf8c) 的 Babepedia、vixenNetwork 采集器(AGPL-3.0;2026-10-07 获取的 revision)。该项目使用 Python,可经插件在 Windows 上运行;Cloudflare 限流和上游字段变化可能导致未取得。只参考公开协议和身份字段,不复制 AGPL 实现,不恢复已关闭的 Stash 适配器,也不引入依赖。HTTP、HTML、图像检查、内容缓存、头像安装和封面边车分别复用现有 `HttpxTransport`、BeautifulSoup 4.15.0、`avatar_provider`、`avatar_picker`、`cover_artwork`。
-真实只读试验取得 Angel Smalls、Christy White、Lena Anderson、Melody Marks、Sweet Sophia 的主图库;Babepedia 的 Blaire Ivory 档案明确列出别名 Lena Anderson。Tushy 2019-08-14《Cam To Me》、Vixen 2019-04-09《I Want It All》的官方封面均已取得。搜索还返回 Lena Paul 等人的作品;Peach 用厂牌、完整名字、发行日和唯一结果筛选,并对详情再核对。没有番号的官方封面按 `ASSET-ID-<id>` 保存,资产字段保持原值。头像保留主图库候选,已有头像不自动覆盖;官方完整出演名单参与合演保护,多人封面需要框选。采集入口 `harvest_western_artwork.py` 每轮至多 16 位,默认只预览,输出来源回执。
+真实只读试验取得 Angel Smalls、Christy White、Lena Anderson、Melody Marks、Sweet Sophia 的主图库;Babepedia 的 Blaire Ivory 档案明确列出别名 Lena Anderson。Tushy 2019-08-14《Cam To Me》、Vixen 2019-04-09《I Want It All》的官方封面均已取得。搜索还返回 Lena Paul 等人的作品;Peach 用厂牌、完整名字、发行日和唯一结果筛选,并对详情再核对。没有番号的官方封面按 `ASSET-ID-<id>` 保存,资产字段保持原值。头像保留主图库候选,已有头像不自动覆盖;官方完整出演名单参与合演保护,多人封面需要框选。采集入口 `harvest_western_artwork.py` 每轮至多 16 位,默认只预览,输出来源回执;封面边车记 `auto:western-artwork@<时间>`,由 `revert_auto_landing.py` 按批撤回。
## 实体身份与职业
公司资料复用 `entity.metadata_json`、HTTPX、官网公司概要表和定义列表与标识采集器。`company_profiles` 只有通用判据(概要标签、服务条款订立方原句),按字段保存出处、原文和批次,只填空;一页多张公司表时按法人名对实体名与别名选表,公司成立与品牌启动分列,集团与分工关系不由代码推导,只作候选。`harvest_company_profiles.py` 默认产复核 JSON,`--input --apply --backup --batch auto:company-profile@…` 按缓存页重放判据后落库,清单里的别名、链接与第三方页面不写。`revert_auto_landing.py` 可撤回同批公司字段及标识,无新增依赖。
-Babepedia 资料采集复用 `babepedia_page` 的主名与别名交叉核对、`performer_profiles` 的整行来源保护和 `performer_alias_followup.land` 的占用检查。英文艺名只在明确允许的来源中登记,JAV 后继保留自己的名字策略。真人账号与出演者共用资料表、别名分组与头像候选;保留账号角色及旧地址。主图可以补空头像,本人档案图库仅作候选,推荐人物排除,单图失败继续其余有限候选。`harvest_western_profiles.py` 每轮至多 16 位,计划、备份、回执与批次撤回齐备;既有资料和头像保留。真实只读复核取得 Ria Kurumi 等 16 份匹配档案,无新增依赖。
+Babepedia 资料采集复用 `babepedia_page` 的主名与别名交叉核对、`performer_profiles` 的整行来源保护和 `performer_alias_followup.land` 的占用检查。英文艺名只在明确允许的来源中登记,单个罗马字词只在它就是页面主名时登记,JAV 后继保留自己的名字策略。真人账号与出演者共用资料表、别名分组与头像候选;保留账号角色及旧地址,与已登记账号说法不一的链接只进回执。出演者主图经 `avatar_followup.match_gallery` 与单人作品封面比上脸才补空头像,账号与本人档案图库仅作候选,推荐人物排除,单图失败继续其余有限候选;候选表只认判词「命中」的档案地址。`harvest_western_profiles.py` 每轮至多 16 位,计划、备份、回执与批次撤回齐备;既有资料和头像保留。真实只读复核取得 Ria Kurumi 等 16 份匹配档案,无新增依赖。
身份分类复用 `entity`、来源关系、`field_owners`、SQLite 迁移与版本触发器。职业与账号角色使用独立多值断言,跨角色身份使用可撤回关系;[Schema.org Person](https://schema.org/Person) 的 `hasOccupation`、`sameAs` 与 [Role](https://schema.org/Role) 提供语义参照,2026-10-06 已核对官方文档。实现不复制外部解析器或新增依赖。目录推断和搜索命中只存候选,公开来源事实与用户复核分别保留状态。
-FC2 卖家名册复用 `sources/fc2.py` 的 `label`、`seller_url` 来源契约、`normalise_code_key`、`upsert_asset_entity`、职业断言和 SQLite 备份。`import_fc2_sellers.py` 读取已有作品快照,不发起采集;账号地址、来源作品号和馆藏作品号必须一致。同名不同账号、作品来源冲突保留在复核产物,既有身份和资料不覆盖。写入归属为 `script:fc2-seller@<批次>`,统一撤回入口 `revert_auto_landing.py` 同时处理账号链接、别名、外部编号、卖家断言及来源关系;有后续资料或引用的实体保留。导航复用 `BoardTabs`,动画作者保留 `creator` 身份与资料路由,通过艺人分类浏览。不新增依赖或外部解析器。
+FC2 卖家名册复用 `sources/fc2.py` 的 `label`、`seller_url` 来源契约、`normalise_code_key`、`upsert_asset_entity`、职业断言和 SQLite 备份。`import_fc2_sellers.py` 读取已有作品快照,不发起采集;账号地址、来源作品号和馆藏作品号必须一致。同名不同账号、作品来源冲突保留在复核产物,既有身份和资料不覆盖;计划按摄取同一判据把集合名归到已有账号,摄取不收的作品记跳过,回收站作品不挂卖家。写入归属为 `script:fc2-seller@<批次>`,统一撤回入口 `revert_auto_landing.py` 同时处理账号链接、别名、外部编号、卖家断言及来源关系;有后续资料或引用的实体保留。导航复用 `BoardTabs`,动画作者保留 `creator` 身份与资料路由,通过艺人分类浏览。不新增依赖或外部解析器。
账号归属复用 `review_decision`、`creator_collection_base`、`write_owned_fields` 和全库归属审计。明确拒绝的资产与账号组合在自动摄取时跳过;用户写入保留复核入口。网黄博主只命中可信个人、内容创作者或发布账号断言,未分类账号保留全部名册入口。`attach_avatar_availability` 集中处理资料页、索引、搜索与统计的作品头像:发布账号缺少本人或出演职业证据时不提供作品帧兜底,已安装图片独立保留。来源核查清单、逐关系回执和备份存于 `peach-data/review/`。
diff --git a/scripts/harvest_western_artwork.py b/scripts/harvest_western_artwork.py
index 171c7326b..d0192c8f1 100644
--- a/scripts/harvest_western_artwork.py
+++ b/scripts/harvest_western_artwork.py
@@ -1,38 +1,62 @@
-"""为指定的出演者保留 Babepedia 头像候选和精确匹配的官方作品封面。"""
+"""为指定的出演者保留 Babepedia 头像候选和精确匹配的官方作品封面。
+
+头像只在 Babepedia 主图与她单人作品封面比上脸时自动装,账号一律只留候选。
+封面边车记 `source` 与 `batch`,`revert_auto_landing.py --source auto:western-artwork` 按批撤回。
+"""
from __future__ import annotations
import argparse
import json
import sys
import time
+from datetime import datetime, timezone
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / 'src'))
-from peach import avatar_picker
-from peach.avatar_provider import (AvatarCandidateCache, MIN_LONG_SIDE, MIN_SHORT_SIDE,
- acceptable_avatar, install_entity_avatar)
+from peach import avatar_cover_face, avatar_picker
+from peach.avatar_provider import AvatarCandidateCache, install_entity_avatar
from peach.config import DATABASE_PATH, GENERATED_DIR, COVER_DIR, REVIEW_DIR
from peach.cover_artwork import install_cover
from peach.entities import resolve_entity_id
from peach.http import HttpxTransport
from peach.review_csv import read_rows
from peach.scripting import open_readonly
-from peach.western_artwork import SITES, artwork_key, babepedia_portraits, filename_date, official_scene
+from peach.western_artwork import (SITES, SOURCE, artwork_key, babepedia_portraits, face_matched_portrait,
+ filename_date, official_scene)
def profile_urls(connection, candidates: Path, ids: list[int]) -> dict[int, str]:
- """按当前实体身份解析候选表中的 Babepedia 资料地址。"""
+ """按当前实体身份解析候选表中判词为「命中」的 Babepedia 资料地址。"""
profiles = {}
for candidate in read_rows(candidates) if candidates.is_file() else ():
old_id = str(candidate.get('entity_id') or '')
- if old_id.isdigit() and candidate.get('profile_url'):
+ if old_id.isdigit() and candidate.get('profile_url') and candidate.get('verdict') == '命中':
resolved = resolve_entity_id(connection, int(old_id))
if resolved in ids:
profiles.setdefault(resolved, candidate['profile_url'])
return profiles
+def install_portrait(args, connection, avatar_root: Path, item: dict, fetched: list) -> None:
+ """出演者的 Babepedia 主图与她单人作品封面比上脸才装;账号只留候选。"""
+ if item['kind'] != 'performer':
+ item['avatar'] = '账号不自动装头像,只留候选'
+ return
+ from peach.avatar_face import FaceProbe
+ from peach.face_match import FaceMatcher
+
+ covers = avatar_cover_face.faces(connection, args.covers, item['id'], FaceProbe())
+ winner, evidence, reason = face_matched_portrait(fetched, covers, FaceMatcher())
+ if winner is None:
+ item['avatar'] = reason
+ return
+ install_entity_avatar(avatar_root, 'performer', item['id'], winner.body, winner.inspected.mime_type,
+ {**winner.origin, 'source_url': winner.origin['upstream_url'],
+ 'source_kind': 'gallery_face_matched', 'face_match': evidence})
+ item['installed'] = winner.inspected.sha256
+
+
def run(args) -> dict:
"""写入仅涉及可重建图片与来源记录,不改 ledger。"""
providers = args.generated / 'provider-cache' / 'performer-avatars'
@@ -56,6 +80,7 @@ def run(args) -> dict:
aliases = avatar_picker.name_chain(connection, entity_id)
try:
portraits = babepedia_portraits(http, name, aliases, profile_url=profiles.get(entity_id, ''))
+ fetched = []
for origin in portraits:
try:
cache = AvatarCandidateCache(providers / 'babepedia')
@@ -66,18 +91,16 @@ def run(args) -> dict:
inspected = avatar_picker.accept_image(body)
item['portraits'].append({**origin, 'sha256': inspected.sha256,
'width': inspected.width, 'height': inspected.height})
+ if origin.get('automatic_install'):
+ fetched.append((origin, body, inspected))
if args.apply:
avatar_picker.keep(providers, entity_id, body, origin)
- destination = avatar_root / f'{kind}-{entity_id}.img'
- if (origin.get('automatic_install', True) and not destination.exists()
- and acceptable_avatar(inspected, MIN_LONG_SIDE, MIN_SHORT_SIDE)):
- install_entity_avatar(avatar_root, kind, entity_id, body, inspected.mime_type,
- {**origin, 'source_url': origin['upstream_url']})
- item['installed'] = inspected.sha256
except Exception as error:
item['issues'].append({'source_url': origin['upstream_url'], 'error': str(error)})
finally:
time.sleep(args.delay)
+ if args.apply and fetched and not (avatar_root / f'{kind}-{entity_id}.img').exists():
+ install_portrait(args, connection, avatar_root, item, fetched)
except Exception as error:
item['issues'].append(str(error))
if args.portraits_only:
@@ -112,7 +135,8 @@ def run(args) -> dict:
else:
# 官方横版剧照不使用 JAV 双联封套判据。
install_cover(target, '', body, (inspected.width, inspected.height),
- evidence={**record, 'provider': 'western-official'})
+ evidence={**record, 'provider': 'western-official',
+ 'source': SOURCE, 'batch': args.batch})
record['installed'] = str(target)
except Exception as error:
record['issue'] = str(error)
@@ -136,6 +160,8 @@ def build_parser():
parser.add_argument('--delay', type=float, default=3)
parser.add_argument('--apply', action='store_true')
parser.add_argument('--portraits-only', action='store_true')
+ parser.add_argument('--batch', default=SOURCE + '@' + datetime.now(timezone.utc).strftime('%Y%m%dT%H%M%SZ'),
+ help='封面边车记的批次,revert_auto_landing.py 按它整批撤回')
return parser
@@ -143,4 +169,6 @@ if __name__ == '__main__':
args = build_parser().parse_args()
if args.delay < 1:
raise SystemExit('请求间隔至少 1 秒')
+ if not args.batch.startswith(SOURCE + '@'):
+ raise SystemExit(f'批次需要以 {SOURCE}@ 开头')
print(json.dumps(run(args), ensure_ascii=False))
diff --git a/scripts/revert_auto_landing.py b/scripts/revert_auto_landing.py
index 335cbd018..2b14867d2 100644
--- a/scripts/revert_auto_landing.py
+++ b/scripts/revert_auto_landing.py
@@ -29,6 +29,9 @@ id 或路径已被别的行占用时那一批拒绝撤回。登记时自动接
「想要」清单的入库对账记在 `want_item.acquired_source` 与 `acquired_batch`(批次号
`auto:want-acquired@<登记时刻>`)。撤回把那几条改回待找,查找计数原样留着。
+西方发行方的无番号作品封面(`ASSET-ID-<id>.jpg`)在 `.scraping.json` 边车里记 `source` 与 `batch`
+(`auto:western-artwork@<时间>`)。撤回删掉封面与同组边车,作品回到没有封面的样子。
+
revert_auto_landing.py --source auto:performer-alias
revert_auto_landing.py --source auto:performer-alias --batch auto:performer-alias@812
revert_auto_landing.py --source auto:performer-profile
@@ -38,6 +41,7 @@ id 或路径已被别的行占用时那一批拒绝撤回。登记时自动接
revert_auto_landing.py --source auto:metadata-tags
revert_auto_landing.py --source auto:vanished-reattach --batch auto:vanished-reattach@3
revert_auto_landing.py --source auto:want-acquired
+ revert_auto_landing.py --source auto:western-artwork --batch auto:western-artwork@20261008T000000Z
默认只列计划;`--apply` 必须同时给 `--backup`,删文件在账本行之后、同一次运行里完成。
"""
@@ -50,12 +54,14 @@ from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "src"))
-from peach import company_profiles, fc2_sellers, record_rehome, sample_images, wants # noqa: E402
-from peach.config import GENERATED_DIR # noqa: E402
+from peach import (company_profiles, fc2_sellers, jav_poster_crop, record_rehome, sample_images, # noqa: E402
+ wants, western_artwork)
+from peach.config import COVER_DIR, GENERATED_DIR # noqa: E402
from peach.metadata_auto_apply import UNION_TAGS_SOURCE # noqa: E402
from peach.scripting import add_ledger_write_args, open_for_write, verify_after_write # noqa: E402
SIDECARS = (".ct", ".provenance.json")
+COVER_SIDECARS = (".face.json", jav_poster_crop.SIDECAR_SUFFIX, ".scraping.json")
def matches(record: dict, source: str, batch: str) -> bool:
@@ -247,6 +253,7 @@ def build_parser() -> argparse.ArgumentParser:
help="要撤回的归属串,与写入时记的逐字相同")
parser.add_argument("--batch", default="", help="只撤这一批;不给就撤这个来源的全部")
parser.add_argument("--logo-root", type=Path, default=GENERATED_DIR / "logos")
+ parser.add_argument("--cover-root", type=Path, default=COVER_DIR)
return parser
@@ -258,6 +265,28 @@ def print_profiles(profiles: list[dict], companies: list[dict]) -> None:
print(f" - 公司资料 {company['entity']}: {','.join(company['fields'])}")
+def print_files(files: list[Path], covers: list[Path]) -> None:
+ """显示要删的标识文件与无番号作品封面。"""
+ for path in files:
+ print(f" - 标识 {path.name}")
+ for path in covers:
+ print(f" - 封面 {path.name}")
+
+
+def remove_files(files: list[Path], covers: list[Path]) -> int:
+ """删掉标识文件与作品封面,连同各自的同组边车;返回删掉的文件数。"""
+ targets = [target for path in files
+ for target in (path, *(path.with_name(path.name + suffix) for suffix in SIDECARS))]
+ targets += [target for path in covers
+ for target in (path, *(path.with_suffix(suffix) for suffix in COVER_SIDECARS))]
+ removed = 0
+ for target in targets:
+ if target.exists():
+ target.unlink()
+ removed += 1
+ return removed
+
+
def main(argv: list[str] | None = None) -> int:
args = build_parser().parse_args(argv)
connection = open_for_write(args)
@@ -271,6 +300,7 @@ def main(argv: list[str] | None = None) -> int:
memberships = planned_memberships(connection, args.source, args.batch)
makers = planned_makers(connection, args.source, args.batch)
files = planned_files(args.logo_root, args.source, args.batch)
+ covers = western_artwork.planned_covers(args.cover_root, args.source, args.batch)
samples = sample_images.planned_revert(connection, args.source, args.batch)
rejections = planned_rejections(connection, args.source, args.batch)
tags = planned_tags(connection, args.source, args.batch)
@@ -288,8 +318,7 @@ def main(argv: list[str] | None = None) -> int:
print(f" - 归属 {membership['entity'][:20]:<20} {membership['agency'][:30]} {membership['source']}")
for maker in makers:
print(f" - 片商 {maker['entity'][:20]:<20} {maker['maker'][:30]} {maker['source']}")
- for path in files:
- print(f" - 标识 {path.name}")
+ print_files(files, covers)
for sample in samples:
print(f" - 样张 {sample['code']:<20} {sample['count']} 张 {sample['source']}")
for rejection in rejections:
@@ -300,7 +329,7 @@ def main(argv: list[str] | None = None) -> int:
print(f" - 接回 {rehome['old_asset_id']:<8} → {rehome['new_asset_id']:<8} "
f"{rehome['name'][:40]} {rehome['batch']}")
print({"链接": len(links), "别名": len(aliases), "资料": len(profiles), "公司资料": len(companies), "卖家": len(sellers), "编号": len(refs),
- "归属": len(memberships), "片商": len(makers), "标识文件": len(files),
+ "归属": len(memberships), "片商": len(makers), "标识文件": len(files), "封面": len(covers),
"样张": sum(sample["count"] for sample in samples), "否决": len(rejections),
"标签": len(tags), "接回": len(rehomes), "想要入库": len(acquired)})
if not args.apply:
@@ -344,12 +373,7 @@ def main(argv: list[str] | None = None) -> int:
integrity, orphans = verify_after_write(connection)
finally:
connection.close()
- removed = 0
- for path in files:
- for target in (path, *(path.with_name(path.name + suffix) for suffix in SIDECARS)):
- if target.exists():
- target.unlink()
- removed += 1
+ removed = remove_files(files, covers)
print({"删除链接": len(links), "删除别名": len(aliases), "删除资料": len(profiles),
"删除编号": len(refs), "删除归属": len(memberships), "删除片商": len(makers),
"删除样张": removed_samples, "删除否决": len(rejections),
diff --git a/src/peach/western_artwork.py b/src/peach/western_artwork.py
index f39353416..9d538f939 100644
--- a/src/peach/western_artwork.py
+++ b/src/peach/western_artwork.py
@@ -15,6 +15,7 @@ from .user_agent import USER_AGENT
SITES = frozenset(('tushy', 'tushyraw', 'vixen', 'blacked', 'blackedraw',
'deeper', 'slayed', 'milfy', 'wifey'))
+SOURCE = 'auto:western-artwork'
PAGE_LIMIT = 4 * 1024 * 1024
TIMEOUT = 20
SEARCH_QUERY = '''query PeachSearch($query:String!,$site:Site!,$first:Int){
@@ -104,6 +105,43 @@ def babepedia_portraits(http: HttpTransport, name: str, aliases=(), *, profile_u
return portraits
+def face_matched_portrait(fetched: list, covers: list, matcher) -> tuple:
+ """Babepedia 图里哪一张是她:与她单人作品封面比上脸才算(ADR-0056),名字相同不算。
+
+ `fetched` 是 `[(origin, body, inspected)]`,主图在前;`covers` 是
+ `avatar_cover_face.faces` 截到的封面脸。没有封面参照、模型不可用或比不上时只留候选,
+ 返回 `(None, {}, 原因)`;比上时返回 `(Candidate, 比对证据, '')`。
+ """
+ from .avatar_followup import Candidate, match_gallery
+
+ found, candidates = [], {}
+ for origin, body, inspected in fetched:
+ choice = {'ref': origin['upstream_url'], 'label': 'Babepedia'}
+ found.append(choice)
+ candidates[choice['ref']] = Candidate(choice, body, origin, inspected)
+ if not covers:
+ return None, {}, '没有单人作品封面可比,只留候选'
+ result = match_gallery(found, covers, matcher, lambda choice: candidates.get(choice['ref']))
+ if result.winner is None or not result.evidence.get('covers'):
+ return None, {}, result.reason or '没有比上封面的图,只留候选'
+ return result.winner, result.evidence, ''
+
+
+def planned_covers(cover_root: Path, source: str, batch: str) -> list[Path]:
+ """边车写着这个来源与批次的无番号作品封面;撤回删掉封面与同组边车。"""
+ if source != SOURCE:
+ return []
+ found = []
+ for sidecar in sorted(Path(cover_root).glob('ASSET-ID-*.scraping.json')):
+ try:
+ record = json.loads(sidecar.read_text(encoding='utf8'))
+ except (OSError, ValueError):
+ continue
+ if isinstance(record, dict) and record.get('source') == source and (not batch or record.get('batch') == batch):
+ found.append(sidecar.with_name(sidecar.name.removesuffix('.scraping.json') + '.jpg'))
+ return found
+
+
def filename_date(name: str, site: str) -> str:
"""发行方前缀后的日期,限定 2000 年后的发行日期格式。"""
match = re.match(rf'^{re.escape(site)}[._ -](\d{{2}}|20\d{{2}})[._ -](\d{{2}})[._ -](\d{{2}})[._ -]',
diff --git a/tests/test_western_artwork.py b/tests/test_western_artwork.py
index e2f68d005..62b0a9e09 100644
--- a/tests/test_western_artwork.py
+++ b/tests/test_western_artwork.py
@@ -1,9 +1,13 @@
-"""西方官方图片的身份绑定、唯一作品匹配与无番号封面。"""
+"""西方官方图片的身份绑定、唯一作品匹配、头像比脸与按批撤回的无番号封面。"""
+import contextlib
import io
import json
import sqlite3
import tempfile
import unittest
+from contextlib import closing
+from types import SimpleNamespace
+from unittest import mock
from unittest.mock import Mock
from pathlib import Path
@@ -13,6 +17,8 @@ from peach import avatar_cover_face, avatar_picker, western_artwork as artwork
from peach.http import HttpResponse
from peach.web_catalog import attach_artwork_fields
from peach.web_state import WebContract
+from scripts import harvest_western_artwork, revert_auto_landing
+from tests.support.ledger import fresh_ledger
def node(name='Lena Anderson', released='2019-08-14T17:30:00Z', slug='cam-to-me'):
@@ -109,6 +115,95 @@ class WesternSourceTests(unittest.TestCase):
self.assertEqual(artwork.filename_date('tushy.19.02.31.lena.mp4', 'tushy'), '')
+def portrait(colour) -> tuple:
+ image = Image.new('RGB', (600, 800), colour)
+ buffer = io.BytesIO(); image.save(buffer, 'JPEG')
+ body = buffer.getvalue()
+ origin = {'upstream_url': f'https://www.babepedia.com/pics/{colour}.jpg', 'automatic_install': True}
+ return origin, body, avatar_picker.accept_image(body)
+
+
+class Matcher:
+ """按图中心的颜色给特征:红色是她,蓝色是别人,封面截图记作她。"""
+ unavailable = ''
+
+ def embedding(self, body):
+ if body == b'cover':
+ return [1.0, 0.0]
+ pixel = Image.open(io.BytesIO(body)).convert('RGB').getpixel((300, 400))
+ return [1.0, 0.0] if pixel[0] > pixel[2] else [0.0, 1.0]
+
+
+class WesternPortraitGateTests(unittest.TestCase):
+ def setUp(self):
+ patcher = mock.patch.object(avatar_cover_face, 'cut', return_value=(b'cover', {}))
+ patcher.start()
+ self.addCleanup(patcher.stop)
+ self.covers = [SimpleNamespace(code='', asset_id=1), SimpleNamespace(code='', asset_id=2)]
+
+ def test_the_portrait_that_matches_her_single_work_covers_is_chosen(self):
+ winner, evidence, reason = artwork.face_matched_portrait([portrait('blue'), portrait('red')],
+ self.covers, Matcher())
+ self.assertEqual(winner.origin['upstream_url'], 'https://www.babepedia.com/pics/red.jpg')
+ self.assertEqual([cover['asset_id'] for cover in evidence['covers']], [1, 2])
+ self.assertEqual(reason, '')
+
+ def test_without_covers_or_a_matching_face_nothing_is_installed(self):
+ self.assertEqual(artwork.face_matched_portrait([portrait('red')], [], Matcher())[0], None)
+ winner, evidence, reason = artwork.face_matched_portrait([portrait('blue')], self.covers, Matcher())
+ self.assertIsNone(winner)
+ self.assertEqual(evidence, {})
+ self.assertIn('比不出', reason)
+
+ def test_an_unavailable_model_installs_nothing(self):
+ matcher = Matcher()
+ matcher.unavailable = '模型未下载'
+ winner, _evidence, reason = artwork.face_matched_portrait([portrait('red')], self.covers, matcher)
+ self.assertIsNone(winner)
+ self.assertIn('模型未下载', reason)
+
+
+class WesternArtworkBatchTests(unittest.TestCase):
+ def setUp(self):
+ directory = tempfile.TemporaryDirectory()
+ self.addCleanup(directory.cleanup)
+ self.root = Path(directory.name).resolve()
+
+ def test_profile_addresses_come_only_from_confirmed_candidate_rows(self):
+ db = fresh_ledger(self.root)
+ with closing(sqlite3.connect(db)) as connection:
+ kept, unsure = (connection.execute(
+ "INSERT INTO entity(kind,canonical_name,normalized_name,created_at,updated_at) "
+ "VALUES('creator',?,?,'','')", (name, name.lower())).lastrowid for name in ('Kept', 'Unsure'))
+ connection.commit()
+ table = self.root / 'babepedia-candidates.csv'
+ table.write_text('entity_id,verdict,profile_url\n'
+ f'{kept},命中,https://www.babepedia.com/babe/Kept\n'
+ f'{unsure},需人工确认,https://www.babepedia.com/babe/Someone\n', encoding='utf-8')
+ self.assertEqual(harvest_western_artwork.profile_urls(connection, table, [kept, unsure]),
+ {kept: 'https://www.babepedia.com/babe/Kept'})
+
+ def test_revert_removes_one_batch_of_covers_with_their_sidecars(self):
+ covers = self.root / 'covers'
+ covers.mkdir()
+ for asset_id, record in ((1, {'source': artwork.SOURCE, 'batch': artwork.SOURCE + '@one'}),
+ (2, {'source': artwork.SOURCE, 'batch': artwork.SOURCE + '@two'}),
+ (3, {'provider': 'western-official'})):
+ (covers / f'ASSET-ID-{asset_id}.jpg').write_bytes(b'jpeg')
+ (covers / f'ASSET-ID-{asset_id}.face.json').write_text('{}', encoding='utf8')
+ (covers / f'ASSET-ID-{asset_id}.scraping.json').write_text(json.dumps(record), encoding='utf8')
+ self.assertEqual([path.name for path in artwork.planned_covers(covers, artwork.SOURCE, '')],
+ ['ASSET-ID-1.jpg', 'ASSET-ID-2.jpg'])
+ db = fresh_ledger(self.root)
+ with contextlib.redirect_stdout(io.StringIO()):
+ revert_auto_landing.main(['--db', str(db), '--apply', '--backup', str(self.root / 'backup.db'),
+ '--source', artwork.SOURCE, '--batch', artwork.SOURCE + '@one',
+ '--cover-root', str(covers), '--logo-root', str(self.root / 'logos')])
+ self.assertEqual(sorted(path.name for path in covers.iterdir()),
+ ['ASSET-ID-2.face.json', 'ASSET-ID-2.jpg', 'ASSET-ID-2.scraping.json',
+ 'ASSET-ID-3.face.json', 'ASSET-ID-3.jpg', 'ASSET-ID-3.scraping.json'])
+
+
class WesternLocalArtworkTests(unittest.TestCase):
def test_cover_projection_and_picker_use_an_asset_key_without_changing_code(self):
with tempfile.TemporaryDirectory() as tmp: