easy-tiler 1.0.3__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.
- easy_tiler/__init__.py +56 -0
- easy_tiler/cli.py +195 -0
- easy_tiler/colors.py +279 -0
- easy_tiler/factories.py +347 -0
- easy_tiler/grid.py +54 -0
- easy_tiler/io.py +17 -0
- easy_tiler/renderer.py +87 -0
- easy_tiler/tiles.py +542 -0
- easy_tiler-1.0.3.dist-info/METADATA +208 -0
- easy_tiler-1.0.3.dist-info/RECORD +12 -0
- easy_tiler-1.0.3.dist-info/WHEEL +4 -0
- easy_tiler-1.0.3.dist-info/entry_points.txt +3 -0
easy_tiler/__init__.py
ADDED
|
@@ -0,0 +1,56 @@
|
|
|
1
|
+
from .colors import ColorConfig
|
|
2
|
+
from .grid import Grid
|
|
3
|
+
from .renderer import Renderer
|
|
4
|
+
from .tiles import (
|
|
5
|
+
ArcTile,
|
|
6
|
+
ArrowTile,
|
|
7
|
+
BumpTile,
|
|
8
|
+
CairoTile,
|
|
9
|
+
CircleTile,
|
|
10
|
+
CornerTile,
|
|
11
|
+
DoughnutTile,
|
|
12
|
+
PentagonTile,
|
|
13
|
+
PuckTile,
|
|
14
|
+
RectangleTile,
|
|
15
|
+
RegularPolygonTile,
|
|
16
|
+
RileyTile,
|
|
17
|
+
SmithTile,
|
|
18
|
+
SquareTile,
|
|
19
|
+
TileBase,
|
|
20
|
+
TileConfig,
|
|
21
|
+
TriangleTile,
|
|
22
|
+
TruchetTile,
|
|
23
|
+
)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def main() -> None:
|
|
27
|
+
"""Run the easy-tiler command."""
|
|
28
|
+
from .cli import main as cli_main
|
|
29
|
+
|
|
30
|
+
cli_main()
|
|
31
|
+
|
|
32
|
+
|
|
33
|
+
__all__ = [
|
|
34
|
+
'ArcTile',
|
|
35
|
+
'ArrowTile',
|
|
36
|
+
'BumpTile',
|
|
37
|
+
'CairoTile',
|
|
38
|
+
'CircleTile',
|
|
39
|
+
'ColorConfig',
|
|
40
|
+
'CornerTile',
|
|
41
|
+
'DoughnutTile',
|
|
42
|
+
'Grid',
|
|
43
|
+
'PentagonTile',
|
|
44
|
+
'PuckTile',
|
|
45
|
+
'RectangleTile',
|
|
46
|
+
'RegularPolygonTile',
|
|
47
|
+
'Renderer',
|
|
48
|
+
'RileyTile',
|
|
49
|
+
'SmithTile',
|
|
50
|
+
'SquareTile',
|
|
51
|
+
'TileBase',
|
|
52
|
+
'TileConfig',
|
|
53
|
+
'TriangleTile',
|
|
54
|
+
'TruchetTile',
|
|
55
|
+
'main',
|
|
56
|
+
]
|
easy_tiler/cli.py
ADDED
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
"""Command-line rendering from YAML configuration."""
|
|
2
|
+
|
|
3
|
+
import argparse
|
|
4
|
+
import inspect
|
|
5
|
+
import math
|
|
6
|
+
from dataclasses import fields
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
from typing import Any
|
|
9
|
+
|
|
10
|
+
import cairo
|
|
11
|
+
import numpy as np
|
|
12
|
+
import yaml
|
|
13
|
+
|
|
14
|
+
from easy_tiler.factories import (
|
|
15
|
+
make_form_factory,
|
|
16
|
+
make_node_factory,
|
|
17
|
+
make_sequence_factory,
|
|
18
|
+
make_tile_factory,
|
|
19
|
+
)
|
|
20
|
+
from easy_tiler.grid import Grid
|
|
21
|
+
from easy_tiler.io import save_png, save_svg
|
|
22
|
+
from easy_tiler.tiles import TileConfig
|
|
23
|
+
|
|
24
|
+
_FACTORIES = {
|
|
25
|
+
'tile': make_tile_factory,
|
|
26
|
+
'sequence': make_sequence_factory,
|
|
27
|
+
'node': make_node_factory,
|
|
28
|
+
'form': make_form_factory,
|
|
29
|
+
}
|
|
30
|
+
_TILE_OPTIONS = {field.name for field in fields(TileConfig) if field.init} - {
|
|
31
|
+
'tile_width',
|
|
32
|
+
'rotation_index',
|
|
33
|
+
'seed',
|
|
34
|
+
}
|
|
35
|
+
_COLOR_OPTIONS = {'gridlines_color', 'stroke', 'stroke_color'}
|
|
36
|
+
_OUTPUT_OPTIONS = {'path', 'formats', 'scale', 'background_col'}
|
|
37
|
+
_GRID_OPTIONS = {field.name for field in fields(Grid)}
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class ConfigurationError(ValueError):
|
|
41
|
+
"""Raised when a YAML config is invalid or cannot be used to render."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
def _mapping(value: Any, name: str) -> dict[str, Any]:
|
|
45
|
+
if not isinstance(value, dict):
|
|
46
|
+
raise ConfigurationError(f'{name} must be a mapping')
|
|
47
|
+
if any(not isinstance(key, str) for key in value):
|
|
48
|
+
raise ConfigurationError(f'{name} mapping keys must be strings')
|
|
49
|
+
return value
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _reject_unknown(options: dict[str, Any], allowed: set[str], name: str) -> None:
|
|
53
|
+
unknown = options.keys() - allowed
|
|
54
|
+
if unknown:
|
|
55
|
+
names = ', '.join(sorted(unknown))
|
|
56
|
+
raise ConfigurationError(f'Unknown {name} option(s): {names}')
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
def _load_yaml(path: Path) -> dict[str, Any]:
|
|
60
|
+
try:
|
|
61
|
+
with path.open(encoding='utf-8') as config_file:
|
|
62
|
+
config = yaml.safe_load(config_file)
|
|
63
|
+
except yaml.YAMLError as exc:
|
|
64
|
+
raise ConfigurationError(f'Invalid YAML in {path}: {exc}') from exc
|
|
65
|
+
except UnicodeError as exc:
|
|
66
|
+
raise ConfigurationError(f'Config {path} is not valid UTF-8: {exc}') from exc
|
|
67
|
+
except OSError as exc:
|
|
68
|
+
raise ConfigurationError(f'Cannot read config {path}: {exc}') from exc
|
|
69
|
+
return _mapping(config, 'Configuration')
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
def _make_factory(config: Any):
|
|
73
|
+
factory_config = _mapping(config, 'factory')
|
|
74
|
+
factory_options = dict(factory_config)
|
|
75
|
+
try:
|
|
76
|
+
kind = factory_options.pop('type')
|
|
77
|
+
except KeyError as exc:
|
|
78
|
+
raise ConfigurationError('factory.type is required') from exc
|
|
79
|
+
if not isinstance(kind, str) or kind not in _FACTORIES:
|
|
80
|
+
supported = ', '.join(_FACTORIES)
|
|
81
|
+
raise ConfigurationError(f'Unsupported factory.type {kind!r}; choose from {supported}')
|
|
82
|
+
|
|
83
|
+
builder = _FACTORIES[kind]
|
|
84
|
+
signature_options = {
|
|
85
|
+
name
|
|
86
|
+
for name, parameter in inspect.signature(builder).parameters.items()
|
|
87
|
+
if parameter.kind is not inspect.Parameter.VAR_KEYWORD
|
|
88
|
+
}
|
|
89
|
+
allowed_options = signature_options | _TILE_OPTIONS | _COLOR_OPTIONS
|
|
90
|
+
_reject_unknown(factory_options, allowed_options, 'factory')
|
|
91
|
+
|
|
92
|
+
if kind == 'node' and 'node_sequence' in factory_options:
|
|
93
|
+
try:
|
|
94
|
+
node_sequence = np.asarray(factory_options['node_sequence'])
|
|
95
|
+
except ValueError as exc:
|
|
96
|
+
raise ConfigurationError('factory.node_sequence must be a rectangular 2D list') from exc
|
|
97
|
+
if node_sequence.ndim != 2 or not node_sequence.size:
|
|
98
|
+
raise ConfigurationError('factory.node_sequence must be a non-empty 2D list')
|
|
99
|
+
factory_options['node_sequence'] = node_sequence
|
|
100
|
+
|
|
101
|
+
try:
|
|
102
|
+
return builder(**factory_options)
|
|
103
|
+
except (TypeError, ValueError) as exc:
|
|
104
|
+
raise ConfigurationError(f'Invalid factory configuration: {exc}') from exc
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def render_config(config_path: str | Path) -> list[Path]:
|
|
108
|
+
"""Render the images declared in a YAML config and return their paths."""
|
|
109
|
+
config_path = Path(config_path)
|
|
110
|
+
config = _load_yaml(config_path)
|
|
111
|
+
_reject_unknown(config, {'grid', 'factory', 'output'}, 'configuration')
|
|
112
|
+
if not {'grid', 'factory', 'output'} <= config.keys():
|
|
113
|
+
missing = ', '.join(sorted({'grid', 'factory', 'output'} - config.keys()))
|
|
114
|
+
raise ConfigurationError(f'Missing configuration section(s): {missing}')
|
|
115
|
+
|
|
116
|
+
grid_options = _mapping(config['grid'], 'grid')
|
|
117
|
+
_reject_unknown(grid_options, _GRID_OPTIONS, 'grid')
|
|
118
|
+
if not {'width', 'height'} <= grid_options.keys():
|
|
119
|
+
raise ConfigurationError('grid.width and grid.height are required')
|
|
120
|
+
for dimension in ('width', 'height'):
|
|
121
|
+
value = grid_options[dimension]
|
|
122
|
+
if isinstance(value, bool) or not isinstance(value, int) or value <= 0:
|
|
123
|
+
raise ConfigurationError(f'grid.{dimension} must be a positive integer')
|
|
124
|
+
try:
|
|
125
|
+
grid = Grid(**grid_options)
|
|
126
|
+
except (TypeError, ValueError) as exc:
|
|
127
|
+
raise ConfigurationError(f'Invalid grid configuration: {exc}') from exc
|
|
128
|
+
|
|
129
|
+
output = _mapping(config['output'], 'output')
|
|
130
|
+
_reject_unknown(output, _OUTPUT_OPTIONS, 'output')
|
|
131
|
+
if 'path' not in output:
|
|
132
|
+
raise ConfigurationError('output.path is required')
|
|
133
|
+
if not isinstance(output['path'], str) or not output['path']:
|
|
134
|
+
raise ConfigurationError('output.path must be a non-empty string')
|
|
135
|
+
output_path = Path(output['path'])
|
|
136
|
+
if not output_path.is_absolute():
|
|
137
|
+
output_path = config_path.resolve().parent / output_path
|
|
138
|
+
|
|
139
|
+
formats = output.get('formats', ['png', 'svg'])
|
|
140
|
+
if (
|
|
141
|
+
not isinstance(formats, list)
|
|
142
|
+
or not formats
|
|
143
|
+
or any(not isinstance(fmt, str) or fmt not in {'png', 'svg'} for fmt in formats)
|
|
144
|
+
):
|
|
145
|
+
raise ConfigurationError(
|
|
146
|
+
'output.formats must be a non-empty list of unique png and/or svg values'
|
|
147
|
+
)
|
|
148
|
+
if len(set(formats)) != len(formats):
|
|
149
|
+
raise ConfigurationError(
|
|
150
|
+
'output.formats must be a non-empty list of unique png and/or svg values'
|
|
151
|
+
)
|
|
152
|
+
|
|
153
|
+
scale = output.get('scale', 1.0)
|
|
154
|
+
if (
|
|
155
|
+
isinstance(scale, bool)
|
|
156
|
+
or not isinstance(scale, (int, float))
|
|
157
|
+
or not math.isfinite(scale)
|
|
158
|
+
or scale <= 0
|
|
159
|
+
):
|
|
160
|
+
raise ConfigurationError('output.scale must be a positive finite number')
|
|
161
|
+
|
|
162
|
+
factory = _make_factory(config['factory'])
|
|
163
|
+
output_path.parent.mkdir(parents=True, exist_ok=True)
|
|
164
|
+
rendered_paths = []
|
|
165
|
+
for image_format in formats:
|
|
166
|
+
image_path = output_path.with_suffix(f'.{image_format}')
|
|
167
|
+
save = save_png if image_format == 'png' else save_svg
|
|
168
|
+
try:
|
|
169
|
+
save(
|
|
170
|
+
str(image_path),
|
|
171
|
+
grid,
|
|
172
|
+
factory,
|
|
173
|
+
scale=scale,
|
|
174
|
+
background_col=output.get('background_col'),
|
|
175
|
+
)
|
|
176
|
+
except (TypeError, ValueError, cairo.Error) as exc:
|
|
177
|
+
raise ConfigurationError(f'Cannot render {image_path}: {exc}') from exc
|
|
178
|
+
rendered_paths.append(image_path)
|
|
179
|
+
return rendered_paths
|
|
180
|
+
|
|
181
|
+
|
|
182
|
+
def main() -> None:
|
|
183
|
+
"""Run the easy-tiler command."""
|
|
184
|
+
parser = argparse.ArgumentParser(
|
|
185
|
+
prog='easy-tiler',
|
|
186
|
+
description='Render tile patterns from a YAML configuration file.',
|
|
187
|
+
)
|
|
188
|
+
parser.add_argument('config', type=Path, help='path to the YAML configuration file')
|
|
189
|
+
args = parser.parse_args()
|
|
190
|
+
try:
|
|
191
|
+
paths = render_config(args.config)
|
|
192
|
+
except (ConfigurationError, OSError) as exc:
|
|
193
|
+
parser.error(str(exc))
|
|
194
|
+
for path in paths:
|
|
195
|
+
print(f'Wrote {path}')
|
easy_tiler/colors.py
ADDED
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Selection of color palettes for use in tiling.
|
|
2
|
+
Custom palettes found on https://y-sunflower.github.io/pypalettes/
|
|
3
|
+
"""
|
|
4
|
+
|
|
5
|
+
from __future__ import annotations
|
|
6
|
+
|
|
7
|
+
import random
|
|
8
|
+
from dataclasses import dataclass, field
|
|
9
|
+
|
|
10
|
+
import colorcet as cc
|
|
11
|
+
from numpy import ndarray
|
|
12
|
+
from pypalettes import load_palette
|
|
13
|
+
|
|
14
|
+
CUSTOM_PALETTES: dict[str, dict[str, str]] = {
|
|
15
|
+
'FridaKahlo': {
|
|
16
|
+
'black': '#121510FF',
|
|
17
|
+
'blue': '#203caaFF',
|
|
18
|
+
'green': '#6D8325FF',
|
|
19
|
+
'beige': '#D6CFB7FF',
|
|
20
|
+
'yellow': '#E5AD4FFF',
|
|
21
|
+
'brown': '#BD5630FF',
|
|
22
|
+
},
|
|
23
|
+
'BlueRidgePkwy': {
|
|
24
|
+
'red': '#EC8FA3FF',
|
|
25
|
+
'orange': '#FCBA65FF',
|
|
26
|
+
'beige': '#FAECCFFF',
|
|
27
|
+
'purple': '#8D7F99FF',
|
|
28
|
+
'green': '#8C9D57FF',
|
|
29
|
+
'blue': '#163343FF',
|
|
30
|
+
},
|
|
31
|
+
'Budnitz': {
|
|
32
|
+
'green': '#86DD45FF',
|
|
33
|
+
'yellow': '#F6E71CFF',
|
|
34
|
+
'orange': '#FDA900FF',
|
|
35
|
+
'red': '#FD5300FF',
|
|
36
|
+
'purple': '#57348BFF',
|
|
37
|
+
},
|
|
38
|
+
'ClaudeMonet': {
|
|
39
|
+
'green': '#184430FF',
|
|
40
|
+
'lightgreen': '#548150FF',
|
|
41
|
+
'orange': '#DEB738FF',
|
|
42
|
+
'brown': '#734321FF',
|
|
43
|
+
'red': '#852419FF',
|
|
44
|
+
'lightblue': '#4885A4FF',
|
|
45
|
+
'blue': '#395A92FF',
|
|
46
|
+
'olive': '#7EA860FF',
|
|
47
|
+
'purple': '#B985BAFF',
|
|
48
|
+
'darkblue': '#4C7899FF',
|
|
49
|
+
'darkgreen': '#2F5136FF',
|
|
50
|
+
'yellow': '#B1B94CFF',
|
|
51
|
+
'beige': '#E5DCBEFF',
|
|
52
|
+
},
|
|
53
|
+
'ColorsOfTheWind': {
|
|
54
|
+
'cyan': '#9cf1ff',
|
|
55
|
+
'pink': '#ff9acd',
|
|
56
|
+
'yellow': '#fff091',
|
|
57
|
+
'green': '#b1ffa6',
|
|
58
|
+
'purple': '#dda3ff',
|
|
59
|
+
'beige': '#E6D5C3',
|
|
60
|
+
'blue': '#b8dbec',
|
|
61
|
+
'gray': '#c9b8ec',
|
|
62
|
+
'red': '#ecb8db',
|
|
63
|
+
'orange': '#ecc9b8',
|
|
64
|
+
},
|
|
65
|
+
'Apricot': {
|
|
66
|
+
'red': '#D72000FF',
|
|
67
|
+
'orange': '#EE6100FF',
|
|
68
|
+
'yellow': '#FFAD0AFF',
|
|
69
|
+
'green': '#1BB6AFFF',
|
|
70
|
+
'blue': '#9093A2FF',
|
|
71
|
+
'purple': '#132157FF',
|
|
72
|
+
},
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
STANDARD_PALETTE: dict[str, tuple[float, float, float, float]] = {
|
|
76
|
+
'black': (0, 0, 0, 1),
|
|
77
|
+
'white': (1, 1, 1, 1),
|
|
78
|
+
'red': (1, 0, 0, 1),
|
|
79
|
+
'lightred': (1, 0.5, 0.5, 1),
|
|
80
|
+
'green': (0, 1, 0, 1),
|
|
81
|
+
'lightgreen': (0.5, 1, 0.5, 1),
|
|
82
|
+
'blue': (0, 0, 1, 1),
|
|
83
|
+
'lightblue': (0.56, 0.83, 1, 1),
|
|
84
|
+
'yellow': (1, 1, 0, 1),
|
|
85
|
+
'lightyellow': (1, 1, 0.5, 1),
|
|
86
|
+
'gray': (0.5, 0.5, 0.5, 1),
|
|
87
|
+
'brown': (0.6, 0.4, 0.2, 1),
|
|
88
|
+
'lightbrown': (0.8, 0.6, 0.4, 1),
|
|
89
|
+
'beige': (0.96, 0.96, 0.86, 1),
|
|
90
|
+
'magenta': (1, 0, 1, 1),
|
|
91
|
+
'lightmagenta': (1, 0.533, 0.82, 1),
|
|
92
|
+
'cyan': (0, 1, 1, 1),
|
|
93
|
+
'lightcyan': (0.5, 1, 1, 1),
|
|
94
|
+
'purple': (0.7, 0.2, 0.5, 1),
|
|
95
|
+
'lightpurple': (0.8, 0.6, 0.8, 1),
|
|
96
|
+
'orange': (1, 0.75, 0.0, 1),
|
|
97
|
+
'lightorange': (1, 0.85, 0.5, 1),
|
|
98
|
+
'pink': (1, 0.5, 0.8, 1),
|
|
99
|
+
'lightpink': (1, 0.8, 0.9, 1),
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
|
|
103
|
+
@dataclass
|
|
104
|
+
class ColorConfig:
|
|
105
|
+
"""Configure tile colors, including sequence/roll choices and color RNG."""
|
|
106
|
+
|
|
107
|
+
primary_color: str | tuple | list | None = None
|
|
108
|
+
secondary_color: str | tuple | list | None = None
|
|
109
|
+
gridlines_color: str | tuple | None = None
|
|
110
|
+
stroke_color: str | tuple | None = None
|
|
111
|
+
stroke: bool = False
|
|
112
|
+
palette: str | CustomPalette = field(default_factory=lambda: 'Standard')
|
|
113
|
+
num_colors: int | None = None
|
|
114
|
+
primary_colors: list | None = None
|
|
115
|
+
secondary_colors: list | None = None
|
|
116
|
+
color_index: int | None = None
|
|
117
|
+
roll_index: int = 0
|
|
118
|
+
seed: float | str | bytes | bytearray | None = None
|
|
119
|
+
|
|
120
|
+
_palette: CustomPalette = field(init=False)
|
|
121
|
+
rng: random.Random = field(init=False)
|
|
122
|
+
|
|
123
|
+
def __post_init__(self) -> None:
|
|
124
|
+
self.rng = random.Random(self.seed)
|
|
125
|
+
self._palette = (
|
|
126
|
+
self.palette
|
|
127
|
+
if isinstance(self.palette, CustomPalette)
|
|
128
|
+
else CustomPalette(self.palette or 'Standard', self.num_colors, self.rng)
|
|
129
|
+
)
|
|
130
|
+
if self.gridlines_color == 'darker':
|
|
131
|
+
self.gridlines_color = self.get_darker_color()
|
|
132
|
+
elif self.gridlines_color == 'brighter':
|
|
133
|
+
self.gridlines_color = self.get_brighter_color()
|
|
134
|
+
else:
|
|
135
|
+
self.gridlines_color = self._palette.get(self.gridlines_color)
|
|
136
|
+
if self.stroke_color == 'darker':
|
|
137
|
+
self.stroke_color = self.get_darker_color()
|
|
138
|
+
elif self.stroke_color == 'brighter':
|
|
139
|
+
self.stroke_color = self.get_brighter_color()
|
|
140
|
+
else:
|
|
141
|
+
self.stroke_color = self._palette.get(self.stroke_color)
|
|
142
|
+
|
|
143
|
+
@classmethod
|
|
144
|
+
def get_palette(cls, palette: str, num_colors: int | None = None) -> list:
|
|
145
|
+
return CustomPalette(palette, num_colors).colors
|
|
146
|
+
|
|
147
|
+
def _resolve_color(
|
|
148
|
+
self,
|
|
149
|
+
val,
|
|
150
|
+
index: int = 0,
|
|
151
|
+
sequence_colors: list | None = None,
|
|
152
|
+
) -> tuple:
|
|
153
|
+
"""Resolve a color value to an RGBA tuple."""
|
|
154
|
+
if val is None:
|
|
155
|
+
return (0, 0, 0, 0)
|
|
156
|
+
|
|
157
|
+
index = self.color_index if self.color_index is not None else index
|
|
158
|
+
|
|
159
|
+
if val in ('sequence', 'roll'):
|
|
160
|
+
if not sequence_colors:
|
|
161
|
+
raise ValueError(f'{val!r} color requires sequence colors')
|
|
162
|
+
if val == 'roll':
|
|
163
|
+
index -= self.roll_index
|
|
164
|
+
return self._palette.get(sequence_colors[index % len(sequence_colors)])
|
|
165
|
+
|
|
166
|
+
if isinstance(val, list):
|
|
167
|
+
val = val[index % len(val)]
|
|
168
|
+
|
|
169
|
+
return self._palette.get(val)
|
|
170
|
+
|
|
171
|
+
def get_primary_color(self, index: int = 0) -> tuple:
|
|
172
|
+
return self._resolve_color(self.primary_color, index, self.primary_colors)
|
|
173
|
+
|
|
174
|
+
def get_secondary_color(self) -> tuple:
|
|
175
|
+
return self._resolve_color(self.secondary_color, sequence_colors=self.secondary_colors)
|
|
176
|
+
|
|
177
|
+
def get_darker_color(self, change: float = 0.2) -> tuple:
|
|
178
|
+
primary_color = self.get_primary_color()
|
|
179
|
+
return (
|
|
180
|
+
max(0.0, primary_color[0] - change),
|
|
181
|
+
max(0.0, primary_color[1] - change),
|
|
182
|
+
max(0.0, primary_color[2] - change),
|
|
183
|
+
primary_color[3],
|
|
184
|
+
)
|
|
185
|
+
|
|
186
|
+
def get_brighter_color(self, change: float = 0.2) -> tuple:
|
|
187
|
+
primary_color = self.get_primary_color()
|
|
188
|
+
return (
|
|
189
|
+
min(1.0, primary_color[0] + change),
|
|
190
|
+
min(1.0, primary_color[1] + change),
|
|
191
|
+
min(1.0, primary_color[2] + change),
|
|
192
|
+
primary_color[3],
|
|
193
|
+
)
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
class CustomPalette:
|
|
197
|
+
"""Load a palette and resolve its colors to RGBA values."""
|
|
198
|
+
|
|
199
|
+
def __init__(
|
|
200
|
+
self,
|
|
201
|
+
name: str = 'Standard',
|
|
202
|
+
num_colors: int | None = None,
|
|
203
|
+
rng: random.Random | None = None,
|
|
204
|
+
) -> None:
|
|
205
|
+
"""
|
|
206
|
+
Initialize the CustomPalette class.
|
|
207
|
+
|
|
208
|
+
name: Name of the palette to load. Can be 'Standard', a custom palette name,
|
|
209
|
+
or a palette name from colorcet.
|
|
210
|
+
num_colors: Number of colors to include in the palette.
|
|
211
|
+
"""
|
|
212
|
+
self.palette: dict[str, tuple[float, float, float, float]] = {}
|
|
213
|
+
self.colors: list[str] | list[tuple[float, float, float, float]] = []
|
|
214
|
+
if rng is None:
|
|
215
|
+
rng = random.Random()
|
|
216
|
+
self.rng = rng
|
|
217
|
+
|
|
218
|
+
if name == 'Standard':
|
|
219
|
+
palette: dict[str, tuple[float, float, float, float]] = STANDARD_PALETTE
|
|
220
|
+
elif name in CUSTOM_PALETTES:
|
|
221
|
+
palette: dict[str, str] = CUSTOM_PALETTES[name]
|
|
222
|
+
else:
|
|
223
|
+
try:
|
|
224
|
+
palette: list[str] = cc.palette[name]
|
|
225
|
+
except KeyError:
|
|
226
|
+
palette: list[str] = load_palette(name)
|
|
227
|
+
|
|
228
|
+
if isinstance(palette, dict):
|
|
229
|
+
self.palette = palette # Dictionary of named colors # ty: ignore[invalid-assignment]
|
|
230
|
+
self.colors = list(palette.values()) # List of hex color strings # ty: ignore[invalid-assignment]
|
|
231
|
+
else:
|
|
232
|
+
self.palette = {}
|
|
233
|
+
self.colors = list(palette)
|
|
234
|
+
|
|
235
|
+
if num_colors is not None:
|
|
236
|
+
self.colors = self.colors[:num_colors]
|
|
237
|
+
|
|
238
|
+
def _hex_to_rgba(self, hex_color: str) -> tuple[float, float, float, float]:
|
|
239
|
+
"""Convert a hex color string to an RGBA tuple."""
|
|
240
|
+
hex_color = hex_color.lstrip('#')
|
|
241
|
+
r = int(hex_color[0:2], 16) / 255.0
|
|
242
|
+
g = int(hex_color[2:4], 16) / 255.0
|
|
243
|
+
b = int(hex_color[4:6], 16) / 255.0
|
|
244
|
+
a = int(hex_color[6:8], 16) / 255.0 if len(hex_color) >= 8 else 1.0
|
|
245
|
+
return (r, g, b, a)
|
|
246
|
+
|
|
247
|
+
def get(
|
|
248
|
+
self,
|
|
249
|
+
val: float | list | tuple | ndarray | str | None,
|
|
250
|
+
) -> tuple[float, float, float, float]:
|
|
251
|
+
"""Create an RGBA color tuple from a variety of inputs."""
|
|
252
|
+
if val is None:
|
|
253
|
+
return (0, 0, 0, 0) # transparent
|
|
254
|
+
if isinstance(val, (int, float)):
|
|
255
|
+
return (val, val, val, 1)
|
|
256
|
+
if isinstance(val, (list, tuple)):
|
|
257
|
+
if len(val) == 3:
|
|
258
|
+
return (*val, 1)
|
|
259
|
+
return tuple(val)
|
|
260
|
+
if isinstance(val, str):
|
|
261
|
+
if val.startswith('#'):
|
|
262
|
+
return self._hex_to_rgba(val)
|
|
263
|
+
if val == 'random_rgb':
|
|
264
|
+
return (self.rng.random(), self.rng.random(), self.rng.random(), 1)
|
|
265
|
+
if val in ('random', 'random_choice'):
|
|
266
|
+
return self.get(self.rng.choice(self.colors))
|
|
267
|
+
if val == 'transparent':
|
|
268
|
+
return (0, 0, 0, 0)
|
|
269
|
+
try:
|
|
270
|
+
return self.get(self.palette[val])
|
|
271
|
+
except KeyError:
|
|
272
|
+
try:
|
|
273
|
+
return STANDARD_PALETTE[
|
|
274
|
+
val
|
|
275
|
+
] # Fall back to standard colors if not found in palette
|
|
276
|
+
except KeyError:
|
|
277
|
+
print(TypeError(f'Unsupported color value: {val} - returning transparent'))
|
|
278
|
+
return (0, 0, 0, 0) # transparent
|
|
279
|
+
return (0, 0, 0, 0) # transparent
|