Cotton code
71 lines · 2.9 KB · PythonRaw
#!/usr/bin/env python3"""Import the passport's Codex paintings (no lettering) into Loom.    python3 scripts/import-passport-materials.py ~/lane-briefs/person-passportThe originals and prompts stay outside the repository. Key the booklet offgreen, derive its contact shadow from its silhouette, and cut the paintedstamp into a border and an ink mask for live type. Requires Pillow/numpy.The face's geometry is measured against the cropped booklet, not the green."""import jsonimport pathlibimport sysimport numpy as npfrom PIL import Image, ImageFilter, ImageOpsCATALOGUE = pathlib.Path(__file__).resolve().parent.parent / 'apps/loom/Sources/CottonPaper/Media.xcassets'def save(name, image):    folder = CATALOGUE / f'{name}.imageset'    folder.mkdir(exist_ok=True)    image.save(folder / f'{name}.png', optimize=True)    (folder / 'Contents.json').write_text(json.dumps({        'images': [            {'filename': f'{name}.png', 'idiom': 'universal', 'scale': '3x'},            {'filename': f'{name}.png', 'idiom': 'mac', 'scale': '2x'},        ],        'info': {'author': 'xcode', 'version': 1},    }, indent=2) + '\n')def main(source):    original = Image.open(source / 'booklet-original.png').convert('RGB')    rgb = np.asarray(original, dtype=np.float32)    green = rgb[:, :, 1] - np.maximum(rgb[:, :, 0], rgb[:, :, 2])    alpha = np.uint8(np.clip((110 - green) / 45, 0, 1) * 255)    book = original.convert('RGBA')    book.putalpha(Image.fromarray(alpha))    book = book.crop(book.getbbox())    book = book.resize((1056, 942), Image.Resampling.LANCZOS)    save('passport-booklet', book)    # Shadow's frame reaches 6% beyond the book on all four sides.    shade = Image.new('L', (1182, 1068))    shade.paste(book.getchannel('A'), (63, 73))    shade = shade.filter(ImageFilter.GaussianBlur(19)).point(lambda a: round(a * .45))    shadow = Image.new('RGBA', shade.size, (0, 0, 0, 0))    shadow.putalpha(shade)    save('passport-shadow', shadow)    stamp = Image.open(source / 'stamp-original.png').convert('L')    ink = ImageOps.invert(stamp)    # The single painted impression's measured bounds and interior.    ink = ink.crop((40, 140, 1865, 680)).resize((660, 210), Image.Resampling.LANCZOS)    border = ink.copy()    border.paste(0, (12, 14, 648, 196))    layer = Image.new('RGBA', border.size, 'white')    layer.putalpha(border)    save('passport-stamp-border', layer)    grain = stamp.crop((100, 200, 1800, 620)).resize((660, 210), Image.Resampling.LANCZOS)    layer = Image.new('RGBA', grain.size, 'white')    layer.putalpha(grain)    save('passport-stamp-grain', layer)    total = sum(p.stat().st_size for p in CATALOGUE.glob('passport-*.imageset/*'))    if total >= 4_000_000:        raise SystemExit(f'passport materials exceed 4 MB: {total}')    print(f'Passport: {total:,} bytes, four painted layers')if __name__ == '__main__':    main(pathlib.Path(sys.argv[1]).expanduser())