Files

142 lines
6.1 KiB
Python

#!/usr/bin/env python3
"""Card-local cleanup of texture falsely classified as lead on Mary's red cloak."""
from pathlib import Path
import hashlib
import json
import sys
import numpy as np
from PIL import Image, ImageDraw, ImageFilter
ROOT = Path(__file__).resolve().parent
REPO = next(p for p in ROOT.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 finish_masks import IllustrationCoverage, compile_finish
from gated_contrast import prepare_gated_illustration
from library import load_tier
from card_workspace import refresh, update_index
LOW_RIDGE = 64
HIGH_RIDGE = 176
def digest(path):
return hashlib.sha256(Path(path).read_bytes()).hexdigest()
def cloak_region(art):
"""Select red cloak panes, not skin, hair, olive cloth, or the red-brown jar."""
rgb = np.asarray(art.convert("RGB"), dtype=np.float32)
red, green, blue = rgb[:, :, 0], rgb[:, :, 1], rgb[:, :, 2]
y, x = np.indices(red.shape)
seed = (
(x > 300) & (x < 1570) & (y > 750)
& (red > 58) & (red > green * 1.35) & (red > blue * 1.20)
& (blue >= green * 0.82)
)
# A narrow expansion crosses the lead at pane edges while remaining local.
region = Image.fromarray(seed.astype(np.uint8) * 255)
region = region.filter(ImageFilter.MaxFilter(17)).filter(ImageFilter.GaussianBlur(3))
return np.asarray(region, dtype=np.float32) / 255.
def correct(root=ROOT):
root = Path(root)
card = json.loads((root / "card.json").read_text())
art = Image.open(REPO / card["art"]).convert("RGBA")
analysis = prepare_gated_illustration(art)
original = analysis.raw_ridges
region = cloak_region(art)
# True bold pane seams retain their original response. Weak painterly
# ridges inside the red glass panes are attenuated, not thresholded globally.
t = np.clip((original.astype(np.float32) - LOW_RIDGE)
/ (HIGH_RIDGE - LOW_RIDGE), 0., 1.)
keep = t * t * (3. - 2. * t)
corrected = np.rint(original * (1. - region * (1. - keep))).astype(np.uint8)
corrected_analysis = IllustrationCoverage(
analysis.pane_weights, corrected, analysis.recipe_id)
source = root / "source"
review = root / "review"
region_path = source / "cloak-finish-correction-region.png"
ridge_path = source / "gated-contrast-ridges-cloak-corrected.png"
Image.fromarray(np.rint(region * 255).astype(np.uint8)).save(region_path)
Image.fromarray(corrected).save(ridge_path)
shared = load_tier(card["tier"], card["layerVersion"])
text = Image.open(source / "text/text-2000.png").convert("RGBA")
report_path = review / "build-validation.json"
report = json.loads(report_path.read_text())
if "cardLocalCorrection" in report["finishRecipe"]:
raise ValueError("Build the shared base masks before applying this local correction")
changed = {}
originals = {}
for printing, key, has_text in (
("normal", "overlay-normal", True),
("boundless", None, False),
("borderless", "backing-borderless", True),
("textless", "frame-textless", False),
):
overlay = Image.open(shared["assets"][key]).convert("RGBA") if key else None
existing = np.asarray(Image.open(root / "high" / printing / "finish-mask.png").convert("L"))
finish = compile_finish(corrected_analysis, printing, overlay,
text if has_text else None)
updated = np.asarray(finish)
count = int(np.count_nonzero(existing != updated))
outside = int(np.count_nonzero((existing != updated) & (region == 0)))
if outside:
raise ValueError(f"{printing}: finish changed outside the cloak region")
changed[printing] = count
if printing == "normal":
originals["normal"] = Image.fromarray(existing)
originals["normal"].convert("RGBA").save(
review / "finish-mask-before-cloak-correction.png")
for label, width in (("low", 500), ("med", 1000), ("high", 2000)):
path = root / label / printing / "finish-mask.png"
export = finish if width == 2000 else finish.resize(
(width, width * 7 // 5), Image.Resampling.BILINEAR)
rgba = export.convert("RGBA")
rgba.putalpha(255)
rgba.save(path)
item = next(x for x in report["printings"][printing]["exports"]
if x["resolution"] == label)
item["files"]["finish-mask.png"] = digest(path)
crop = (350, 600, 1650, 2100)
preview = Image.new("RGB", (900, 570), "#11161c")
draw = ImageDraw.Draw(preview)
for i, (name, picture) in enumerate((
("Before", originals["normal"]), ("Cloak-corrected", Image.fromarray(
np.asarray(Image.open(root / "high/normal/finish-mask.png").convert("L"))))
)):
draw.text((i * 450 + 10, 8), name, fill="white")
view = picture.crop(crop).resize((430, 500), Image.Resampling.LANCZOS)
preview.paste(view.convert("RGB"), (i * 450 + 10, 42))
preview.save(review / "cloak-finish-before-after.png")
report["finishRecipe"]["cardLocalCorrection"] = {
"id": "mary-red-cloak-texture-cleanup-v1",
"scope": "Mary's red cloak panes only; no shared-recipe or face-art change",
"method": "Red-pane color selection with 8 px expansion and 3 px feather; "
"attenuate ridge confidence below 176/255 using smoothstep from 64/255",
"script": str(Path(__file__).relative_to(REPO)),
"scriptSHA256": digest(__file__),
"region": str(region_path.relative_to(REPO)),
"regionSHA256": digest(region_path),
"correctedRidge": str(ridge_path.relative_to(REPO)),
"correctedRidgeSHA256": digest(ridge_path),
"changedMasterPixelsByPrinting": changed,
"outsideRegionChangedPixels": 0,
}
report["visualReview"]["static"] = "pending inspection of cloak correction"
report_path.write_text(json.dumps(report, indent=2) + "\n")
refresh(root)
update_index()
print("Card-local cloak finish correction applied:", changed)
if __name__ == "__main__":
correct()