"""Портреты кокпита -> hooks/faces.ts: растр в штрихи SVG по цветам (приложение вырезает из Svg). vectorize.py ПАПКА_ПОРТРЕТОВ hooks/faces.ts 64 13 Размер и число цветов - наибольшие, при которых восемь самых тяжелых лиц линейки держат предел Svg в 131 072 знака (проверяет hooks/lineup.test.ts). """ import json import sys from pathlib import Path from PIL import Image src, out, size, colors = Path(sys.argv[1]), Path(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]) def encode(path: Path) -> list: img = Image.open(path).convert('RGB') w, h = img.size side = int(min(w, h) * 0.62) # круг держит лицо, не бюст left, top = (w - side) // 2, int(h * 0.06) img = img.crop((left, top, left + side, top + side)).resize((size, size), Image.LANCZOS) img = img.quantize(colors, method=Image.Quantize.MEDIANCUT, dither=Image.Dither.NONE) pal, px = img.getpalette(), img.load() counts: dict[int, int] = {} for y in range(size): for x in range(size): counts[px[x, y]] = counts.get(px[x, y], 0) + 1 bg = max(counts, key=counts.get) # самый частый цвет - подложкой, его штрихи не пишутся runs: dict[int, list[str]] = {} for y in range(size): x = 0 while x < size: c, s = px[x, y], x while x < size and px[x, y] == c: x += 1 if c != bg: runs.setdefault(c, []).append(f'M{s} {y}.5h{x - s}') hexed = lambda c: '#%02x%02x%02x' % tuple(pal[c * 3:c * 3 + 3]) return [hexed(bg), [[hexed(c), ''.join(d)] for c, d in runs.items()]] faces = {f.stem: encode(f) for f in sorted(src.glob('*.png'))} out.write_text( '// Собрано hooks/vectorize.py из cockpit/static/faces, руками не править.\n' f'export const FACE_PX = {size}\n' 'export const FACES: Record]> = ' + json.dumps(faces, separators=(',', ':')) + '\n' )