Files
Sanctification/artifacts/cards/BP-033-jonathan/build.py

257 lines
15 KiB
Python

#!/usr/bin/env python3
"""Assemble Jonathan Common v01 from selected candidate 02 and pinned shared layers."""
from pathlib import Path
import json
import os
import subprocess
import sys
import xml.etree.ElementTree as ET
from xml.sax.saxutils import escape
import numpy as np
from PIL import Image, ImageDraw, ImageFilter, ImageFont
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 / "artifacts/layers"))
sys.path.insert(0, str(REPO / "tools/card-production"))
from library import digest, load_tier # noqa: E402
from assemble_card import check, contrast, document, metric_box, save # noqa: E402
from finish_masks import RECIPE_PATH, RECIPE_SHA256, compile_finish, prepare_illustration # noqa: E402
from card_workspace import refresh, update_index # noqa: E402
def main():
manifest = json.loads((ROOT / "manifest.json").read_text())
card = json.loads((ROOT / "card.json").read_text())
check(manifest["stage"] != "approved", "Approved card is frozen; create a new revision.")
check(card["cardId"] == "BP-033" and card["tier"] == "common", "Wrong card or tier.")
check(card.get("artApproval") and card.get("assemblyAuthorization"), "User art selection/assembly authorization missing.")
check(card["selectedArtCandidate"] == "candidate-02", "Art selection changed.")
check(card["reference"] == "1 Samuel 20:42" and card["translation"] == "NKJV", "Scripture reference changed.")
check(card["verseLines"] == [
"“The LORD be between you and me,",
"and between your descendants",
"and my descendants, forever.”",
], "User-supplied spoken excerpt changed.")
check(" ".join(card["verseLines"]) == card["excerpt"], "Excerpt and typeset lines diverge.")
check(card["referenceDisplay"] == "1 Samuel 20:42 • NKJV", "Reference display changed.")
check(card["finishMaskSelection"]["id"] == "raw-ridges-v1", "Finish recipe changed.")
shared = load_tier("common", card["layerVersion"])
layout, assets = shared["layout"], shared["assets"]
check(layout["canvas"] == [2000, 2800], "Shared layout canvas changed.")
sizes = dict(layout["fontSizes"])
check(sizes["title"] == card["titleFontSize"], "Title size changed.")
check(len(card["verseLines"]) <= layout["maximumVerseLines"], "Too many verse lines.")
fonts = REPO / "fonts"
font_manifest = json.loads((fonts / "manifest.json").read_text())
faces = {role: dict(font_manifest["productionTypography"][role]) for role in ("title", "verse", "reference")}
for role, face in faces.items():
face["family"] = "P052" if role == "title" else "Sanctification P052"
for filename, record in font_manifest["files"].items():
check(digest(fonts / filename) == record["sha256"], f"Shared font changed: {filename}")
review = ROOT / "review"
text_dir = ROOT / "source/text"
text_dir.mkdir(parents=True, exist_ok=True)
font_config = review / "fonts.conf"
font_config.write_text(f'<fontconfig><dir>{fonts}</dir><cachedir>{review / "font-cache"}</cachedir></fontconfig>')
env = dict(os.environ, FONTCONFIG_FILE=str(font_config))
def ink(*args):
return subprocess.check_output(["inkscape", *map(str, args)], env=env, text=True, stderr=subprocess.PIPE).strip()
def render(source, target):
ink(source, "--export-type=png", f"--export-filename={target}", "--export-width=2000", "--export-height=2800")
art_path = REPO / card["art"]
art = Image.open(art_path).convert("RGBA")
check(art.size == (2000, 2800) and art.getchannel("A").getextrema() == (255, 255),
"Selected art must be opaque 2000x2800.")
check(digest(art_path) == card["artSHA256"] == card["artApproval"]["artSHA256"],
"Selected art or approval hash changed.")
baselines = layout["baselines"]["verseByLineCount"][str(len(card["verseLines"]))]
rows = [{"id": "title", "role": "title", "text": card["name"].upper(),
"baseline": layout["baselines"]["title"] + card.get("titleOpticalShift", 0)}]
rows += [{"id": f"verse-{i}", "role": "verse", "text": line, "baseline": baseline}
for i, (line, baseline) in enumerate(zip(card["verseLines"], baselines))]
rows += [{"id": "reference", "role": "reference", "text": card["referenceDisplay"],
"baseline": layout["baselines"]["reference"]}]
font_checks = []
for role, face in faces.items():
font = fonts / face["file"]
style = "Bold" if role == "title" else "Medium"
matched = Path(subprocess.check_output(
["fc-match", "--format=%{file}", face["family"] + ":style=" + style], env=env, text=True
)).resolve()
check(matched == font.resolve(), f"Font fallback: {role}")
charset = subprocess.check_output(["fc-query", "--format=%{charset}", str(font)], text=True).split()
ranges = [(int(t.split("-")[0], 16), int(t.split("-")[-1], 16)) for t in charset]
check(all(any(lo <= ord(ch) <= hi for lo, hi in ranges)
for row in rows if row["role"] == role for ch in row["text"]), f"Missing glyph: {role}")
check(sizes[role] >= layout["fontMinimums"][role], f"Font below minimum: {role}")
font_checks.append({"role": role, "path": str(font.relative_to(REPO)), "sha256": digest(font),
"size": sizes[role], "weight": face["weight"],
"fallbackUsed": False, "missingGlyphs": []})
svg = text_dir / "text.svg"
document(rows, sizes, faces).write(svg, encoding="unicode")
text_png = text_dir / "text-2000.png"
render(svg, text_png)
lettering = Image.open(text_png).convert("RGBA")
lettering_alpha = np.asarray(lettering.getchannel("A"))
query = {parts[0]: list(map(float, parts[1:]))
for line in ink(svg, "--query-all").splitlines()
if len(parts := line.split(",")) == 5}
glyphs = []
for row in rows:
source = text_dir / (row["id"] + "-unclipped.svg")
target = source.with_suffix(".png")
document([row], sizes, faces).write(source, encoding="unicode")
render(source, target)
bounds = Image.open(target).getchannel("A").getbbox()
rx, ry, rw, rh = layout["textRegions"][row["role"]]
x, y, w, h = query[row["id"]]
check(bounds and rx <= bounds[0] and ry <= bounds[1]
and bounds[2] <= rx + rw and bounds[3] <= ry + rh,
f"Actual glyph overflow: {row['id']}")
check(rx <= x and ry <= y and x + w <= rx + rw and y + h <= ry + rh,
f"Text object overflow: {row['id']}")
glyphs.append({**row, "objectBounds": query[row["id"]],
"unclippedInkBounds": list(bounds),
"region": layout["textRegions"][row["role"]], "pass": True})
metrics = metric_box(fonts / faces["reference"]["file"], sizes["reference"])
reference_box = [rows[-1]["baseline"] - metrics["ascent"], rows[-1]["baseline"] + metrics["descent"]]
reference_ink = glyphs[-1]["unclippedInkBounds"]
check(reference_ink[1] >= reference_box[0] and reference_ink[3] <= reference_box[1],
"Reference escapes font metric box.")
protected = lettering.getchannel("A").filter(ImageFilter.MaxFilter(25)).filter(ImageFilter.GaussianBlur(8))
protection_min = int(np.min(np.asarray(protected)[lettering_alpha >= 128]))
check(protection_min >= 216, "Insufficient glyph protection.")
analysis = prepare_illustration(art)
Image.fromarray(analysis.raw_ridges).save(ROOT / "source/raw-ridges.png")
Image.fromarray(np.rint(analysis.pane_weights * 255).astype(np.uint8)).save(ROOT / "source/pane-coverage.png")
card.update({"verseBaselines": list(baselines), "titleBaselines": [rows[0]["baseline"]],
"referenceBaseline": rows[-1]["baseline"],
"typographyPolicy": "Common v2 pinned baselines and regions; no central flourish."})
save(ROOT / "card.json", card)
report = {
"status": "pending", "cardId": card["cardId"], "revision": manifest["revision"],
"artApproval": card["artApproval"], "finalCardApproval": None,
"inputs": {"art": {"path": card["art"], "sha256": digest(art_path)},
"fit": json.loads((ROOT / "source/art-provenance-candidate-02.json").read_text()),
"cardSHA256": digest(ROOT / "card.json"), "builderSHA256": digest(Path(__file__)),
"typographyHelperSHA256": digest(REPO / "tools/card-production/assemble_card.py")},
"sharedLayers": {"tier": "common", "version": shared["version"],
"manifestSHA256": shared["manifestSHA256"], "reviewStatus": shared["reviewStatus"],
"assets": {key: {"path": str(path.relative_to(REPO)), "sha256": digest(path)}
for key, path in assets.items()}},
"sharedFontManifestSHA256": digest(fonts / "manifest.json"),
"typography": {"fonts": font_checks, "glyphs": glyphs, "fontMetrics": metrics,
"titleOpticalShift": card.get("titleOpticalShift", 0),
"referenceLineBox": reference_box, "textLayerSHA256": digest(text_png),
"centeringPolicy": "Pinned Common v2 baselines; no central flourish."},
"textMask": {"expansionRadius": 12, "gaussianRadius": 8, "units": "master pixels",
"derivation": "Actual lettering alpha: MaxFilter(25), GaussianBlur(8)",
"minimumProtectionAtGlyphAlpha128": protection_min},
"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(ROOT / "source/raw-ridges.png"),
"paneCoverageSHA256": digest(ROOT / "source/pane-coverage.png"),
"illustrationAnalyses": 1},
"textContrast": {}, "tools": {"inkscape": ink("--version"),
"pillow": Image.__version__, "numpy": np.__version__},
"printings": {}, "visualReview": {"static": "pending", "movingLight": "not performed"},
}
for printing in ("normal", "borderless"):
backing = np.asarray(Image.open(assets["backing-" + printing]).convert("RGBA"))
ratio = float(np.min(contrast([38, 63, 80], backing[:, :, :3][lettering_alpha >= 128])))
check(ratio >= 7, f"Text/backing contrast below 7:1: {printing}")
report["textContrast"][printing] = round(ratio, 2)
specs = (("normal", "overlay-normal", True), ("boundless", None, False),
("borderless", "backing-borderless", True), ("textless", "frame-textless", False))
for printing, key, has_text in specs:
overlay = Image.open(assets[key]).convert("RGBA") if key else None
face = art.copy()
if overlay is not None:
check(overlay.size == art.size, "Overlay registration mismatch.")
face = Image.alpha_composite(face, overlay)
if printing in ("normal", "textless"):
corners = ((0, 0), (1999, 0), (0, 2799), (1999, 2799))
check(all(overlay.getpixel(xy)[3] == 255 for xy in corners),
"Framed corner transparency.")
if has_text:
check(np.all(np.asarray(overlay.getchannel("A"))[lettering_alpha > 0] == 255),
"Glyphs outside backing.")
face = Image.alpha_composite(face, lettering)
check(face.getchannel("A").getextrema() == (255, 255), "Transparent final face.")
if printing == "boundless":
check(np.array_equal(np.asarray(face), np.asarray(art)), "Boundless differs from source art.")
finish = compile_finish(analysis, printing, overlay, lettering if has_text else None)
if overlay is not None:
check(np.all(np.asarray(finish)[np.asarray(overlay.getchannel("A")) == 255] == 0),
"Finish leaks onto opaque overlay.")
text_mask = protected if has_text else Image.new("L", (2000, 2800), 0)
exports = []
for label, width in (("low", 500), ("med", 1000), ("high", 2000)):
folder = ROOT / label / printing
folder.mkdir(parents=True, exist_ok=True)
dimensions = (width, width * 7 // 5)
face.resize(dimensions, Image.Resampling.LANCZOS).save(folder / "card.png")
for filename, data in (("finish-mask.png", finish), ("text-mask.png", text_mask)):
reduced = data if width == 2000 else data.resize(dimensions, Image.Resampling.BILINEAR)
rgba = reduced.convert("RGBA")
rgba.putalpha(255)
rgba.save(folder / filename)
exports.append({"resolution": label, "dimensions": list(dimensions),
"files": {filename: digest(folder / filename)
for filename in ("card.png", "finish-mask.png", "text-mask.png")}})
editable = ROOT / "high" / printing / "card.svg"
def link(path):
return f'<image width="2000" height="2800" xlink:href="{escape(os.path.relpath(path, editable.parent))}"/>'
text_body = ET.tostring(document(rows, sizes, faces).getroot()[0], encoding="unicode") if has_text else ""
editable.write_text('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" '
'width="2000" height="2800" viewBox="0 0 2000 2800">'
+ link(art_path) + (link(assets[key]) if key else "") + text_body + "</svg>")
report["printings"][printing] = {"overlay": key, "text": has_text, "exports": exports}
save(ROOT / "source/typography-layout.json",
{"rows": rows, "fontSizes": sizes, "regions": layout["textRegions"],
"fontMetrics": metrics, "policy": card["typographyPolicy"]})
board_font = ImageFont.truetype(str(fonts / "P052-Bold.otf"), 22)
for filename, asset_name in (("printings-comparison.png", "card.png"),
("finish-masks-comparison.png", "finish-mask.png")):
board = Image.new("RGB", (1200, 480), "#11161c")
draw = ImageDraw.Draw(board)
for i, printing in enumerate(("normal", "boundless", "borderless", "textless")):
draw.text((i * 300 + 10, 8), printing.title(), font=board_font, fill="#f4ead4")
preview = Image.open(ROOT / "med" / printing / asset_name).convert("RGB")
board.paste(preview.resize((280, 392), Image.Resampling.LANCZOS), (i * 300 + 10, 50))
board.save(review / filename)
report["status"] = "passed"
save(review / "build-validation.json", report)
manifest["stage"] = "assembly-review"
save(ROOT / "manifest.json", manifest)
profile_path = ROOT.parents[1] / "card.json"
profile = json.loads(profile_path.read_text())
profile.update({"selectedRevision": manifest["revision"], "stage": "assembly-review", "approval": None})
save(profile_path, profile)
refresh(ROOT)
update_index()
print("BP-033 v01: Common four-printing assembly and structural checks passed; final approval pending.")
if __name__ == "__main__":
main()