cockatrice-custom-tokens/scripts/render_cards.py

94 lines
4.7 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

"""Deterministic Pillow text overlays for TOML-defined reminder cards."""
from io import BytesIO
from pathlib import Path
from PIL import Image, ImageDraw, ImageFont
FONTS = Path(__file__).resolve().parents[1] / 'assets/fonts'
def wrap(draw, text, font, width):
lines = []
for paragraph in text.split('\n'):
if not paragraph.strip():
lines.append('')
continue
line = ''
for word in paragraph.split():
if draw.textlength(word, font=font) > width:
raise ValueError(f'Word cannot fit the text panel: {word}')
candidate = f'{line} {word}'.strip()
if draw.textlength(candidate, font=font) > width:
lines.append(line)
line = word
else:
line = candidate
lines.append(line)
return lines
def render_card(folder, token):
options = token['render']
allowed = {'template', 'box', 'title', 'footer', 'font_size', 'min_font_size', 'title_size', 'color'}
if not isinstance(options, dict) or options.keys() - allowed:
raise ValueError('render must be a table with only supported layout options')
relative = options.get('template')
if not isinstance(relative, str):
raise ValueError('render.template is required')
template = folder / relative
if not relative.startswith('templates/') or '..' in Path(relative).parts or template.resolve() != template.absolute():
raise ValueError('render.template must be a non-symlink file inside templates/')
with Image.open(template) as original:
image = original.convert('RGBA')
draw = ImageDraw.Draw(image)
box = options.get('box', [100, 150, 650, 1050])
if (not isinstance(box, list) or len(box) != 4 or any(type(v) is not int for v in box)
or not 0 <= box[0] < box[2] <= image.width or not 0 <= box[1] < box[3] <= image.height):
raise ValueError('render.box must be [left, top, right, bottom] inside the template')
left, top, right, bottom = box
width = right - left
sizes = {name: options.get(name, default) for name, default in
[('font_size', 28), ('min_font_size', 22), ('title_size', 44)]}
if any(type(v) is not int or not 8 <= v <= 200 for v in sizes.values()) or sizes['min_font_size'] > sizes['font_size']:
raise ValueError('Invalid render font sizes (8–200, minimum <= preferred)')
title = options.get('title', token['name'])
body = token['description'].strip()
footer = options.get('footer', '')
if not isinstance(title, str) or not title.strip() or not isinstance(footer, str):
raise ValueError('render.title and render.footer must be strings; title must not be empty')
title_font = ImageFont.truetype(str(FONTS / 'DejaVuSerif-Bold.ttf'), sizes['title_size'], layout_engine=ImageFont.Layout.BASIC)
title_lines = wrap(draw, title, title_font, width)
title_step = sum(title_font.getmetrics()) + 4
title_height = len(title_lines) * title_step
footer_font = ImageFont.truetype(str(FONTS / 'DejaVuSerif.ttf'), 16, layout_engine=ImageFont.Layout.BASIC)
footer_lines = wrap(draw, footer, footer_font, width) if footer else []
footer_height = len(footer_lines) * 23
body_top = top + title_height + 35
available = bottom - body_top - (footer_height + 25 if footer else 0)
fitted = None
for size in range(sizes['font_size'], sizes['min_font_size'] - 1, -1):
font = ImageFont.truetype(str(FONTS / 'DejaVuSerif.ttf'), size, layout_engine=ImageFont.Layout.BASIC)
try:
lines = wrap(draw, body, font, width)
except ValueError:
continue
step = sum(font.getmetrics()) + 5
if len(lines) * step <= available:
fitted = (font, lines, step)
break
if fitted is None:
raise ValueError(f'{token["name"]}: reminder text does not fit; shorten it or enlarge render.box (minimum font size is enforced)')
color = options.get('color', '#192b3b')
for index, line in enumerate(title_lines):
x = left + (width - draw.textlength(line, font=title_font)) / 2
draw.text((x, top + index * title_step), line, font=title_font, fill=color, anchor='lt')
draw.line((left + 35, body_top - 20, right - 35, body_top - 20), fill='#ad772b', width=2)
font, lines, step = fitted
for index, line in enumerate(lines):
draw.text((left, body_top + index * step), line, font=font, fill=color, anchor='lt')
for index, line in enumerate(footer_lines):
draw.text((left, bottom - footer_height + index * 23), line, font=footer_font, fill=color, anchor='lt')
output = BytesIO()
image.save(output, format='PNG', optimize=False, compress_level=9)
return output.getvalue()