Files
Sanctification/artifacts/cards/BP-003-abraham/build.py

178 lines
16 KiB
Python
Executable File

#!/usr/bin/env python3
"""Build BP-003 Abraham v02 as a bespoke Legendary card."""
from __future__ import annotations
from copy import deepcopy
from pathlib import Path
import hashlib,json,os,shutil,subprocess,sys,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/'tools/card-production'))
from card_workspace import refresh,update_index
from finish_masks import RECIPE_PATH,RECIPE_SHA256,load_recipe,prepare_illustration
CANVAS=(2000,2800)
PRINTINGS=('normal','boundless','borderless','textless')
RESOLUTIONS=(('low',500),('med',1000),('high',2000))
PROOF=ROOT/'review/legendary-layout-prototype-v3'
def digest(p):return hashlib.sha256(Path(p).read_bytes()).hexdigest()
def check(v,m):
if not v:raise ValueError(m)
def save_json(p,v):Path(p).parent.mkdir(parents=True,exist_ok=True);Path(p).write_text(json.dumps(v,indent=2)+'\n')
def a8(im):check('A' in im.getbands(),'alpha-bearing component required');return np.asarray(im.getchannel('A'),dtype=np.uint8)
def split_selected(source,frame_out,backing_out,text_out):
root=ET.parse(source).getroot();children=list(root)
check(children and children[0].tag.endswith('defs'),'selected SVG lacks defs')
def write(path,predicate,include_defs=True):
out=ET.Element(root.tag,root.attrib)
if include_defs:out.append(deepcopy(children[0]))
for child in children[1:]:
if predicate(child):out.append(deepcopy(child))
ET.register_namespace('','http://www.w3.org/2000/svg');ET.register_namespace('xlink','http://www.w3.org/1999/xlink')
ET.ElementTree(out).write(path,encoding='unicode')
write(frame_out,lambda c:c.attrib.get('id')=='promise-frame')
write(backing_out,lambda c:c.attrib.get('id') in ('title-backing','verse-backing'))
write(text_out,lambda c:c.tag.endswith('text'),False)
def main():
card_path=ROOT/'card.json';manifest_path=ROOT/'manifest.json'
card=json.loads(card_path.read_text());manifest=json.loads(manifest_path.read_text())
art_path=ROOT/'source/art-master.png';art=Image.open(art_path).convert('RGBA')
check(art.size==CANVAS and art.getchannel('A').getextrema()==(255,255),'art must be opaque 2000x2800')
check(digest(art_path)==card['artSHA256'],'selected art changed')
selected={
'normal':PROOF/'composed-preview-2000.png',
'compositionSvg':PROOF/'composed-preview.svg',
'validation':PROOF/'preview-validation.json',
}
for p in selected.values():check(p.is_file(),f'missing selected prototype input: {p}')
proof=json.loads(selected['validation'].read_text());check(proof['status']=='passed','selected prototype did not pass')
fonts=REPO/'fonts';font_manifest_path=fonts/'manifest.json';font_manifest=json.loads(font_manifest_path.read_text())
title_font=fonts/'P052-Bold.otf';body_font=fonts/'SanctificationP052-Medium.otf'
for f in (title_font,body_font):check(digest(f)==font_manifest['files'][f.name]['sha256'],f'font mismatch: {f.name}')
review=ROOT/'review';layers=ROOT/'source/layers';text_dir=ROOT/'source/text';material=ROOT/'source/material'
for d in (review,layers,text_dir,material):d.mkdir(parents=True,exist_ok=True)
cache=review/'font-cache';cache.mkdir(exist_ok=True);conf=review/'fonts.conf';conf.write_text(f'<fontconfig><dir>{fonts}</dir><cachedir>{cache}</cachedir></fontconfig>')
env=dict(os.environ,FONTCONFIG_FILE=str(conf))
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')
def resolved(fam,style):return Path(subprocess.check_output(['fc-match','-f','%{file}',f'{fam}:style={style}'],env=env,text=True).strip()).resolve()
check(resolved('P052','Bold')==title_font.resolve(),'title fallback')
check(resolved('Sanctification P052','Medium')==body_font.resolve(),'body fallback')
shutil.copy2(selected['normal'],ROOT/'source/selected-normal-2000.png')
shutil.copy2(selected['compositionSvg'],layers/'selected-composition.svg')
frame_svg=layers/'frame.svg';backing_svg=layers/'backing.svg';text_svg=text_dir/'text.svg'
split_selected(selected['compositionSvg'],frame_svg,backing_svg,text_svg)
render(frame_svg,layers/'frame-2000.png');render(backing_svg,layers/'backing-2000.png');render(text_svg,text_dir/'text-2000.png')
frame=Image.open(layers/'frame-2000.png').convert('RGBA');backing=Image.open(layers/'backing-2000.png').convert('RGBA');text=Image.open(text_dir/'text-2000.png').convert('RGBA')
for n,im in [('frame',frame),('backing',backing),('text',text)]:check(im.size==CANVAS,f'{n} registration')
overlay=Image.alpha_composite(frame,backing);overlay.save(layers/'overlay-normal-2000.png');backing.save(layers/'backing-borderless-2000.png');frame.save(layers/'frame-textless-2000.png')
fa=a8(frame).astype(np.float32)/255.;ba=a8(backing).astype(np.float32)/255.;oa=a8(overlay).astype(np.float32)/255.;ta=a8(text).astype(np.float32)/255.
check(np.all(a8(backing)[ta>0]==255),'text outside opaque backing')
selected_normal=Image.open(ROOT/'source/selected-normal-2000.png').convert('RGBA');check(selected_normal.getchannel('A').getextrema()==(255,255),'selected normal not opaque')
reconstructed=Image.alpha_composite(Image.alpha_composite(Image.alpha_composite(art,frame),backing),text);reconstructed.save(review/'normal-reconstructed.png')
delta=np.abs(np.asarray(selected_normal,dtype=np.int16)[:,:,:3]-np.asarray(reconstructed,dtype=np.int16)[:,:,:3]);changed=np.any(delta>0,axis=2)
faces={
'normal':selected_normal,
'boundless':art.copy(),
'borderless':Image.alpha_composite(Image.alpha_composite(art,backing),text),
'textless':Image.alpha_composite(art,frame),
}
check(np.array_equal(np.asarray(faces['boundless']),np.asarray(art)),'boundless differs from art')
check(np.array_equal(np.asarray(faces['textless']),np.asarray(Image.alpha_composite(art,frame))),'textless composition')
protected=text.getchannel('A').filter(ImageFilter.MaxFilter(25)).filter(ImageFilter.GaussianBlur(8))
check(int(np.min(np.asarray(protected)[ta>=.5]))>=216,'weak text protection')
analysis=prepare_illustration(art)
Image.fromarray(analysis.raw_ridges).save(material/'base-raw-ridges.png')
Image.fromarray(np.rint(analysis.pane_weights*255).astype(np.uint8)).save(material/'base-pane-coverage.png')
base=analysis.pane_weights*(1-analysis.raw_ridges.astype(np.float32)/255.)
finish={
'normal':base*(1-oa)*(1-ta),
'boundless':base,
'borderless':base*(1-ba)*(1-ta),
'textless':base*(1-fa),
}
components={
'normal':['base-art','promise-frame','title-and-covenant-backings','text'],
'boundless':['base-art'],
'borderless':['base-art','title-and-covenant-backings','text'],
'textless':['base-art','promise-frame'],
}
report={
'status':'pending','cardId':card['cardId'],'revision':manifest['revision'],'finalCardApproval':None,
'assemblyAuthorization':"Okay. I think this feels good. Let's generate the prints/masks",
'selectedPrototype':{'path':str(PROOF.relative_to(REPO)),'normalSHA256':digest(selected['normal']),'validationSHA256':digest(selected['validation']),'authority':'v3 rope-free comparison PNG'},
'inputs':{'art':{'path':str(art_path.relative_to(REPO)),'sha256':digest(art_path)},'builderSHA256':digest(Path(__file__))},
'bespokeLayers':{'template':'BP-003-abraham-promise-v1','canvas':list(CANVAS),'compositionOrder':['base-art','active-frame/backing','active-text'],'printingComponents':components},
'typography':{'sharedFontManifestSHA256':digest(font_manifest_path),'title':{'font':title_font.name,'weight':700,'size':132},'verse':{'font':body_font.name,'weight':500,'size':54,'lines':['“Look toward heaven,','and number the stars,','if you are able to number them.','… So shall your offspring be.”']},'reference':{'font':body_font.name,'weight':500,'size':48,'text':card['referenceDisplay']},'proofChecks':proof['typography']},
'textMask':{'expansionRadius':12,'gaussianRadius':8,'units':'master pixels'},
'finishRecipe':{'id':load_recipe()['id'],'sha256':RECIPE_SHA256,'path':str(RECIPE_PATH.relative_to(REPO)),'illustrationAnalyses':1,'rawRidgesSHA256':digest(material/'base-raw-ridges.png'),'paneCoverageSHA256':digest(material/'base-pane-coverage.png')},
'normalAuthorityCheck':{'productionEqualsSelectedPrototype':True,'selectedSHA256':digest(selected['normal']),'productionSHA256':None,'reconstructionChangedPixels':int(np.count_nonzero(changed)),'reconstructionMaximumChannelDelta':int(delta.max())},
'printings':{},'tools':{'inkscape':ink('--version'),'pillow':Image.__version__,'numpy':np.__version__},
'visualReview':{'static':'pending user review','movingLight':'not performed','userApproval':'pending'},
}
head='<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">'
def node(editable,source):return f'<image width="2000" height="2800" xlink:href="{escape(os.path.relpath(source,editable.parent))}"/>'
source_single={'normal':ROOT/'source/selected-normal-2000.png','boundless':art_path}
for printing in PRINTINGS:
face=faces[printing];check(face.getchannel('A').getextrema()==(255,255),f'{printing} nonopaque')
fm=Image.fromarray(np.rint(np.clip(finish[printing],0,1)*255).astype(np.uint8),'L');has_text=printing in ('normal','borderless');exports=[]
for label,width in RESOLUTIONS:
size=(width,width*7//5);folder=ROOT/label/printing;folder.mkdir(parents=True,exist_ok=True)
if printing=='normal' and width==2000:shutil.copy2(selected['normal'],folder/'card.png')
else:(face if width==2000 else face.resize(size,Image.Resampling.LANCZOS)).save(folder/'card.png')
(fm if width==2000 else fm.resize(size,Image.Resampling.BILINEAR)).convert('RGBA').save(folder/'finish-mask.png')
if has_text:(protected if width==2000 else protected.resize(size,Image.Resampling.BILINEAR)).convert('RGBA').save(folder/'text-mask.png')
names=['card.png','finish-mask.png']+(['text-mask.png'] if has_text else [])
exports.append({'resolution':label,'dimensions':list(size),'files':{n:digest(folder/n) for n in names}})
editable=ROOT/'high'/printing/'card.svg'
if printing in source_single:body=node(editable,source_single[printing])
else:
body=node(editable,art_path)
body+=node(editable,backing if False else (layers/'backing-2000.png')) if printing=='borderless' else node(editable,layers/'frame-2000.png')
if printing=='borderless':body+=node(editable,text_dir/'text-2000.png')
editable.write_text(head+body+'</svg>')
report['printings'][printing]={'components':components[printing],'textMask':has_text,'finishCoverage':'base illustration suppressed by active opaque frame/backing and lettering','exports':exports}
report['normalAuthorityCheck']['productionSHA256']=digest(ROOT/'high/normal/card.png')
check(report['normalAuthorityCheck']['productionSHA256']==report['normalAuthorityCheck']['selectedSHA256'],'normal changed from v3')
save_json(layers/'layout.json',{'id':'BP-003-abraham-promise-v1','canvas':list(CANVAS),'selectedProof':str(PROOF.relative_to(REPO)),'governingIdea':'Promise between earth and heaven','depthOrder':['base-art','active-frame/backing','active-text'],'printingComponents':components,'ornament':'Restrained indigo-gold frame, two small rope-free pilgrim camels, celestial title plaque, curved covenant backing and single lower rule.'})
save_json(ROOT/'source/typography-layout.json',{'canvas':list(CANVAS),'policy':'Bespoke Legendary fixed coordinates; measured four-line quotation on opaque backing.','titleAnchor':[1525,248],'verseAnchorX':1511,'verseBaselines':[2165,2272,2379,2486],'referenceBaseline':2625,'fontSizes':{'title':132,'verse':54,'reference':48},'verseLines':report['typography']['verse']['lines'],'reference':card['referenceDisplay'],'checks':proof['typography']['checks']})
save_json(ROOT/'source/production-inputs.json',{'selectedProof':str(PROOF.relative_to(REPO)),'files':{n:{'path':str(p.relative_to(REPO)),'sha256':digest(p)} for n,p in selected.items()},'fonts':{f.name:digest(f) for f in (title_font,body_font)},'finishRecipeSHA256':RECIPE_SHA256})
label_font=ImageFont.truetype(str(title_font),24)
for filename,item in [('printings-comparison.png','card.png'),('finish-masks-comparison.png','finish-mask.png')]:
sheet=Image.new('RGB',(1600,610),'#11161c');d=ImageDraw.Draw(sheet)
for i,printing in enumerate(PRINTINGS):
d.text((i*400+14,12),printing.title(),font=label_font,fill='#f4ead4');im=Image.open(ROOT/'med'/printing/item).convert('RGB');im.thumbnail((370,518),Image.Resampling.LANCZOS if item=='card.png' else Image.Resampling.BILINEAR);sheet.paste(im,(i*400+14,56))
sheet.save(review/filename)
checker=Image.new('RGBA',CANVAS,(30,34,40,255));arr=np.asarray(checker).copy()
for y in range(0,2800,100):
for x in range(0,2000,100):
if (x//100+y//100)%2:arr[y:y+100,x:x+100,:3]=[56,61,69]
checker=Image.fromarray(arr,'RGBA');items=[('Base art',art),('Frame',frame),('Backings',backing),('Text',text)]
sheet=Image.new('RGB',(1200,500),'#11161c');d=ImageDraw.Draw(sheet)
for i,(label,layer) in enumerate(items):
d.text((i*300+10,8),label,font=label_font,fill='#f4ead4');comp=checker.copy();comp.alpha_composite(layer);comp.thumbnail((280,392),Image.Resampling.LANCZOS);sheet.paste(comp.convert('RGB'),(i*300+10,50))
sheet.save(review/'layers-comparison.png')
detail=Image.new('RGB',(1500,760),'#11161c');d=ImageDraw.Draw(detail)
for i,(label,path) in enumerate([('Normal card',ROOT/'high/normal/card.png'),('Normal finish',ROOT/'high/normal/finish-mask.png'),('Text protection',ROOT/'high/normal/text-mask.png')]):
d.text((i*500+12,12),label,font=label_font,fill='#f4ead4');im=Image.open(path).convert('RGB').crop((850,1700,2000,2800));im.thumbnail((480,690),Image.Resampling.LANCZOS);detail.paste(im,(i*500+10,48))
detail.save(review/'promise-panel-finish-detail.png')
report['status']='passed';save_json(review/'build-validation.json',report)
save_json(review/'static-review.json',{'status':'passed-structural-user-visual-review-pending','cardId':card['cardId'],'revision':manifest['revision'],'checks':{'selectedNormalPreservedByteForByte':True,'fourPrintingComposition':'passed','layerRegistration':'passed','opaqueFaces':'passed','textOnOpaqueBacking':'passed','lowMedHighExports':'passed'},'reviewAssets':['printings-comparison.png','layers-comparison.png','finish-masks-comparison.png','promise-panel-finish-detail.png'],'staticVisualAssessment':'Pending user review of production printings and masks.','movingLightReview':'Not performed.','finalCardApproval':None})
card.update({'artApproval':{'by':'user','scope':'v02 night artwork and Legendary layout prototype v3','note':report['assemblyAuthorization']},'artStatus':'Selected v02 illustration approved for production assembly','layoutStatus':'Bespoke Legendary promise-between-earth-and-heaven production candidate assembled; four printings and masks await user review.','template':'BP-003-abraham-promise-v1','printingComponents':components,'typographyCandidate':{'titleFontSize':132,'verseFontSize':54,'verseBaselineGap':107,'referenceFontSize':48,'lineBreaks':report['typography']['verse']['lines']},'finishRecipe':'raw-ridges-v1','assemblyAuthorization':{'by':'user','note':report['assemblyAuthorization']}});save_json(card_path,card)
manifest['stage']='assembly-review';manifest['approval']=None;save_json(manifest_path,manifest)
profile_path=ROOT.parents[1]/'card.json';profile=json.loads(profile_path.read_text());profile.update({'stage':'assembly-review','selectedRevision':manifest['revision'],'approval':None});save_json(profile_path,profile)
refresh(ROOT);update_index();print(f"{card['cardId']} {manifest['revision']}: four printings and masks exported; structural validation passed.")
if __name__=='__main__':main()