290 lines
14 KiB
Python
290 lines
14 KiB
Python
#!/usr/bin/env python3
|
|
"""Card-local transfer of Ezekiel's gated-contrast finish-mask treatment to Ruth.
|
|
|
|
'trial' writes review outputs only. 'install' first rebuilds the trial, preserves
|
|
all raw-ridges masks and validation, then changes only the twelve finish maps.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
from pathlib import Path
|
|
import hashlib
|
|
import json
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
|
|
import numpy as np
|
|
from PIL import Image, ImageDraw, ImageFilter, ImageFont
|
|
|
|
HERE = Path(__file__).resolve().parent
|
|
REVISION = HERE.parents[1]
|
|
REPO = next(p for p in HERE.parents if (p / "docs/card-layer-pipeline.md").is_file())
|
|
sys.path.insert(0, str(REPO / "tools/card-production"))
|
|
sys.path.insert(0, str(REPO / "artifacts/layers"))
|
|
from card_workspace import refresh
|
|
from finish_masks import extract_raw_ridges, prepare_illustration, RECIPE_SHA256
|
|
from library import load_tier
|
|
|
|
ART = REVISION / "source/art-master-candidate-03.png"
|
|
TEXT = REVISION / "source/text/text-2000.png"
|
|
VALIDATION = REVISION / "review/build-validation.json"
|
|
CARD = REVISION / "card.json"
|
|
RECIPE = HERE / "recipe.json"
|
|
SELECTED = HERE / "selected"
|
|
BASELINE = HERE / "baseline"
|
|
WIDTHS = {"high": 2000, "med": 1000, "low": 500}
|
|
COMPONENTS = {
|
|
"normal": "overlay-normal",
|
|
"borderless": "backing-borderless",
|
|
"textless": "frame-textless",
|
|
"boundless": None,
|
|
}
|
|
|
|
|
|
def digest(path: Path) -> str:
|
|
return hashlib.sha256(path.read_bytes()).hexdigest()
|
|
|
|
|
|
def save_json(path: Path, value: object) -> None:
|
|
path.write_text(json.dumps(value, indent=2, ensure_ascii=False) + "\n")
|
|
|
|
|
|
def smooth(lo: float, hi: float, values: np.ndarray) -> np.ndarray:
|
|
fraction = np.clip((values - lo) / (hi - lo), 0.0, 1.0)
|
|
return fraction * fraction * (3.0 - 2.0 * fraction)
|
|
|
|
|
|
def alpha(path: Path) -> np.ndarray:
|
|
image = Image.open(path).convert("RGBA")
|
|
assert image.size == (2000, 2800), path
|
|
return np.asarray(image.getchannel("A"), dtype=np.float32) / 255.0
|
|
|
|
|
|
def grayscale_rgba(gray: Image.Image, path: Path) -> None:
|
|
result = gray.convert("RGBA")
|
|
result.putalpha(255)
|
|
result.save(path)
|
|
|
|
|
|
def build_trial() -> dict:
|
|
config = json.loads(RECIPE.read_text())
|
|
card = json.loads(CARD.read_text())
|
|
manifest = json.loads((REVISION / "manifest.json").read_text())
|
|
assert card["cardId"] == "BP-022" and card["selectedArtCandidate"] == "candidate-03"
|
|
assert manifest["stage"] == "assembly-review"
|
|
assert card["artSHA256"] == digest(ART)
|
|
assert config["id"] == "ruth-gated-contrast-trial-v1"
|
|
assert (2000, 2800) == Image.open(ART).size
|
|
for path in (TEXT, VALIDATION, RECIPE):
|
|
assert path.is_file(), path
|
|
|
|
baseline_report = json.loads(VALIDATION.read_text())
|
|
if baseline_report["finishRecipe"]["id"] != "raw-ridges-v1":
|
|
backup = BASELINE / "build-validation-raw-ridges.json"
|
|
assert backup.is_file(), "An installed contrast build needs its preserved raw baseline"
|
|
baseline_report = json.loads(backup.read_text())
|
|
assert baseline_report["inputs"]["art"]["sha256"] == card["artSHA256"]
|
|
|
|
shared = load_tier("uncommon", "v3")
|
|
art = Image.open(ART).convert("RGBA")
|
|
assert art.getchannel("A").getextrema() == (255, 255)
|
|
filtered_path = HERE / "filtered-art.png"
|
|
subprocess.run(["convert", str(ART), "-kuwahara", config["preprocess"]["imageMagickKuwahara"], str(filtered_path)], check=True)
|
|
filtered = Image.open(filtered_path).convert("RGB")
|
|
assert filtered.size == (2000, 2800)
|
|
smoothed_raw = extract_raw_ridges(filtered)
|
|
Image.fromarray(smoothed_raw).save(HERE / "smoothed-ridges-2000.png")
|
|
|
|
canny_path = HERE / "canny-edges-2000.png"
|
|
subprocess.run(["convert", str(filtered_path), "-colorspace", "Gray", "-canny", config["preprocess"]["canny"], str(canny_path)], check=True)
|
|
gray_image = Image.open(filtered_path).convert("L")
|
|
gray = np.asarray(gray_image, dtype=np.float32) / 255.0
|
|
edge = np.asarray(Image.open(canny_path).convert("L").filter(ImageFilter.MaxFilter(config["edgeDilation"])), dtype=np.float32) / 255.0
|
|
local_max = np.asarray(gray_image.filter(ImageFilter.MaxFilter(config["localMaxSize"])), dtype=np.float32) / 255.0
|
|
darkness = 1.0 - smooth(*config["darknessSmoothstep"], gray)
|
|
contrast = smooth(*config["contrastSmoothstep"], local_max - gray)
|
|
ridge_confidence = np.maximum(config["smoothedRawRidgeWeight"] * smoothed_raw.astype(np.float32) / 255.0,
|
|
config["gatedEdgeWeight"] * edge * darkness * contrast)
|
|
ridge_confidence = np.clip(ridge_confidence, 0.0, 1.0)
|
|
ridge_path = HERE / "gated-contrast-ridges-2000.png"
|
|
Image.fromarray(np.rint(ridge_confidence * 255).astype(np.uint8)).save(ridge_path)
|
|
ridges = np.asarray(Image.open(ridge_path).convert("L"), dtype=np.float32) / 255.0
|
|
|
|
illustration = prepare_illustration(art)
|
|
text_alpha = alpha(TEXT)
|
|
SELECTED.mkdir(exist_ok=True)
|
|
printings = {}
|
|
for printing, component in COMPONENTS.items():
|
|
overlay_path = shared["assets"][component] if component else None
|
|
overlay_alpha = alpha(overlay_path) if overlay_path else 0.0
|
|
active_text = text_alpha if printing in ("normal", "borderless") else 0.0
|
|
active = 1.0 - (1.0 - overlay_alpha) * (1.0 - active_text)
|
|
coverage = np.rint(illustration.pane_weights * (1.0 - ridges) * (1.0 - active) * 255).astype(np.uint8)
|
|
assert coverage.shape == (2800, 2000)
|
|
if overlay_path is not None:
|
|
assert np.all(coverage[overlay_alpha == 1] == 0), printing
|
|
if isinstance(active_text, np.ndarray):
|
|
assert np.all(coverage[active_text == 1] == 0), printing
|
|
master = Image.fromarray(coverage)
|
|
files = {}
|
|
for label, width in WIDTHS.items():
|
|
image = master if width == 2000 else master.resize((width, width * 7 // 5), Image.Resampling.BILINEAR)
|
|
path = SELECTED / f"{printing}-{width}-finish-mask.png"
|
|
grayscale_rgba(image, path)
|
|
actual = np.asarray(Image.open(path).convert("RGBA"))
|
|
assert actual.shape == (width * 7 // 5, width, 4)
|
|
assert np.array_equal(actual[:, :, 0], actual[:, :, 1])
|
|
assert np.array_equal(actual[:, :, 1], actual[:, :, 2])
|
|
assert np.all(actual[:, :, 3] == 255)
|
|
files[label] = {"path": str(path.relative_to(REVISION)), "sha256": digest(path), "dimensions": [width, width * 7 // 5]}
|
|
printings[printing] = {
|
|
"component": component,
|
|
"overlay": str(overlay_path.relative_to(REPO)) if overlay_path else None,
|
|
"usesText": isinstance(active_text, np.ndarray),
|
|
"meanMasterCoverage": round(float(coverage.mean()) / 255.0, 5),
|
|
"files": files,
|
|
}
|
|
|
|
art_view = art.convert("RGB").resize((500, 700), Image.Resampling.LANCZOS)
|
|
raw_view = Image.open(REVISION / "low/normal/finish-mask.png").convert("RGB")
|
|
if json.loads(VALIDATION.read_text())["finishRecipe"]["id"] != "raw-ridges-v1":
|
|
raw_view = Image.open(BASELINE / "normal-500-raw-ridges-finish-mask.png").convert("RGB")
|
|
selected_view = Image.open(SELECTED / "normal-500-finish-mask.png").convert("RGB")
|
|
board = Image.new("RGB", (1520, 750), "#11161c")
|
|
draw = ImageDraw.Draw(board)
|
|
font = ImageFont.truetype(str(REPO / "fonts/P052-Bold.otf"), 23)
|
|
for index, (label, view) in enumerate((("Artwork", art_view), ("Raw-ridges", raw_view), ("Gated contrast", selected_view))):
|
|
x = 10 + index * 505
|
|
draw.text((x + 6, 8), label, fill="#f4ead4", font=font)
|
|
board.paste(view, (x, 40))
|
|
board.save(HERE / "comparison-500.png")
|
|
|
|
unchanged = {}
|
|
for printing in COMPONENTS:
|
|
unchanged[printing] = {}
|
|
for label in WIDTHS:
|
|
unchanged[printing][label] = {
|
|
item: digest(REVISION / label / printing / item)
|
|
for item in ("card.png", "text-mask.png")
|
|
}
|
|
report = {
|
|
"status": "structural checks passed; card-local trial; not installed",
|
|
"method": "Ezekiel gated-contrast parameters transferred unchanged to Ruth",
|
|
"cardId": "BP-022",
|
|
"artSHA256": card["artSHA256"],
|
|
"textSHA256": digest(TEXT),
|
|
"sharedLayerManifestSHA256": shared["manifestSHA256"],
|
|
"sourceRecipe": config["source"],
|
|
"sourceRecipeSHA256": digest(REPO / config["source"]),
|
|
"recipeSHA256": digest(RECIPE),
|
|
"approvedBasePaneRecipeSHA256": RECIPE_SHA256,
|
|
"filteredArtSHA256": digest(filtered_path),
|
|
"smoothedRidgeSHA256": digest(HERE / "smoothed-ridges-2000.png"),
|
|
"cannySHA256": digest(canny_path),
|
|
"contrastRidgeSHA256": digest(ridge_path),
|
|
"printings": printings,
|
|
"unchangedCardAndTextMaskSHA256": unchanged,
|
|
"comparison": "review/finish-mask-trial-01/comparison-500.png",
|
|
"movingLightReview": "not performed",
|
|
"installed": False,
|
|
}
|
|
save_json(HERE / "trial-validation.json", report)
|
|
return report
|
|
|
|
|
|
def install() -> None:
|
|
trial = build_trial()
|
|
card = json.loads(CARD.read_text())
|
|
report = json.loads(VALIDATION.read_text())
|
|
if report["finishRecipe"]["id"] == "ruth-gated-contrast-trial-v1":
|
|
for printing in COMPONENTS:
|
|
for label, width in WIDTHS.items():
|
|
target = REVISION / label / printing / "finish-mask.png"
|
|
assert digest(target) == trial["printings"][printing]["files"][label]["sha256"]
|
|
print("BP-022 v01: gated-contrast finish maps already installed.")
|
|
return
|
|
assert report["status"] == "passed" and report["finishRecipe"]["id"] == "raw-ridges-v1"
|
|
assert report["inputs"]["art"]["sha256"] == card["artSHA256"]
|
|
BASELINE.mkdir(exist_ok=True)
|
|
backup_report = BASELINE / "build-validation-raw-ridges.json"
|
|
if backup_report.exists():
|
|
old = json.loads(backup_report.read_text())
|
|
assert old["finishRecipe"]["id"] == "raw-ridges-v1"
|
|
assert old["inputs"]["art"]["sha256"] == card["artSHA256"]
|
|
else:
|
|
shutil.copyfile(VALIDATION, backup_report)
|
|
|
|
changes = {}
|
|
for printing in COMPONENTS:
|
|
changes[printing] = {}
|
|
for export in report["printings"][printing]["exports"]:
|
|
label = export["resolution"]
|
|
width = WIDTHS[label]
|
|
target = REVISION / label / printing / "finish-mask.png"
|
|
source = SELECTED / f"{printing}-{width}-finish-mask.png"
|
|
assert digest(target) == export["files"]["finish-mask.png"]
|
|
assert digest(source) == trial["printings"][printing]["files"][label]["sha256"]
|
|
backup = BASELINE / f"{printing}-{width}-raw-ridges-finish-mask.png"
|
|
if backup.exists():
|
|
assert digest(backup) == digest(target)
|
|
else:
|
|
shutil.copyfile(target, backup)
|
|
old_sha = digest(target)
|
|
shutil.copyfile(source, target)
|
|
new_sha = digest(target)
|
|
assert new_sha == digest(source)
|
|
export["files"]["finish-mask.png"] = new_sha
|
|
changes[printing][label] = {"width": width, "baselineSHA256": old_sha, "selectedSHA256": new_sha}
|
|
for unchanged in ("card.png", "text-mask.png"):
|
|
assert digest(REVISION / label / printing / unchanged) == export["files"][unchanged]
|
|
|
|
previous_recipe = report["finishRecipe"]
|
|
report["finishRecipe"] = {
|
|
"id": "ruth-gated-contrast-trial-v1",
|
|
"status": "user-requested card-local working assembly treatment; final card and moving-light approval pending",
|
|
"userDirection": "Can we do the contrast mask that we did for Ezekiel?",
|
|
"trialRecipe": "review/finish-mask-trial-01/recipe.json",
|
|
"trialRecipeSHA256": digest(RECIPE),
|
|
"ridgeMap": "review/finish-mask-trial-01/gated-contrast-ridges-2000.png",
|
|
"ridgeMapSHA256": digest(HERE / "gated-contrast-ridges-2000.png"),
|
|
"trialBuilderSHA256": digest(Path(__file__)),
|
|
"sourceEzekielRecipeSHA256": trial["sourceRecipeSHA256"],
|
|
"basePaneRecipe": previous_recipe,
|
|
"baselineBuildValidation": "review/finish-mask-trial-01/baseline/build-validation-raw-ridges.json",
|
|
}
|
|
card["finishMaskSelection"] = {
|
|
"id": "ruth-gated-contrast-trial-v1",
|
|
"by": "user",
|
|
"note": "Can we do the contrast mask that we did for Ezekiel?",
|
|
"status": "working assembly trial; final visual approval pending",
|
|
"recipe": "review/finish-mask-trial-01/recipe.json",
|
|
}
|
|
save_json(CARD, card)
|
|
report["inputs"]["cardSHA256"] = digest(CARD)
|
|
report["visualReview"] = {"static": "contrast-mask trial installed; static review pending", "movingLight": "not performed"}
|
|
report["finishMaskSelection"] = {"status": "working assembly trial installed", "changes": changes}
|
|
save_json(VALIDATION, report)
|
|
save_json(HERE / "installation.json", {
|
|
"status": "installed for BP-022 v01 working assembly; final card approval pending",
|
|
"userDirection": card["finishMaskSelection"]["note"],
|
|
"artSHA256": card["artSHA256"],
|
|
"baselineValidationSHA256": digest(backup_report),
|
|
"trialValidationSHA256": digest(HERE / "trial-validation.json"),
|
|
"changes": changes,
|
|
"cardFacesAndTextMasks": "unchanged and hash-verified",
|
|
"movingLightReview": "not performed",
|
|
})
|
|
refresh(REVISION)
|
|
print("BP-022 v01: gated-contrast finish maps installed for twelve working exports; faces and text masks unchanged.")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
if len(sys.argv) != 2 or sys.argv[1] not in ("trial", "install"):
|
|
raise SystemExit("usage: contrast_mask.py trial|install")
|
|
if sys.argv[1] == "trial":
|
|
build_trial()
|
|
print("BP-022 v01: card-local gated-contrast trial built; production finish maps unchanged.")
|
|
else:
|
|
install()
|
|
|