feat(assets): manifest v2 with per-style renditions, --style CLI and automatic checks

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
dasemuandClaude Opus 5.5 committed 2026-10-19 04:09:00 +02:00
1 parent ff78dc5b14
commit 1cf5b1460d
3 files changed
+748 -119

No files matched your search

+295 -55
View File
@@ -1,15 +1,18 @@
"""Asset manifest management: import generated images, key out sprite backgrounds, """Asset manifest management: import generated images, key out sprite backgrounds,
fall back to placeholders, and build contact sheets for visual review. fall back to placeholders, and build contact sheets for visual review.
The manifest (``<work>/assets/assets.json``) is the single source of truth for every The manifest (``<work>/assets/assets.json``, v2) is the single source of truth for every
image: prompt, origin, hash and review status. Image generation itself happens image. Art *styles* (prompt base + templates) are declared once; each asset has one
*rendition* per style (origin, hash, review status). Image generation itself happens
outside this module (an MCP tool driven by an agent); ``import`` ingests its result. outside this module (an MCP tool driven by an agent); ``import`` ingests its result.
""" """
import argparse import argparse
import base64 import base64
import hashlib import hashlib
import io
import json import json
import shutil
from pathlib import Path from pathlib import Path
from typing import Any from typing import Any
@@ -27,6 +30,11 @@ USABLE = {"processed", "approved"}
KEY_FULL = 60 # at or above: fully transparent KEY_FULL = 60 # at or above: fully transparent
KEY_NONE = 20 # at or below: fully opaque KEY_NONE = 20 # at or below: fully opaque
# Sprite sanity bounds (checked on the keyed, untrimmed image when the raw file exists).
COVERAGE_MIN = 0.15
COVERAGE_MAX = 0.85
ALPHA_VISIBLE = 16
def sha256_file(path: Path) -> str: def sha256_file(path: Path) -> str:
return hashlib.sha256(path.read_bytes()).hexdigest() return hashlib.sha256(path.read_bytes()).hexdigest()
@@ -35,6 +43,13 @@ def sha256_file(path: Path) -> str:
def load_manifest(work_root: Path) -> dict[str, Any]: def load_manifest(work_root: Path) -> dict[str, Any]:
data = json.loads((work_root / MANIFEST).read_text(encoding="utf-8")) data = json.loads((work_root / MANIFEST).read_text(encoding="utf-8"))
validate(data, "manifest") validate(data, "manifest")
styles = data["styles"]
if data["default_style"] not in styles:
raise ValueError(f"default_style {data['default_style']!r} is not in styles")
for asset in data["assets"]:
unknown = set(asset["renditions"]) - set(styles)
if unknown:
raise ValueError(f"{asset['id']}: renditions for unknown styles {sorted(unknown)}")
return data return data
@@ -51,11 +66,157 @@ def find_asset(manifest: dict[str, Any], asset_id: str) -> dict[str, Any]:
raise KeyError(f"unknown asset id: {asset_id}") raise KeyError(f"unknown asset id: {asset_id}")
def full_prompt(manifest: dict[str, Any], asset: dict[str, Any]) -> str: def resolve_style(manifest: dict[str, Any], style: str | None) -> str:
"""Prompt actually sent to the generator: base + kind template + asset prompt.""" """``style`` or the manifest default; raises ``ValueError`` for an unknown style."""
style = style or manifest["default_style"]
if style not in manifest["styles"]:
raise ValueError(f"unknown style {style!r}; known: {sorted(manifest['styles'])}")
return style
def asset_name(asset: dict[str, Any]) -> str:
"""File stem: the id without its ``bg_`` / ``sprite_`` prefix."""
return asset["id"].split("_", 1)[1]
def style_file(asset: dict[str, Any], style: str) -> str:
"""Final image path (relative to the assets dir): ``<bg|sprites>/<style>/<name>.webp``."""
kind_dir = "bg" if asset["kind"] == "background" else "sprites"
return f"{kind_dir}/{style}/{asset_name(asset)}.webp"
def raw_path_rel(asset: dict[str, Any], style: str) -> str:
return f"raw/{style}/{asset['id']}.png"
def usable_rendition(asset: dict[str, Any], style: str) -> dict[str, Any] | None:
"""The style's rendition if it is processed/approved, else None."""
rendition = asset["renditions"].get(style)
return rendition if rendition and rendition["status"] in USABLE else None
def full_prompt(manifest: dict[str, Any], asset: dict[str, Any], style: str | None = None) -> str:
"""Prompt actually sent to the generator: style base + kind template + asset prompt."""
cfg = manifest["styles"][resolve_style(manifest, style)]
kind = "variant" if asset.get("reference") and asset["kind"] == "sprite" else asset["kind"] kind = "variant" if asset.get("reference") and asset["kind"] == "sprite" else asset["kind"]
template = manifest["templates"][kind] return "\n\n".join(
return "\n\n".join(p for p in (manifest["base_prompt"], template, asset["prompt"]) if p) p for p in (cfg["base_prompt"], cfg["templates"][kind], asset["prompt"]) if p
)
# --- migration ----------------------------------------------------------------
def migrate_v1(work_root: Path, style: str, label: str | None = None) -> dict[str, Any]:
"""Convert a v1 manifest (flat base_prompt/templates/per-asset files) to v2 in place.
The old data becomes the rendition of ``style`` (the default); image files move into the
per-style directories. Returns the new manifest.
"""
path = work_root / MANIFEST
old = json.loads(path.read_text(encoding="utf-8"))
if "styles" in old:
raise ValueError("manifest is already v2")
assets_dir = work_root / "assets"
new_assets = []
for a in old["assets"]:
asset = {k: a[k] for k in ("id", "kind", "character", "expression", "prompt") if k in a}
asset["reference"] = a.get("reference")
rendition = {
k: a[k]
for k in ("source", "generation_id", "raw_file", "file", "sha256", "status", "notes")
if k in a
}
target = style_file(asset, style)
raw_target = raw_path_rel(asset, style)
for key, dest in (("file", target), ("raw_file", raw_target)):
src = rendition.get(key)
if not src:
continue
if (assets_dir / src).is_file() and src != dest:
(assets_dir / dest).parent.mkdir(parents=True, exist_ok=True)
shutil.move(assets_dir / src, assets_dir / dest)
rendition[key] = dest
asset["renditions"] = {style: rendition}
new_assets.append(asset)
new = {
"default_style": style,
"styles": {
style: {
"label": label or style,
"base_prompt": old["base_prompt"],
"templates": old["templates"],
}
},
"assets": new_assets,
}
save_manifest(work_root, new)
return new
# --- automatic checks -----------------------------------------------------------
def sprite_metrics(img: Image.Image) -> tuple[float, tuple[int, int, int, int] | None]:
"""Opaque-pixel fraction and bbox of the visible area of an RGBA image."""
alpha = img.getchannel("A").point(lambda a: 255 if a > ALPHA_VISIBLE else 0)
hist = alpha.histogram()
return hist[255] / (img.width * img.height), alpha.getbbox()
def check_rendition(
work_root: Path, manifest: dict[str, Any], asset: dict[str, Any], style: str
) -> list[str]:
"""Automatic sanity checks for one usable rendition; returns failure messages."""
rendition = usable_rendition(asset, style)
if not rendition:
return []
assets_dir = work_root / "assets"
final = assets_dir / rendition["file"]
tag = f"{asset['id']} [{style}]"
if not final.is_file():
return [f"{tag}: file {rendition['file']} is missing"]
failures = []
if asset["kind"] == "background":
with Image.open(final) as img:
if img.size != BG_SIZE:
failures.append(
f"{tag}: background is {img.width}x{img.height}, "
f"expected {BG_SIZE[0]}x{BG_SIZE[1]}"
)
else:
raw_rel = rendition.get("raw_file")
raw = assets_dir / raw_rel if raw_rel else None
if raw and raw.is_file(): # untrimmed: coverage and top-edge are meaningful
with Image.open(raw) as img:
coverage, bbox = sprite_metrics(chroma_key(img))
if bbox and bbox[1] <= 0:
failures.append(f"{tag}: sprite touches the top edge (head cropped)")
else: # final files are trimmed to the bbox: only coverage applies
with Image.open(final) as img:
coverage, _ = sprite_metrics(img.convert("RGBA"))
if not COVERAGE_MIN <= coverage <= COVERAGE_MAX:
failures.append(
f"{tag}: sprite opaque coverage {coverage:.0%} outside "
f"{COVERAGE_MIN:.0%}-{COVERAGE_MAX:.0%}"
)
ref_id = asset.get("reference")
if ref_id and asset["kind"] == "sprite":
ref_r = find_asset(manifest, ref_id)["renditions"].get(style)
ref_file = assets_dir / ref_r["file"] if ref_r and ref_r.get("file") else None
if ref_file and ref_file.is_file() and sha256_file(final) == sha256_file(ref_file):
failures.append(f"{tag}: identical to its reference {ref_id} (sha256 match)")
return failures
def check_style(
work_root: Path, manifest: dict[str, Any], style: str, ids: list[str] | None = None
) -> list[str]:
failures: list[str] = []
for asset in manifest["assets"]:
if not ids or asset["id"] in ids:
failures += check_rendition(work_root, manifest, asset, style)
return failures
# --- import ----------------------------------------------------------------- # --- import -----------------------------------------------------------------
@@ -85,26 +246,30 @@ def decode_output(result: dict[str, Any], index: int = 0) -> bytes:
return raw return raw
def import_image(work_root: Path, asset_id: str, raw: bytes, generation_id: str | None) -> Path: def import_image(
work_root: Path, asset_id: str, raw: bytes, generation_id: str | None, style: str | None = None
) -> Path:
manifest = load_manifest(work_root) manifest = load_manifest(work_root)
style = resolve_style(manifest, style)
asset = find_asset(manifest, asset_id) asset = find_asset(manifest, asset_id)
raw_rel = f"raw/{asset_id}.png" raw_rel = raw_path_rel(asset, style)
raw_path = work_root / "assets" / raw_rel raw_path = work_root / "assets" / raw_rel
raw_path.parent.mkdir(parents=True, exist_ok=True) raw_path.parent.mkdir(parents=True, exist_ok=True)
with Image.open(_bytes_io(raw)) as img: with Image.open(io.BytesIO(raw)) as img:
img.convert("RGB").save(raw_path, "PNG") img.convert("RGB").save(raw_path, "PNG")
asset.update(raw_file=raw_rel, generation_id=generation_id, status="generated") rendition = asset["renditions"].setdefault(style, {})
asset.setdefault("source", "chatgpt-web") rendition.update(
raw_file=raw_rel,
file=style_file(asset, style),
generation_id=generation_id,
sha256=None,
status="generated",
)
rendition.setdefault("source", "chatgpt-web")
save_manifest(work_root, manifest) save_manifest(work_root, manifest)
return raw_path return raw_path
def _bytes_io(raw: bytes):
import io
return io.BytesIO(raw)
# --- processing ------------------------------------------------------------- # --- processing -------------------------------------------------------------
@@ -137,9 +302,10 @@ def trim_and_scale_sprite(img: Image.Image, height: int = SPRITE_HEIGHT) -> Imag
return img.resize((max(1, round(img.width * scale)), height), Image.Resampling.LANCZOS) return img.resize((max(1, round(img.width * scale)), height), Image.Resampling.LANCZOS)
def process_asset(work_root: Path, asset: dict[str, Any]) -> None: def process_asset(work_root: Path, asset: dict[str, Any], style: str) -> None:
raw_path = work_root / "assets" / asset["raw_file"] rendition = asset["renditions"][style]
final = work_root / "assets" / asset["file"] raw_path = work_root / "assets" / rendition["raw_file"]
final = work_root / "assets" / rendition["file"]
final.parent.mkdir(parents=True, exist_ok=True) final.parent.mkdir(parents=True, exist_ok=True)
with Image.open(raw_path) as img: with Image.open(raw_path) as img:
if asset["kind"] == "sprite": if asset["kind"] == "sprite":
@@ -147,8 +313,8 @@ def process_asset(work_root: Path, asset: dict[str, Any]) -> None:
else: else:
out = ImageOps.fit(img.convert("RGB"), BG_SIZE, Image.Resampling.LANCZOS) out = ImageOps.fit(img.convert("RGB"), BG_SIZE, Image.Resampling.LANCZOS)
out.save(final, "WEBP", quality=90, method=6) out.save(final, "WEBP", quality=90, method=6)
asset["sha256"] = sha256_file(final) rendition["sha256"] = sha256_file(final)
asset["status"] = "processed" rendition["status"] = "processed"
def placeholder(asset: dict[str, Any], label_color: str = "#d8cfc0") -> Image.Image: def placeholder(asset: dict[str, Any], label_color: str = "#d8cfc0") -> Image.Image:
@@ -170,20 +336,30 @@ def placeholder(asset: dict[str, Any], label_color: str = "#d8cfc0") -> Image.Im
return img return img
def ensure_placeholder(work_root: Path, asset: dict[str, Any]) -> None: def ensure_placeholder(work_root: Path, asset: dict[str, Any], style: str) -> None:
final = work_root / "assets" / asset["file"] rendition = asset["renditions"].setdefault(style, {})
rendition["file"] = style_file(asset, style)
final = work_root / "assets" / rendition["file"]
final.parent.mkdir(parents=True, exist_ok=True) final.parent.mkdir(parents=True, exist_ok=True)
placeholder(asset).save(final, "WEBP", quality=90) placeholder(asset).save(final, "WEBP", quality=90)
asset.update(source="placeholder", status="placeholder", sha256=sha256_file(final)) rendition.update(source="placeholder", status="placeholder", sha256=sha256_file(final))
def contact_sheet(work_root: Path, ids: list[str], out: Path, thumb: int = 360) -> Path: def contact_sheet(
work_root: Path, ids: list[str], out: Path, style: str | None = None, thumb: int = 360
) -> Path:
"""Tile raw or processed images (sprites over a checkerboard) for visual review.""" """Tile raw or processed images (sprites over a checkerboard) for visual review."""
manifest = load_manifest(work_root) manifest = load_manifest(work_root)
style = resolve_style(manifest, style)
tiles = [] tiles = []
for asset_id in ids: for asset_id in ids:
asset = find_asset(manifest, asset_id) asset = find_asset(manifest, asset_id)
rel = asset["file"] if asset["status"] in USABLE else asset.get("raw_file") rendition = asset["renditions"].get(style) or {}
rel = (
rendition.get("file")
if rendition.get("status") in USABLE
else rendition.get("raw_file")
)
if not rel: if not rel:
continue continue
with Image.open(work_root / "assets" / rel) as img: with Image.open(work_root / "assets" / rel) as img:
@@ -215,49 +391,97 @@ def _checker(size: tuple[int, int], cell: int = 20) -> Image.Image:
# --- CLI -------------------------------------------------------------------- # --- CLI --------------------------------------------------------------------
def _style_of(args: argparse.Namespace, manifest: dict[str, Any]) -> str:
try:
return resolve_style(manifest, args.style)
except ValueError as exc:
raise SystemExit(f"assets: {exc}") from exc
def _cmd_import(args: argparse.Namespace) -> int: def _cmd_import(args: argparse.Namespace) -> int:
work = load_work(args.work) work = load_work(args.work)
style = _style_of(args, load_manifest(work.root))
result = load_tool_result(args.tool_result) result = load_tool_result(args.tool_result)
raw = decode_output(result, args.index) raw = decode_output(result, args.index)
path = import_image(work.root, args.asset_id, raw, result.get("generationId")) path = import_image(work.root, args.asset_id, raw, result.get("generationId"), style)
print(f"{args.asset_id}: imported {path} ({len(raw)} bytes, sha256 verified)") print(f"{args.asset_id} [{style}]: imported {path} ({len(raw)} bytes, sha256 verified)")
return 0 return 0
def _cmd_process(args: argparse.Namespace) -> int: def _cmd_process(args: argparse.Namespace) -> int:
work = load_work(args.work) work = load_work(args.work)
manifest = load_manifest(work.root) manifest = load_manifest(work.root)
style = _style_of(args, manifest)
done = []
for asset in manifest["assets"]: for asset in manifest["assets"]:
if args.ids and asset["id"] not in args.ids: if args.ids and asset["id"] not in args.ids:
continue continue
if asset["status"] == "generated" or (args.force and asset.get("raw_file")): rendition = asset["renditions"].get(style)
process_asset(work.root, asset) if rendition and (
print(f"{asset['id']}: processed") rendition["status"] == "generated" or (args.force and rendition.get("raw_file"))
):
process_asset(work.root, asset, style)
done.append(asset["id"])
print(f"{asset['id']} [{style}]: processed")
save_manifest(work.root, manifest) save_manifest(work.root, manifest)
return 0 failures = check_style(work.root, manifest, style, done)
for line in failures:
print(f"CHECK FAILED {line}")
return 1 if failures else 0
def _cmd_check(args: argparse.Namespace) -> int:
work = load_work(args.work)
manifest = load_manifest(work.root)
styles = [_style_of(args, manifest)] if args.style else list(manifest["styles"])
failures = []
for style in styles:
failures += check_style(work.root, manifest, style, args.ids)
for line in failures:
print(f"CHECK FAILED {line}")
print(f"check: {len(failures)} failure(s) in {', '.join(styles)}")
return 1 if failures else 0
def _bucket(rendition: dict[str, Any] | None) -> str:
if rendition is None:
return "missing"
return "approved" if rendition["status"] == "approved" else "pending"
def _cmd_status(args: argparse.Namespace) -> int: def _cmd_status(args: argparse.Namespace) -> int:
work = load_work(args.work) work = load_work(args.work)
manifest = load_manifest(work.root) manifest = load_manifest(work.root)
if args.set: if args.set:
asset = find_asset(manifest, args.set[0]) style = _style_of(args, manifest)
asset["status"] = args.set[1] rendition = find_asset(manifest, args.set[0])["renditions"].get(style)
if rendition is None:
raise SystemExit(f"assets: {args.set[0]} has no {style!r} rendition")
rendition["status"] = args.set[1]
if len(args.set) > 2: if len(args.set) > 2:
asset["notes"] = args.set[2] rendition["notes"] = args.set[2]
save_manifest(work.root, manifest) save_manifest(work.root, manifest)
styles = [_style_of(args, manifest)] if args.style else list(manifest["styles"])
print(f"{'asset':<28}" + "".join(f"{s:<14}" for s in styles))
for asset in manifest["assets"]: for asset in manifest["assets"]:
print(f"{asset['status']:<11} {asset['id']}") cells = [(asset["renditions"].get(s) or {}).get("status", "missing") for s in styles]
print(f"{asset['id']:<28}" + "".join(f"{c:<14}" for c in cells))
for s in styles:
counts = {"approved": 0, "pending": 0, "missing": 0}
for asset in manifest["assets"]:
counts[_bucket(asset["renditions"].get(s))] += 1
print(f"{s}: " + ", ".join(f"{n} {k}" for k, n in counts.items()))
return 0 return 0
def _cmd_placeholders(args: argparse.Namespace) -> int: def _cmd_placeholders(args: argparse.Namespace) -> int:
work = load_work(args.work) work = load_work(args.work)
manifest = load_manifest(work.root) manifest = load_manifest(work.root)
style = _style_of(args, manifest)
for asset in manifest["assets"]: for asset in manifest["assets"]:
if asset["status"] not in USABLE: if not usable_rendition(asset, style):
ensure_placeholder(work.root, asset) ensure_placeholder(work.root, asset, style)
print(f"{asset['id']}: placeholder") print(f"{asset['id']} [{style}]: placeholder")
save_manifest(work.root, manifest) save_manifest(work.root, manifest)
return 0 return 0
@@ -265,13 +489,21 @@ def _cmd_placeholders(args: argparse.Namespace) -> int:
def _cmd_prompt(args: argparse.Namespace) -> int: def _cmd_prompt(args: argparse.Namespace) -> int:
work = load_work(args.work) work = load_work(args.work)
manifest = load_manifest(work.root) manifest = load_manifest(work.root)
print(full_prompt(manifest, find_asset(manifest, args.asset_id))) print(full_prompt(manifest, find_asset(manifest, args.asset_id), _style_of(args, manifest)))
return 0 return 0
def _cmd_sheet(args: argparse.Namespace) -> int: def _cmd_sheet(args: argparse.Namespace) -> int:
work = load_work(args.work) work = load_work(args.work)
print(contact_sheet(work.root, args.ids, args.out)) style = _style_of(args, load_manifest(work.root))
print(contact_sheet(work.root, args.ids, args.out, style))
return 0
def _cmd_migrate(args: argparse.Namespace) -> int:
work = load_work(args.work)
new = migrate_v1(work.root, args.style, args.label)
print(f"migrated {len(new['assets'])} assets to manifest v2 (style {args.style!r})")
return 0 return 0
@@ -279,29 +511,37 @@ def register(sub: argparse._SubParsersAction) -> None:
parser = sub.add_parser("assets", help="Manage the asset manifest and images") parser = sub.add_parser("assets", help="Manage the asset manifest and images")
cmds = parser.add_subparsers(dest="assets_command", required=True) cmds = parser.add_subparsers(dest="assets_command", required=True)
p = cmds.add_parser("prompt", help="Print the full generation prompt for an asset") def add(name: str, help_: str, handler, style: bool = True) -> argparse.ArgumentParser:
p.add_argument("asset_id") p = cmds.add_parser(name, help=help_)
p.set_defaults(handler=_cmd_prompt) if style:
p.add_argument("--style", help="Art style id (default: the manifest's default_style)")
p.set_defaults(handler=handler)
return p
p = cmds.add_parser("import", help="Decode a stored query_tasks result into an asset") p = add("prompt", "Print the full generation prompt for an asset", _cmd_prompt)
p.add_argument("asset_id")
p = add("import", "Decode a stored query_tasks result into an asset", _cmd_import)
p.add_argument("asset_id") p.add_argument("asset_id")
p.add_argument("tool_result", type=Path) p.add_argument("tool_result", type=Path)
p.add_argument("--index", type=int, default=0) p.add_argument("--index", type=int, default=0)
p.set_defaults(handler=_cmd_import)
p = cmds.add_parser("process", help="Cut out sprites / fit backgrounds") p = add("process", "Cut out sprites / fit backgrounds, then run the checks", _cmd_process)
p.add_argument("ids", nargs="*") p.add_argument("ids", nargs="*")
p.add_argument("--force", action="store_true", help="Reprocess already processed assets") p.add_argument("--force", action="store_true", help="Reprocess already processed assets")
p.set_defaults(handler=_cmd_process)
p = cmds.add_parser("status", help="List statuses, or --set ID STATUS [NOTE]") p = add("check", "Automatic checks (all styles unless --style)", _cmd_check)
p.add_argument("ids", nargs="*")
p = add("status", "Per-style status matrix, or --set ID STATUS [NOTE]", _cmd_status)
p.add_argument("--set", nargs="+", metavar="ARG") p.add_argument("--set", nargs="+", metavar="ARG")
p.set_defaults(handler=_cmd_status)
p = cmds.add_parser("placeholders", help="Create placeholders for unusable assets") add("placeholders", "Create placeholders for unusable assets", _cmd_placeholders)
p.set_defaults(handler=_cmd_placeholders)
p = cmds.add_parser("sheet", help="Build a contact sheet PNG for review") p = add("sheet", "Build a contact sheet PNG for review", _cmd_sheet)
p.add_argument("out", type=Path) p.add_argument("out", type=Path)
p.add_argument("ids", nargs="+") p.add_argument("ids", nargs="+")
p.set_defaults(handler=_cmd_sheet)
p = add("migrate", "Convert a v1 manifest to v2 (old data becomes STYLE)", _cmd_migrate, False)
p.add_argument("style", help="Style id for the existing renditions")
p.add_argument("--label", help="Display label of that style (default: the id)")
+98 -64
View File
@@ -4,15 +4,50 @@
"title": "Asset manifest", "title": "Asset manifest",
"type": "object", "type": "object",
"required": [ "required": [
"base_prompt", "default_style",
"templates", "styles",
"assets" "assets"
], ],
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
"base_prompt": { "default_style": {
"type": "string" "type": "string"
}, },
"styles": {
"type": "object",
"minProperties": 1,
"additionalProperties": {
"type": "object",
"required": [
"label",
"base_prompt",
"templates"
],
"additionalProperties": false,
"properties": {
"label": {
"type": "string",
"description": "Player-facing name of the style"
},
"base_prompt": {
"type": "string"
},
"templates": {
"type": "object",
"required": [
"background",
"sprite",
"variant"
],
"additionalProperties": {
"type": "string"
},
"description": "Kind-specific prompt templates appended after base_prompt"
}
}
},
"description": "Art styles keyed by style id"
},
"assets": { "assets": {
"type": "array", "type": "array",
"items": { "items": {
@@ -21,10 +56,7 @@
"id", "id",
"kind", "kind",
"prompt", "prompt",
"source", "renditions"
"file",
"sha256",
"status"
], ],
"additionalProperties": false, "additionalProperties": false,
"properties": { "properties": {
@@ -47,21 +79,7 @@
}, },
"prompt": { "prompt": {
"type": "string", "type": "string",
"description": "Asset-specific prompt; the full prompt sent is base_prompt + kind prompt + this" "description": "Asset-specific prompt; the full prompt sent is the style's base_prompt + kind template + this"
},
"source": {
"enum": [
"chatgpt-web",
"zenvairo-media",
"placeholder",
"manual"
]
},
"generation_id": {
"type": [
"string",
"null"
]
}, },
"reference": { "reference": {
"type": [ "type": [
@@ -70,51 +88,67 @@
], ],
"description": "Asset id used as reference image (identity consistency)" "description": "Asset id used as reference image (identity consistency)"
}, },
"raw_file": { "renditions": {
"type": [ "type": "object",
"string", "additionalProperties": {
"null" "type": "object",
], "required": [
"description": "Original generated image, relative to the work's assets dir" "file",
}, "status"
"file": { ],
"type": "string", "additionalProperties": false,
"description": "Final processed image used by the game, relative to the work's assets dir" "properties": {
}, "source": {
"sha256": { "enum": [
"type": [ "chatgpt-web",
"string", "zenvairo-media",
"null" "placeholder",
], "manual"
"pattern": "^[0-9a-f]{64}$" ]
}, },
"status": { "generation_id": {
"enum": [ "type": [
"planned", "string",
"generated", "null"
"processed", ]
"approved", },
"rejected", "raw_file": {
"placeholder" "type": [
] "string",
}, "null"
"notes": { ],
"type": "string" "description": "Original generated image, relative to the work's assets dir"
},
"file": {
"type": "string",
"description": "Final processed image used by the game, relative to the work's assets dir"
},
"sha256": {
"type": [
"string",
"null"
],
"pattern": "^[0-9a-f]{64}$"
},
"status": {
"enum": [
"planned",
"generated",
"processed",
"approved",
"rejected",
"placeholder"
]
},
"notes": {
"type": "string"
}
}
},
"description": "One image per art style, keyed by style id"
} }
} }
} }
},
"templates": {
"type": "object",
"required": [
"background",
"sprite",
"variant"
],
"additionalProperties": {
"type": "string"
},
"description": "Kind-specific prompt templates appended after base_prompt"
} }
} }
} }
+355
View File
@@ -0,0 +1,355 @@
import json
import os
import shutil
import subprocess
from pathlib import Path
import pytest
import test_renpy_gen
from PIL import Image
from vnpipe import assets, cli, renpy_gen
from vnpipe.config import load_work
from vnpipe.schema import SchemaError
FIXTURES = Path(__file__).parent / "fixtures"
STYLES = {
"paint": {
"label": "Paint",
"base_prompt": "PAINT base.",
"templates": {
"background": "PAINT bg.",
"sprite": "PAINT sprite.",
"variant": "PAINT var.",
},
},
"ink": {
"label": "Ink",
"base_prompt": "INK base.",
"templates": {"background": "INK bg.", "sprite": "INK sprite.", "variant": "INK var."},
},
}
def v2_manifest() -> dict:
return {
"default_style": "paint",
"styles": json.loads(json.dumps(STYLES)),
"assets": [
{
"id": "bg_theatre",
"kind": "background",
"prompt": "A stage.",
"reference": None,
"renditions": {},
},
{
"id": "sprite_poet_neutral",
"kind": "sprite",
"character": "poet",
"expression": "neutral",
"prompt": "Neutral.",
"reference": None,
"renditions": {},
},
{
"id": "sprite_poet_indignant",
"kind": "sprite",
"character": "poet",
"expression": "indignant",
"prompt": "Angry.",
"reference": "sprite_poet_neutral",
"renditions": {},
},
],
}
@pytest.fixture
def work_root(tmp_path):
root = tmp_path / "w"
shutil.copytree(FIXTURES / "mini_work", root)
(root / "assets").mkdir()
assets.save_manifest(root, v2_manifest())
return root
def green_sprite(path: Path, fill: float = 0.4, top: int = 100) -> None:
"""1000x1500 chroma-green field with an opaque block of roughly ``fill`` of the area."""
img = Image.new("RGB", (1000, 1500), (0, 177, 64))
h = round(1500 * fill)
img.paste((120, 60, 50), (250, top, 750, min(1500, top + h * 2)))
path.parent.mkdir(parents=True, exist_ok=True)
img.save(path)
def set_rendition(root, asset_id, style, **fields):
manifest = assets.load_manifest(root)
asset = assets.find_asset(manifest, asset_id)
rendition = asset["renditions"].setdefault(style, {"file": assets.style_file(asset, style)})
rendition.update(fields)
assets.save_manifest(root, manifest)
def test_schema_rejects_v1_shape():
old = {"base_prompt": "x", "templates": {}, "assets": []}
with pytest.raises(SchemaError):
assets.validate(old, "manifest")
def test_unknown_style_and_default(work_root):
manifest = assets.load_manifest(work_root)
assert assets.resolve_style(manifest, None) == "paint"
with pytest.raises(ValueError, match="unknown style"):
assets.resolve_style(manifest, "nope")
manifest["default_style"] = "nope"
(work_root / assets.MANIFEST).write_text(json.dumps(manifest), encoding="utf-8")
with pytest.raises(ValueError, match="default_style"):
assets.load_manifest(work_root)
def test_full_prompt_per_style(work_root):
manifest = assets.load_manifest(work_root)
bg, base, var = manifest["assets"]
assert assets.full_prompt(manifest, bg) == "PAINT base.\n\nPAINT bg.\n\nA stage."
assert assets.full_prompt(manifest, bg, "ink").startswith("INK base.\n\nINK bg.")
assert "INK sprite." in assets.full_prompt(manifest, base, "ink")
assert "INK var." in assets.full_prompt(manifest, var, "ink")
def test_style_file_layout():
bg, sprite = v2_manifest()["assets"][:2]
assert assets.style_file(bg, "ink") == "bg/ink/theatre.webp"
assert assets.style_file(sprite, "ink") == "sprites/ink/poet_neutral.webp"
assert assets.raw_path_rel(sprite, "ink") == "raw/ink/sprite_poet_neutral.png"
def test_import_and_process_per_style(work_root):
green_sprite(work_root / "assets/raw/ink/sprite_poet_neutral.png")
raw = (work_root / "assets/raw/ink/sprite_poet_neutral.png").read_bytes()
assets.import_image(work_root, "sprite_poet_neutral", raw, "gid-1", "ink")
manifest = assets.load_manifest(work_root)
rendition = manifest["assets"][1]["renditions"]["ink"]
assert (
rendition["status"] == "generated" and rendition["file"] == "sprites/ink/poet_neutral.webp"
)
assert "paint" not in manifest["assets"][1]["renditions"]
assert cli.main(["--work", str(work_root), "assets", "process", "--style", "ink"]) == 0
manifest = assets.load_manifest(work_root)
rendition = manifest["assets"][1]["renditions"]["ink"]
assert rendition["status"] == "processed" and rendition["sha256"]
assert (work_root / "assets/sprites/ink/poet_neutral.webp").is_file()
def test_status_matrix(work_root, capsys):
set_rendition(work_root, "bg_theatre", "paint", status="approved")
set_rendition(work_root, "bg_theatre", "ink", status="generated")
assert cli.main(["--work", str(work_root), "assets", "status"]) == 0
out = capsys.readouterr().out
theatre = next(ln for ln in out.splitlines() if ln.startswith("bg_theatre"))
assert theatre.split() == ["bg_theatre", "approved", "generated"]
assert "paint: 1 approved, 0 pending, 2 missing" in out
assert "ink: 0 approved, 1 pending, 2 missing" in out
def test_placeholders_only_for_chosen_style(work_root):
cli.main(["--work", str(work_root), "assets", "placeholders", "--style", "ink"])
manifest = assets.load_manifest(work_root)
assert all(set(a["renditions"]) == {"ink"} for a in manifest["assets"])
assert (work_root / "assets/bg/ink/theatre.webp").is_file()
assert not (work_root / "assets/bg/paint").exists()
def test_check_background_size(work_root):
path = work_root / "assets/bg/paint/theatre.webp"
path.parent.mkdir(parents=True)
Image.new("RGB", (1280, 720)).save(path)
set_rendition(work_root, "bg_theatre", "paint", status="approved")
manifest = assets.load_manifest(work_root)
(msg,) = assets.check_style(work_root, manifest, "paint")
assert "1280x720" in msg
Image.new("RGB", assets.BG_SIZE).save(path)
assert assets.check_style(work_root, manifest, "paint") == []
def test_check_sprite_coverage_and_top_edge(work_root):
raw = work_root / "assets/raw/paint/sprite_poet_neutral.png"
final = work_root / "assets/sprites/paint/poet_neutral.webp"
final.parent.mkdir(parents=True)
Image.new("RGBA", (10, 10)).save(final)
set_rendition(
work_root,
"sprite_poet_neutral",
"paint",
status="approved",
raw_file="raw/paint/sprite_poet_neutral.png",
)
manifest = assets.load_manifest(work_root)
green_sprite(raw, fill=0.4) # 500x1200 block of 1000x1500 = 40%
assert assets.check_style(work_root, manifest, "paint") == []
green_sprite(raw, fill=0.4, top=0)
(msg,) = assets.check_style(work_root, manifest, "paint")
assert "top edge" in msg
green_sprite(raw, fill=0.05) # 500x150 = 10%
(msg,) = assets.check_style(work_root, manifest, "paint")
assert "coverage" in msg
def test_check_variant_identical_to_reference(work_root):
for name in ("poet_neutral", "poet_indignant"):
path = work_root / f"assets/sprites/paint/{name}.webp"
path.parent.mkdir(parents=True, exist_ok=True)
img = Image.new("RGBA", (100, 100), (0, 0, 0, 0))
img.paste((10, 10, 10, 255), (20, 20, 80, 80))
img.save(path) # byte-identical files
for asset_id in ("sprite_poet_neutral", "sprite_poet_indignant"):
set_rendition(work_root, asset_id, "paint", status="approved")
manifest = assets.load_manifest(work_root)
(msg,) = assets.check_style(work_root, manifest, "paint")
assert "sprite_poet_indignant" in msg and "identical to its reference" in msg
# same asset under another style is not compared with the paint reference
assert assets.check_style(work_root, manifest, "ink") == []
assert cli.main(["--work", str(work_root), "assets", "check"]) == 1
def test_process_runs_checks_and_fails(work_root):
green_sprite(work_root / "assets/raw/paint/sprite_poet_neutral.png", top=0)
set_rendition(
work_root,
"sprite_poet_neutral",
"paint",
status="generated",
raw_file="raw/paint/sprite_poet_neutral.png",
)
assert cli.main(["--work", str(work_root), "assets", "process"]) == 1
def test_migrate_v1(tmp_path):
root = tmp_path / "w"
shutil.copytree(FIXTURES / "mini_work", root)
(root / "assets/bg").mkdir(parents=True)
(root / "assets/raw").mkdir()
(root / "assets/bg/theatre.webp").write_bytes(b"x")
(root / "assets/raw/bg_theatre.png").write_bytes(b"y")
old = {
"base_prompt": "B",
"templates": {"background": "b", "sprite": "s", "variant": "v"},
"assets": [
{
"id": "bg_theatre",
"kind": "background",
"prompt": "P",
"source": "chatgpt-web",
"generation_id": "g",
"reference": None,
"raw_file": "raw/bg_theatre.png",
"file": "bg/theatre.webp",
"sha256": "a" * 64,
"status": "approved",
"notes": "n",
}
],
}
(root / assets.MANIFEST).write_text(json.dumps(old), encoding="utf-8")
assert cli.main(["--work", str(root), "assets", "migrate", "paint", "--label", "Paint"]) == 0
manifest = assets.load_manifest(root)
assert manifest["default_style"] == "paint"
assert manifest["styles"]["paint"] == {
"label": "Paint",
"base_prompt": "B",
"templates": old["templates"],
}
rendition = manifest["assets"][0]["renditions"]["paint"]
assert (
rendition["file"] == "bg/paint/theatre.webp"
and rendition["raw_file"] == "raw/paint/bg_theatre.png"
)
assert rendition["status"] == "approved" and rendition["notes"] == "n"
assert (root / "assets/bg/paint/theatre.webp").read_bytes() == b"x"
assert (root / "assets/raw/paint/bg_theatre.png").read_bytes() == b"y"
assert not (root / "assets/bg/theatre.webp").exists()
with pytest.raises(ValueError, match="already v2"):
assets.migrate_v1(root, "paint")
# --- Ren'Py generation ------------------------------------------------------------------------
def gen(work_root, tmp_path, with_test=False):
work = load_work(work_root)
annotated = json.loads((FIXTURES / "annotated_mini.json").read_text(encoding="utf-8"))
out = tmp_path / "proj"
renpy_gen.generate(work, annotated, out, with_test=with_test)
return out
def approve(root, asset_id, style, size=(100, 100)):
manifest = assets.load_manifest(root)
asset = assets.find_asset(manifest, asset_id)
path = root / "assets" / assets.style_file(asset, style)
path.parent.mkdir(parents=True, exist_ok=True)
Image.new("RGBA", size, (5, 5, 5, 255)).save(path)
set_rendition(root, asset_id, style, status="approved")
def test_renpy_condition_switch_and_fallback(work_root, tmp_path):
approve(work_root, "bg_theatre", "paint")
approve(work_root, "bg_theatre", "ink")
approve(work_root, "sprite_poet_neutral", "paint") # only the default style
approve(work_root, "sprite_poet_indignant", "ink") # only a non-default style
out = gen(work_root, tmp_path)
images = (out / "game/images.rpy").read_text(encoding="utf-8")
assert (
"image bg theatre = ConditionSwitch(\"persistent.art_style == 'ink'\", "
'"images/bg/ink/theatre.webp", "True", "images/bg/paint/theatre.webp")'
) in images
assert 'image poet neutral = "images/sprites/paint/poet_neutral.webp"' in images
# ink-only rendition: the default style still needs a (placeholder) fallback file
assert "images/sprites/ink/poet_indignant.webp" in images
assert (
'ConditionSwitch("persistent.art_style == \'ink\'", "images/sprites/ink/poet_indignant'
in images
)
assert (out / "game/images/sprites/paint/poet_indignant.webp").is_file()
assert (out / "game/images/bg/ink/theatre.webp").is_file()
styles = (out / "game/styles.rpy").read_text(encoding="utf-8")
assert 'default persistent.art_style = "paint"' in styles
assert "define vn_art_styles = [('paint', 'Paint'), ('ink', 'Ink')]" in styles
assert "@@" not in styles
assert "call vn_pick_art_style" in (out / "game/script.rpy").read_text(encoding="utf-8")
screens = (out / "game/screens.rpy").read_text(encoding="utf-8")
assert "Estilo visual" in screens and 'SetField(persistent, "art_style", style_id)' in screens
def test_renpy_no_anime_renditions_is_plain_default(work_root, tmp_path):
approve(work_root, "bg_theatre", "paint")
set_rendition(work_root, "bg_theatre", "ink", status="generated") # not approved: ignored
out = gen(work_root, tmp_path)
images = (out / "game/images.rpy").read_text(encoding="utf-8")
assert 'image bg theatre = "images/bg/paint/theatre.webp"' in images
assert "ConditionSwitch" not in images
assert not (out / "game/images/bg/ink").exists()
def test_e2e_picks_last_style(work_root, tmp_path):
out = gen(work_root, tmp_path, with_test=True)
text = (out / "game/e2e_test.rpy").read_text(encoding="utf-8")
assert 'click "Ink"' in text and 'assert screen "vn_art_style_picker"' in text
assert "@@" not in text
@pytest.mark.skipif(not test_renpy_gen.SDK.exists(), reason="Ren'Py SDK not found (set RENPY_SDK)")
def test_two_style_project_lints_and_plays(work_root, tmp_path):
"""Picker, preferences and ConditionSwitch images in a real Ren'Py run."""
approve(work_root, "bg_theatre", "paint")
approve(work_root, "bg_theatre", "ink")
out = gen(work_root, tmp_path, with_test=True)
home = tmp_path / "home"
home.mkdir()
env = {**os.environ, "HOME": str(home)}
lint = subprocess.run(
[str(test_renpy_gen.SDK), str(out), "lint"], capture_output=True, text=True, env=env
)
report = lint.stdout + lint.stderr
assert lint.returncode == 0 and "error" not in report.lower(), report
test_renpy_gen.run_e2e(out, home)