#!/usr/bin/env python3
"""Assemble approved Cain and Abel candidate 02 using shared Common v2, without art edits.
Adapted from the accepted Mark Common builder; uses two semantic verse lines.
"""
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
from assemble_card import check, contrast, document, metric_box, save
from finish_masks import RECIPE_PATH, RECIPE_SHA256, compile_finish, prepare_illustration
from card_workspace import refresh, update_index
def main():
card = json.loads((ROOT / 'card.json').read_text())
manifest = json.loads((ROOT / 'manifest.json').read_text())
check(manifest['stage'] != 'approved', 'Approved cards are frozen.')
check(card['cardId'] == 'BP-048' and card['tier'] == 'common', 'Wrong identity/tier.')
check(card.get('artApproval') and card.get('assemblyAuthorization'), 'User authorization missing.')
check(card['selectedArtCandidate'] == 'candidate-02', 'Art selection changed.')
check(card['excerpt'] == card['verse'] == 'And the LORD respected Abel and his offering, but He did not respect Cain and his offering.', 'Verse changed.')
check(' '.join(card['verseLines']) == card['excerpt'], 'Verse line content mismatch.')
check(card['reference'] == 'Genesis 4:4–5' and card['translation'] == 'NKJV', 'Reference changed.')
check(card['referenceDisplay'] == 'Genesis 4:4–5 • NKJV', 'Reference display changed.')
check(card['finishMaskSelection']['id'] == 'raw-ridges-v1', 'Recipe changed.')
shared = load_tier('common', card['layerVersion'])
layout, assets = shared['layout'], shared['assets']
sizes = dict(layout['fontSizes'])
check(layout['canvas'] == [2000, 2800], 'Canvas changed.')
check(sizes['title'] == card['titleFontSize'], 'Title size changed.')
check(len(card['verseLines']) <= layout['maximumVerseLines'], 'Too many verse lines.')
fonts = REPO / 'fonts'
fm = json.loads((fonts / 'manifest.json').read_text())
faces = {r: dict(fm['productionTypography'][r]) for r in ('title', 'verse', 'reference')}
for role, face in faces.items():
face['family'] = 'P052' if role == 'title' else 'Sanctification P052'
for filename, record in fm['files'].items():
check(digest(fonts / filename) == record['sha256'], f'Shared font changed: {filename}')
review, textdir = ROOT / 'review', ROOT / 'source/text'
textdir.mkdir(parents=True, exist_ok=True)
config = review / 'fonts.conf'
config.write_text(f'{fonts}{review / "font-cache"}')
env = dict(os.environ, FONTCONFIG_FILE=str(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')
artpath = REPO / card['art']
check(digest(artpath) == card['artSHA256'] == card['artApproval']['artSHA256'], 'Approved art hash changed.')
fit = json.loads((ROOT / 'source/art-provenance-candidate-02.json').read_text())
check(digest(ROOT / fit['native']) == fit['nativeSHA256'], 'Native source changed.')
check(digest(artpath) == fit['masterSHA256'], 'Fit source mismatch.')
art = Image.open(artpath).convert('RGBA')
check(art.size == (2000, 2800) and art.getchannel('A').getextrema() == (255, 255), 'Art registration/opacity failed.')
baselines = layout['baselines']['verseByLineCount'][str(len(card['verseLines']))]
rows = [{'id': 'title', 'role': 'title', 'text': card['name'].upper(), 'baseline': layout['baselines']['title'] + card['titleOpticalShift']}]
rows += [{'id': f'verse-{i}', 'role': 'verse', 'text': line, 'baseline': y} for i, (line, y) in enumerate(zip(card['verseLines'], baselines))]
rows += [{'id': 'reference', 'role': 'reference', 'text': card['referenceDisplay'], 'baseline': layout['baselines']['reference']}]
fontchecks = []
for role, face in faces.items():
font = fonts / face['file']
match = Path(subprocess.check_output(['fc-match', '--format=%{file}', face['family'] + (':style=Bold' if role == 'title' else ':style=Medium')], env=env, text=True)).resolve()
check(match == font.resolve(), f'Font fallback: {role}')
ranges = [(int(t.split('-')[0], 16), int(t.split('-')[-1], 16)) for t 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}')
fontchecks.append({'role': role, 'path': str(font.relative_to(REPO)), 'sha256': digest(font), 'size': sizes[role], 'weight': face['weight'], 'fallbackUsed': False, 'missingGlyphs': []})
svg, textpng = textdir / 'text.svg', textdir / 'text-2000.png'
document(rows, sizes, faces).write(svg, encoding='unicode')
render(svg, textpng)
text = Image.open(textpng).convert('RGBA')
ta = np.asarray(text.getchannel('A'))
query = {p[0]: list(map(float, p[1:])) for line in ink(svg, '--query-all').splitlines() if len(p := line.split(',')) == 5}
glyphs = []
for row in rows:
src = textdir / (row['id'] + '-unclipped.svg')
document([row], sizes, faces).write(src, encoding='unicode')
render(src, src.with_suffix('.png'))
bb = Image.open(src.with_suffix('.png')).getchannel('A').getbbox()
rx, ry, rw, rh = layout['textRegions'][row['role']]
x, y, w, h = query[row['id']]
check(bb and rx <= bb[0] and ry <= bb[1] and bb[2] <= rx + rw and bb[3] <= ry + rh, f'Unclipped ink overflow: {row["id"]}')
check(rx <= x and ry <= y and x + w <= rx + rw and y + h <= ry + rh, f'Object overflow: {row["id"]}')
glyphs.append({**row, 'objectBounds': query[row['id']], 'unclippedInkBounds': list(bb), 'region': layout['textRegions'][row['role']], 'pass': True})
metrics = metric_box(fonts / faces['reference']['file'], sizes['reference'])
refbox = [rows[-1]['baseline'] - metrics['ascent'], rows[-1]['baseline'] + metrics['descent']]
check(glyphs[-1]['unclippedInkBounds'][1] >= refbox[0] and glyphs[-1]['unclippedInkBounds'][3] <= refbox[1], 'Reference escapes metric box.')
protected = text.getchannel('A').filter(ImageFilter.MaxFilter(25)).filter(ImageFilter.GaussianBlur(8))
coverage = int(np.min(np.asarray(protected)[ta >= 128]))
check(coverage >= 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 two-line semantic verse; pinned sizes/baselines; 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(artpath)}, 'fit': fit, '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': {k: {'path': str(p.relative_to(REPO)), 'sha256': digest(p)} for k, p in assets.items()}},
'sharedFontManifestSHA256': digest(fonts / 'manifest.json'),
'typography': {'fonts': fontchecks, 'glyphs': glyphs, 'fontMetrics': metrics, 'titleOpticalShift': card['titleOpticalShift'], 'referenceLineBox': refbox, 'textLayerSHA256': digest(textpng)},
'textMask': {'expansionRadius': 12, 'gaussianRadius': 8, 'units': 'master pixels', 'derivation': 'Actual lettering alpha: MaxFilter(25), GaussianBlur(8)', 'minimumProtectionAtGlyphAlpha128': coverage},
'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 manual inspection', 'movingLight': 'not performed'}}
for printing in ('normal', 'borderless'):
base = np.asarray(Image.open(assets['backing-' + printing]).convert('RGBA'))
ratio = float(np.min(contrast([38, 63, 80], base[:, :, :3][ta >= 128])))
check(ratio >= 7, 'Text contrast below 7:1.')
report['textContrast'][printing] = round(ratio, 2)
for printing, key, has_text in (('normal', 'overlay-normal', True), ('boundless', None, False), ('borderless', 'backing-borderless', True), ('textless', 'frame-textless', False)):
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'):
check(all(overlay.getpixel(xy)[3] == 255 for xy in ((0, 0), (1999, 0), (0, 2799), (1999, 2799))), 'Framed corners not opaque.')
if has_text:
check(np.all(np.asarray(overlay.getchannel('A'))[ta > 0] == 255), 'Glyphs outside opaque backing.')
face = Image.alpha_composite(face, text)
check(face.getchannel('A').getextrema() == (255, 255), 'Final face transparency.')
check(printing != 'boundless' or np.array_equal(np.asarray(face), np.asarray(art)), 'Boundless differs from art.')
finish = compile_finish(analysis, printing, overlay, text 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 overlay.')
tm = protected if has_text else Image.new('L', art.size, 0)
exports = []
for label, width in (('low', 500), ('med', 1000), ('high', 2000)):
folder = ROOT / label / printing
folder.mkdir(parents=True, exist_ok=True)
dims = (width, width * 7 // 5)
face.resize(dims, Image.Resampling.LANCZOS).save(folder / 'card.png')
for filename, data in (('finish-mask.png', finish), ('text-mask.png', tm)):
reduced = data if width == 2000 else data.resize(dims, Image.Resampling.BILINEAR)
rgba = reduced.convert('RGBA')
rgba.putalpha(255)
rgba.save(folder / filename)
exports.append({'resolution': label, 'dimensions': list(dims), 'files': {n: digest(folder / n) for n in ('card.png', 'finish-mask.png', 'text-mask.png')}})
editable = ROOT / 'high' / printing / 'card.svg'
def link(path):
return f''
body = ET.tostring(document(rows, sizes, faces).getroot()[0], encoding='unicode') if has_text else ''
editable.write_text('')
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']})
label_font = ImageFont.truetype(str(fonts / 'P052-Bold.otf'), 22)
for filename, asset 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=label_font, fill='#f4ead4')
preview = Image.open(ROOT / 'med' / printing / asset).convert('RGB')
board.paste(preview.resize((280, 392), Image.Resampling.LANCZOS), (i * 300 + 10, 50))
board.save(review / filename)
assessment = review / 'assembly-review.json'
if assessment.is_file():
report['visualReview'] = json.loads(assessment.read_text())
art_review = json.loads((ROOT / card['artReview']).read_text())
report['artQualityGate'] = {'record': card['artReview'], 'verdict': art_review['verdict'], 'layoutCaution': art_review.get('layoutCaution'), 'userApprovedArtwork': True}
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-048 v01: all four Common printings and structural checks passed; final approval pending.')
if __name__ == '__main__':
main()