Skip to content

armgit / peach

Public Imported from GitHub
0

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

feat(scripts): 演示库画面改用人工复核过的图库人像

longmeidao80103557d81f
diff --git a/scripts/demo-portraits.json b/scripts/demo-portraits.json
new file mode 100644
index 000000000..01da565bf
--- /dev/null
+++ b/scripts/demo-portraits.json
@@ -0,0 +1,385 @@
+{
+ "note": "演示素材清单。逐张看过画面后钉死:不露点,画面可放进公开文档。图库按来源优先级排出的第一张答的是「先试哪张」,不是「哪张能见人」,所以这里不按顺序自动取,只认这份清单。",
+ "provider": "gfriends",
+ "reviewed": "2026-09-16",
+ "entries": [
+ {
+ "name": "宇野栞菜",
+ "key": "えりか",
+ "category": "1-Diaz",
+ "filename": "宇野栞菜.jpg",
+ "sha256": "bdeb94a7ec9c25a666a8dee3d37e7ae4e45cc9b6a5d4cb02ee0798b1b15fa827",
+ "width": 2880,
+ "height": 1800
+ },
+ {
+ "name": "涼宮琴音",
+ "key": "あおい",
+ "category": "1-Diaz",
+ "filename": "涼宮琴音.jpg",
+ "sha256": "5b8b2556184238e38ca83e22f8e5cbc0d0d81183c4114fbc828faa7909320c82",
+ "width": 2880,
+ "height": 1800
+ },
+ {
+ "name": "白浜果歩",
+ "key": "白浜果歩",
+ "category": "1-Diaz",
+ "filename": "白浜果歩.jpg",
+ "sha256": "a04e105f5df710d80739cafdf9249cc3afd5cbc9cc63fa618c9f34d71e36b7f0",
+ "width": 2880,
+ "height": 1800
+ },
+ {
+ "name": "石田佳蓮",
+ "key": "石田 佳蓮",
+ "category": "1-Diaz",
+ "filename": "石田 佳蓮.jpg",
+ "sha256": "b9a99c1580e35404f7c1fe33eafed9f108851ba352ab6585d5b1879df48d7476",
+ "width": 2880,
+ "height": 1800
+ },
+ {
+ "name": "篠倉珠生",
+ "key": "篠倉珠生",
+ "category": "1-Diaz",
+ "filename": "篠倉珠生.jpg",
+ "sha256": "99621b46d1d9648d069164cdf5429d8d947825b85e57a5b3ea8d89670ae67248",
+ "width": 2880,
+ "height": 1800
+ },
+ {
+ "name": "若月まりあ",
+ "key": "二ノ宮麗華",
+ "category": "1-Diaz",
+ "filename": "若月まりあ.jpg",
+ "sha256": "4849d190ab3a09fa7db78dbcda664cf041a71a9997e8acf8779ef32fa391030c",
+ "width": 2880,
+ "height": 1800
+ },
+ {
+ "name": "蒼山愛奈",
+ "key": "蒼山愛奈",
+ "category": "1-Diaz",
+ "filename": "蒼山愛奈.jpg",
+ "sha256": "d59b3e2a0fe69d90a025ba9a387335a59f4937d1db5751e15e813f19d2939042",
+ "width": 2880,
+ "height": 1800
+ },
+ {
+ "name": "長瀬麻美",
+ "key": "水谷彩也加",
+ "category": "1-Diaz",
+ "filename": "長瀬麻美.jpg",
+ "sha256": "360e6b945f6ae3b85e4007848b03a86b2ab8c6a35933c0d3fd76f5af21a7e716",
+ "width": 2880,
+ "height": 1800
+ },
+ {
+ "name": "浅野心愛",
+ "key": "浅野心愛",
+ "category": "1-FALENO",
+ "filename": "浅野心愛.jpg",
+ "sha256": "48fc44c56ee28c983065aac46cd763e5f4f35d2b88dd2d8ea5e0c0d33bddf59f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "浜辺やよい",
+ "key": "浜辺やよい",
+ "category": "1-FALENO",
+ "filename": "浜辺やよい.jpg",
+ "sha256": "e7de85b55ecdc7b5d813ae9022803b09f7adfd964cc72d7eb5cb36b60524cfee",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "澪奈あすみ",
+ "key": "澪奈あすみ",
+ "category": "1-FALENO",
+ "filename": "澪奈あすみ.jpg",
+ "sha256": "b7ee6d20301a56e6e85fbc30852032ed8e4e5e44fe3b7965a16290d0b7b2ab9b",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "瀧本くるみ",
+ "key": "瀧本くるみ",
+ "category": "1-FALENO",
+ "filename": "瀧本くるみ.jpg",
+ "sha256": "ef9d5aceb881d034d89672ecff2a5024b99933e5f748ec98b00c7ccd2348591f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "瀬戸ひなこ",
+ "key": "瀬戸ひなこ",
+ "category": "1-FALENO",
+ "filename": "瀬戸ひなこ.jpg",
+ "sha256": "c92102f1a274f75be41a19c8ce2a22ed34560d25363b7faad3e43eb91800a70f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "甘夏唯",
+ "key": "甘夏唯",
+ "category": "1-FALENO",
+ "filename": "甘夏唯.jpg",
+ "sha256": "e0061d620e555e837d45328ba55b49e96b3d0fd6f64a7445afd246816a385237",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "生田さな",
+ "key": "生田さな",
+ "category": "1-FALENO",
+ "filename": "生田さな.jpg",
+ "sha256": "e30c8f1d68769579632b576780713d3ebeff12218c4958b0bf7a4fb9f20bd764",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "生田みなみ",
+ "key": "生田みなみ",
+ "category": "1-FALENO",
+ "filename": "生田みなみ.jpg",
+ "sha256": "edfe42dacdb3f1cddeea3ab7dceb1870cc73042f594acc3b127d7497f2f1225f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "田中レモン",
+ "key": "田中レモン",
+ "category": "1-FALENO",
+ "filename": "田中レモン.jpg",
+ "sha256": "cc636011dffab76071e6ed779e158f642211badd2785e31a277284163cf798c6",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "田井虹TINY",
+ "key": "田井虹 TINY",
+ "category": "1-FALENO",
+ "filename": "田井虹 TINY.jpg",
+ "sha256": "852430de8feef47b00ffac3641aec02c0580de23d3486023e504ee11ba08a97a",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "由衣陽菜",
+ "key": "由衣陽菜",
+ "category": "1-FALENO",
+ "filename": "由衣陽菜.jpg",
+ "sha256": "27e404d944dd356f93290a2bde592a6aef0225e658c3aa017d293f9ae0a53049",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "白坂有以",
+ "key": "白坂有以",
+ "category": "1-FALENO",
+ "filename": "白坂有以.jpg",
+ "sha256": "3f1614c3b0923092b7847c5e3a962548f0bd39ba02be6f9c46bb9ea22ee93399",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "百崎きっか",
+ "key": "百崎きっか",
+ "category": "1-FALENO",
+ "filename": "百崎きっか.jpg",
+ "sha256": "1e4e0ec27685edbfb5c12a716d1b7459c40df7ff170e6a6c0e5635c92ad48f18",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "神代にな",
+ "key": "神代にな",
+ "category": "1-FALENO",
+ "filename": "神代にな.jpg",
+ "sha256": "a2c1d8b295c1f733bfbace7a6a84fd883bbe63962487b4867eef15b379251b49",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "神喜ミア",
+ "key": "神喜ミア",
+ "category": "1-FALENO",
+ "filename": "神喜ミア.jpg",
+ "sha256": "ccb252f9f86dd35ab564a17938904d1362c68f85f9c7ca5c0d694ed45dd0e5e6",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "神木サラ",
+ "key": "神木サラ",
+ "category": "1-FALENO",
+ "filename": "神木サラ.jpg",
+ "sha256": "60468196a7d26679b8c79ab4df48cdfc80a9a0c1fca8de2d8e53a87c0d50a14c",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "神木蘭",
+ "key": "神木蘭",
+ "category": "1-FALENO",
+ "filename": "神木蘭.jpg",
+ "sha256": "ea3b3e20bf6118fb102a3f5b17b5faee3e29ce0e1335a7ad84fda12412ff566f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "篠宮るい",
+ "key": "篠宮るい",
+ "category": "1-FALENO",
+ "filename": "篠宮るい.jpg",
+ "sha256": "de41ce82750c219ee9c9e71f655769d6233640b69d401ae3cf33931be93e987a",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "紺野るり",
+ "key": "紺野るり",
+ "category": "1-FALENO",
+ "filename": "紺野るり.jpg",
+ "sha256": "438cf86eca93af001ff301ad51cb0a2d4840eac6bcb86af7f5e08204a2cdae6f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "絵恋空",
+ "key": "絵恋空",
+ "category": "1-FALENO",
+ "filename": "絵恋空.jpg",
+ "sha256": "b07e82cb908535f0091891f98b13d311b6e47072652607b6997d6d849bb68617",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "絵麗奈",
+ "key": "絵麗奈",
+ "category": "1-FALENO",
+ "filename": "絵麗奈.jpg",
+ "sha256": "ba360ffe228e1d529d541544a5374b005408d2ce82a8ead1923fa0bf90faf2d3",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "綿貫こよみ",
+ "key": "綿貫こよみ",
+ "category": "1-FALENO",
+ "filename": "綿貫こよみ.jpg",
+ "sha256": "a07d5d26e6c7e13b21df7ed02394c972626a17c72f403a4a26329baed2799849",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "美乃すずめ",
+ "key": "美乃すずめ",
+ "category": "1-FALENO",
+ "filename": "美乃すずめ.jpg",
+ "sha256": "cdba7dae1c812be1386d1e8460b2dd05bb1504841caa5b7a17a293336f034063",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "美咲そのか",
+ "key": "美咲そのか",
+ "category": "1-FALENO",
+ "filename": "美咲そのか.jpg",
+ "sha256": "3c9ecfe032f8a5a0e43849fe8d412701cef5b4b40a115b7afed699b70434dc23",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "臼井リカ",
+ "key": "臼井リカ",
+ "category": "1-FALENO",
+ "filename": "臼井リカ.jpg",
+ "sha256": "d09a49b9f443836d3a9090308336f5d787c1a6ee453519a295855c1a2e62c207",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "茉城まみ",
+ "key": "茉城まみ",
+ "category": "1-FALENO",
+ "filename": "茉城まみ.jpg",
+ "sha256": "bff969443186f73038be12dd21ecb0ad9e9fe9a01bf8aab3d56a452a0c93cf30",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "菜月ひかる",
+ "key": "菜月ひかる",
+ "category": "1-FALENO",
+ "filename": "菜月ひかる.jpg",
+ "sha256": "b27a57abcd130e1dd58d5067d7ee3ccdc159f7829688f872801d7ddbc0a9a693",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "藤井蘭々",
+ "key": "藤井蘭々",
+ "category": "1-FALENO",
+ "filename": "藤井蘭々.jpg",
+ "sha256": "d2278f159af8f0e898913bc8c8b175a1b1f219ddc01e22c8454fc9b52855df83",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "逢月ひまり",
+ "key": "逢月ひまり",
+ "category": "1-FALENO",
+ "filename": "逢月ひまり.jpg",
+ "sha256": "53eae493e020d1d8ef165514d59bcef5ad44e53684656ebf491f8452280613e2",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "降矢あすか",
+ "key": "降矢あすか",
+ "category": "1-FALENO",
+ "filename": "降矢あすか.jpg",
+ "sha256": "f3031d0777d8b4aeedc5c1f4ac661acabcfbbe2c77f2f2acd268b57a7299b10f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "雛乃ゆな",
+ "key": "雛乃ゆな",
+ "category": "1-FALENO",
+ "filename": "雛乃ゆな.jpg",
+ "sha256": "4cd91e6c4a5aa791ec2433ace57a40f02d9a9628ac4a4ec037eb1375826e40a6",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "青嶋なづき",
+ "key": "青嶋なづき",
+ "category": "1-FALENO",
+ "filename": "青嶋なづき.jpg",
+ "sha256": "ad27a79ac6d0e4b7f5e5ca90e5f777356b8f9c4bce5842587d86140b1cc5e19f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "高嶋めいみ",
+ "key": "高嶋めいみ",
+ "category": "1-FALENO",
+ "filename": "高嶋めいみ.jpg",
+ "sha256": "70a80d1afcb5e6c37909a4b8517f05eb89a937a0b581281e4e79b23d9b5f536f",
+ "width": 1500,
+ "height": 2125
+ },
+ {
+ "name": "黒澤ななみ",
+ "key": "黒澤ななみ",
+ "category": "1-FALENO",
+ "filename": "黒澤ななみ.jpg",
+ "sha256": "5b564d9abd7a7c1b4209123dacc9fefb2ff5d8c52e042795d23f683957a7ba5c",
+ "width": 1500,
+ "height": 2125
+ }
+ ]
+}
diff --git a/scripts/demo_dataset.py b/scripts/demo_dataset.py
index 6dd1841be..47f09b4d6 100644
--- a/scripts/demo_dataset.py
+++ b/scripts/demo_dataset.py
@@ -1,9 +1,17 @@
#!/usr/bin/env python3
-"""生成一套 SFW 合成演示媒体库,供截图、教程与性能基准使用。
+"""生成一套 SFW 演示媒体库,供截图、教程与性能基准使用。
-演示素材不取自真实馆藏:画面是 FFmpeg lavfi 的渐变、测试图与分形,海报是 Pillow 画的
-几何图,作品、厂牌、系列、出演者和标签全部虚构。词表不与 `catalog_rules` 里的成人
-词表相交,由 `tests/test_demo_dataset.py` 把守。
+演示素材不取自真实馆藏。画面有两种来源,由 `--art` 选:
+
+- `portrait`(默认):人像取自 Gfriends 图库里一份人工逐张看过的清单
+ (`scripts/demo-portraits.json`),封面、头像与播放画面都由这张人像排版而成,
+ 出演者用清单里的规范艺名。界面因此有真实馆藏的样子。
+- `synthetic`:画面是 FFmpeg lavfi 的渐变、测试图与分形,海报是 Pillow 画的几何图,
+ 出演者也是虚构名。不联网,规模基准与测试用它。
+
+两种模式下作品、厂牌、系列和标签一律虚构,不与 `catalog_rules` 的成人词表相交,由
+`tests/test_demo_dataset.py` 把守——真实艺名配虚构作品,演示素材因此不会断言
+「某人演过某片」这种它没有资格断言的事。
生成的目录能直接被 `peach scan` 与 `peach process` 消费:
@@ -18,7 +26,8 @@
`scripts/apply_metadata_tags.py --source local_nfo` 按字段落地。
本脚本只写目标目录,不碰任何账本;`--video stub` 用占位字节代替真实编码,
-给几十万条的规模测试用。
+给几十万条的规模测试用。`portrait` 模式取回的人像缓存在输出目录的 `.portrait-cache/`,
+重跑不重新联网。
"""
from __future__ import annotations
@@ -37,11 +46,18 @@ PROJECT_ROOT = Path(__file__).resolve().parent.parent
SRC_DIR = PROJECT_ROOT / "src"
if str(SRC_DIR) not in sys.path:
sys.path.insert(0, str(SRC_DIR))
+# 测试按文件路径加载本脚本,那条路径下 `scripts/` 不一定在 sys.path 上。
+SCRIPTS_DIR = Path(__file__).resolve().parent
+if str(SCRIPTS_DIR) not in sys.path:
+ sys.path.insert(0, str(SCRIPTS_DIR))
+import demo_portraits # noqa: E402
from peach.config import FFMPEG_DIR # noqa: E402
from peach.ffmpeg import FFmpegResolver # noqa: E402
MANIFEST_NAME = "demo-manifest.json"
+#: 取回的人像放在输出目录旁边,重跑不再联网。
+PORTRAIT_CACHE = ".portrait-cache"
#: 厂牌:番号前缀与显示名。前缀满足 `catalog_rules` 的厂牌番号形状(2 到 8 个字母加连字符)。
STUDIOS: tuple[tuple[str, str], ...] = (
@@ -52,7 +68,8 @@ STUDIOS: tuple[tuple[str, str], ...] = (
("SEAS", "四季纪录"),
)
SERIES: tuple[str, ...] = ("城市漫步", "慢生活厨房", "山野四季", "手作日常", "夜景延时")
-PERFORMERS: tuple[str, ...] = (
+#: `synthetic` 模式的出演者。`portrait` 模式改用清单里的规范艺名,见 `performer_names`。
+SYNTHETIC_PERFORMERS: tuple[str, ...] = (
"林晚晴", "顾清和", "苏念安", "陈知夏", "周见山", "何以宁", "白露", "江小满",
)
CREATORS: tuple[str, ...] = ("山间小屋", "城市步行者", "厨房观察员")
@@ -126,13 +143,17 @@ class DemoItem:
nfo: str = ""
poster: str = ""
gallery: list[str] = field(default_factory=list)
+ #: `portrait` 模式下这条作品的画面用清单里的哪一位;`synthetic` 模式为空。
+ portrait: str = ""
def build_parser() -> argparse.ArgumentParser:
- parser = argparse.ArgumentParser(description="生成 SFW 合成演示媒体库")
+ parser = argparse.ArgumentParser(description="生成 SFW 演示媒体库")
parser.add_argument("--output", type=Path, required=True, help="生成到这个目录(不存在则创建)")
parser.add_argument("--count", type=int, default=24, help="作品数量")
parser.add_argument("--seed", type=int, default=7, help="随机种子;同一种子生成同一套内容")
+ parser.add_argument("--art", choices=("portrait", "synthetic"), default="portrait",
+ help="portrait 按清单取人像排版;synthetic 用几何图与 lavfi 画面,不联网")
parser.add_argument("--video", choices=("ffmpeg", "stub"), default="ffmpeg",
help="ffmpeg 真实编码短片;stub 只写占位字节,给规模测试用")
parser.add_argument("--duration", type=int, default=8, help="每条短片的秒数(ffmpeg 模式)")
@@ -140,11 +161,34 @@ def build_parser() -> argparse.ArgumentParser:
return parser
-def plan_items(count: int, seed: int, duration: int) -> list[DemoItem]:
- """按种子排出全部作品的资料,不碰文件系统。"""
+def assign_portraits(count: int, rng: random.Random,
+ portraits: list) -> list:
+ """给每条作品配一位。清单用尽就从头再来,配到谁由种子定。
+
+ 竖版与横版分开轮转:竖屏作品配竖版人像,横屏配横版,画面才不用靠裁切硬凑。
+ 清单里横版只有八张,横屏作品比它多得多,所以横版会重复出现——重复的是画面,
+ 卡片上的番号与标题各不相同,看的人不会以为是同一条作品。
+ """
+ tall = [p for p in portraits if not p.landscape]
+ wide = [p for p in portraits if p.landscape] or tall
+ rng.shuffle(tall)
+ rng.shuffle(wide)
+ return [tall, wide]
+
+
+def plan_items(count: int, seed: int, duration: int, *,
+ performers: tuple[str, ...] = SYNTHETIC_PERFORMERS,
+ portraits: list | None = None) -> list[DemoItem]:
+ """按种子排出全部作品的资料,不碰文件系统。
+
+ 给了 `portraits` 就按人像清单配出演者:卡片上的名字和封面上的脸必须是同一个人,
+ 否则细看就穿帮。
+ """
if count < 1:
raise ValueError("--count 至少为 1")
rng = random.Random(seed)
+ tall, wide = assign_portraits(count, rng, portraits) if portraits else ([], [])
+ cursor = {"竖屏": 0, "横屏": 0}
coded = max(1, round(count * 0.7))
bare = 1 if count >= 6 else 0
creator_made = max(0, count - coded - bare)
@@ -161,8 +205,14 @@ def plan_items(count: int, seed: int, duration: int) -> list[DemoItem]:
source_name, _ = VISUAL_SOURCES[rng.randrange(len(VISUAL_SOURCES))]
tags = [orientation, rng.choice(("1080P", "4K", "60fps"))]
tags += rng.sample(CONTENT_TAGS, k=2)
+ pool = tall if orientation == "竖屏" else wide
+ chosen = None
+ if pool:
+ chosen = pool[cursor[orientation] % len(pool)]
+ cursor[orientation] += 1
base = dict(title=title, original_title=original, orientation=orientation,
- duration=max(2, duration), visual_source=source_name, tags=tags)
+ duration=max(2, duration), visual_source=source_name, tags=tags,
+ portrait=chosen.name if chosen else "")
if index < coded:
prefix, studio = STUDIOS[index % len(STUDIOS)]
code = f"{prefix}-{index + 1:03d}"
@@ -172,7 +222,9 @@ def plan_items(count: int, seed: int, duration: int) -> list[DemoItem]:
kind="coded", path=f"{code}/{code}.mp4", code=code, studio=studio,
series=rng.choice(SERIES),
release_date=f"{rng.choice((2025, 2026))}-{rng.randint(1, 12):02d}-{rng.randint(1, 28):02d}",
- performers=rng.sample(PERFORMERS, k=rng.choice((1, 1, 2))),
+ # 有人像就以画面上那位为准,封面的脸和卡片的名字必须对得上。
+ performers=([chosen.name] if chosen
+ else rng.sample(performers, k=rng.choice((1, 1, 2)))),
nfo=f"{code}/{code}.nfo", poster=f"{code}/{code}-poster.jpg", gallery=gallery, **base))
elif index < coded + creator_made:
creator = CREATORS[index % len(CREATORS)]
@@ -255,31 +307,97 @@ def write_video(ffmpeg: str | None, item: DemoItem, destination: Path, seed: int
raise RuntimeError(f"ffmpeg 生成 {destination.name} 失败:{result.stderr.strip()[:300]}")
+class PortraitArt:
+ """人像模式下的画面产出:取图、画封面、渲染播放画面。
+
+ 取回的人像和渲染好的底图都按「一位一张」缓存——一套库里同一位常出现好几次,
+ 每次重新取图重新渲染,二十四条作品要多花十几倍时间。
+ """
+
+ def __init__(self, portraits: list, cache_dir: Path, fetch) -> None:
+ self.by_name = {portrait.name: portrait for portrait in portraits}
+ self.cache_dir = cache_dir
+ self.fetch = fetch
+ self.sources: dict[str, Path] = {}
+ self.frames: dict[tuple[str, str], Path] = {}
+
+ def source(self, item: DemoItem) -> Path:
+ if item.portrait not in self.sources:
+ self.sources[item.portrait] = self.fetch(self.by_name[item.portrait],
+ self.cache_dir)
+ return self.sources[item.portrait]
+
+ def cover(self, item: DemoItem, destination: Path) -> None:
+ # 创作者型没有番号,那一行留空让标题上移;底行落到创作者名上。
+ demo_portraits.draw_cover(
+ self.source(item), destination, code=item.code, title=item.title,
+ performer=item.portrait, studio=item.studio or item.creator or "未署名",
+ year=(item.release_date[:4] or "2026"), orientation=item.orientation)
+
+ def video(self, item: DemoItem, destination: Path, ffmpeg: str) -> None:
+ key = (item.portrait, item.orientation)
+ if key not in self.frames:
+ base = self.cache_dir / f"frame-{item.orientation}-{len(self.frames):03d}.png"
+ demo_portraits.draw_frame(self.source(item), base, item.orientation)
+ self.frames[key] = base
+ demo_portraits.render_video(ffmpeg, self.frames[key], destination,
+ duration=item.duration, orientation=item.orientation)
+
+
+def resolve_portraits(art: str, portraits: list | None) -> list | None:
+ """定下这一趟用哪套人像。`synthetic` 返回 None,走几何图那条路。"""
+ if art != "portrait":
+ return None
+ if portraits is None:
+ portraits = demo_portraits.load_manifest()
+ if not portraits:
+ raise RuntimeError("人像清单是空的;修好 scripts/demo-portraits.json,或改用 --art synthetic")
+ return portraits
+
+
def generate(output: Path, *, count: int, seed: int, video: str, duration: int,
- ffmpeg: str | None = None, report=lambda line: None) -> list[DemoItem]:
- """把整套演示库写进 `output`,返回作品清单(同时落成 `demo-manifest.json`)。"""
+ ffmpeg: str | None = None, art: str = "synthetic",
+ portraits: list | None = None,
+ fetch=demo_portraits.fetch, report=lambda line: None) -> list[DemoItem]:
+ """把整套演示库写进 `output`,返回作品清单(同时落成 `demo-manifest.json`)。
+
+ `art="portrait"` 时按清单取人像;`portraits` 与 `fetch` 可注入,测试因此不必联网。
+ """
output = output.resolve()
output.mkdir(parents=True, exist_ok=True)
if video == "ffmpeg" and ffmpeg is None:
raise RuntimeError("需要 ffmpeg 才能编码短片;装好 ffmpeg,或改用 --video stub")
- items = plan_items(count, seed, duration)
+ using = resolve_portraits(art, portraits)
+ items = plan_items(count, seed, duration,
+ performers=(tuple(p.name for p in using) if using
+ else SYNTHETIC_PERFORMERS),
+ portraits=using)
rng = random.Random(seed ^ 0x5EED)
# 规模测试里几十万张图逐张画太慢:占位模式下每种扩展名只画第一张,其余复制。
templates: dict[str, Path] = {}
+ artist = PortraitArt(using, output / PORTRAIT_CACHE, fetch) if using else None
def picture(destination: Path) -> None:
template = templates.get(destination.suffix.lower())
- if video == "stub" and template is not None:
+ # 模板复用只给合成画面:人像模式下复制第一张,整套库的封面就成了同一个人,
+ # 而每张卡片上的出演者各不相同——那正是这套素材要避免的穿帮。
+ if video == "stub" and template is not None and artist is None:
destination.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(template, destination)
return
- draw_poster(destination, item, rng)
+ if artist and item.portrait:
+ artist.cover(item, destination)
+ else:
+ draw_poster(destination, item, rng)
templates.setdefault(destination.suffix.lower(), destination)
started = time.time()
for index, item in enumerate(items, 1):
target = output / item.path
- write_video(ffmpeg if video == "ffmpeg" else None, item, target, seed + index)
+ if artist and item.portrait and video == "ffmpeg":
+ artist.video(item, target, ffmpeg)
+ else:
+ write_video(ffmpeg if video == "ffmpeg" else None, item, target, seed + index)
if item.nfo:
(output / item.nfo).write_text(render_nfo(item), encoding="utf-8")
if item.poster:
@@ -288,7 +406,8 @@ def generate(output: Path, *, count: int, seed: int, video: str, duration: int,
picture(output / photo)
if index % 10 == 0 or index == len(items):
report(f" {time.time() - started:5.0f}s {index}/{len(items)}")
- manifest = dict(seed=seed, count=count, video=video, generated_at=time.strftime("%Y-%m-%d %H:%M:%S"),
+ manifest = dict(seed=seed, count=count, video=video, art=art,
+ generated_at=time.strftime("%Y-%m-%d %H:%M:%S"),
items=[asdict(item) for item in items])
(output / MANIFEST_NAME).write_text(json.dumps(manifest, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
return items
@@ -326,12 +445,16 @@ def main(argv: list[str] | None = None) -> int:
ffmpeg = str(choice.path) if choice else None
try:
items = generate(args.output, count=args.count, seed=args.seed, video=args.video,
- duration=args.duration, ffmpeg=ffmpeg, report=lambda line: print(line, flush=True))
- except (RuntimeError, ValueError) as error:
+ duration=args.duration, ffmpeg=ffmpeg, art=args.art,
+ report=lambda line: print(line, flush=True))
+ except (RuntimeError, ValueError, OSError) as error:
print(f"✗ {error}")
return 2
kinds = {kind: sum(1 for item in items if item.kind == kind) for kind in ("coded", "creator", "bare")}
print(f"✓ 生成 {len(items)} 条:番号型 {kinds['coded']}、创作者型 {kinds['creator']}、裸文件 {kinds['bare']}")
+ faces = {item.portrait for item in items if item.portrait}
+ if faces:
+ print(f" 画面用了清单里的 {len(faces)} 位;人像缓存在 {args.output.resolve() / PORTRAIT_CACHE}")
print(next_steps(args.output))
return 0
diff --git a/scripts/demo_portraits.py b/scripts/demo_portraits.py
new file mode 100644
index 000000000..ce5325771
--- /dev/null
+++ b/scripts/demo_portraits.py
@@ -0,0 +1,259 @@
+"""演示库的人像素材:按钉死的清单取图,再排成封面、头像与播放画面。
+
+图片字节不进仓库(ADR-0026),进仓库的只有 `demo-portraits.json` 这份清单——去哪取、
+取到的该是什么哈希。生成器运行时按清单取一次,缓存在输出目录旁边。
+
+**清单是人工逐张看过后钉死的,不按图库自己的顺序自动取。** 图库把目录前缀当来源优先级
+排序,排第一的答的是「先试哪一张」,不是「哪一张能放进公开文档」:实测排在前面的大图
+多是片商宣传素材,内衣、泳装乃至露点都在里面。自动取必然翻车,所以这里只认清单。
+"""
+from __future__ import annotations
+
+import hashlib
+import json
+import subprocess
+import urllib.parse
+import urllib.request
+from dataclasses import dataclass
+from pathlib import Path
+
+MANIFEST_PATH = Path(__file__).resolve().parent / "demo-portraits.json"
+GFRIENDS_RAW = "https://raw.githubusercontent.com/gfriends/gfriends/master/Content/"
+#: 单张图的上限。清单里最大的一张 2880x1800 约 2.1 MB,留一倍余量;越界说明取错了东西。
+MAX_IMAGE_BYTES = 4 * 1024 * 1024
+
+COVER_LANDSCAPE = (800, 538)
+COVER_PORTRAIT = (600, 900)
+AVATAR_SIDE = 480
+FRAME_LANDSCAPE = (1280, 720)
+FRAME_PORTRAIT = (720, 1280)
+
+#: 封面与画面上的文字要落到 CJK 字形上。按平台找一份,找不到就不写字——
+#: 缺字体的机器上宁可出一张没有标题的封面,也不要满屏豆腐块。
+FONT_CANDIDATES = (
+ "C:/Windows/Fonts/msyh.ttc",
+ "C:/Windows/Fonts/simhei.ttf",
+ "/System/Library/Fonts/PingFang.ttc",
+ "/System/Library/Fonts/Hiragino Sans GB.ttc",
+ "/usr/share/fonts/opentype/noto/NotoSansCJK-Regular.ttc",
+ "/usr/share/fonts/truetype/noto/NotoSansCJK-Regular.ttc",
+)
+
+
+@dataclass(frozen=True)
+class Portrait:
+ """清单里的一条:去哪取、取到的该是什么。"""
+
+ name: str
+ key: str
+ category: str
+ filename: str
+ sha256: str
+ width: int
+ height: int
+
+ @property
+ def url(self) -> str:
+ return (GFRIENDS_RAW + urllib.parse.quote(self.category)
+ + "/" + urllib.parse.quote(self.filename))
+
+ @property
+ def cache_name(self) -> str:
+ """缓存文件名带哈希前缀:清单换了图,旧缓存不会被当成新的。"""
+ return f"{self.sha256[:16]}-{self.category}.jpg"
+
+ @property
+ def landscape(self) -> bool:
+ return self.width > self.height
+
+
+def load_manifest(path: Path | None = None) -> list[Portrait]:
+ """读清单。顺序就是清单里的顺序,按种子取用由调用方决定。"""
+ document = json.loads((path or MANIFEST_PATH).read_text(encoding="utf-8"))
+ return [Portrait(**entry) for entry in document["entries"]]
+
+
+def fetch(portrait: Portrait, cache_dir: Path, *, opener=urllib.request.urlopen) -> Path:
+ """取一张图到缓存,校验哈希。缓存命中就不再联网。
+
+ 哈希不符是硬错误,不是可以将就的降级:清单的全部意义就是「取到的是我看过的那张」,
+ 校验放过去等于回到自动取图。
+ """
+ cache_dir.mkdir(parents=True, exist_ok=True)
+ target = cache_dir / portrait.cache_name
+ if target.is_file() and hashlib.sha256(target.read_bytes()).hexdigest() == portrait.sha256:
+ return target
+ request = urllib.request.Request(portrait.url, headers={"User-Agent": "peach-demo-dataset"})
+ with opener(request, timeout=60) as response:
+ body = response.read(MAX_IMAGE_BYTES + 1)
+ if len(body) > MAX_IMAGE_BYTES:
+ raise RuntimeError(f"{portrait.name} 的图超过 {MAX_IMAGE_BYTES} 字节,取错了东西")
+ digest = hashlib.sha256(body).hexdigest()
+ if digest != portrait.sha256:
+ raise RuntimeError(
+ f"{portrait.name} 的图与清单对不上:清单 {portrait.sha256[:16]},取到 {digest[:16]}。"
+ "图库换了这一张,重新人工看过再更新清单。")
+ target.write_bytes(body)
+ return target
+
+
+def load_font(size: int):
+ from PIL import ImageFont
+
+ for candidate in FONT_CANDIDATES:
+ path = Path(candidate)
+ if path.is_file():
+ try:
+ return ImageFont.truetype(str(path), size)
+ except OSError:
+ continue
+ return None
+
+
+def _ellipsize(draw, text: str, font, room: int) -> str:
+ """放不下就截断加省略号。长标题横着写出画框比截断难看得多。"""
+ if draw.textlength(text, font=font) <= room:
+ return text
+ trimmed = text
+ while trimmed and draw.textlength(trimmed + "…", font=font) > room:
+ trimmed = trimmed[:-1]
+ return (trimmed + "…") if trimmed else ""
+
+
+def _cover_box(image, size: tuple[int, int], anchor: float = 0.15):
+ """放大裁切填满画框,取景偏上以保住脸。"""
+ from PIL import Image
+
+ scale = max(size[0] / image.width, size[1] / image.height)
+ big = image.resize((round(image.width * scale), round(image.height * scale)),
+ Image.LANCZOS)
+ left = max(0, (big.width - size[0]) // 2)
+ top = max(0, min(int((big.height - size[1]) * anchor), big.height - size[1]))
+ return big.crop((left, top, left + size[0], top + size[1]))
+
+
+def draw_cover(source: Path, destination: Path, *, code: str, title: str,
+ performer: str, studio: str, year: str, orientation: str) -> None:
+ """封面:人像占一侧,另一侧排番号、标题与出演者。
+
+ 横屏作品用横版封面,这也是番号作品封面的实际形状;竖屏作品用竖版,文字压在底部。
+ 人像不拉伸、不靠模糊背景撑满——那两种做法出来都是「头像撑成海报」的样子。
+ """
+ from PIL import Image, ImageDraw
+
+ image = Image.open(source).convert("RGB")
+ # 四行文字:番号、标题、出演者、年份与厂牌。字号与行距一起定,逐行累加落位,
+ # 不按固定偏移量硬写——竖版的文字块比横版矮,写死偏移会溢出画面底边。
+ rows = [row for row in ((code, 26, "#8a919c", 0), (title, 42, "#f3f5f8", 14),
+ (performer, 24, "#c5cad1", 18),
+ (f"{year} · {studio}", 21, "#8a919c", 26)) if row[0]]
+ fonts = [load_font(size) for _, size, _, _ in rows]
+ block = sum(size + lead for (_, size, _, lead) in rows)
+
+ if orientation == "竖屏":
+ canvas = _cover_box(image, COVER_PORTRAIT).convert("RGB")
+ width, height = COVER_PORTRAIT
+ # 上面一段做渐变过渡,文字全部落在下面的实心段——纯渐变带的顶部太淡,
+ # 第一行番号压在画面亮部时基本看不见。
+ fade, solid = 72, block + 56
+ overlay = Image.new("RGBA", (width, fade + solid), (10, 11, 14, 220))
+ painter = ImageDraw.Draw(overlay)
+ for row in range(fade):
+ painter.line([(0, row), (width, row)],
+ fill=(10, 11, 14, int(220 * (row / fade) ** 1.2)))
+ canvas.paste(overlay, (0, height - fade - solid), overlay)
+ left, cursor = 34, height - solid + 24
+ else:
+ canvas = Image.new("RGB", COVER_LANDSCAPE, "#14161a")
+ panel = round(COVER_LANDSCAPE[0] * 0.44)
+ canvas.paste(_cover_box(image, (panel, COVER_LANDSCAPE[1]), anchor=0.12), (0, 0))
+ left = panel + 44
+ cursor = (COVER_LANDSCAPE[1] - block) // 2
+
+ draw = ImageDraw.Draw(canvas, "RGBA")
+ if fonts[0] is None:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ canvas.save(destination,
+ format="PNG" if destination.suffix.lower() == ".png" else "JPEG",
+ quality=90)
+ return
+ room = canvas.width - left - 30
+ for (text, size, colour, lead), font in zip(rows, fonts):
+ cursor += lead
+ draw.text((left, cursor), _ellipsize(draw, text, font, room), font=font, fill=colour)
+ cursor += size
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ canvas.save(destination, format="PNG" if destination.suffix.lower() == ".png" else "JPEG",
+ quality=90)
+
+
+def draw_avatar(source: Path, destination: Path) -> None:
+ """头像:按短边取正方形,偏上取景。"""
+ from PIL import Image
+
+ image = Image.open(source).convert("RGB")
+ side = min(image.width, image.height)
+ left = (image.width - side) // 2
+ top = int((image.height - side) * 0.12)
+ square = image.crop((left, top, left + side, top + side))
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ square.resize((AVATAR_SIDE, AVATAR_SIDE), Image.LANCZOS).save(destination, quality=90)
+
+
+#: 裁切填满能接受的形状差距。人像与画面同朝向时落在这个区间内,直接铺满;
+#: 差得太远(竖版人像塞进横画面)再退回居中加模糊背景,否则会裁得只剩一条。
+FILL_RATIO_RANGE = (0.6, 1.7)
+
+
+def draw_frame(source: Path, destination: Path, orientation: str) -> None:
+ """播放画面的底图。
+
+ 人像与画面同朝向就裁切铺满——真实视频的画面本来就是满的,中间一块人像配一圈
+ 模糊背景,一看就是拿静态图凑的。朝向对不上才退回居中加模糊背景。
+
+ 按两倍渲染——缓推是在这张底图上放大的,原生分辨率推起来会抖。
+ """
+ from PIL import Image, ImageFilter
+
+ size = FRAME_PORTRAIT if orientation == "竖屏" else FRAME_LANDSCAPE
+ image = Image.open(source).convert("RGB")
+ fit = (image.width / image.height) / (size[0] / size[1])
+ if FILL_RATIO_RANGE[0] <= fit <= FILL_RATIO_RANGE[1]:
+ frame = _cover_box(image, size, anchor=0.22)
+ else:
+ frame = _cover_box(image, size, anchor=0.5)
+ frame = frame.filter(ImageFilter.GaussianBlur(size[0] // 46)).point(
+ lambda v: int(v * 0.5))
+ front = image.copy()
+ front.thumbnail((size[0], size[1]), Image.LANCZOS)
+ frame.paste(front, ((size[0] - front.width) // 2, (size[1] - front.height) // 2))
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ frame.resize((size[0] * 2, size[1] * 2), Image.LANCZOS).save(destination)
+
+
+def video_command(ffmpeg: str, base: Path, destination: Path, *, duration: int,
+ orientation: str) -> list[str]:
+ """人像缓推:一镜到底的慢推,没有转场也没有文字动画。
+
+ `d` 取满整段时长的帧数,缓推才不会中途回弹重来。
+ """
+ size = FRAME_PORTRAIT if orientation == "竖屏" else FRAME_LANDSCAPE
+ frames = max(1, duration * 30)
+ return [
+ ffmpeg, "-y", "-v", "error", "-loop", "1", "-i", str(base),
+ "-vf", (f"zoompan=z='min(zoom+0.0004,1.14)':d={frames}:"
+ "x='iw/2-(iw/zoom/2)':y='ih/2-(ih/zoom/2)':"
+ f"s={size[0]}x{size[1]}:fps=30,format=yuv420p"),
+ "-t", str(duration), "-an", "-c:v", "libx264", "-preset", "veryfast",
+ "-crf", "26", "-movflags", "+faststart", str(destination),
+ ]
+
+
+def render_video(ffmpeg: str, base: Path, destination: Path, *, duration: int,
+ orientation: str) -> None:
+ destination.parent.mkdir(parents=True, exist_ok=True)
+ result = subprocess.run(
+ video_command(ffmpeg, base, destination, duration=duration, orientation=orientation),
+ capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=300)
+ if result.returncode != 0 or not destination.is_file() or destination.stat().st_size == 0:
+ raise RuntimeError(f"ffmpeg 生成 {destination.name} 失败:{result.stderr.strip()[:300]}")
diff --git a/tests/test_demo_dataset.py b/tests/test_demo_dataset.py
index 03b49d9a6..a4cdd38f9 100644
--- a/tests/test_demo_dataset.py
+++ b/tests/test_demo_dataset.py
@@ -1,11 +1,16 @@
-"""`scripts/demo_dataset.py`:SFW 合成演示库要能被 scan 与 process 离线消费。
+"""`scripts/demo_dataset.py`:SFW 演示库要能被 scan 与 process 离线消费。
-README 承诺「文档中的演示素材仅限 SFW」,这里把承诺变成门槛:演示词表不得与
+README 承诺「文档中的演示素材仅限 SFW」,这里把承诺变成门槛:作品词表不得与
`catalog_rules` 的成人词表相交;生成的目录布局要和 `library_nfo` 的边车规则对得上;
`process_library` 跑完不能向任何外部来源发过请求。
+
+`portrait` 模式的人像来自 `scripts/demo-portraits.json`。这些测试不联网,用本地造的
+图片和注入的取图函数走同一条代码路径,验证的是清单的形状、字节校验与「卡片上的名字
+就是封面上那位」。清单里每一张画面本身能不能见人由人工判定,测试不代替那一步。
"""
from __future__ import annotations
+import hashlib
import importlib.util
import json
import sqlite3
@@ -31,9 +36,9 @@ from support.ledger import fresh_ledger
ROOT = Path(__file__).resolve().parents[1]
-def load_script():
- path = ROOT / "scripts" / "demo_dataset.py"
- spec = importlib.util.spec_from_file_location("peach_script_demo_dataset", path)
+def load_script(name: str = "demo_dataset"):
+ path = ROOT / "scripts" / f"{name}.py"
+ spec = importlib.util.spec_from_file_location(f"peach_script_{name}", path)
module = importlib.util.module_from_spec(spec)
sys.modules[spec.name] = module
spec.loader.exec_module(module)
@@ -62,7 +67,8 @@ class DemoDatasetTests(unittest.TestCase):
catalog_rules.ROLE_TAGS, catalog_rules.APPEARANCE_TAGS, catalog_rules.POSITION_TAGS,
catalog_rules.STORY_TAGS, catalog_rules.RELATIONSHIP_TAGS, catalog_rules.SCENE_TAGS,
catalog_rules.ATTRIBUTE_TAGS)
- vocabulary = set(self.demo.CONTENT_TAGS) | set(self.demo.SERIES) | set(self.demo.PERFORMERS)
+ vocabulary = set(self.demo.CONTENT_TAGS) | set(self.demo.SERIES)
+ vocabulary |= set(self.demo.SYNTHETIC_PERFORMERS)
vocabulary |= set(self.demo.CREATORS) | {name for _, name in self.demo.STUDIOS}
vocabulary |= {title for title, _ in self.demo.TITLES} | set(self.demo.PLOTS)
self.assertEqual(vocabulary & adult, set())
@@ -191,5 +197,149 @@ class DemoDatasetTests(unittest.TestCase):
self.assertIn(self.demo.MANIFEST_NAME, text)
+class PortraitManifestTests(unittest.TestCase):
+ """人像清单与取图边界。不联网。"""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.portraits = load_script("demo_portraits")
+
+ def test_manifest_entries_are_complete_unique_and_large_enough(self):
+ entries = self.portraits.load_manifest()
+ self.assertGreaterEqual(len(entries), 8)
+ names = [entry.name for entry in entries]
+ digests = [entry.sha256 for entry in entries]
+ # 名字重复会让两条作品挂在同一位名下却是两张脸;哈希重复是同一张图的别名没去干净。
+ self.assertEqual(len(set(names)), len(names))
+ self.assertEqual(len(set(digests)), len(digests))
+ self.assertTrue(any(entry.landscape for entry in entries), "横屏作品需要横版人像")
+ for entry in entries:
+ self.assertEqual(len(entry.sha256), 64, entry.name)
+ self.assertTrue(entry.name.strip() and "\n" not in entry.name, entry.name)
+ # 封面最长边 900、播放底图两倍渲染到 2560,小于 640 的原图撑不起来。
+ self.assertGreaterEqual(max(entry.width, entry.height), 640, entry.name)
+ self.assertTrue(entry.url.startswith("https://"), entry.name)
+
+ def test_fetch_refuses_bytes_that_do_not_match_the_manifest(self):
+ entry = self.portraits.load_manifest()[0]
+ with tempfile.TemporaryDirectory() as tmp:
+ with self.assertRaises(RuntimeError) as caught:
+ self.portraits.fetch(entry, Path(tmp), opener=_opener(b"not the picture"))
+ self.assertIn(entry.name, str(caught.exception))
+ self.assertEqual(list(Path(tmp).glob("*.jpg")), [], "校验没过就不该留下文件")
+
+ def test_fetch_keeps_bytes_whose_digest_matches(self):
+ body = b"pretend this is a jpeg"
+ entry = self.portraits.Portrait(
+ name="试用", key="試用", category="1-Test", filename="試用.jpg",
+ sha256=hashlib.sha256(body).hexdigest(), width=1500, height=2125)
+ with tempfile.TemporaryDirectory() as tmp:
+ first = self.portraits.fetch(entry, Path(tmp), opener=_opener(body))
+ self.assertEqual(first.read_bytes(), body)
+ # 命中缓存就不该再取一次;再给一个会抛的 opener,它不该被调用。
+ again = self.portraits.fetch(entry, Path(tmp), opener=_refusing_opener)
+ self.assertEqual(again, first)
+
+
+class PortraitDatasetTests(unittest.TestCase):
+ """`--art portrait` 的生成路径。人像用本地造的图,取图函数注入,不联网。"""
+
+ @classmethod
+ def setUpClass(cls):
+ cls.demo = load_script()
+ cls.portraits = load_script("demo_portraits")
+
+ def setUp(self):
+ self.tmp = tempfile.TemporaryDirectory()
+ self.addCleanup(self.tmp.cleanup)
+ self.root = Path(self.tmp.name).resolve()
+ self.made: dict[str, Path] = {}
+ self.entries = [
+ self._entry("立花ひなの", 1500, 2125),
+ self._entry("三条あかり", 1500, 2125),
+ self._entry("長峰さやか", 2880, 1800),
+ self._entry("御崎るか", 2880, 1800),
+ ]
+
+ def _entry(self, name: str, width: int, height: int):
+ from PIL import Image
+
+ path = self.root / "pretend" / f"{name}.jpg"
+ path.parent.mkdir(parents=True, exist_ok=True)
+ Image.new("RGB", (width, height), (90, 110, 150)).save(path, quality=70)
+ self.made[name] = path
+ return self.portraits.Portrait(
+ name=name, key=name, category="1-Test", filename=f"{name}.jpg",
+ sha256=hashlib.sha256(path.read_bytes()).hexdigest(),
+ width=width, height=height)
+
+ def _fetch(self, entry, cache_dir):
+ return self.made[entry.name]
+
+ def _generate(self, name: str, **kwargs):
+ output = self.root / name
+ items = self.demo.generate(
+ output, count=kwargs.pop("count", 9), seed=kwargs.pop("seed", 7),
+ video=kwargs.pop("video", "stub"), duration=kwargs.pop("duration", 4),
+ art="portrait", portraits=self.entries, fetch=self._fetch, **kwargs)
+ return output, items
+
+ def test_every_work_names_the_face_that_is_on_its_cover(self):
+ output, items = self._generate("faces")
+ known = {entry.name for entry in self.entries}
+ for item in items:
+ self.assertIn(item.portrait, known, item.path)
+ if item.kind == "coded":
+ # 卡片上的出演者就是封面上那位;对不上细看就穿帮。
+ self.assertEqual(item.performers, [item.portrait], item.code)
+ manifest = json.loads((output / self.demo.MANIFEST_NAME).read_text(encoding="utf-8"))
+ self.assertEqual(manifest["art"], "portrait")
+
+ def test_orientation_picks_a_portrait_of_the_same_shape(self):
+ _, items = self._generate("shapes", count=16)
+ shape = {entry.name: entry.landscape for entry in self.entries}
+ for item in items:
+ self.assertEqual(shape[item.portrait], item.orientation == "横屏", item.path)
+
+ def test_covers_are_written_at_the_documented_sizes(self):
+ from PIL import Image
+
+ output, items = self._generate("covers")
+ for item in items:
+ if not item.poster:
+ continue
+ with Image.open(output / item.poster) as cover:
+ expected = (self.portraits.COVER_PORTRAIT if item.orientation == "竖屏"
+ else self.portraits.COVER_LANDSCAPE)
+ self.assertEqual(cover.size, expected, item.poster)
+
+ def test_an_empty_manifest_is_refused_with_a_hint(self):
+ with self.assertRaises(RuntimeError) as caught:
+ self.demo.generate(self.root / "none", count=1, seed=1, video="stub",
+ duration=2, art="portrait", portraits=[])
+ self.assertIn("--art synthetic", str(caught.exception))
+
+
+def _opener(body: bytes):
+ class _Response:
+ def read(self, *args):
+ return body
+
+ def __enter__(self):
+ return self
+
+ def __exit__(self, *args):
+ return False
+
+ def opener(request, timeout=None):
+ return _Response()
+
+ return opener
+
+
+def _refusing_opener(request, timeout=None):
+ raise AssertionError("缓存命中后不该再联网")
+
+
if __name__ == "__main__":
unittest.main()
diff --git a/tests/test_dependency_policy.py b/tests/test_dependency_policy.py
index a4faef192..645148663 100644
--- a/tests/test_dependency_policy.py
+++ b/tests/test_dependency_policy.py
@@ -55,6 +55,9 @@ class DependencyPolicyTests(unittest.TestCase):
"zeroconf": "zeroconf",
}
imported = set()
+ # `scripts/` 下的模块彼此 import 走顶层名字(那个目录就在 sys.path 上),
+ # 这是同一个仓库里的文件,不是要声明归属的外部依赖。
+ siblings = {path.stem for path in (ROOT / "scripts").rglob("*.py")}
for folder in (ROOT / "src", ROOT / "scripts"):
for path in folder.rglob("*.py"):
tree = ast.parse(path.read_text(encoding="utf-8-sig"))
@@ -63,7 +66,7 @@ class DependencyPolicyTests(unittest.TestCase):
imported.update(alias.name.split(".")[0] for alias in node.names)
elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
imported.add(node.module.split(".")[0])
- external = imported - sys.stdlib_module_names - {"peach"}
+ external = imported - sys.stdlib_module_names - {"peach"} - siblings
self.assertEqual(external - owners.keys(), set())
requirements = self.pyproject["project"]["dependencies"][:]