pboot-validator 1.0.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.
- pboot_validator/__init__.py +461 -0
- pboot_validator/_internal/__init__.py +0 -0
- pboot_validator/_internal/_config.py +408 -0
- pboot_validator/_internal/_contextlib.py +84 -0
- pboot_validator/_internal/_core_metadata.py +97 -0
- pboot_validator/_internal/_core_utils.py +156 -0
- pboot_validator/_internal/_dataclasses.py +327 -0
- pboot_validator/_internal/_decorators.py +906 -0
- pboot_validator/_internal/_decorators_v1.py +174 -0
- pboot_validator/_internal/_discriminated_union.py +510 -0
- pboot_validator/_internal/_docs_extraction.py +128 -0
- pboot_validator/_internal/_fields.py +910 -0
- pboot_validator/_internal/_forward_ref.py +23 -0
- pboot_validator/_internal/_generate_schema.py +3053 -0
- pboot_validator/_internal/_generics.py +572 -0
- pboot_validator/_internal/_git.py +27 -0
- pboot_validator/_internal/_import_utils.py +20 -0
- pboot_validator/_internal/_known_annotated_metadata.py +412 -0
- pboot_validator/_internal/_mock_val_ser.py +241 -0
- pboot_validator/_internal/_model_construction.py +833 -0
- pboot_validator/_internal/_namespace_utils.py +300 -0
- pboot_validator/_internal/_repr.py +129 -0
- pboot_validator/_internal/_schema_gather.py +49 -0
- pboot_validator/_internal/_schema_generation_shared.py +126 -0
- pboot_validator/_internal/_serializers.py +59 -0
- pboot_validator/_internal/_signature.py +193 -0
- pboot_validator/_internal/_type_refs.py +128 -0
- pboot_validator/_internal/_typing_extra.py +506 -0
- pboot_validator/_internal/_utils.py +433 -0
- pboot_validator/_internal/_validate_call.py +141 -0
- pboot_validator/_internal/_validators.py +541 -0
- pboot_validator/_migration.py +317 -0
- pboot_validator/alias_generators.py +62 -0
- pboot_validator/aliases.py +136 -0
- pboot_validator/annotated_handlers.py +123 -0
- pboot_validator/class_validators.py +5 -0
- pboot_validator/color.py +605 -0
- pboot_validator/config.py +1295 -0
- pboot_validator/dataclasses.py +385 -0
- pboot_validator/datetime_parse.py +5 -0
- pboot_validator/decorator.py +5 -0
- pboot_validator/deprecated/__init__.py +0 -0
- pboot_validator/deprecated/class_validators.py +257 -0
- pboot_validator/deprecated/config.py +72 -0
- pboot_validator/deprecated/copy_internals.py +224 -0
- pboot_validator/deprecated/decorator.py +286 -0
- pboot_validator/deprecated/json.py +142 -0
- pboot_validator/deprecated/parse.py +81 -0
- pboot_validator/deprecated/tools.py +104 -0
- pboot_validator/env_settings.py +5 -0
- pboot_validator/error_wrappers.py +5 -0
- pboot_validator/errors.py +185 -0
- pboot_validator/experimental/__init__.py +1 -0
- pboot_validator/experimental/arguments_schema.py +44 -0
- pboot_validator/experimental/missing_sentinel.py +29 -0
- pboot_validator/experimental/pipeline.py +684 -0
- pboot_validator/fields.py +2065 -0
- pboot_validator/functional_serializers.py +461 -0
- pboot_validator/functional_validators.py +920 -0
- pboot_validator/generics.py +5 -0
- pboot_validator/json.py +5 -0
- pboot_validator/json_schema.py +3283 -0
- pboot_validator/main.py +1947 -0
- pboot_validator/mypy.py +1469 -0
- pboot_validator/networks.py +1417 -0
- pboot_validator/parse.py +5 -0
- pboot_validator/plugin/__init__.py +190 -0
- pboot_validator/plugin/_loader.py +56 -0
- pboot_validator/plugin/_schema_validator.py +152 -0
- pboot_validator/py.typed +0 -0
- pboot_validator/root_model.py +189 -0
- pboot_validator/schema.py +5 -0
- pboot_validator/tools.py +5 -0
- pboot_validator/type_adapter.py +780 -0
- pboot_validator/types.py +3405 -0
- pboot_validator/typing.py +5 -0
- pboot_validator/utils.py +5 -0
- pboot_validator/v1/__init__.py +131 -0
- pboot_validator/v1/_hypothesis_plugin.py +391 -0
- pboot_validator/v1/annotated_types.py +72 -0
- pboot_validator/v1/class_validators.py +361 -0
- pboot_validator/v1/color.py +494 -0
- pboot_validator/v1/config.py +191 -0
- pboot_validator/v1/dataclasses.py +503 -0
- pboot_validator/v1/datetime_parse.py +248 -0
- pboot_validator/v1/decorator.py +264 -0
- pboot_validator/v1/env_settings.py +350 -0
- pboot_validator/v1/error_wrappers.py +161 -0
- pboot_validator/v1/errors.py +646 -0
- pboot_validator/v1/fields.py +1253 -0
- pboot_validator/v1/generics.py +400 -0
- pboot_validator/v1/json.py +112 -0
- pboot_validator/v1/main.py +1130 -0
- pboot_validator/v1/mypy.py +950 -0
- pboot_validator/v1/networks.py +747 -0
- pboot_validator/v1/parse.py +66 -0
- pboot_validator/v1/py.typed +0 -0
- pboot_validator/v1/schema.py +1163 -0
- pboot_validator/v1/tools.py +92 -0
- pboot_validator/v1/types.py +1213 -0
- pboot_validator/v1/typing.py +627 -0
- pboot_validator/v1/utils.py +807 -0
- pboot_validator/v1/validators.py +768 -0
- pboot_validator/v1/version.py +38 -0
- pboot_validator/validate_call_decorator.py +121 -0
- pboot_validator/validators.py +5 -0
- pboot_validator/version.py +113 -0
- pboot_validator/warnings.py +130 -0
- pboot_validator-1.0.0.dist-info/METADATA +93 -0
- pboot_validator-1.0.0.dist-info/RECORD +112 -0
- pboot_validator-1.0.0.dist-info/WHEEL +4 -0
- pboot_validator-1.0.0.dist-info/licenses/LICENSE +21 -0
pboot_validator/color.py
ADDED
|
@@ -0,0 +1,605 @@
|
|
|
1
|
+
"""Color definitions are used as per the CSS3
|
|
2
|
+
[CSS Color Module Level 3](http://www.w3.org/TR/css3-color/#svg-color) specification.
|
|
3
|
+
|
|
4
|
+
A few colors have multiple names referring to the sames colors, eg. `grey` and `gray` or `aqua` and `cyan`.
|
|
5
|
+
|
|
6
|
+
In these cases the _last_ color when sorted alphabetically takes preferences,
|
|
7
|
+
eg. `Color((0, 255, 255)).as_named() == 'cyan'` because "cyan" comes after "aqua".
|
|
8
|
+
|
|
9
|
+
Warning: Deprecated
|
|
10
|
+
The `Color` class is deprecated, use `pydantic_extra_types` instead.
|
|
11
|
+
See [`pydantic-extra-types.Color`](../usage/types/extra_types/color_types.md)
|
|
12
|
+
for more information.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
import math
|
|
16
|
+
import re
|
|
17
|
+
from collections.abc import Callable
|
|
18
|
+
from colorsys import hls_to_rgb, rgb_to_hls
|
|
19
|
+
from typing import Any, TypeAlias, cast
|
|
20
|
+
|
|
21
|
+
from pydantic_core import CoreSchema, PydanticCustomError, core_schema
|
|
22
|
+
from typing_extensions import deprecated
|
|
23
|
+
|
|
24
|
+
from ._internal import _repr
|
|
25
|
+
from ._internal._schema_generation_shared import GetJsonSchemaHandler as _GetJsonSchemaHandler
|
|
26
|
+
from .json_schema import JsonSchemaValue
|
|
27
|
+
from .warnings import PydanticDeprecatedSince20
|
|
28
|
+
|
|
29
|
+
ColorTuple: TypeAlias = tuple[int, int, int] | tuple[int, int, int, float]
|
|
30
|
+
ColorType: TypeAlias = ColorTuple | str
|
|
31
|
+
HslColorTuple: TypeAlias = tuple[float, float, float] | tuple[float, float, float, float]
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
class RGBA:
|
|
35
|
+
"""Internal use only as a representation of a color."""
|
|
36
|
+
|
|
37
|
+
__slots__ = 'r', 'g', 'b', 'alpha', '_tuple'
|
|
38
|
+
|
|
39
|
+
def __init__(self, r: float, g: float, b: float, alpha: float | None):
|
|
40
|
+
self.r = r
|
|
41
|
+
self.g = g
|
|
42
|
+
self.b = b
|
|
43
|
+
self.alpha = alpha
|
|
44
|
+
|
|
45
|
+
self._tuple: tuple[float, float, float, float | None] = (r, g, b, alpha)
|
|
46
|
+
|
|
47
|
+
def __getitem__(self, item: Any) -> Any:
|
|
48
|
+
return self._tuple[item]
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
# these are not compiled here to avoid import slowdown, they'll be compiled the first time they're used, then cached
|
|
52
|
+
_r_255 = r'(\d{1,3}(?:\.\d+)?)'
|
|
53
|
+
_r_comma = r'\s*,\s*'
|
|
54
|
+
_r_alpha = r'(\d(?:\.\d+)?|\.\d+|\d{1,2}%)'
|
|
55
|
+
_r_h = r'(-?\d+(?:\.\d+)?|-?\.\d+)(deg|rad|turn)?'
|
|
56
|
+
_r_sl = r'(\d{1,3}(?:\.\d+)?)%'
|
|
57
|
+
r_hex_short = r'\s*(?:#|0x)?([0-9a-f])([0-9a-f])([0-9a-f])([0-9a-f])?\s*'
|
|
58
|
+
r_hex_long = r'\s*(?:#|0x)?([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})([0-9a-f]{2})?\s*'
|
|
59
|
+
# CSS3 RGB examples: rgb(0, 0, 0), rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 50%)
|
|
60
|
+
r_rgb = rf'\s*rgba?\(\s*{_r_255}{_r_comma}{_r_255}{_r_comma}{_r_255}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
|
|
61
|
+
# CSS3 HSL examples: hsl(270, 60%, 50%), hsla(270, 60%, 50%, 0.5), hsla(270, 60%, 50%, 50%)
|
|
62
|
+
r_hsl = rf'\s*hsla?\(\s*{_r_h}{_r_comma}{_r_sl}{_r_comma}{_r_sl}(?:{_r_comma}{_r_alpha})?\s*\)\s*'
|
|
63
|
+
# CSS4 RGB examples: rgb(0 0 0), rgb(0 0 0 / 0.5), rgb(0 0 0 / 50%), rgba(0 0 0 / 50%)
|
|
64
|
+
r_rgb_v4_style = rf'\s*rgba?\(\s*{_r_255}\s+{_r_255}\s+{_r_255}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
|
|
65
|
+
# CSS4 HSL examples: hsl(270 60% 50%), hsl(270 60% 50% / 0.5), hsl(270 60% 50% / 50%), hsla(270 60% 50% / 50%)
|
|
66
|
+
r_hsl_v4_style = rf'\s*hsla?\(\s*{_r_h}\s+{_r_sl}\s+{_r_sl}(?:\s*/\s*{_r_alpha})?\s*\)\s*'
|
|
67
|
+
|
|
68
|
+
# colors where the two hex characters are the same, if all colors match this the short version of hex colors can be used
|
|
69
|
+
repeat_colors = {int(c * 2, 16) for c in '0123456789abcdef'}
|
|
70
|
+
rads = 2 * math.pi
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
@deprecated(
|
|
74
|
+
'The `Color` class is deprecated, use `pydantic_extra_types` instead. '
|
|
75
|
+
'See https://pydantic.dev/docs/validation/latest/api/pydantic-extra-types/pydantic_extra_types_color/.',
|
|
76
|
+
category=PydanticDeprecatedSince20,
|
|
77
|
+
)
|
|
78
|
+
class Color(_repr.Representation):
|
|
79
|
+
"""Represents a color."""
|
|
80
|
+
|
|
81
|
+
__slots__ = '_original', '_rgba'
|
|
82
|
+
|
|
83
|
+
def __init__(self, value: ColorType) -> None:
|
|
84
|
+
self._rgba: RGBA
|
|
85
|
+
self._original: ColorType
|
|
86
|
+
if isinstance(value, (tuple, list)):
|
|
87
|
+
self._rgba = parse_tuple(value)
|
|
88
|
+
elif isinstance(value, str):
|
|
89
|
+
self._rgba = parse_str(value)
|
|
90
|
+
elif isinstance(value, Color):
|
|
91
|
+
self._rgba = value._rgba
|
|
92
|
+
value = value._original
|
|
93
|
+
else:
|
|
94
|
+
raise PydanticCustomError(
|
|
95
|
+
'color_error', 'value is not a valid color: value must be a tuple, list or string'
|
|
96
|
+
)
|
|
97
|
+
|
|
98
|
+
# if we've got here value must be a valid color
|
|
99
|
+
self._original = value
|
|
100
|
+
|
|
101
|
+
@classmethod
|
|
102
|
+
def __get_pydantic_json_schema__(
|
|
103
|
+
cls, core_schema: core_schema.CoreSchema, handler: _GetJsonSchemaHandler
|
|
104
|
+
) -> JsonSchemaValue:
|
|
105
|
+
field_schema = {}
|
|
106
|
+
field_schema.update(type='string', format='color')
|
|
107
|
+
return field_schema
|
|
108
|
+
|
|
109
|
+
def original(self) -> ColorType:
|
|
110
|
+
"""Original value passed to `Color`."""
|
|
111
|
+
return self._original
|
|
112
|
+
|
|
113
|
+
def as_named(self, *, fallback: bool = False) -> str:
|
|
114
|
+
"""Returns the name of the color if it can be found in `COLORS_BY_VALUE` dictionary,
|
|
115
|
+
otherwise returns the hexadecimal representation of the color or raises `ValueError`.
|
|
116
|
+
|
|
117
|
+
Args:
|
|
118
|
+
fallback: If True, falls back to returning the hexadecimal representation of
|
|
119
|
+
the color instead of raising a ValueError when no named color is found.
|
|
120
|
+
|
|
121
|
+
Returns:
|
|
122
|
+
The name of the color, or the hexadecimal representation of the color.
|
|
123
|
+
|
|
124
|
+
Raises:
|
|
125
|
+
ValueError: When no named color is found and fallback is `False`.
|
|
126
|
+
"""
|
|
127
|
+
if self._rgba.alpha is None:
|
|
128
|
+
rgb = cast(tuple[int, int, int], self.as_rgb_tuple())
|
|
129
|
+
try:
|
|
130
|
+
return COLORS_BY_VALUE[rgb]
|
|
131
|
+
except KeyError as e:
|
|
132
|
+
if fallback:
|
|
133
|
+
return self.as_hex()
|
|
134
|
+
else:
|
|
135
|
+
raise ValueError('no named color found, use fallback=True, as_hex() or as_rgb()') from e
|
|
136
|
+
else:
|
|
137
|
+
return self.as_hex()
|
|
138
|
+
|
|
139
|
+
def as_hex(self) -> str:
|
|
140
|
+
"""Returns the hexadecimal representation of the color.
|
|
141
|
+
|
|
142
|
+
Hex string representing the color can be 3, 4, 6, or 8 characters depending on whether the string
|
|
143
|
+
a "short" representation of the color is possible and whether there's an alpha channel.
|
|
144
|
+
|
|
145
|
+
Returns:
|
|
146
|
+
The hexadecimal representation of the color.
|
|
147
|
+
"""
|
|
148
|
+
values = [float_to_255(c) for c in self._rgba[:3]]
|
|
149
|
+
if self._rgba.alpha is not None:
|
|
150
|
+
values.append(float_to_255(self._rgba.alpha))
|
|
151
|
+
|
|
152
|
+
as_hex = ''.join(f'{v:02x}' for v in values)
|
|
153
|
+
if all(c in repeat_colors for c in values):
|
|
154
|
+
as_hex = ''.join(as_hex[c] for c in range(0, len(as_hex), 2))
|
|
155
|
+
return '#' + as_hex
|
|
156
|
+
|
|
157
|
+
def as_rgb(self) -> str:
|
|
158
|
+
"""Color as an `rgb(<r>, <g>, <b>)` or `rgba(<r>, <g>, <b>, <a>)` string."""
|
|
159
|
+
if self._rgba.alpha is None:
|
|
160
|
+
return f'rgb({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)})'
|
|
161
|
+
else:
|
|
162
|
+
return (
|
|
163
|
+
f'rgba({float_to_255(self._rgba.r)}, {float_to_255(self._rgba.g)}, {float_to_255(self._rgba.b)}, '
|
|
164
|
+
f'{round(self._alpha_float(), 2)})'
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
def as_rgb_tuple(self, *, alpha: bool | None = None) -> ColorTuple:
|
|
168
|
+
"""Returns the color as an RGB or RGBA tuple.
|
|
169
|
+
|
|
170
|
+
Args:
|
|
171
|
+
alpha: Whether to include the alpha channel. There are three options for this input:
|
|
172
|
+
|
|
173
|
+
- `None` (default): Include alpha only if it's set. (e.g. not `None`)
|
|
174
|
+
- `True`: Always include alpha.
|
|
175
|
+
- `False`: Always omit alpha.
|
|
176
|
+
|
|
177
|
+
Returns:
|
|
178
|
+
A tuple that contains the values of the red, green, and blue channels in the range 0 to 255.
|
|
179
|
+
If alpha is included, it is in the range 0 to 1.
|
|
180
|
+
"""
|
|
181
|
+
r, g, b = (float_to_255(c) for c in self._rgba[:3])
|
|
182
|
+
if alpha is None:
|
|
183
|
+
if self._rgba.alpha is None:
|
|
184
|
+
return r, g, b
|
|
185
|
+
else:
|
|
186
|
+
return r, g, b, self._alpha_float()
|
|
187
|
+
elif alpha:
|
|
188
|
+
return r, g, b, self._alpha_float()
|
|
189
|
+
else:
|
|
190
|
+
# alpha is False
|
|
191
|
+
return r, g, b
|
|
192
|
+
|
|
193
|
+
def as_hsl(self) -> str:
|
|
194
|
+
"""Color as an `hsl(<h>, <s>, <l>)` or `hsl(<h>, <s>, <l>, <a>)` string."""
|
|
195
|
+
if self._rgba.alpha is None:
|
|
196
|
+
h, s, li = self.as_hsl_tuple(alpha=False) # type: ignore
|
|
197
|
+
return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%})'
|
|
198
|
+
else:
|
|
199
|
+
h, s, li, a = self.as_hsl_tuple(alpha=True) # type: ignore
|
|
200
|
+
return f'hsl({h * 360:0.0f}, {s:0.0%}, {li:0.0%}, {round(a, 2)})'
|
|
201
|
+
|
|
202
|
+
def as_hsl_tuple(self, *, alpha: bool | None = None) -> HslColorTuple:
|
|
203
|
+
"""Returns the color as an HSL or HSLA tuple.
|
|
204
|
+
|
|
205
|
+
Args:
|
|
206
|
+
alpha: Whether to include the alpha channel.
|
|
207
|
+
|
|
208
|
+
- `None` (default): Include the alpha channel only if it's set (e.g. not `None`).
|
|
209
|
+
- `True`: Always include alpha.
|
|
210
|
+
- `False`: Always omit alpha.
|
|
211
|
+
|
|
212
|
+
Returns:
|
|
213
|
+
The color as a tuple of hue, saturation, lightness, and alpha (if included).
|
|
214
|
+
All elements are in the range 0 to 1.
|
|
215
|
+
|
|
216
|
+
Note:
|
|
217
|
+
This is HSL as used in HTML and most other places, not HLS as used in Python's `colorsys`.
|
|
218
|
+
"""
|
|
219
|
+
h, l, s = rgb_to_hls(self._rgba.r, self._rgba.g, self._rgba.b) # noqa: E741
|
|
220
|
+
if alpha is None:
|
|
221
|
+
if self._rgba.alpha is None:
|
|
222
|
+
return h, s, l
|
|
223
|
+
else:
|
|
224
|
+
return h, s, l, self._alpha_float()
|
|
225
|
+
if alpha:
|
|
226
|
+
return h, s, l, self._alpha_float()
|
|
227
|
+
else:
|
|
228
|
+
# alpha is False
|
|
229
|
+
return h, s, l
|
|
230
|
+
|
|
231
|
+
def _alpha_float(self) -> float:
|
|
232
|
+
return 1 if self._rgba.alpha is None else self._rgba.alpha
|
|
233
|
+
|
|
234
|
+
@classmethod
|
|
235
|
+
def __get_pydantic_core_schema__(
|
|
236
|
+
cls, source: type[Any], handler: Callable[[Any], CoreSchema]
|
|
237
|
+
) -> core_schema.CoreSchema:
|
|
238
|
+
return core_schema.with_info_plain_validator_function(
|
|
239
|
+
cls._validate, serialization=core_schema.to_string_ser_schema()
|
|
240
|
+
)
|
|
241
|
+
|
|
242
|
+
@classmethod
|
|
243
|
+
def _validate(cls, __input_value: Any, _: Any) -> 'Color':
|
|
244
|
+
return cls(__input_value)
|
|
245
|
+
|
|
246
|
+
def __str__(self) -> str:
|
|
247
|
+
return self.as_named(fallback=True)
|
|
248
|
+
|
|
249
|
+
def __repr_args__(self) -> '_repr.ReprArgs':
|
|
250
|
+
return [(None, self.as_named(fallback=True))] + [('rgb', self.as_rgb_tuple())]
|
|
251
|
+
|
|
252
|
+
def __eq__(self, other: Any) -> bool:
|
|
253
|
+
return isinstance(other, Color) and self.as_rgb_tuple() == other.as_rgb_tuple()
|
|
254
|
+
|
|
255
|
+
def __hash__(self) -> int:
|
|
256
|
+
return hash(self.as_rgb_tuple())
|
|
257
|
+
|
|
258
|
+
|
|
259
|
+
def parse_tuple(value: tuple[Any, ...]) -> RGBA:
|
|
260
|
+
"""Parse a tuple or list to get RGBA values.
|
|
261
|
+
|
|
262
|
+
Args:
|
|
263
|
+
value: A tuple or list.
|
|
264
|
+
|
|
265
|
+
Returns:
|
|
266
|
+
An `RGBA` tuple parsed from the input tuple.
|
|
267
|
+
|
|
268
|
+
Raises:
|
|
269
|
+
PydanticCustomError: If tuple is not valid.
|
|
270
|
+
"""
|
|
271
|
+
if len(value) == 3:
|
|
272
|
+
r, g, b = (parse_color_value(v) for v in value)
|
|
273
|
+
return RGBA(r, g, b, None)
|
|
274
|
+
elif len(value) == 4:
|
|
275
|
+
r, g, b = (parse_color_value(v) for v in value[:3])
|
|
276
|
+
return RGBA(r, g, b, parse_float_alpha(value[3]))
|
|
277
|
+
else:
|
|
278
|
+
raise PydanticCustomError('color_error', 'value is not a valid color: tuples must have length 3 or 4')
|
|
279
|
+
|
|
280
|
+
|
|
281
|
+
def parse_str(value: str) -> RGBA:
|
|
282
|
+
"""Parse a string representing a color to an RGBA tuple.
|
|
283
|
+
|
|
284
|
+
Possible formats for the input string include:
|
|
285
|
+
|
|
286
|
+
* named color, see `COLORS_BY_NAME`
|
|
287
|
+
* hex short eg. `<prefix>fff` (prefix can be `#`, `0x` or nothing)
|
|
288
|
+
* hex long eg. `<prefix>ffffff` (prefix can be `#`, `0x` or nothing)
|
|
289
|
+
* `rgb(<r>, <g>, <b>)`
|
|
290
|
+
* `rgba(<r>, <g>, <b>, <a>)`
|
|
291
|
+
|
|
292
|
+
Args:
|
|
293
|
+
value: A string representing a color.
|
|
294
|
+
|
|
295
|
+
Returns:
|
|
296
|
+
An `RGBA` tuple parsed from the input string.
|
|
297
|
+
|
|
298
|
+
Raises:
|
|
299
|
+
ValueError: If the input string cannot be parsed to an RGBA tuple.
|
|
300
|
+
"""
|
|
301
|
+
value_lower = value.lower()
|
|
302
|
+
try:
|
|
303
|
+
r, g, b = COLORS_BY_NAME[value_lower]
|
|
304
|
+
except KeyError:
|
|
305
|
+
pass
|
|
306
|
+
else:
|
|
307
|
+
return ints_to_rgba(r, g, b, None)
|
|
308
|
+
|
|
309
|
+
m = re.fullmatch(r_hex_short, value_lower)
|
|
310
|
+
if m:
|
|
311
|
+
*rgb, a = m.groups()
|
|
312
|
+
r, g, b = (int(v * 2, 16) for v in rgb)
|
|
313
|
+
if a:
|
|
314
|
+
alpha: float | None = int(a * 2, 16) / 255
|
|
315
|
+
else:
|
|
316
|
+
alpha = None
|
|
317
|
+
return ints_to_rgba(r, g, b, alpha)
|
|
318
|
+
|
|
319
|
+
m = re.fullmatch(r_hex_long, value_lower)
|
|
320
|
+
if m:
|
|
321
|
+
*rgb, a = m.groups()
|
|
322
|
+
r, g, b = (int(v, 16) for v in rgb)
|
|
323
|
+
if a:
|
|
324
|
+
alpha = int(a, 16) / 255
|
|
325
|
+
else:
|
|
326
|
+
alpha = None
|
|
327
|
+
return ints_to_rgba(r, g, b, alpha)
|
|
328
|
+
|
|
329
|
+
m = re.fullmatch(r_rgb, value_lower) or re.fullmatch(r_rgb_v4_style, value_lower)
|
|
330
|
+
if m:
|
|
331
|
+
return ints_to_rgba(*m.groups()) # type: ignore
|
|
332
|
+
|
|
333
|
+
m = re.fullmatch(r_hsl, value_lower) or re.fullmatch(r_hsl_v4_style, value_lower)
|
|
334
|
+
if m:
|
|
335
|
+
return parse_hsl(*m.groups()) # type: ignore
|
|
336
|
+
|
|
337
|
+
raise PydanticCustomError('color_error', 'value is not a valid color: string not recognised as a valid color')
|
|
338
|
+
|
|
339
|
+
|
|
340
|
+
def ints_to_rgba(r: int | str, g: int | str, b: int | str, alpha: float | None = None) -> RGBA:
|
|
341
|
+
"""Converts integer or string values for RGB color and an optional alpha value to an `RGBA` object.
|
|
342
|
+
|
|
343
|
+
Args:
|
|
344
|
+
r: An integer or string representing the red color value.
|
|
345
|
+
g: An integer or string representing the green color value.
|
|
346
|
+
b: An integer or string representing the blue color value.
|
|
347
|
+
alpha: A float representing the alpha value. Defaults to None.
|
|
348
|
+
|
|
349
|
+
Returns:
|
|
350
|
+
An instance of the `RGBA` class with the corresponding color and alpha values.
|
|
351
|
+
"""
|
|
352
|
+
return RGBA(parse_color_value(r), parse_color_value(g), parse_color_value(b), parse_float_alpha(alpha))
|
|
353
|
+
|
|
354
|
+
|
|
355
|
+
def parse_color_value(value: int | str, max_val: int = 255) -> float:
|
|
356
|
+
"""Parse the color value provided and return a number between 0 and 1.
|
|
357
|
+
|
|
358
|
+
Args:
|
|
359
|
+
value: An integer or string color value.
|
|
360
|
+
max_val: Maximum range value. Defaults to 255.
|
|
361
|
+
|
|
362
|
+
Raises:
|
|
363
|
+
PydanticCustomError: If the value is not a valid color.
|
|
364
|
+
|
|
365
|
+
Returns:
|
|
366
|
+
A number between 0 and 1.
|
|
367
|
+
"""
|
|
368
|
+
try:
|
|
369
|
+
color = float(value)
|
|
370
|
+
except ValueError:
|
|
371
|
+
raise PydanticCustomError('color_error', 'value is not a valid color: color values must be a valid number')
|
|
372
|
+
if 0 <= color <= max_val:
|
|
373
|
+
return color / max_val
|
|
374
|
+
else:
|
|
375
|
+
raise PydanticCustomError(
|
|
376
|
+
'color_error',
|
|
377
|
+
'value is not a valid color: color values must be in the range 0 to {max_val}',
|
|
378
|
+
{'max_val': max_val},
|
|
379
|
+
)
|
|
380
|
+
|
|
381
|
+
|
|
382
|
+
def parse_float_alpha(value: None | str | float | int) -> float | None:
|
|
383
|
+
"""Parse an alpha value checking it's a valid float in the range 0 to 1.
|
|
384
|
+
|
|
385
|
+
Args:
|
|
386
|
+
value: The input value to parse.
|
|
387
|
+
|
|
388
|
+
Returns:
|
|
389
|
+
The parsed value as a float, or `None` if the value was None or equal 1.
|
|
390
|
+
|
|
391
|
+
Raises:
|
|
392
|
+
PydanticCustomError: If the input value cannot be successfully parsed as a float in the expected range.
|
|
393
|
+
"""
|
|
394
|
+
if value is None:
|
|
395
|
+
return None
|
|
396
|
+
try:
|
|
397
|
+
if isinstance(value, str) and value.endswith('%'):
|
|
398
|
+
alpha = float(value[:-1]) / 100
|
|
399
|
+
else:
|
|
400
|
+
alpha = float(value)
|
|
401
|
+
except ValueError:
|
|
402
|
+
raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be a valid float')
|
|
403
|
+
|
|
404
|
+
if math.isclose(alpha, 1):
|
|
405
|
+
return None
|
|
406
|
+
elif 0 <= alpha <= 1:
|
|
407
|
+
return alpha
|
|
408
|
+
else:
|
|
409
|
+
raise PydanticCustomError('color_error', 'value is not a valid color: alpha values must be in the range 0 to 1')
|
|
410
|
+
|
|
411
|
+
|
|
412
|
+
def parse_hsl(h: str, h_units: str, sat: str, light: str, alpha: float | None = None) -> RGBA:
|
|
413
|
+
"""Parse raw hue, saturation, lightness, and alpha values and convert to RGBA.
|
|
414
|
+
|
|
415
|
+
Args:
|
|
416
|
+
h: The hue value.
|
|
417
|
+
h_units: The unit for hue value.
|
|
418
|
+
sat: The saturation value.
|
|
419
|
+
light: The lightness value.
|
|
420
|
+
alpha: Alpha value.
|
|
421
|
+
|
|
422
|
+
Returns:
|
|
423
|
+
An instance of `RGBA`.
|
|
424
|
+
"""
|
|
425
|
+
s_value, l_value = parse_color_value(sat, 100), parse_color_value(light, 100)
|
|
426
|
+
|
|
427
|
+
h_value = float(h)
|
|
428
|
+
if h_units in {None, 'deg'}:
|
|
429
|
+
h_value = h_value % 360 / 360
|
|
430
|
+
elif h_units == 'rad':
|
|
431
|
+
h_value = h_value % rads / rads
|
|
432
|
+
else:
|
|
433
|
+
# turns
|
|
434
|
+
h_value = h_value % 1
|
|
435
|
+
|
|
436
|
+
r, g, b = hls_to_rgb(h_value, l_value, s_value)
|
|
437
|
+
return RGBA(r, g, b, parse_float_alpha(alpha))
|
|
438
|
+
|
|
439
|
+
|
|
440
|
+
def float_to_255(c: float) -> int:
|
|
441
|
+
"""Converts a float value between 0 and 1 (inclusive) to an integer between 0 and 255 (inclusive).
|
|
442
|
+
|
|
443
|
+
Args:
|
|
444
|
+
c: The float value to be converted. Must be between 0 and 1 (inclusive).
|
|
445
|
+
|
|
446
|
+
Returns:
|
|
447
|
+
The integer equivalent of the given float value rounded to the nearest whole number.
|
|
448
|
+
|
|
449
|
+
Raises:
|
|
450
|
+
ValueError: If the given float value is outside the acceptable range of 0 to 1 (inclusive).
|
|
451
|
+
"""
|
|
452
|
+
return int(round(c * 255))
|
|
453
|
+
|
|
454
|
+
|
|
455
|
+
COLORS_BY_NAME = {
|
|
456
|
+
'aliceblue': (240, 248, 255),
|
|
457
|
+
'antiquewhite': (250, 235, 215),
|
|
458
|
+
'aqua': (0, 255, 255),
|
|
459
|
+
'aquamarine': (127, 255, 212),
|
|
460
|
+
'azure': (240, 255, 255),
|
|
461
|
+
'beige': (245, 245, 220),
|
|
462
|
+
'bisque': (255, 228, 196),
|
|
463
|
+
'black': (0, 0, 0),
|
|
464
|
+
'blanchedalmond': (255, 235, 205),
|
|
465
|
+
'blue': (0, 0, 255),
|
|
466
|
+
'blueviolet': (138, 43, 226),
|
|
467
|
+
'brown': (165, 42, 42),
|
|
468
|
+
'burlywood': (222, 184, 135),
|
|
469
|
+
'cadetblue': (95, 158, 160),
|
|
470
|
+
'chartreuse': (127, 255, 0),
|
|
471
|
+
'chocolate': (210, 105, 30),
|
|
472
|
+
'coral': (255, 127, 80),
|
|
473
|
+
'cornflowerblue': (100, 149, 237),
|
|
474
|
+
'cornsilk': (255, 248, 220),
|
|
475
|
+
'crimson': (220, 20, 60),
|
|
476
|
+
'cyan': (0, 255, 255),
|
|
477
|
+
'darkblue': (0, 0, 139),
|
|
478
|
+
'darkcyan': (0, 139, 139),
|
|
479
|
+
'darkgoldenrod': (184, 134, 11),
|
|
480
|
+
'darkgray': (169, 169, 169),
|
|
481
|
+
'darkgreen': (0, 100, 0),
|
|
482
|
+
'darkgrey': (169, 169, 169),
|
|
483
|
+
'darkkhaki': (189, 183, 107),
|
|
484
|
+
'darkmagenta': (139, 0, 139),
|
|
485
|
+
'darkolivegreen': (85, 107, 47),
|
|
486
|
+
'darkorange': (255, 140, 0),
|
|
487
|
+
'darkorchid': (153, 50, 204),
|
|
488
|
+
'darkred': (139, 0, 0),
|
|
489
|
+
'darksalmon': (233, 150, 122),
|
|
490
|
+
'darkseagreen': (143, 188, 143),
|
|
491
|
+
'darkslateblue': (72, 61, 139),
|
|
492
|
+
'darkslategray': (47, 79, 79),
|
|
493
|
+
'darkslategrey': (47, 79, 79),
|
|
494
|
+
'darkturquoise': (0, 206, 209),
|
|
495
|
+
'darkviolet': (148, 0, 211),
|
|
496
|
+
'deeppink': (255, 20, 147),
|
|
497
|
+
'deepskyblue': (0, 191, 255),
|
|
498
|
+
'dimgray': (105, 105, 105),
|
|
499
|
+
'dimgrey': (105, 105, 105),
|
|
500
|
+
'dodgerblue': (30, 144, 255),
|
|
501
|
+
'firebrick': (178, 34, 34),
|
|
502
|
+
'floralwhite': (255, 250, 240),
|
|
503
|
+
'forestgreen': (34, 139, 34),
|
|
504
|
+
'fuchsia': (255, 0, 255),
|
|
505
|
+
'gainsboro': (220, 220, 220),
|
|
506
|
+
'ghostwhite': (248, 248, 255),
|
|
507
|
+
'gold': (255, 215, 0),
|
|
508
|
+
'goldenrod': (218, 165, 32),
|
|
509
|
+
'gray': (128, 128, 128),
|
|
510
|
+
'green': (0, 128, 0),
|
|
511
|
+
'greenyellow': (173, 255, 47),
|
|
512
|
+
'grey': (128, 128, 128),
|
|
513
|
+
'honeydew': (240, 255, 240),
|
|
514
|
+
'hotpink': (255, 105, 180),
|
|
515
|
+
'indianred': (205, 92, 92),
|
|
516
|
+
'indigo': (75, 0, 130),
|
|
517
|
+
'ivory': (255, 255, 240),
|
|
518
|
+
'khaki': (240, 230, 140),
|
|
519
|
+
'lavender': (230, 230, 250),
|
|
520
|
+
'lavenderblush': (255, 240, 245),
|
|
521
|
+
'lawngreen': (124, 252, 0),
|
|
522
|
+
'lemonchiffon': (255, 250, 205),
|
|
523
|
+
'lightblue': (173, 216, 230),
|
|
524
|
+
'lightcoral': (240, 128, 128),
|
|
525
|
+
'lightcyan': (224, 255, 255),
|
|
526
|
+
'lightgoldenrodyellow': (250, 250, 210),
|
|
527
|
+
'lightgray': (211, 211, 211),
|
|
528
|
+
'lightgreen': (144, 238, 144),
|
|
529
|
+
'lightgrey': (211, 211, 211),
|
|
530
|
+
'lightpink': (255, 182, 193),
|
|
531
|
+
'lightsalmon': (255, 160, 122),
|
|
532
|
+
'lightseagreen': (32, 178, 170),
|
|
533
|
+
'lightskyblue': (135, 206, 250),
|
|
534
|
+
'lightslategray': (119, 136, 153),
|
|
535
|
+
'lightslategrey': (119, 136, 153),
|
|
536
|
+
'lightsteelblue': (176, 196, 222),
|
|
537
|
+
'lightyellow': (255, 255, 224),
|
|
538
|
+
'lime': (0, 255, 0),
|
|
539
|
+
'limegreen': (50, 205, 50),
|
|
540
|
+
'linen': (250, 240, 230),
|
|
541
|
+
'magenta': (255, 0, 255),
|
|
542
|
+
'maroon': (128, 0, 0),
|
|
543
|
+
'mediumaquamarine': (102, 205, 170),
|
|
544
|
+
'mediumblue': (0, 0, 205),
|
|
545
|
+
'mediumorchid': (186, 85, 211),
|
|
546
|
+
'mediumpurple': (147, 112, 219),
|
|
547
|
+
'mediumseagreen': (60, 179, 113),
|
|
548
|
+
'mediumslateblue': (123, 104, 238),
|
|
549
|
+
'mediumspringgreen': (0, 250, 154),
|
|
550
|
+
'mediumturquoise': (72, 209, 204),
|
|
551
|
+
'mediumvioletred': (199, 21, 133),
|
|
552
|
+
'midnightblue': (25, 25, 112),
|
|
553
|
+
'mintcream': (245, 255, 250),
|
|
554
|
+
'mistyrose': (255, 228, 225),
|
|
555
|
+
'moccasin': (255, 228, 181),
|
|
556
|
+
'navajowhite': (255, 222, 173),
|
|
557
|
+
'navy': (0, 0, 128),
|
|
558
|
+
'oldlace': (253, 245, 230),
|
|
559
|
+
'olive': (128, 128, 0),
|
|
560
|
+
'olivedrab': (107, 142, 35),
|
|
561
|
+
'orange': (255, 165, 0),
|
|
562
|
+
'orangered': (255, 69, 0),
|
|
563
|
+
'orchid': (218, 112, 214),
|
|
564
|
+
'palegoldenrod': (238, 232, 170),
|
|
565
|
+
'palegreen': (152, 251, 152),
|
|
566
|
+
'paleturquoise': (175, 238, 238),
|
|
567
|
+
'palevioletred': (219, 112, 147),
|
|
568
|
+
'papayawhip': (255, 239, 213),
|
|
569
|
+
'peachpuff': (255, 218, 185),
|
|
570
|
+
'peru': (205, 133, 63),
|
|
571
|
+
'pink': (255, 192, 203),
|
|
572
|
+
'plum': (221, 160, 221),
|
|
573
|
+
'powderblue': (176, 224, 230),
|
|
574
|
+
'purple': (128, 0, 128),
|
|
575
|
+
'red': (255, 0, 0),
|
|
576
|
+
'rosybrown': (188, 143, 143),
|
|
577
|
+
'royalblue': (65, 105, 225),
|
|
578
|
+
'saddlebrown': (139, 69, 19),
|
|
579
|
+
'salmon': (250, 128, 114),
|
|
580
|
+
'sandybrown': (244, 164, 96),
|
|
581
|
+
'seagreen': (46, 139, 87),
|
|
582
|
+
'seashell': (255, 245, 238),
|
|
583
|
+
'sienna': (160, 82, 45),
|
|
584
|
+
'silver': (192, 192, 192),
|
|
585
|
+
'skyblue': (135, 206, 235),
|
|
586
|
+
'slateblue': (106, 90, 205),
|
|
587
|
+
'slategray': (112, 128, 144),
|
|
588
|
+
'slategrey': (112, 128, 144),
|
|
589
|
+
'snow': (255, 250, 250),
|
|
590
|
+
'springgreen': (0, 255, 127),
|
|
591
|
+
'steelblue': (70, 130, 180),
|
|
592
|
+
'tan': (210, 180, 140),
|
|
593
|
+
'teal': (0, 128, 128),
|
|
594
|
+
'thistle': (216, 191, 216),
|
|
595
|
+
'tomato': (255, 99, 71),
|
|
596
|
+
'turquoise': (64, 224, 208),
|
|
597
|
+
'violet': (238, 130, 238),
|
|
598
|
+
'wheat': (245, 222, 179),
|
|
599
|
+
'white': (255, 255, 255),
|
|
600
|
+
'whitesmoke': (245, 245, 245),
|
|
601
|
+
'yellow': (255, 255, 0),
|
|
602
|
+
'yellowgreen': (154, 205, 50),
|
|
603
|
+
}
|
|
604
|
+
|
|
605
|
+
COLORS_BY_VALUE = {v: k for k, v in COLORS_BY_NAME.items()}
|