#!/usr/bin/env python3 """Assemble Elisha Common v01 with pinned shared layers and raw-ridge finish.""" 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 ( # noqa: E402 RECIPE_PATH, RECIPE_SHA256, compile_finish, prepare_illustration, ) 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 revision.") check(card["cardId"] == "BP-028" and card["tier"] == "common", "Wrong Elisha card or tier.") check(card.get("artApproval") and card.get("assemblyAuthorization"), "Artwork and assembly authorization required.") check(card["selectedArtCandidate"] == "candidate-04", "Artwork selection changed.") check(card["translation"] == "NKJV" and card["reference"] == "2 Kings 6:16", "Scripture selection changed.") check(" ".join(card["verseLines"]) == card["excerpt"] and len(card["verseLines"]) == 2, "Two-line direct speech changed.") check(card["referenceDisplay"] == f'{card["reference"]} • {card["translation"]}', "Reference display changed.") check(card["finishMaskSelection"]["id"] == "raw-ridges-v1", "Finish recipe changed.") shared = load_tier(card["tier"], card["layerVersion"]) layout, assets = shared["layout"], shared["assets"] 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 name, record in font_manifest["files"].items(): check(digest(fonts / name) == record["sha256"], f"Shared font changed: {name}") 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'{fonts}{review / "font-cache"}') 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(src, dst): ink(src, "--export-type=png", f"--export-filename={dst}", "--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), "Art must be opaque 2000x2800.") check(digest(art_path) == card["artSHA256"], "Selected art hash changed.") sizes = dict(layout["fontSizes"]) check(sizes["title"] == card["titleFontSize"], "Pinned title font size changed.") baselines = layout["baselines"]["verseByLineCount"][str(len(card["verseLines"]))] rows = [{"id": "title", "role": "title", "text": card["name"].upper(), "baseline": layout["baselines"]["title"]}] 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}") ranges = [(int(part.split("-")[0], 16), int(part.split("-")[-1], 16)) for part in subprocess.check_output(["fc-query", "--format=%{charset}", str(font)], text=True).split()] check(all(any(lo <= ord(c) <= hi for lo, hi in ranges) for row in rows if row["role"] == role for c 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) text = Image.open(text_png).convert("RGBA") text_alpha = np.asarray(text.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: src = text_dir / (row["id"] + "-unclipped.svg") dst = src.with_suffix(".png") document([row], sizes, faces).write(src, encoding="unicode") render(src, dst) bounds = Image.open(dst).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"]] rb = glyphs[-1]["unclippedInkBounds"] check(rb[1] >= reference_box[0] and rb[3] <= reference_box[1], "Reference escapes font-metric box.") protected = text.getchannel("A").filter(ImageFilter.MaxFilter(25)).filter(ImageFilter.GaussianBlur(8)) protection_min = int(np.min(np.asarray(protected)[text_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 flourishes."}) 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.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(value.relative_to(REPO)), "sha256": digest(value)} for key, value in assets.items()}}, "sharedFontManifestSHA256": digest(fonts / "manifest.json"), "typography": {"fonts": font_checks, "glyphs": glyphs, "fontMetrics": metrics, "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 kind in ("normal", "borderless"): backing = np.asarray(Image.open(assets["backing-" + kind]).convert("RGBA")) ratio = float(np.min(contrast([38, 63, 80], backing[:, :, :3][text_alpha >= 128]))) check(ratio >= 7, f"Text/backing contrast below 7:1: {kind}") report["textContrast"][kind] = 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: 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"))[text_alpha > 0] == 255), "Glyphs outside backing.") face = Image.alpha_composite(face, text) 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, text if has_text else None) if overlay: 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 name, 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 / name) exports.append({"resolution": label, "dimensions": list(dimensions), "files": {name: digest(folder / name) for name in ("card.png", "finish-mask.png", "text-mask.png")}}) editable = ROOT / "high" / printing / "card.svg" def link(path): return f'' text_body = ET.tostring(document(rows, sizes, faces).getroot()[0], encoding="unicode") if has_text else "" editable.write_text('' + link(art_path) + (link(assets[key]) if key else "") + text_body + "") 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-028 v01: Common four-printing assembly and structural checks passed; final approval pending.") if __name__ == "__main__": main()