#!/usr/bin/env python3 """Rebuild only finish masks in a successor card revision.""" from __future__ import annotations import copy import json import os from pathlib import Path import sys import xml.etree.ElementTree as ET import numpy as np from PIL import Image REPO = next(p for p in Path(__file__).resolve().parents if (p / "docs/card-layer-pipeline.md").is_file()) sys.path.insert(0, str(REPO / "artifacts/layers")) from library import load_tier, digest from card_workspace import refresh, update_index from finish_masks import (RECIPE_PATH, RECIPE_SHA256, compile_finish, prepare_illustration) PRINTINGS = ( ("normal", "overlay-normal", True), ("boundless", None, False), ("borderless", "backing-borderless", True), ("textless", "frame-textless", False), ) SIZES = (("low", 500), ("med", 1000), ("high", 2000)) USER_DIRECTION = ("Yeah. Let's restore raw ridges, then go back and fix esther, " "mary, ezekiel. Just the finish mask needs to be changed. " "and we can move it straight to the finished artifact") def read(path: Path) -> dict: return json.loads(path.read_text()) def write(path: Path, value: dict) -> None: path.write_text(json.dumps(value, indent=2) + "\n") def baseline_from_report(report: dict) -> dict: preserved = {} for printing in report["printings"]: preserved[printing] = {} for item in report["printings"][printing]["exports"]: preserved[printing][item["resolution"]] = { name: item["files"][name] for name in ("card.png", "text-mask.png") } return { "sourceRevision": report["revision"], "sourceFinishRecipe": copy.deepcopy(report["finishRecipe"]), "unchangedExportHashes": preserved, } def check_preserved_exports(root: Path, baseline: dict) -> None: for printing, sizes in baseline["unchangedExportHashes"].items(): for label, files in sizes.items(): for filename, expected in files.items(): path = root / label / printing / filename if digest(path) != expected: raise ValueError(f"Non-finish export changed: {path}") def rebase_editable_links(root: Path, card_folder: str) -> None: """Keep copied v01 SVG inputs valid at the deeper working-revision path.""" accepted = REPO / "artifacts/cards" / card_folder for path in root.rglob("*.svg"): original = accepted / path.relative_to(root) if not original.is_file(): continue original_tree = ET.parse(original) tree = ET.parse(path) old_nodes = list(original_tree.getroot().iter()) new_nodes = list(tree.getroot().iter()) if len(old_nodes) != len(new_nodes): raise ValueError(f"Editable SVG structure changed: {path}") changed = False for old, new in zip(old_nodes, new_nodes): for attr in ("href", "{http://www.w3.org/1999/xlink}href"): value = old.get(attr) if not value or value.startswith(("data:", "#")): continue target = (original.parent / value).resolve() if target.is_relative_to(accepted): target = root / target.relative_to(accepted) relative = os.path.relpath(target, path.parent) if new.get(attr) != relative: new.set(attr, relative) changed = True if changed: ET.register_namespace("", "http://www.w3.org/2000/svg") ET.register_namespace("xlink", "http://www.w3.org/1999/xlink") tree.write(path, encoding="unicode") def rebuild(root: Path) -> None: root = Path(root).resolve() if not root.is_relative_to(REPO / "in-progress/cards"): raise ValueError("Finish-only rebuild requires a working revision") manifest_path = root / "manifest.json" report_path = root / "review/build-validation.json" card_path = root / "card.json" manifest = read(manifest_path) card = read(card_path) report = read(report_path) rebase_editable_links(root, card["folderName"]) baseline_path = root / "source/finish-only-baseline.json" if baseline_path.exists(): baseline = read(baseline_path) else: if report["revision"] == root.name: raise ValueError("No prior approved build report to establish a finish-only baseline") baseline = baseline_from_report(report) accepted = REPO / "artifacts/cards" / card["folderName"] / "manifest.json" if accepted.is_file() and read(accepted)["revision"] == baseline["sourceRevision"]: baseline["sourceApprovedManifestSHA256"] = digest(accepted) write(baseline_path, baseline) if baseline["sourceRevision"] == root.name: raise ValueError("A finish-only revision must advance the revision number") check_preserved_exports(root, baseline) art_path = root / "source" / Path(card["art"]).name if digest(art_path) != card["artSHA256"]: raise ValueError("Approved artwork changed") art = Image.open(art_path).convert("RGBA") if art.size != (2000, 2800) or art.getchannel("A").getextrema() != (255, 255): raise ValueError("Expected an opaque 2000 x 2800 approved art master") text = Image.open(root / "source/text/text-2000.png").convert("RGBA") shared = load_tier(card["tier"], card["layerVersion"]) analysis = prepare_illustration(art) raw_path = root / "source/raw-ridges.png" pane_path = root / "source/pane-coverage.png" Image.fromarray(analysis.raw_ridges).save(raw_path) Image.fromarray(np.rint(analysis.pane_weights * 255).astype(np.uint8)).save(pane_path) for printing, overlay_key, has_text in PRINTINGS: overlay = (Image.open(shared["assets"][overlay_key]).convert("RGBA") if overlay_key else None) finish = compile_finish(analysis, printing, overlay, text if has_text else None) if overlay is not None: opaque = np.asarray(overlay.getchannel("A")) == 255 if np.any(np.asarray(finish)[opaque] != 0): raise ValueError(f"{printing}: finish leaks onto an opaque overlay") for label, width in SIZES: output = root / label / printing / "finish-mask.png" resized = (finish if width == 2000 else finish.resize( (width, width * 7 // 5), Image.Resampling.BILINEAR)) rgba = resized.convert("RGBA") rgba.putalpha(255) rgba.save(output) export = next(item for item in report["printings"][printing]["exports"] if item["resolution"] == label) export["files"]["finish-mask.png"] = digest(output) old_selection = copy.deepcopy(card.get("finishMaskSelection")) card["art"] = str(art_path.relative_to(REPO)) card["finishMaskSelection"] = { "id": "raw-ridges-v1", "by": "user", "note": USER_DIRECTION, "source": f"finish-only {root.name} revision", } card["previousFinishMaskSelection"] = old_selection card.pop("finishMaskLocalCorrection", None) card["finishMaskChangeAuthorization"] = { "by": "user", "note": USER_DIRECTION, "scope": "Finish maps only; preserve all card faces, text masks, artwork, and shared layers.", } card["stage"] = "assembly-review" card["selectedRevision"] = root.name card["approval"] = None write(card_path, card) report["revision"] = root.name report["finalCardApproval"] = None report["inputs"]["art"] = {"path": card["art"], "sha256": digest(art_path)} report["inputs"]["cardSHA256"] = digest(card_path) report["inputs"]["builderSHA256"] = digest(Path(__file__)) report["finishRecipe"] = { "id": "raw-ridges-v1", "sha256": RECIPE_SHA256, "path": str(RECIPE_PATH.relative_to(REPO)), "moduleSHA256": digest(REPO / "tools/card-production/finish_masks.py"), "rawRidgeSHA256": digest(raw_path), "paneCoverageSHA256": digest(pane_path), "illustrationAnalyses": 1, } report["finishOnlyRevision"] = { "sourceRevision": baseline["sourceRevision"], "sourceApprovedManifestSHA256": baseline.get("sourceApprovedManifestSHA256"), "baseline": str(baseline_path.relative_to(REPO)), "baselineSHA256": digest(baseline_path), "unchangedCardFacesAndTextMasks": True, "changedAssets": "finish-mask.png for all four printings at low, med, and high", "userDirection": USER_DIRECTION, } report["tools"].pop("imageMagick", None) report["visualReview"] = {"static": "pending finish-map inspection", "movingLight": "not performed"} report["status"] = "passed" write(report_path, report) manifest["revision"] = root.name manifest["stage"] = "assembly-review" manifest["approval"] = None write(manifest_path, manifest) check_preserved_exports(root, baseline) refresh(root) update_index() print(f"{card['cardId']} {root.name}: twelve raw-ridge finish masks rebuilt; " "all card faces and text masks byte-identical to the approved baseline.") if __name__ == "__main__": if len(sys.argv) != 2: raise SystemExit("Usage: rebuild_finish_only.py WORKING_REVISION") rebuild(Path(sys.argv[1]))