Update card production workflow and workspaces
This commit is contained in:
@@ -1,8 +1,8 @@
|
||||
# Shared card production tools
|
||||
|
||||
`finish_masks.py` implements the approved `raw-ridges-v1` finish recipe for future stained-glass cards. It analyzes fitted opaque 2000×2800 artwork directly, without depending on spike diagnostics. Existing cards, proof builders and runtime fixtures are not migrated.
|
||||
`finish_masks.py` defaults new stained-glass cards to `raw-ridges-v1` again. It analyzes fitted opaque 2000×2800 artwork directly. Existing cards, proof builders and runtime fixtures are not migrated.
|
||||
|
||||
The immutable [recipe](recipes/raw-ridges-v1.json) pins all parameters and is hash-checked by the module. [Approval](recipes/raw-ridges-v1-approval.json) records the user's approval and the two reference Normal mask hashes. Changes to the recipe require a new revision; overrides are a separate reviewed recipe.
|
||||
The immutable [raw-ridges recipe](recipes/raw-ridges-v1.json) and its [historical approval](recipes/raw-ridges-v1-approval.json) and reference hashes remain intact. The [gated-contrast recipe](recipes/gated-contrast-v1.json) remains available by explicit selection for cards that need it. Changes to either recipe require a new revision.
|
||||
|
||||
For reusable frame/backing inputs, load a pinned version from the [shared tier layer library](../../artifacts/layers/README.md). The [four-tier comparison](../../spikes/tier-layer-library-proof/README.md) demonstrates shared layers and this finish module together without migrating historical fixtures.
|
||||
|
||||
@@ -22,7 +22,7 @@ python3 tools/card-production/finish_masks.py \
|
||||
--output path/output/masks
|
||||
```
|
||||
|
||||
The output contains `card-id-normal-{2000,1000,500}-mask.png`, raw-ridge and pane-weight diagnostics, and a validation/provenance JSON with source hashes, recipe/module hashes and library versions. All finish exports are opaque grayscale RGBA. Diagnostics are authoring data, not extra runtime textures. The command does not compose card faces, create glyph-protection maps, install fixtures or modify shaders.
|
||||
The output contains `card-id-normal-{2000,1000,500}-mask.png`, raw-ridge and pane-weight diagnostics, and a validation/provenance JSON with source hashes and recipe/module hashes. Add `--recipe gated-contrast-v1` to use the alternative contrast extractor. All finish exports are opaque grayscale RGBA. Diagnostics are authoring data, not extra runtime textures. The command does not compose card faces, create glyph-protection maps, install fixtures or modify shaders.
|
||||
|
||||
| Printing | `--overlay` | `--text` |
|
||||
|---|---|---|
|
||||
@@ -56,7 +56,7 @@ for printing, overlay_path, text_path in [
|
||||
exports = export_finish(master, output_dir, card_id, printing)
|
||||
```
|
||||
|
||||
Record `raw-ridges-v1`, the recipe hash, source revision/fit transform and actual component hashes in the assembler's validation. The module owns numeric extraction; the pipeline owns printing composition and review requirements. New stained-glass assembly uses this helper rather than copying finish code from an older proof.
|
||||
Record the selected recipe ID/hash, source revision/fit transform and actual component hashes in the assembler's validation. The module owns numeric extraction; the pipeline owns printing composition and review requirements. New assembly defaults to `raw-ridges-v1`; a revision's existing selection remains pinned on rebuild.
|
||||
|
||||
## Verification
|
||||
|
||||
@@ -67,19 +67,23 @@ python3 -m unittest discover -s tools/card-production/tests -p 'test_*.py'
|
||||
python3 tools/card-production/tests/check_approved_refs.py
|
||||
```
|
||||
|
||||
Tests cover source-edge handling, dark colored lines, broad shadow steps, canvas validation, actual alpha union, removed-component recovery, retained leading, invalid printing inputs and opaque exports for all four printings. The reference check regenerates raw confidence and Normal masks for The Fall and Burning Bush in a temporary directory, comparing every approved mask SHA-256 at 2000, 1000 and 500px widths. It writes only its check report beside the tests; it does not rebuild existing card assets.
|
||||
Tests cover source-edge handling, dark colored lines, broad shadow steps, canvas validation, actual alpha union, removed-component recovery, retained leading, invalid printing inputs and opaque exports for all four printings. The reference check regenerates historical raw confidence and Normal masks for The Fall and Burning Bush in a temporary directory, comparing every approved mask SHA-256 at 2000, 1000 and 500px widths. It writes only its check report beside the tests; it does not rebuild existing card assets.
|
||||
|
||||
[Reference check report](tests/approved-reference-check.json) records reproduction. The approved references are retained in `spikes/finish-mask-line-continuity-proof/raw-ridges/`. Approval of those Normal fixtures establishes the recipe; new art and other printings still need their own static and moving-light review. Raw ridges can include etched flecks and painted strokes, so inspect coating mottling without adding unreviewed cleanup to v1.
|
||||
The historical reference check requires `spikes/finish-mask-line-continuity-proof/`, which is absent from this checkout. It currently stops before comparison with a missing-source error. The versioned raw-ridge recipe hash and unit tests remain verifiable; do not treat the unavailable reference check as a pass.
|
||||
|
||||
[Historical reference check report](tests/approved-reference-check.json) records an earlier successful reproduction. Approval of those Normal fixtures established the recipe; new art and other printings still need their own static and moving-light review. Raw ridges can include etched flecks and painted strokes, so inspect coating mottling without adding unreviewed cleanup to v1.
|
||||
|
||||
|
||||
## Reviewed central-flourish card assembly
|
||||
|
||||
[assemble_card.py](assemble_card.py) assembles the refreshed BE-042, BE-010 and BE-002 working revisions with explicitly pinned `v3` shared layers. Each revision's `build.py` supplies its directory; builders do not depend on spike outputs. Artwork approval, font hashes/resolution, wording, glyph coverage, minimum sizes and unclipped bounds are required. The assembler derives the fixed reference line box from the font tables, centers combined verse ink in the remaining band, validates title/ornament clearance and checks reference stress cases at all three resolutions.
|
||||
|
||||
It analyzes fitted artwork once through `raw-ridges-v1`, composes all four printings, derives matching finish/text masks, writes low/med/high exports and editable high SVGs, then refreshes the working manifests at assembly-review. Approved card packages are frozen; the tool does not approve cards or install harness fixtures. It requires a layout with the declared central-flourish spacing policy and does not provide a Common or bespoke Legendary layout.
|
||||
It analyzes fitted artwork once through `raw-ridges-v1` for a new revision, composes all four printings, derives matching finish/text masks, writes low/med/high exports and editable high SVGs, then refreshes the working manifests at assembly-review. A prior build's recipe or explicit card-local selection remains pinned. Approved card packages are frozen; the tool does not approve cards or install harness fixtures. It requires a layout with the declared central-flourish spacing policy and does not provide a Common or bespoke Legendary layout.
|
||||
|
||||
```sh
|
||||
python3 tools/card-production/assemble_card.py --root in-progress/cards/ID-title/revisions/v02
|
||||
```
|
||||
|
||||
Read each revision's `review/build-validation.json` and `review/printings-comparison.png` for measured results and visual-review scope.
|
||||
|
||||
An explicitly user-authorized card-local `verseLayout` can select up to three lines, `fontSize` within the pinned minimum/default range, and `lineHeight` at least the font size. It requires `approval.by: user` and the authorization wording in `approval.note`. This overrides only text metrics in memory; it does not change shared assets, text regions or reference/flourish spacing. All actual glyph, collision and minimum-size checks still apply. The build report records the exception. Cards without this field retain their existing metrics and line limit.
|
||||
|
||||
@@ -10,11 +10,48 @@ REPO=Path(__file__).resolve().parents[2]
|
||||
sys.path.insert(0,str(REPO/'artifacts/layers'));sys.path.insert(0,str(Path(__file__).resolve().parent))
|
||||
from library import load_tier,digest
|
||||
from card_workspace import refresh,update_index
|
||||
from finish_masks import prepare_illustration,compile_finish,RECIPE_PATH,RECIPE_SHA256
|
||||
from finish_masks import prepare_illustration,compile_finish,RECIPE_PATH,RECIPE_SHA256,DEFAULT_RECIPE_ID
|
||||
from gated_contrast import prepare_gated_illustration,RECIPE_PATH as GATED_RECIPE_PATH,RECIPE_SHA256 as GATED_RECIPE_SHA256
|
||||
NS='{http://www.w3.org/2000/svg}';ET.register_namespace('','http://www.w3.org/2000/svg')
|
||||
def check(ok,msg):
|
||||
if not ok:raise ValueError(msg)
|
||||
def save(p,v):p.write_text(json.dumps(v,indent=2)+'\n')
|
||||
def resolve_finish_selection(card,report_path):
|
||||
"""Preserve a revision's prior choice; only a new assembly gets the new default."""
|
||||
explicit=card.get('finishMaskSelection')
|
||||
if explicit:
|
||||
ident=explicit.get('id')
|
||||
if ident in ('raw-ridges-v1','gated-contrast-v1'):return ident
|
||||
if explicit.get('recipe') and isinstance(ident,str):return 'raw-ridges-v1' # Card-local post-assembly replacement.
|
||||
raise ValueError(f'Unsupported finish-mask selection: {ident}')
|
||||
if report_path.is_file():
|
||||
previous=json.loads(report_path.read_text()).get('finishRecipe',{}).get('id')
|
||||
if previous in ('raw-ridges-v1','gated-contrast-v1'):return previous
|
||||
if previous:raise ValueError(f'Existing finish recipe {previous} needs an explicit selection')
|
||||
return DEFAULT_RECIPE_ID
|
||||
def resolve_verse_layout(layout,card):
|
||||
"""Apply an explicitly authorized card-local text layout, never shared assets."""
|
||||
result=copy.deepcopy(layout)
|
||||
override=card.get('verseLayout')
|
||||
if override is None:return result
|
||||
check(isinstance(override,dict),'Verse layout must be an object.')
|
||||
check(set(override)<= {'approval','lineCount','fontSize','lineHeight'},'Unsupported verse layout override.')
|
||||
approval=override.get('approval',{})
|
||||
check(isinstance(approval,dict) and approval.get('by')=='user' and isinstance(approval.get('note'),str) and approval['note'].strip(),'Verse layout requires explicit user authorization.')
|
||||
count=override.get('lineCount')
|
||||
check(type(count) is int and 1<=count<=3 and str(count) in layout['baselines']['verseByLineCount'],'Unsupported verse line count.')
|
||||
check(count==len(card['verseLines']),'Verse layout count mismatch.')
|
||||
size=override.get('fontSize',layout['fontSizes']['verse'])
|
||||
height=override.get('lineHeight',95)
|
||||
import math
|
||||
for value in [size,height]:check(type(value) in [int,float] and math.isfinite(value),'Verse metrics must be finite numbers.')
|
||||
check(layout['fontMinimums']['verse']<=size<=layout['fontSizes']['verse'],'Verse size outside approved range.')
|
||||
check(height>=size,'Verse line height is too tight.')
|
||||
result['maximumVerseLines']=count
|
||||
result['fontSizes']['verse']=size
|
||||
start=layout['baselines']['verseByLineCount'][str(count)][0]
|
||||
result['baselines']['verseByLineCount'][str(count)]=[start+i*height for i in range(count)]
|
||||
return result
|
||||
def metric_box(font,size):
|
||||
b=font.read_bytes();tables={}
|
||||
for i in range(struct.unpack_from('>H',b,4)[0]):
|
||||
@@ -33,11 +70,11 @@ def document(rows,sizes,faces):
|
||||
return ET.ElementTree(page)
|
||||
def assemble(root):
|
||||
root=Path(root).resolve();manifest=json.loads((root/'manifest.json').read_text());card=json.loads((root/'card.json').read_text());check(manifest['stage']!='approved','Approved revisions are frozen.');check(card.get('artApproval'),'Artwork approval required before assembly.')
|
||||
shared=load_tier(card['tier'],card['layerVersion']);layout=shared['layout'];assets=shared['assets'];check('spacing' in layout,'This builder requires an explicitly pinned central-flourish spacing layout.')
|
||||
shared=load_tier(card['tier'],card['layerVersion']);layout=resolve_verse_layout(shared['layout'],card);assets=shared['assets'];check('spacing' in layout,'This builder requires an explicitly pinned central-flourish spacing layout.')
|
||||
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 name,record in fm['files'].items():check(digest(fonts/name)==record['sha256'],f'Font input changed: {name}')
|
||||
textdir=root/'source/text';textdir.mkdir(parents=True,exist_ok=True);review=root/'review';review.mkdir(exist_ok=True);config=review/'fonts.conf';config.write_text(f'<fontconfig><dir>{fonts}</dir><cachedir>{review/"font-cache"}</cachedir></fontconfig>');env=dict(os.environ,FONTCONFIG_FILE=str(config))
|
||||
textdir=root/'source/text';textdir.mkdir(parents=True,exist_ok=True);review=root/'review';review.mkdir(exist_ok=True);config=review/'fonts.conf';config.write_text(f'<?xml version="1.0"?>\n<!DOCTYPE fontconfig SYSTEM "urn:fontconfig:fonts.dtd">\n<fontconfig><dir>{fonts}</dir><cachedir>{review/"font-cache"}</cachedir></fontconfig>\n');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,*args):ink(src,*args,'--export-type=png',f'--export-filename={dst}','--export-width=2000','--export-height=2800')
|
||||
def query(src):
|
||||
@@ -63,7 +100,9 @@ def assemble(root):
|
||||
# Title centering preserves the reviewed visual-bounds policy and multiline size.
|
||||
initial=textdir/'initial-title.svg';document(title,sizes,faces).write(initial,encoding='unicode');qb=query(initial);top=min(qb[r['id']][1] for r in title);bottom=max(qb[r['id']][1]+qb[r['id']][3] for r in title)
|
||||
geom=layout['spacing']['geometry']['borderless'];header_visual=next(e['flourishVisualBounds'] for e in geom['flourishes'] if e['id']=='header');pad=layout['spacing']['titleClearance'];tupper=geom['headerInnerTop']+pad;tlower=header_visual[1]-pad;check(bottom-top<=tlower-tupper,'Title cannot fit with required flourish clearance.')
|
||||
shift=(tupper+tlower-top-bottom)/2
|
||||
title_optical_shift=card.get('titleOpticalShift',0)
|
||||
check(isinstance(title_optical_shift,(int,float)) and not isinstance(title_optical_shift,bool),'Title optical shift must be numeric.')
|
||||
shift=(tupper+tlower-top-bottom)/2+title_optical_shift
|
||||
for row in title:row['baseline']+=shift
|
||||
# Verse centering uses actual rendered combined ink, not fixed margins.
|
||||
vi=row_image(verse,'initial-verse-unclipped');bb=vi.getchannel('A').getbbox();check(bb,'No verse ink.');delta=(upper+line_top-bb[1]-bb[3])/2
|
||||
@@ -91,9 +130,19 @@ def assemble(root):
|
||||
for i,case in enumerate(stress):
|
||||
bb=resized_bounds(textdir/f'stress-reference-{i}.png');gap=ob[1]-bb[3];check(gap>=20*width/2000-1,'Scaled reference clearance failure.');scaled.append({'width':width,'text':case['text'],'actualClearance':gap,'minimumWithRounding':20*width/2000-1,'alphaThreshold':128})
|
||||
protected=text.getchannel('A').filter(ImageFilter.MaxFilter(25)).filter(ImageFilter.GaussianBlur(8));coverage=int(np.min(np.asarray(protected)[ta>=128]));check(coverage>=216,'Text protection fails to cover glyphs.')
|
||||
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')
|
||||
finish_recipe=resolve_finish_selection(card,review/'build-validation.json')
|
||||
analysis=prepare_gated_illustration(art) if finish_recipe=='gated-contrast-v1' else prepare_illustration(art)
|
||||
ridge_path=root/'source'/('gated-contrast-ridges.png' if finish_recipe=='gated-contrast-v1' else 'raw-ridges.png')
|
||||
Image.fromarray(analysis.raw_ridges).save(ridge_path);Image.fromarray(np.rint(analysis.pane_weights*255).astype(np.uint8)).save(root/'source/pane-coverage.png')
|
||||
if 'finishMaskSelection' not in card:card['finishMaskSelection']={'id':finish_recipe,'source':'preserved prior build' if (review/'build-validation.json').is_file() else 'shared default'}
|
||||
card.update({'verseBaselines':[row['baseline'] for row in verse],'titleBaselines':[row['baseline'] for row in title],'referenceBaseline':ref['baseline'],'typographyPolicy':'fixed-reference-line-box-and-visible-verse-centering'});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':json.loads((root/'source/art-provenance.json').read_text()),'cardSHA256':digest(root/'card.json'),'builderSHA256':digest(Path(__file__))},'sharedLayers':{'tier':card['tier'],'version':shared['version'],'manifestSHA256':shared['manifestSHA256'],'reviewStatus':shared['reviewStatus'],'assets':{k:{'path':str(v.relative_to(REPO)),'sha256':digest(v)} for k,v in assets.items()}},'sharedFontManifestSHA256':digest(fonts/'manifest.json'),'typography':{'fonts':fontchecks,'glyphs':glyphs,'fontMetrics':metrics,'referenceBaseline':ref['baseline'],'referenceLineBox':[line_top,line_bottom],'referenceLineBoxToFlourish':lower-line_bottom,'actualReferenceClearance':lower-rb[3],'upperFlourishToVerse':above,'verseToReferenceLineBox':below,'centeringError':abs(above-below),'titleToFlourish':titleclear,'stressReferences':stress,'scaledRasterChecks':scaled,'textLayerSHA256':digest(textpath)},'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},'tools':{'inkscape':ink('--version'),'pillow':Image.__version__,'numpy':np.__version__},'printings':{},'visualReview':{'static':'pending','movingLight':'not performed'}}
|
||||
if finish_recipe=='gated-contrast-v1':
|
||||
finish_details={'id':finish_recipe,'sha256':GATED_RECIPE_SHA256,'path':str(GATED_RECIPE_PATH.relative_to(REPO)),'moduleSHA256':digest(REPO/'tools/card-production/gated_contrast.py'),'basePaneRecipe':{'id':'raw-ridges-v1','sha256':RECIPE_SHA256},'ridgeConfidenceSHA256':digest(ridge_path),'paneCoverageSHA256':digest(root/'source/pane-coverage.png'),'illustrationAnalyses':1}
|
||||
else:
|
||||
finish_details={'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(ridge_path),'paneCoverageSHA256':digest(root/'source/pane-coverage.png'),'illustrationAnalyses':1}
|
||||
report={'status':'pending','cardId':card['cardId'],'revision':manifest['revision'],'artApproval':card['artApproval'],'finalCardApproval':None,'inputs':{'art':{'path':card['art'],'sha256':digest(artpath)},'fit':json.loads((root/'source/art-provenance.json').read_text()),'cardSHA256':digest(root/'card.json'),'builderSHA256':digest(Path(__file__))},'sharedLayers':{'tier':card['tier'],'version':shared['version'],'manifestSHA256':shared['manifestSHA256'],'reviewStatus':shared['reviewStatus'],'assets':{k:{'path':str(v.relative_to(REPO)),'sha256':digest(v)} for k,v in assets.items()}},'sharedFontManifestSHA256':digest(fonts/'manifest.json'),'typography':{'fonts':fontchecks,'glyphs':glyphs,'titleOpticalShift':title_optical_shift,'fontMetrics':metrics,'referenceBaseline':ref['baseline'],'referenceLineBox':[line_top,line_bottom],'referenceLineBoxToFlourish':lower-line_bottom,'actualReferenceClearance':lower-rb[3],'upperFlourishToVerse':above,'verseToReferenceLineBox':below,'centeringError':abs(above-below),'titleToFlourish':titleclear,'stressReferences':stress,'scaledRasterChecks':scaled,'textLayerSHA256':digest(textpath)},'textMask':{'expansionRadius':12,'gaussianRadius':8,'units':'master pixels','derivation':'Actual lettering alpha: MaxFilter(25), GaussianBlur(8)','minimumProtectionAtGlyphAlpha128':coverage},'finishRecipe':finish_details,'tools':{'inkscape':ink('--version'),'pillow':Image.__version__,'numpy':np.__version__},'printings':{},'visualReview':{'static':'pending','movingLight':'not performed'}}
|
||||
if finish_recipe=='gated-contrast-v1':report['tools']['imageMagick']=subprocess.check_output(['convert','-version'],text=True).splitlines()[0]
|
||||
report['typography']['cardLocalVerseLayout']=card.get('verseLayout')
|
||||
backingcontrast=[]
|
||||
for kind in ['normal','borderless']:
|
||||
base=Image.open(assets['backing-'+kind]).convert('RGBA');arr=np.asarray(base);actual=float(np.min(contrast([38,63,80],arr[:,:,:3][ta>=128])));check(actual>=7,'Actual text/backing contrast below 7:1.')
|
||||
@@ -118,7 +167,7 @@ def assemble(root):
|
||||
def link(path):return f'<image width="2000" height="2800" xlink:href="{escape(os.path.relpath(path,editable.parent))}"/>'
|
||||
textbody=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(artpath)+(link(assets[key]) if key else '')+textbody+'</svg>');report['printings'][printing]={'overlay':key,'text':has_text,'exports':exports}
|
||||
save(root/'source/typography-layout.json',{'fontMetrics':metrics,'regions':regions,'rows':rows,'policy':'Approved 20px flourish spacing; fixed reference line box; actual verse ink centering.','fontSizes':sizes})
|
||||
save(root/'source/typography-layout.json',{'fontMetrics':metrics,'regions':regions,'rows':rows,'titleOpticalShift':title_optical_shift,'policy':'Approved 20px flourish spacing; fixed reference line box; actual verse ink centering; recorded card-specific title optical shift.','fontSizes':sizes})
|
||||
board=Image.new('RGB',(1200,480),'#11161c');d=ImageDraw.Draw(board);label_font=ImageFont.truetype(str(fonts/'P052-Bold.otf'),22)
|
||||
for i,printing in enumerate(['normal','boundless','borderless','textless']):
|
||||
d.text((i*300+10,8),printing.title(),font=label_font,fill='#f4ead4');board.paste(Image.open(root/'med'/printing/'card.png').convert('RGB').resize((280,392),Image.Resampling.LANCZOS),(i*300+10,50))
|
||||
|
||||
@@ -7,11 +7,13 @@ import hashlib
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import numpy as np
|
||||
from PIL import Image, ImageFilter, __version__ as pillow_version
|
||||
|
||||
RECIPE_PATH = Path(__file__).resolve().parent / 'recipes/raw-ridges-v1.json'
|
||||
RECIPE_SHA256 = '23331ce56a717edb4e6f85956d11fdd98397009c4e6dd230d8c334c77571dd18'
|
||||
DEFAULT_RECIPE_ID = 'raw-ridges-v1'
|
||||
PRINTINGS = ('normal', 'textless', 'borderless', 'boundless')
|
||||
|
||||
def sha256(path: Path) -> str:
|
||||
@@ -104,20 +106,24 @@ def compile_finish(illustration: IllustrationCoverage, printing: str,
|
||||
if (text is not None) != requires_text:
|
||||
raise ValueError(f'{printing} requires rendered text' if requires_text else f'{printing} has no text')
|
||||
r = load_recipe()
|
||||
if illustration.recipe_id != r['id'] or illustration.size != tuple(r['canvas']):
|
||||
raise ValueError('Illustration coverage must use the approved recipe and master canvas')
|
||||
if illustration.recipe_id not in (r['id'], 'gated-contrast-v1') or illustration.size != tuple(r['canvas']):
|
||||
raise ValueError('Illustration coverage must use a supported recipe and master canvas')
|
||||
panes, ridges = illustration.pane_weights, illustration.raw_ridges
|
||||
if panes.shape != ridges.shape or ridges.dtype != np.uint8:
|
||||
raise ValueError('Invalid illustration coverage arrays')
|
||||
if not np.all(np.isfinite(panes)) or np.any((panes < 0) | (panes > 1)):
|
||||
raise ValueError('Pane coverage must be finite within [0, 1]')
|
||||
oa = 0. if overlay is None else _component_alpha(overlay, illustration.size, 'Overlay')
|
||||
if illustration.recipe_id == 'gated-contrast-v1' and isinstance(oa, np.ndarray):
|
||||
oa = oa.astype(np.float32)
|
||||
if printing in ('normal', 'textless'):
|
||||
height, width = ridges.shape
|
||||
corners = ((0, 0), (0, width-1), (height-1, 0), (height-1, width-1))
|
||||
if any(oa[y, x] != 1 for y, x in corners):
|
||||
raise ValueError('Framed printings require opaque overlay corners; geometry owns rounding')
|
||||
ta = 0. if text is None else _component_alpha(text, illustration.size, 'Text')
|
||||
if illustration.recipe_id == 'gated-contrast-v1' and isinstance(ta, np.ndarray):
|
||||
ta = ta.astype(np.float32)
|
||||
protection = 1 - (1-oa)*(1-ta)
|
||||
confidence = ridges.astype(np.float32) / 255.
|
||||
coverage = np.rint(panes*(1-confidence)*(1-protection)*255).astype(np.uint8)
|
||||
@@ -144,6 +150,8 @@ def export_finish(master: Image.Image, output: Path, name: str, printing: str) -
|
||||
|
||||
def main() -> None:
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('--recipe', choices=('gated-contrast-v1', 'raw-ridges-v1'),
|
||||
default=DEFAULT_RECIPE_ID)
|
||||
parser.add_argument('--art', type=Path, required=True)
|
||||
parser.add_argument('--printing', choices=PRINTINGS, required=True)
|
||||
parser.add_argument('--overlay', type=Path)
|
||||
@@ -155,23 +163,31 @@ def main() -> None:
|
||||
art = Image.open(args.art)
|
||||
overlay = Image.open(args.overlay) if args.overlay else None
|
||||
text = Image.open(args.text) if args.text else None
|
||||
illustration = prepare_illustration(art)
|
||||
if args.recipe == 'gated-contrast-v1':
|
||||
from gated_contrast import prepare_gated_illustration, RECIPE_PATH as selected_path, RECIPE_SHA256 as selected_sha
|
||||
illustration = prepare_gated_illustration(art)
|
||||
else:
|
||||
selected_path, selected_sha = RECIPE_PATH, RECIPE_SHA256
|
||||
illustration = prepare_illustration(art)
|
||||
master = compile_finish(illustration, args.printing, overlay, text)
|
||||
exports = export_finish(master, args.output, args.name, args.printing)
|
||||
except (OSError, ValueError) as error:
|
||||
parser.error(str(error))
|
||||
# Diagnostics are authoring inputs; they are not required runtime samplers.
|
||||
Image.fromarray(illustration.raw_ridges).save(args.output / f'{args.name}-raw-ridges.png')
|
||||
ridge_name = 'gated-contrast-ridges' if args.recipe == 'gated-contrast-v1' else 'raw-ridges'
|
||||
Image.fromarray(illustration.raw_ridges).save(args.output / f'{args.name}-{ridge_name}.png')
|
||||
Image.fromarray(np.rint(illustration.pane_weights*255).astype(np.uint8)).save(
|
||||
args.output / f'{args.name}-pane-coverage.png')
|
||||
sources = {name: {'path': str(path.resolve()), 'sha256': sha256(path)}
|
||||
for name, path in [('art', args.art), ('overlay', args.overlay), ('text', args.text)] if path}
|
||||
report = {'status': 'passed', 'recipe': load_recipe()['id'], 'recipePath': str(RECIPE_PATH),
|
||||
'recipeSha256': RECIPE_SHA256, 'moduleSha256': sha256(Path(__file__)),
|
||||
report = {'status': 'passed', 'recipe': args.recipe, 'recipePath': str(selected_path),
|
||||
'recipeSha256': selected_sha, 'moduleSha256': sha256(Path(__file__)),
|
||||
'tools': {'numpy': np.__version__, 'pillow': pillow_version},
|
||||
'printing': args.printing, 'inputs': sources, 'exports': exports,
|
||||
'review': {'structural': 'Canvas and component contract checked',
|
||||
'static': 'Pending', 'movingLight': 'Pending', 'userApproval': 'Pending for this card'}}
|
||||
if args.recipe == 'gated-contrast-v1':
|
||||
report['tools']['imageMagick'] = subprocess.check_output(['convert', '-version'], text=True).splitlines()[0]
|
||||
(args.output / f'{args.name}-{args.printing}-finish-validation.json').write_text(json.dumps(report, indent=2)+'\n')
|
||||
print(json.dumps({'recipe': report['recipe'], 'printing': args.printing, 'exports': exports}, indent=2))
|
||||
|
||||
|
||||
53
tools/card-production/gated_contrast.py
Normal file
53
tools/card-production/gated_contrast.py
Normal file
@@ -0,0 +1,53 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Shared gated-contrast finish extraction; compilation remains in finish_masks."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import tempfile
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageFilter
|
||||
|
||||
from finish_masks import IllustrationCoverage, _smooth, extract_raw_ridges, prepare_illustration
|
||||
|
||||
RECIPE_PATH = Path(__file__).resolve().parent / 'recipes/gated-contrast-v1.json'
|
||||
RECIPE_SHA256 = '2cfaa28b96c66f440ed810f7a68a44f8584bb1bf2a9da1c71d74a49c6949d37a'
|
||||
|
||||
|
||||
def load_recipe() -> dict:
|
||||
if hashlib.sha256(RECIPE_PATH.read_bytes()).hexdigest() != RECIPE_SHA256:
|
||||
raise ValueError('gated-contrast-v1 recipe changed; create a new revision instead')
|
||||
return json.loads(RECIPE_PATH.read_text())
|
||||
|
||||
|
||||
def prepare_gated_illustration(art: Image.Image) -> IllustrationCoverage:
|
||||
"""Analyze fitted opaque art once using Ezekiel/Ruth's selected contrast math."""
|
||||
recipe = load_recipe()
|
||||
base = prepare_illustration(art)
|
||||
with tempfile.TemporaryDirectory(prefix='gated-contrast-') as temporary:
|
||||
folder = Path(temporary)
|
||||
source = folder / 'art.png'
|
||||
filtered_path = folder / 'filtered.png'
|
||||
canny_path = folder / 'canny.png'
|
||||
art.save(source)
|
||||
subprocess.run(['convert', str(source), '-kuwahara', recipe['preprocess']['imageMagickKuwahara'],
|
||||
str(filtered_path)], check=True)
|
||||
subprocess.run(['convert', str(filtered_path), '-colorspace', 'Gray', '-canny',
|
||||
recipe['preprocess']['canny'], str(canny_path)], check=True)
|
||||
filtered = Image.open(filtered_path).convert('RGB')
|
||||
gray_image = filtered.convert('L')
|
||||
gray = np.asarray(gray_image, dtype=np.float32) / 255.
|
||||
edge = np.asarray(Image.open(canny_path).convert('L').filter(
|
||||
ImageFilter.MaxFilter(recipe['edgeDilation'])), dtype=np.float32) / 255.
|
||||
local_max = np.asarray(gray_image.filter(ImageFilter.MaxFilter(recipe['localMaxSize'])),
|
||||
dtype=np.float32) / 255.
|
||||
smoothed_raw = extract_raw_ridges(filtered).astype(np.float32) / 255.
|
||||
darkness = 1. - _smooth(*recipe['darknessSmoothstep'], gray)
|
||||
contrast = _smooth(*recipe['contrastSmoothstep'], local_max - gray)
|
||||
confidence = np.maximum(recipe['smoothedRawRidgeWeight'] * smoothed_raw,
|
||||
recipe['gatedEdgeWeight'] * edge * darkness * contrast)
|
||||
ridges = np.rint(np.clip(confidence, 0., 1.) * 255).astype(np.uint8)
|
||||
return IllustrationCoverage(base.pane_weights, ridges, recipe['id'])
|
||||
222
tools/card-production/rebuild_finish_only.py
Normal file
222
tools/card-production/rebuild_finish_only.py
Normal file
@@ -0,0 +1,222 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Rebuild only finish masks in a successor card revision."""
|
||||
from __future__ import annotations
|
||||
|
||||
import copy
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image
|
||||
|
||||
REPO = next(p for p in Path(__file__).resolve().parents if
|
||||
(p / "docs/card-layer-pipeline.md").is_file())
|
||||
sys.path.insert(0, str(REPO / "artifacts/layers"))
|
||||
|
||||
from library import load_tier, digest
|
||||
from card_workspace import refresh, update_index
|
||||
from finish_masks import (RECIPE_PATH, RECIPE_SHA256, compile_finish,
|
||||
prepare_illustration)
|
||||
|
||||
PRINTINGS = (
|
||||
("normal", "overlay-normal", True),
|
||||
("boundless", None, False),
|
||||
("borderless", "backing-borderless", True),
|
||||
("textless", "frame-textless", False),
|
||||
)
|
||||
SIZES = (("low", 500), ("med", 1000), ("high", 2000))
|
||||
USER_DIRECTION = ("Yeah. Let's restore raw ridges, then go back and fix esther, "
|
||||
"mary, ezekiel. Just the finish mask needs to be changed. "
|
||||
"and we can move it straight to the finished artifact")
|
||||
|
||||
|
||||
def read(path: Path) -> dict:
|
||||
return json.loads(path.read_text())
|
||||
|
||||
|
||||
def write(path: Path, value: dict) -> None:
|
||||
path.write_text(json.dumps(value, indent=2) + "\n")
|
||||
|
||||
|
||||
def baseline_from_report(report: dict) -> dict:
|
||||
preserved = {}
|
||||
for printing in report["printings"]:
|
||||
preserved[printing] = {}
|
||||
for item in report["printings"][printing]["exports"]:
|
||||
preserved[printing][item["resolution"]] = {
|
||||
name: item["files"][name]
|
||||
for name in ("card.png", "text-mask.png")
|
||||
}
|
||||
return {
|
||||
"sourceRevision": report["revision"],
|
||||
"sourceFinishRecipe": copy.deepcopy(report["finishRecipe"]),
|
||||
"unchangedExportHashes": preserved,
|
||||
}
|
||||
|
||||
|
||||
def check_preserved_exports(root: Path, baseline: dict) -> None:
|
||||
for printing, sizes in baseline["unchangedExportHashes"].items():
|
||||
for label, files in sizes.items():
|
||||
for filename, expected in files.items():
|
||||
path = root / label / printing / filename
|
||||
if digest(path) != expected:
|
||||
raise ValueError(f"Non-finish export changed: {path}")
|
||||
|
||||
|
||||
def rebase_editable_links(root: Path, card_folder: str) -> None:
|
||||
"""Keep copied v01 SVG inputs valid at the deeper working-revision path."""
|
||||
accepted = REPO / "artifacts/cards" / card_folder
|
||||
for path in root.rglob("*.svg"):
|
||||
original = accepted / path.relative_to(root)
|
||||
if not original.is_file():
|
||||
continue
|
||||
original_tree = ET.parse(original)
|
||||
tree = ET.parse(path)
|
||||
old_nodes = list(original_tree.getroot().iter())
|
||||
new_nodes = list(tree.getroot().iter())
|
||||
if len(old_nodes) != len(new_nodes):
|
||||
raise ValueError(f"Editable SVG structure changed: {path}")
|
||||
changed = False
|
||||
for old, new in zip(old_nodes, new_nodes):
|
||||
for attr in ("href", "{http://www.w3.org/1999/xlink}href"):
|
||||
value = old.get(attr)
|
||||
if not value or value.startswith(("data:", "#")):
|
||||
continue
|
||||
target = (original.parent / value).resolve()
|
||||
if target.is_relative_to(accepted):
|
||||
target = root / target.relative_to(accepted)
|
||||
relative = os.path.relpath(target, path.parent)
|
||||
if new.get(attr) != relative:
|
||||
new.set(attr, relative)
|
||||
changed = True
|
||||
if changed:
|
||||
ET.register_namespace("", "http://www.w3.org/2000/svg")
|
||||
ET.register_namespace("xlink", "http://www.w3.org/1999/xlink")
|
||||
tree.write(path, encoding="unicode")
|
||||
|
||||
|
||||
def rebuild(root: Path) -> None:
|
||||
root = Path(root).resolve()
|
||||
if not root.is_relative_to(REPO / "in-progress/cards"):
|
||||
raise ValueError("Finish-only rebuild requires a working revision")
|
||||
manifest_path = root / "manifest.json"
|
||||
report_path = root / "review/build-validation.json"
|
||||
card_path = root / "card.json"
|
||||
manifest = read(manifest_path)
|
||||
card = read(card_path)
|
||||
report = read(report_path)
|
||||
rebase_editable_links(root, card["folderName"])
|
||||
baseline_path = root / "source/finish-only-baseline.json"
|
||||
if baseline_path.exists():
|
||||
baseline = read(baseline_path)
|
||||
else:
|
||||
if report["revision"] == root.name:
|
||||
raise ValueError("No prior approved build report to establish a finish-only baseline")
|
||||
baseline = baseline_from_report(report)
|
||||
accepted = REPO / "artifacts/cards" / card["folderName"] / "manifest.json"
|
||||
if accepted.is_file() and read(accepted)["revision"] == baseline["sourceRevision"]:
|
||||
baseline["sourceApprovedManifestSHA256"] = digest(accepted)
|
||||
write(baseline_path, baseline)
|
||||
if baseline["sourceRevision"] == root.name:
|
||||
raise ValueError("A finish-only revision must advance the revision number")
|
||||
check_preserved_exports(root, baseline)
|
||||
|
||||
art_path = root / "source" / Path(card["art"]).name
|
||||
if digest(art_path) != card["artSHA256"]:
|
||||
raise ValueError("Approved artwork changed")
|
||||
art = Image.open(art_path).convert("RGBA")
|
||||
if art.size != (2000, 2800) or art.getchannel("A").getextrema() != (255, 255):
|
||||
raise ValueError("Expected an opaque 2000 x 2800 approved art master")
|
||||
text = Image.open(root / "source/text/text-2000.png").convert("RGBA")
|
||||
shared = load_tier(card["tier"], card["layerVersion"])
|
||||
analysis = prepare_illustration(art)
|
||||
raw_path = root / "source/raw-ridges.png"
|
||||
pane_path = root / "source/pane-coverage.png"
|
||||
Image.fromarray(analysis.raw_ridges).save(raw_path)
|
||||
Image.fromarray(np.rint(analysis.pane_weights * 255).astype(np.uint8)).save(pane_path)
|
||||
|
||||
for printing, overlay_key, has_text in PRINTINGS:
|
||||
overlay = (Image.open(shared["assets"][overlay_key]).convert("RGBA")
|
||||
if overlay_key else None)
|
||||
finish = compile_finish(analysis, printing, overlay, text if has_text else None)
|
||||
if overlay is not None:
|
||||
opaque = np.asarray(overlay.getchannel("A")) == 255
|
||||
if np.any(np.asarray(finish)[opaque] != 0):
|
||||
raise ValueError(f"{printing}: finish leaks onto an opaque overlay")
|
||||
for label, width in SIZES:
|
||||
output = root / label / printing / "finish-mask.png"
|
||||
resized = (finish if width == 2000 else finish.resize(
|
||||
(width, width * 7 // 5), Image.Resampling.BILINEAR))
|
||||
rgba = resized.convert("RGBA")
|
||||
rgba.putalpha(255)
|
||||
rgba.save(output)
|
||||
export = next(item for item in report["printings"][printing]["exports"]
|
||||
if item["resolution"] == label)
|
||||
export["files"]["finish-mask.png"] = digest(output)
|
||||
|
||||
old_selection = copy.deepcopy(card.get("finishMaskSelection"))
|
||||
card["art"] = str(art_path.relative_to(REPO))
|
||||
card["finishMaskSelection"] = {
|
||||
"id": "raw-ridges-v1",
|
||||
"by": "user",
|
||||
"note": USER_DIRECTION,
|
||||
"source": f"finish-only {root.name} revision",
|
||||
}
|
||||
card["previousFinishMaskSelection"] = old_selection
|
||||
card.pop("finishMaskLocalCorrection", None)
|
||||
card["finishMaskChangeAuthorization"] = {
|
||||
"by": "user", "note": USER_DIRECTION,
|
||||
"scope": "Finish maps only; preserve all card faces, text masks, artwork, and shared layers.",
|
||||
}
|
||||
card["stage"] = "assembly-review"
|
||||
card["selectedRevision"] = root.name
|
||||
card["approval"] = None
|
||||
write(card_path, card)
|
||||
|
||||
report["revision"] = root.name
|
||||
report["finalCardApproval"] = None
|
||||
report["inputs"]["art"] = {"path": card["art"], "sha256": digest(art_path)}
|
||||
report["inputs"]["cardSHA256"] = digest(card_path)
|
||||
report["inputs"]["builderSHA256"] = digest(Path(__file__))
|
||||
report["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(raw_path),
|
||||
"paneCoverageSHA256": digest(pane_path),
|
||||
"illustrationAnalyses": 1,
|
||||
}
|
||||
report["finishOnlyRevision"] = {
|
||||
"sourceRevision": baseline["sourceRevision"],
|
||||
"sourceApprovedManifestSHA256": baseline.get("sourceApprovedManifestSHA256"),
|
||||
"baseline": str(baseline_path.relative_to(REPO)),
|
||||
"baselineSHA256": digest(baseline_path),
|
||||
"unchangedCardFacesAndTextMasks": True,
|
||||
"changedAssets": "finish-mask.png for all four printings at low, med, and high",
|
||||
"userDirection": USER_DIRECTION,
|
||||
}
|
||||
report["tools"].pop("imageMagick", None)
|
||||
report["visualReview"] = {"static": "pending finish-map inspection",
|
||||
"movingLight": "not performed"}
|
||||
report["status"] = "passed"
|
||||
write(report_path, report)
|
||||
|
||||
manifest["revision"] = root.name
|
||||
manifest["stage"] = "assembly-review"
|
||||
manifest["approval"] = None
|
||||
write(manifest_path, manifest)
|
||||
check_preserved_exports(root, baseline)
|
||||
refresh(root)
|
||||
update_index()
|
||||
print(f"{card['cardId']} {root.name}: twelve raw-ridge finish masks rebuilt; "
|
||||
"all card faces and text masks byte-identical to the approved baseline.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
if len(sys.argv) != 2:
|
||||
raise SystemExit("Usage: rebuild_finish_only.py WORKING_REVISION")
|
||||
rebuild(Path(sys.argv[1]))
|
||||
21
tools/card-production/recipes/gated-contrast-v1.json
Normal file
21
tools/card-production/recipes/gated-contrast-v1.json
Normal file
@@ -0,0 +1,21 @@
|
||||
{
|
||||
"id": "gated-contrast-v1",
|
||||
"canvas": [2000, 2800],
|
||||
"basePaneRecipe": "raw-ridges-v1",
|
||||
"preprocess": {
|
||||
"imageMagickKuwahara": "5x5",
|
||||
"canny": "0x1+5%+15%"
|
||||
},
|
||||
"edgeDilation": 7,
|
||||
"darknessSmoothstep": [0.32, 0.67],
|
||||
"localMaxSize": 11,
|
||||
"contrastSmoothstep": [0.02, 0.12],
|
||||
"smoothedRawRidgeWeight": 0.25,
|
||||
"gatedEdgeWeight": 0.95,
|
||||
"ridgeQuantization": "Round max confidence to uint8 before compilation",
|
||||
"compile": "paneWeight * (1 - ridgeConfidence) * (1 - actualOverlayAndTextAlpha)",
|
||||
"sourceTrials": [
|
||||
"artifacts/cards/BP-020-ezekiel/review/finish-mask-trial-01/gated-trial.json",
|
||||
"in-progress/cards/BP-022-ruth/revisions/v01/review/finish-mask-trial-01/recipe.json"
|
||||
]
|
||||
}
|
||||
42
tools/card-production/tests/test_finish_default.py
Normal file
42
tools/card-production/tests/test_finish_default.py
Normal file
@@ -0,0 +1,42 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from assemble_card import resolve_finish_selection
|
||||
from gated_contrast import RECIPE_PATH as GATED_RECIPE_PATH, RECIPE_SHA256 as GATED_RECIPE_SHA256, load_recipe as load_gated_recipe
|
||||
from finish_masks import DEFAULT_RECIPE_ID, RECIPE_PATH, RECIPE_SHA256, load_recipe, sha256
|
||||
|
||||
|
||||
class FinishDefaultSelection(unittest.TestCase):
|
||||
def test_new_card_uses_approved_raw_ridges(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
self.assertEqual(resolve_finish_selection({}, Path(folder) / 'missing.json'), DEFAULT_RECIPE_ID)
|
||||
self.assertEqual(DEFAULT_RECIPE_ID, 'raw-ridges-v1')
|
||||
self.assertEqual(load_recipe()['id'], DEFAULT_RECIPE_ID)
|
||||
self.assertEqual(sha256(RECIPE_PATH), RECIPE_SHA256)
|
||||
|
||||
def test_existing_recipe_stays_pinned(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
report = Path(folder) / 'build-validation.json'
|
||||
report.write_text(json.dumps({'finishRecipe': {'id': 'raw-ridges-v1'}}))
|
||||
self.assertEqual(resolve_finish_selection({}, report), 'raw-ridges-v1')
|
||||
report.write_text(json.dumps({'finishRecipe': {'id': 'gated-contrast-v1'}}))
|
||||
self.assertEqual(resolve_finish_selection({}, report), 'gated-contrast-v1')
|
||||
self.assertEqual(load_gated_recipe()['id'], 'gated-contrast-v1')
|
||||
self.assertEqual(sha256(GATED_RECIPE_PATH), GATED_RECIPE_SHA256)
|
||||
|
||||
def test_explicit_selection_and_local_replacement(self):
|
||||
with tempfile.TemporaryDirectory() as folder:
|
||||
report = Path(folder) / 'build-validation.json'
|
||||
report.write_text(json.dumps({'finishRecipe': {'id': 'raw-ridges-v1'}}))
|
||||
self.assertEqual(resolve_finish_selection({'finishMaskSelection': {'id': 'gated-contrast-v1'}}, report), 'gated-contrast-v1')
|
||||
self.assertEqual(resolve_finish_selection({'finishMaskSelection': {'id': 'ruth-gated-contrast-trial-v1', 'recipe': 'review/recipe.json'}}, report), 'raw-ridges-v1')
|
||||
with self.assertRaises(ValueError):
|
||||
resolve_finish_selection({'finishMaskSelection': {'id': 'unknown'}}, report)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
unittest.main()
|
||||
45
tools/card-production/tests/test_verse_layout.py
Normal file
45
tools/card-production/tests/test_verse_layout.py
Normal file
@@ -0,0 +1,45 @@
|
||||
import copy
|
||||
import json
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
REPO = Path(__file__).resolve().parents[3]
|
||||
sys.path.insert(0, str(REPO / 'tools/card-production'))
|
||||
from assemble_card import resolve_verse_layout
|
||||
|
||||
class VerseLayoutTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.layout = json.loads((REPO / 'artifacts/layers/rare/v3/layout.json').read_text())
|
||||
self.card = {'verseLines': ['a', 'b', 'c'], 'verseLayout': {
|
||||
'approval': {'by': 'user', 'note': 'Use three lines'},
|
||||
'lineCount': 3, 'fontSize': 80, 'lineHeight': 95}}
|
||||
|
||||
def test_no_override_preserves_defaults(self):
|
||||
self.assertEqual(resolve_verse_layout(self.layout, {}), self.layout)
|
||||
|
||||
def test_local_three_lines_without_shared_mutation(self):
|
||||
before = copy.deepcopy(self.layout)
|
||||
actual = resolve_verse_layout(self.layout, self.card)
|
||||
self.assertEqual(actual['maximumVerseLines'], 3)
|
||||
self.assertEqual(actual['baselines']['verseByLineCount']['3'], [2320, 2415, 2510])
|
||||
self.assertEqual(self.layout, before)
|
||||
|
||||
def test_unauthorized_rejected(self):
|
||||
self.card['verseLayout'].pop('approval')
|
||||
with self.assertRaises(ValueError): resolve_verse_layout(self.layout, self.card)
|
||||
|
||||
def test_invalid_metrics_rejected(self):
|
||||
for key, value in [('fontSize',75),('fontSize',81),('fontSize',True),('lineHeight',float('nan')),('lineHeight',79),('lineCount',4)]:
|
||||
card = copy.deepcopy(self.card)
|
||||
card['verseLayout'][key] = value
|
||||
with self.subTest(key=key,value=value), self.assertRaises(ValueError):
|
||||
resolve_verse_layout(self.layout, card)
|
||||
|
||||
def test_geometry_override_rejected(self):
|
||||
self.card['verseLayout']['textRegions'] = {}
|
||||
with self.assertRaises(ValueError): resolve_verse_layout(self.layout, self.card)
|
||||
|
||||
def test_count_mismatch_rejected(self):
|
||||
self.card['verseLines'].pop()
|
||||
with self.assertRaises(ValueError): resolve_verse_layout(self.layout, self.card)
|
||||
Reference in New Issue
Block a user