iroai 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
iroai/__init__.py ADDED
@@ -0,0 +1,4 @@
1
+ from .config import SHIFTS
2
+ from .core import to_lab, extract, save, merge, ramp, hue
3
+
4
+ __all__ = ["to_lab", "extract", "save", "merge", "ramp", "hue", "SHIFTS"]
iroai/config.py ADDED
@@ -0,0 +1 @@
1
+ SHIFTS = {'none': (0, 0), 'mid': (60, 25), 'strong': (115, 75)}
iroai/core.py ADDED
@@ -0,0 +1,143 @@
1
+ import struct
2
+ import sys
3
+ import zlib
4
+ from pathlib import Path
5
+
6
+ import numpy as np
7
+ from PIL import Image
8
+
9
+ M1 = np.array([[0.4122214708, 0.5363325363, 0.0514459929],
10
+ [0.2119034982, 0.6806995451, 0.1073969566],
11
+ [0.0883024619, 0.2817188376, 0.6299787005]])
12
+ M2 = np.array([[0.2104542553, 0.7936177850, -0.0040720468],
13
+ [1.9779984951, -2.4285922050, 0.4505937099],
14
+ [0.0259040371, 0.7827717662, -0.8086757660]])
15
+ M1I, M2I = np.linalg.inv(M1), np.linalg.inv(M2)
16
+
17
+
18
+ def to_lab(rgb):
19
+ c = np.asarray(rgb, float) / 255
20
+ c = np.where(c <= 0.04045, c / 12.92, ((c + 0.055) / 1.055) ** 2.4)
21
+ return np.cbrt(c @ M1.T) @ M2.T
22
+
23
+
24
+ def lin(L, z):
25
+ return (np.array([L, z.real, z.imag]) @ M2I.T) ** 3 @ M1I.T
26
+
27
+
28
+ def to_rgb(L, z):
29
+ c = np.clip(lin(L, z), 0, 1)
30
+ c = np.where(c <= 0.0031308, c * 12.92, 1.055 * c ** (1 / 2.4) - 0.055)
31
+ return tuple(int(v) for v in np.round(c * 255))
32
+
33
+
34
+ def hue(z):
35
+ return np.angle(z, deg=True) % 360
36
+
37
+
38
+ def cmax(L, h):
39
+ u, lo, hi = np.exp(1j * np.radians(h)), 0.0, 0.5
40
+ for _ in range(24):
41
+ m = (lo + hi) / 2
42
+ c = lin(L, m * u)
43
+ lo, hi = (m, hi) if c.min() >= -1e-6 and c.max() <= 1 + 1e-6 else (lo, m)
44
+ return lo
45
+
46
+
47
+ def ramp(L, z, n, light, shadow, shift, tint, lo, hi):
48
+ h = hue(z)
49
+ rel = abs(z) / max(cmax(L, h), 1e-9)
50
+ lo, hi = min(lo, L / 2), max(hi, (L + 1) / 2)
51
+ b = int(np.clip(round((L - lo) / (hi - lo) * (n - 1)), 1, n - 2))
52
+ out = []
53
+ for i in range(n):
54
+ up = i > b
55
+ s = (i - b) / (n - 1 - b) if up else (b - i) / b
56
+ t, deg, sat = (light, shift[0], 0.5) if up else (shadow, shift[1], 0.86)
57
+ d = (t - h + 180) % 360 - 180
58
+ hs = h + np.sign(d) * min(abs(d), deg * s)
59
+ e = 1 - (1 - s) ** 1.3
60
+ Ls = L + (hi - L) * e if up else L - (L - lo) * e
61
+ c = rel * (1 + (sat - rel) * s) * cmax(Ls, hs)
62
+ zs = c * np.exp(1j * np.radians(hs)) + tint * (1 - rel) * s * np.exp(1j * np.radians(t))
63
+ out.append(to_rgb(Ls, min(abs(zs), cmax(Ls, hue(zs))) * np.exp(1j * np.angle(zs))))
64
+ return out, b
65
+
66
+
67
+ def merge(ramps, tol, fixed):
68
+ cols = [c for r in ramps for c in r]
69
+ n, lab = len(ramps[0]), to_lab(np.array(cols))
70
+ D = np.linalg.norm(lab[:, None] - lab[None], axis=-1)
71
+ rep, grp = list(range(len(cols))), {i: {i} for i in range(len(cols))}
72
+ pairs = sorted((D[i, j], i, j) for i in range(len(cols)) for j in range(i) if i // n != j // n and D[i, j] < tol)
73
+ for _, i, j in pairs:
74
+ a, b = rep[i], rep[j]
75
+ if a == b or (a in fixed and b in fixed) or {m // n for m in grp[a]} & {m // n for m in grp[b]}:
76
+ continue
77
+ g = grp[a] | grp[b]
78
+ for r in [x for x in (a, b) if x in fixed] or sorted((a, b), key=lambda x: max(D[x, m] for m in g)):
79
+ if max(D[r, m] for m in g) <= tol and all(
80
+ (m % n == 0 or lab[rep[m - 1], 0] < lab[r, 0]) and
81
+ (m % n == n - 1 or lab[rep[m + 1], 0] > lab[r, 0]) for m in g):
82
+ for m in g:
83
+ rep[m] = r
84
+ del grp[a], grp[b]
85
+ grp[r] = g
86
+ break
87
+ return [[cols[rep[k * n + j]] for j in range(n)] for k in range(len(ramps))]
88
+
89
+
90
+ def extract(path, k):
91
+ im = Image.open(path).convert('RGBA')
92
+ im.thumbnail((256, 256), Image.Resampling.NEAREST)
93
+ px = np.asarray(im).reshape(-1, 4)
94
+ rgb, w = np.unique(px[px[:, 3] > 127, :3], axis=0, return_counts=True)
95
+ if not len(rgb):
96
+ raise ValueError('no opaque pixels in image')
97
+ lab = to_lab(rgb)
98
+ ab = lab[:, 1] + 1j * lab[:, 2]
99
+ rng = np.random.default_rng(0)
100
+ c = ab[[w.argmax()]]
101
+ while len(c) < k:
102
+ d = np.abs(ab[:, None] - c).min(1)
103
+ if d.max() < 0.02:
104
+ break
105
+ c = np.append(c, rng.choice(ab, p=d ** 2 * w / (d ** 2 * w).sum()))
106
+ for _ in range(50):
107
+ lbl = np.abs(ab[:, None] - c).argmin(1)
108
+ c = np.array([np.average(ab[lbl == j], weights=w[lbl == j]) if (lbl == j).any() else c[j]
109
+ for j in range(len(c))])
110
+ lbl = np.abs(ab[:, None] - c).argmin(1)
111
+ bases = [(np.average(lab[lbl == j, 0], weights=w[lbl == j]), c[j]) for j in range(len(c)) if (lbl == j).any()]
112
+ return sorted(bases, key=lambda b: (abs(b[1]) > 0.03, hue(b[1])))
113
+
114
+
115
+ def save_ase(path, ramps, pal, name):
116
+ h, w = len(ramps), len(ramps[0])
117
+ chunk = lambda t, d: struct.pack('<IH', len(d) + 6, t) + d
118
+ frame = b''.join([
119
+ chunk(0x2007, struct.pack('<HHI8x', 1, 0, 0)),
120
+ chunk(0x2019, struct.pack('<III8x', len(pal), 0, len(pal) - 1) +
121
+ b''.join(struct.pack('<H4BH', 1, *c, 255, len(x)) + x.encode() for x, c in pal)),
122
+ chunk(0x2004, struct.pack('<6HB3xH', 3, 0, 0, 0, 0, 0, 255, len(name)) + name),
123
+ chunk(0x2005, struct.pack('<HhhBHh5x2H', 0, 0, 0, 255, 2, 0, w, h) +
124
+ zlib.compress(bytes(v for row in ramps for c in row for v in (*c, 255))))])
125
+ frame = struct.pack('<IHHH2xI', 16 + len(frame), 0xF1FA, 4, 100, 4) + frame
126
+ Path(path).write_bytes(struct.pack('<IHHHHHIHIIB3xHBBhhHH84x', 128 + len(frame), 0xA5E0, 1, w, h, 32, 1,
127
+ 100, 0, 0, 0, len(pal), 1, 1, 0, 0, 16, 16) + frame)
128
+
129
+
130
+ def save(ramps, out, scale):
131
+ Path(out).parent.mkdir(parents=True, exist_ok=True)
132
+ arr = np.array(ramps, np.uint8)
133
+ Image.fromarray(arr).resize((arr.shape[1] * scale, arr.shape[0] * scale), Image.Resampling.NEAREST).save(f'{out}.png')
134
+ hexes = [[f'{r:02x}{g:02x}{b:02x}' for r, g, b in row] for row in ramps]
135
+ uniq = dict.fromkeys((h, c) for row, hr in zip(ramps, hexes) for c, h in zip(row, hr))
136
+ Path(f'{out}.hex').write_text(''.join(h + '\n' for h, _ in uniq))
137
+ Path(f'{out}.gpl').write_text(f'GIMP Palette\nName: {Path(out).stem}\nColumns: {arr.shape[1]}\n#\n' +
138
+ ''.join(f'{r:3d} {g:3d} {b:3d}\t{h}\n' for h, (r, g, b) in uniq))
139
+ save_ase(f'{out}.aseprite', ramps, list(uniq), Path(out).stem.encode())
140
+ tty = sys.stdout.isatty()
141
+ for row, hr in zip(ramps, hexes):
142
+ print(' '.join((f'\x1b[48;2;{r};{g};{b}m \x1b[0m' if tty else '') + h for (r, g, b), h in zip(row, hr)))
143
+ print(f'{len(uniq)} colors -> {out}.png .gpl .hex .aseprite')
iroai/main.py ADDED
@@ -0,0 +1,54 @@
1
+ import argparse
2
+ import os
3
+ import re
4
+ from pathlib import Path
5
+
6
+ from .config import SHIFTS
7
+ from .core import extract, hue, merge, ramp, save, to_lab
8
+
9
+
10
+ def shift_arg(s):
11
+ if s in SHIFTS:
12
+ return SHIFTS[s]
13
+ v = [float(x) for x in s.split(',')]
14
+ return v[0], v[-1]
15
+
16
+
17
+ def main():
18
+ p = argparse.ArgumentParser(description=__doc__)
19
+ p.add_argument('src', nargs='+', help='hex colors (e.g. 3a7bd5 e0533a) or one reference image')
20
+ p.add_argument('-n', '--steps', type=int, default=9, help='shades per ramp, 3-16')
21
+ p.add_argument('-k', '--ramps', type=int, default=6, help='ramps to extract from an image')
22
+ p.add_argument('--shift', type=shift_arg, default='mid',
23
+ help='none | mid | strong | degrees as LIGHT,DARK (e.g. 80,40)')
24
+ p.add_argument('--light', default='ffd700', help='color highlights shift toward (sunlight)')
25
+ p.add_argument('--shadow', default='2a0c42', help='color shadows shift toward (sky-lit shadow)')
26
+ p.add_argument('--tint', type=float, default=0.03, help='light/shadow cast on grays (0 = none)')
27
+ p.add_argument('--range', type=float, nargs=2, default=(0.2, 0.96), metavar=('DARK', 'LIGHT'),
28
+ help='lightness range 0-1; 1 = pure white top')
29
+ p.add_argument('--merge', type=float, default=0, metavar='TOL',
30
+ help='make similar colors in different ramps identical (OKLab distance, e.g. 0.04)')
31
+ p.add_argument('-o', '--out', default='palette',
32
+ help='output path, e.g. forest, out/forest or out/ (folders are created); writes .png .gpl .hex .aseprite')
33
+ p.add_argument('--scale', type=int, default=16, help='swatch size in the PNG')
34
+ a = p.parse_args()
35
+ image = len(a.src) == 1 and Path(a.src[0]).is_file()
36
+ if not 3 <= a.steps <= 16:
37
+ p.error('--steps must be 3-16')
38
+ for s in [a.light, a.shadow] + ([] if image else a.src):
39
+ if not re.fullmatch(r'#?[0-9a-fA-F]{6}', s):
40
+ p.error(f'invalid hex color or missing image: {s}')
41
+ lab = lambda s: to_lab([int(s.lstrip('#')[i:i + 2], 16) for i in (0, 2, 4)])
42
+ try:
43
+ bases = extract(a.src[0], a.ramps) if image else [(v[0], complex(*v[1:])) for v in map(lab, a.src)]
44
+ except (OSError, ValueError) as e:
45
+ p.error(str(e))
46
+ lh, sh = (hue(complex(*lab(s)[1:])) for s in (a.light, a.shadow))
47
+ ramps, bs = zip(*(ramp(L, z, a.steps, lh, sh, a.shift, a.tint, *a.range) for L, z in bases))
48
+ if a.merge > 0:
49
+ ramps = merge(ramps, a.merge, {k * a.steps + b for k, b in enumerate(bs)})
50
+ save(ramps, str(Path(a.out, 'palette')) if a.out.endswith(('/', os.sep)) else a.out, a.scale)
51
+
52
+
53
+ if __name__ == '__main__':
54
+ main()
@@ -0,0 +1,34 @@
1
+ Metadata-Version: 2.3
2
+ Name: iroai
3
+ Version: 0.1.0
4
+ Summary: Hue-shifted pixel-art color ramps from hex colors or a reference image.
5
+ Author: Enrico Shippole
6
+ Author-email: Enrico Shippole <enricoship@gmail.com>
7
+ Requires-Dist: numpy>=2.5.5
8
+ Requires-Dist: pillow>=13.0.0
9
+ Requires-Python: >=3.12
10
+ Description-Content-Type: text/markdown
11
+
12
+ Generate hue-shifted pixel-art color ramps from hex colors or a reference image. Based on color theory from Color and Light by James Gurney.
13
+
14
+ Installation:
15
+ ```bash
16
+ uv pip install iroai
17
+ ```
18
+
19
+ Usage:
20
+ ```bash
21
+ uv run iroai 3a7bd5 e0533a [options]
22
+ uv run iroai input.png [options]
23
+ ```
24
+
25
+ Options (defaults shown):
26
+ - `-n 9` shades per ramp (3–16)
27
+ - `-k 6` ramps to extract from an image
28
+ - `--shift mid` hue shift: `none`, `mid`, `strong`, or `LIGHT,DARK` degrees
29
+ - `--light ffd700` / `--shadow 2a0c42` colors highlights and shadows shift toward
30
+ - `--merge 0.04` make similar colors in different ramps identical (off by default)
31
+ - `--range 0.2 0.96` lightness range (`1` = pure white top)
32
+ - `--tint 0.03` warm/cool cast on grays
33
+ - `-o palette` output path, e.g. `out/forest` or `out/` (folders are created); writes `.png`, `.gpl`, `.hex`, `.aseprite`
34
+ - `--scale 16` swatch size in the PNG# iroai
@@ -0,0 +1,8 @@
1
+ iroai/__init__.py,sha256=P7HESOd9E4Tl121FdtZ4GxMlgJcw8X8J6s_1xpPqKDc,159
2
+ iroai/config.py,sha256=XyRXkA2-Zi8H73HEV4w8yg1rcg-4lGG8Z8L8KlF1PZk,63
3
+ iroai/core.py,sha256=A7UrHfva4LmzgBUaAZH3f5nIyywXowF8wj6oFLn1gSY,6223
4
+ iroai/main.py,sha256=l41jehnGDMjNlFlPYonF472LlkDQvZ6vBEbDyenj5DM,2668
5
+ iroai-0.1.0.dist-info/WHEEL,sha256=e4_1dyBeezi8ZjfxrZ3bnVOxFDa3ksqVqH0jTHkUZ3k,81
6
+ iroai-0.1.0.dist-info/entry_points.txt,sha256=XrJKjGJGE00FiAALOcqYHphfr8785ZO2eb6izoO-xLY,43
7
+ iroai-0.1.0.dist-info/METADATA,sha256=58L67wXMxEUkWsTj-_wihFGDRjLffPx99cvcgx_6aCY,1218
8
+ iroai-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: uv 0.12.19
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,3 @@
1
+ [console_scripts]
2
+ iroai = iroai.main:main
3
+