tesserae-utils 0.2.1__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.
tess_utils/__init__.py ADDED
@@ -0,0 +1,26 @@
1
+ """Shared converters for the Tesserae projects (tess-utils Brief, ADR-0017).
2
+
3
+ Pure functions that turn the value forms a TDL file writes into the single form tre takes. Nothing
4
+ here imports ``tess_re``, ``tess_el``, ``tess_dl``, ``tess_ui`` or ``tess_shell``, and the 0.1
5
+ modules import nothing outside the standard library.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ from tess_utils.color import parse_color
11
+ from tess_utils.enums import to_tre_word
12
+ from tess_utils.image import decode_image
13
+ from tess_utils.radius import expand_radius
14
+ from tess_utils.sides import expand_sides, to_tre_order
15
+
16
+ __version__ = "0.2.1"
17
+
18
+ __all__ = [
19
+ "__version__",
20
+ "decode_image",
21
+ "expand_radius",
22
+ "expand_sides",
23
+ "parse_color",
24
+ "to_tre_order",
25
+ "to_tre_word",
26
+ ]
tess_utils/color.py ADDED
@@ -0,0 +1,72 @@
1
+ """Colour: the written forms of TDL to tre's ``(r, g, b, a)`` of 0 to 255 integers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ Color = tuple[int, int, int, int]
8
+
9
+ _FUNCTION = re.compile(r"rgba?\(\s*([^)]*?)\s*\)", re.IGNORECASE)
10
+
11
+
12
+ def parse_color(text: object) -> Color:
13
+ """Read a colour written as ``#RRGGBB``, ``#RRGGBBAA`` (alpha last), ``#RGB``, ``#RGBA``,
14
+ ``rgb(r g b)`` or ``rgba(r g b a)`` (spaces or commas; red to blue 0 to 255, alpha 0.0 to 1.0)
15
+ or ``transparent``. Returns tre's ``(r, g, b, a)``, each an integer 0 to 255.
16
+
17
+ Raises :class:`ValueError` naming the bad part, also for a value that is not text. The
18
+ parameter is typed ``object`` on purpose: a compiled build (mypyc) would raise ``TypeError`` for
19
+ a wrongly typed argument, and the source and the compiled file must behave alike.
20
+ """
21
+ if not isinstance(text, str):
22
+ raise ValueError(f"a colour is written as text, not {type(text).__name__}")
23
+ written = text.strip()
24
+ if written.lower() == "transparent":
25
+ return (0, 0, 0, 0)
26
+ if written.startswith("#"):
27
+ return _hex(written, text)
28
+ if match := _FUNCTION.fullmatch(written):
29
+ return _function(match.group(1), text)
30
+ raise ValueError(
31
+ f"not a colour: {text!r}; write #RRGGBB, #RRGGBBAA, rgba(r g b a) or transparent"
32
+ )
33
+
34
+
35
+ def _hex(written: str, text: str) -> Color:
36
+ bad = next((c for c in written[1:] if c not in "0123456789abcdefABCDEF"), None)
37
+ if bad is not None:
38
+ raise ValueError(f"not a colour: {text!r}; {bad!r} is not a hex digit")
39
+ digits = written[1:]
40
+ if len(digits) not in (3, 4, 6, 8):
41
+ raise ValueError(
42
+ f"not a colour: {text!r}; a hex colour has 3, 4, 6 or 8 digits, not {len(digits)}"
43
+ )
44
+ if len(digits) in (3, 4):
45
+ digits = "".join(c * 2 for c in digits)
46
+ channels = [int(digits[i : i + 2], 16) for i in range(0, len(digits), 2)]
47
+ if len(channels) == 3:
48
+ channels.append(255)
49
+ r, g, b, a = channels
50
+ return (r, g, b, a)
51
+
52
+
53
+ def _function(inside: str, text: str) -> Color:
54
+ parts = inside.replace(",", " ").split()
55
+ if len(parts) not in (3, 4):
56
+ raise ValueError(f"not a colour: {text!r}; rgba() takes 3 or 4 numbers, not {len(parts)}")
57
+ try:
58
+ r, g, b = (int(p) for p in parts[:3])
59
+ except ValueError:
60
+ raise ValueError(
61
+ f"not a colour: {text!r}; red, green and blue are whole numbers 0 to 255"
62
+ ) from None
63
+ try:
64
+ alpha = float(parts[3]) if len(parts) == 4 else 1.0
65
+ except ValueError:
66
+ raise ValueError(f"not a colour: {text!r}; alpha is a number 0.0 to 1.0") from None
67
+ for name, value in (("red", r), ("green", g), ("blue", b)):
68
+ if not 0 <= value <= 255:
69
+ raise ValueError(f"not a colour: {text!r}; {name} is {value}, not 0 to 255")
70
+ if not 0.0 <= alpha <= 1.0: # also false for nan
71
+ raise ValueError(f"not a colour: {text!r}; alpha is {alpha:g}, not 0.0 to 1.0")
72
+ return (r, g, b, round(alpha * 255))
tess_utils/enums.py ADDED
@@ -0,0 +1,17 @@
1
+ """Enum words: TDL's upper case to tre's lower case."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import re
6
+
7
+ _WORD = re.compile(r"[A-Za-z][A-Za-z0-9]*(_[A-Za-z0-9]+)*")
8
+
9
+
10
+ def to_tre_word(name: object) -> str:
11
+ """``SPACE_BETWEEN`` to ``space_between``, ``HORIZONTAL`` to ``horizontal``. A name is letters,
12
+ digits and single underscores, starting with a letter; anything else is an error."""
13
+ if not isinstance(name, str) or _WORD.fullmatch(name) is None:
14
+ raise ValueError(
15
+ f"not an enum word: {name!r}; write letters, digits and _, like SPACE_BETWEEN"
16
+ )
17
+ return name.lower()
tess_utils/image.py ADDED
@@ -0,0 +1,77 @@
1
+ """Image file bytes to the pixels tre's ``image`` node takes (RGBA8).
2
+
3
+ Pillow is imported inside :func:`decode_image`, never at module import time, so a consumer that
4
+ only needs colours never loads it. Pillow is not part of the compiled release either: it is a
5
+ normal runtime dependency of whoever calls the function (the ``image`` extra).
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import io
11
+ import warnings
12
+
13
+ _FORMATS = {"PNG", "JPEG", "GIF", "WEBP"}
14
+
15
+
16
+ def decode_image(data: object, max_side: object = 4096) -> tuple[int, int, bytes]:
17
+ """Decode the bytes of a PNG, JPEG, GIF or WebP image to ``(width, height, rgba)``.
18
+
19
+ ``rgba`` is straight-alpha RGBA8, ``len(rgba) == width * height * 4``, rows from top to bottom:
20
+ what tre's ``image`` node takes as ``rgba``, ``pixel_width`` and ``pixel_height``.
21
+
22
+ - An animated GIF or WebP gives its first frame only.
23
+ - EXIF orientation is applied (``ImageOps.exif_transpose``), so a rotated JPEG is upright.
24
+ - Palette, greyscale, CMYK and 16-bit images are converted to RGBA; a palette transparency is
25
+ kept as alpha.
26
+ - The header size is read first: a width or height over ``max_side`` (default 4096) is a
27
+ ``ValueError`` before any pixel is decoded. Pillow's decompression-bomb warning is turned
28
+ into an error for the duration of the call only (``warnings.catch_warnings``); Pillow's
29
+ global ``MAX_IMAGE_PIXELS`` is not touched.
30
+ - Every failure is a ``ValueError``: wrong argument types, empty or corrupt or truncated data,
31
+ another format (BMP, TIFF, SVG, text), a zero-sized image, a size over the limit. No Pillow
32
+ exception type escapes. The parameters are typed ``object`` so a compiled build behaves
33
+ like the source.
34
+ """
35
+ if not isinstance(data, bytes | bytearray | memoryview):
36
+ raise ValueError(f"image data is bytes, not {type(data).__name__}")
37
+ if isinstance(max_side, bool) or not isinstance(max_side, int):
38
+ raise ValueError(f"max_side is a whole number of pixels, not {max_side!r}")
39
+ if max_side < 1:
40
+ raise ValueError(f"max_side is at least 1, not {max_side}")
41
+ raw = bytes(data)
42
+ if not raw:
43
+ raise ValueError("image data is empty")
44
+
45
+ from PIL import Image, ImageOps, UnidentifiedImageError # lazy: see the module docstring
46
+
47
+ try:
48
+ with warnings.catch_warnings():
49
+ warnings.simplefilter("error", Image.DecompressionBombWarning)
50
+ with Image.open(io.BytesIO(raw)) as img:
51
+ if img.format not in _FORMATS:
52
+ raise ValueError("not a png, jpeg, gif or webp image")
53
+ width, height = img.size
54
+ if width < 1 or height < 1:
55
+ raise ValueError(f"the image has no pixels ({width}x{height})")
56
+ if width > max_side or height > max_side:
57
+ raise ValueError(
58
+ f"the image is {width}x{height} pixels, over the limit of {max_side}"
59
+ )
60
+ img.load()
61
+ upright = ImageOps.exif_transpose(img)
62
+ if upright.mode in ("I;16", "I;16L", "I;16B", "I;16N", "I"):
63
+ upright = upright.point(lambda v: v / 256).convert("L")
64
+ rgba = upright.convert("RGBA")
65
+ out_w, out_h = rgba.size
66
+ pixels = rgba.tobytes()
67
+ except ValueError as error:
68
+ # Pillow's own errors (UnidentifiedImageError, DecompressionBombError) are ValueError
69
+ # subclasses; ours carry a clear message already.
70
+ if type(error) is ValueError:
71
+ raise
72
+ raise ValueError(f"cannot read the image: {error}") from None
73
+ except UnidentifiedImageError:
74
+ raise ValueError("not a png, jpeg, gif or webp image") from None
75
+ except Exception as error: # OSError, SyntaxError, EOFError, struct.error, warnings as errors
76
+ raise ValueError(f"cannot read the image: {type(error).__name__}: {error}") from None
77
+ return (out_w, out_h, pixels)
tess_utils/py.typed ADDED
File without changes
tess_utils/radius.py ADDED
@@ -0,0 +1,36 @@
1
+ """Corner radii, in the form tre takes."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Sequence
7
+
8
+ Radii = tuple[float, float, float, float]
9
+
10
+
11
+ def _radius(value: object) -> float:
12
+ if isinstance(value, bool) or not isinstance(value, int | float):
13
+ raise ValueError(f"a radius is a number, not {value!r}")
14
+ if not math.isfinite(value):
15
+ raise ValueError(f"a radius is not finite: {value!r}")
16
+ if value < 0:
17
+ raise ValueError(f"a radius cannot be negative: {value!r}")
18
+ return float(value)
19
+
20
+
21
+ def expand_radius(value: object) -> Radii:
22
+ """One number (every corner) or four numbers from the top-left corner clockwise, to
23
+ ``(top_left, top_right, bottom_right, bottom_left)``, the form tre takes. A radius is never
24
+ negative; a list of other than four numbers is an error."""
25
+ if isinstance(value, str):
26
+ raise ValueError(f"a radius is a number, not text: {value!r}")
27
+ if isinstance(value, Sequence):
28
+ if len(value) != 4:
29
+ raise ValueError(
30
+ "a list of radii has four numbers from the top-left corner clockwise, "
31
+ f"not {len(value)}"
32
+ )
33
+ top_left, top_right, bottom_right, bottom_left = (_radius(v) for v in value)
34
+ return (top_left, top_right, bottom_right, bottom_left)
35
+ one = _radius(value)
36
+ return (one, one, one, one)
tess_utils/sides.py ADDED
@@ -0,0 +1,53 @@
1
+ """Four-sided values (padding, margin, inset, thickness) and tre's order for them."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import math
6
+ from collections.abc import Mapping, Sequence
7
+
8
+ Sides = tuple[float, float, float, float]
9
+
10
+ _NAMES = ("left", "top", "right", "bottom")
11
+
12
+
13
+ def _number(value: object, what: str) -> float:
14
+ if isinstance(value, bool) or not isinstance(value, int | float):
15
+ raise ValueError(f"{what} is a number, not {value!r}")
16
+ if not math.isfinite(value):
17
+ raise ValueError(f"{what} is not finite: {value!r}")
18
+ return float(value)
19
+
20
+
21
+ def expand_sides(value: object) -> Sides:
22
+ """One number (every side), or four numbers, or named sides, to ``(left, top, right, bottom)``.
23
+
24
+ A mapping names ``left``, ``top``, ``right`` and ``bottom`` in any case; a side it does not name
25
+ is 0. A list of two or three numbers is an error (ADR-0014 D72), as is an unknown side name.
26
+ A negative number is allowed: whether a side may be negative is the caller's rule. Anything
27
+ else is a ``ValueError`` (the parameter is typed ``object`` so a compiled build behaves alike).
28
+ """
29
+ if isinstance(value, Mapping):
30
+ found = {str(name).lower(): _number(v, f"side {name}") for name, v in value.items()}
31
+ unknown = [name for name in found if name not in _NAMES]
32
+ if unknown:
33
+ raise ValueError(f"unknown side {unknown[0]!r}; the sides are {', '.join(_NAMES)}")
34
+ left, top, right, bottom = (found.get(name, 0.0) for name in _NAMES)
35
+ return (left, top, right, bottom)
36
+ if isinstance(value, str):
37
+ raise ValueError(f"sides are numbers, not text: {value!r}")
38
+ if isinstance(value, Sequence):
39
+ if len(value) != 4:
40
+ raise ValueError(
41
+ f"a list of sides has four numbers (left, top, right, bottom), not {len(value)}"
42
+ )
43
+ left, top, right, bottom = (_number(v, "a side") for v in value)
44
+ return (left, top, right, bottom)
45
+ one = _number(value, "a side")
46
+ return (one, one, one, one)
47
+
48
+
49
+ def to_tre_order(sides: Sides) -> Sides:
50
+ """``(left, top, right, bottom)`` to ``(top, right, bottom, left)``, the order tre's margins
51
+ use."""
52
+ left, top, right, bottom = sides
53
+ return (top, right, bottom, left)
@@ -0,0 +1,73 @@
1
+ Metadata-Version: 2.5
2
+ Name: tesserae-utils
3
+ Version: 0.2.1
4
+ Summary: Shared converters for the Tesserae projects: the value forms a TDL file writes, as the one form tre takes.
5
+ Project-URL: Repository, https://github.com/mindderivative/tess-utils
6
+ Author: Mind Derivative
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Classifier: Development Status :: 3 - Alpha
10
+ Classifier: Operating System :: OS Independent
11
+ Classifier: Programming Language :: Python :: 3 :: Only
12
+ Classifier: Programming Language :: Python :: 3.14
13
+ Classifier: Typing :: Typed
14
+ Requires-Python: >=3.14
15
+ Provides-Extra: image
16
+ Requires-Dist: pillow>=11; extra == 'image'
17
+ Description-Content-Type: text/markdown
18
+
19
+ # tess-utils
20
+
21
+ Shared converters for the Tesserae projects (`tess-shell`, Tesserae UI). It is on PyPI as
22
+ `tesserae-utils` (the repository is `tess-utils`), and its converters have no dependencies (only
23
+ `decode_image` needs Pillow, see below): tre stays a rendering engine with one entry form, and
24
+ the forms a TDL file writes (colours, four-sided values, corner radii, enum words) are turned into
25
+ that form here, once.
26
+
27
+ Import name `tess_utils`. Python 3.14 or later. MIT.
28
+
29
+ ```python
30
+ from tess_utils import expand_radius, expand_sides, parse_color, to_tre_order, to_tre_word
31
+
32
+ parse_color("#89b4fa80") # (137, 180, 250, 128)
33
+ to_tre_order(expand_sides({"Left": 24})) # (0.0, 0.0, 0.0, 24.0)
34
+ expand_radius([0, 0, 8, 8]) # (0.0, 0.0, 8.0, 8.0)
35
+ to_tre_word("SPACE_BETWEEN") # "space_between"
36
+ ```
37
+
38
+ `decode_image(data, max_side=4096)` turns the bytes of a PNG, JPEG, GIF or WebP file into
39
+ `(width, height, rgba)` (straight-alpha RGBA8, top row first: tre's `image` node). Pillow is imported
40
+ inside the function, so `import tess_utils` never loads it, and it is not in the compiled file: the
41
+ caller installs it (`pip install tesserae-utils[image]`, `Pillow>=11`). A side over `max_side` is
42
+ refused from the header, before any pixel is decoded; every failure is a `ValueError`.
43
+
44
+ ## What belongs here
45
+
46
+ A function is added when at least two projects use it, it is a few lines of our own code (a mapped
47
+ library only for work that would be a project of its own, ADR-0019), it imports no Tesserae package,
48
+ it has no dependency and no UI or schema meaning, and it has tests. Schema, typing and UI meaning
49
+ stay in the projects.
50
+
51
+ ## Development
52
+
53
+ ```
54
+ UV_PROJECT_ENVIRONMENT=~/Projects/pyDev/pyEnvs/tess-utils uv sync
55
+ uv run ruff check src tests && uv run mypy && uv run pytest -q
56
+ ```
57
+
58
+ Versions are git tags (`v0.1.0`) and `CHANGELOG.md`. A release is published to PyPI as
59
+ `tesserae-utils` by `.github/workflows/release.yml` (Trusted Publishing, on a `vX.Y.Z` tag, with an
60
+ approval in the `pypi` environment). Separately, the Tesserae consumers carry a compiled copy
61
+ (maintainer, 2026-11-08): one `.so` (`mypyc`), a file on a GitHub release, which each consumer
62
+ downloads, checks against its SHA-256 and carries in `_vendor/` with a stamp. See `tools/build_so.py`.
63
+
64
+ The sync script that copies a release into a consumer (`vendor.json` manifest plus a short script in
65
+ each consumer, the vault's recommendation C) is not written yet: it is open question 3 of the
66
+ tess-utils Brief, and the first consumer, `tess-shell`, writes it when it takes the file. The build
67
+ tool's stamp (`build/so/tess_utils.stamp.json`: version, Python tag, platform, SHA-256) is what that
68
+ script checks.
69
+
70
+ A compiled file raises `TypeError` for a wrongly typed argument, which the source would not, so the
71
+ public functions take `object` and validate: the source and the `.so` raise the same `ValueError`
72
+ (the tests run against both: `uv run python tools/build_so.py --test`).
73
+
@@ -0,0 +1,11 @@
1
+ tess_utils/__init__.py,sha256=KUr0blcDc4z1u6GEDvLY1u_dJeCZTvQQVIdZ5EgNlSw,766
2
+ tess_utils/color.py,sha256=gKzS3-alzDwN4rwYjrR6jz4Soi91ngatwkDcM_UbzWg,3015
3
+ tess_utils/enums.py,sha256=2YuM5IDta5iUNnLje_K9iq_fpt_HfACArBLWM3nb-OY,611
4
+ tess_utils/image.py,sha256=7JrCmmAO5nvCpufIJS8CDYFFqAAMguCfIwnVI6MIsI4,3987
5
+ tess_utils/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ tess_utils/radius.py,sha256=gr5CJQ2vUS8V3QVdrZTjqUkRVvurya-d8lB93DJlIv0,1385
7
+ tess_utils/sides.py,sha256=DVmIEveOF4oM19LHTxcw2mpWLRsvhoiQ8SwSmNX1vb8,2258
8
+ tesserae_utils-0.2.1.dist-info/METADATA,sha256=ow1wBgFvLXo9cFXnrI5iFLgLDkBXGMV2Ph56QejzOUI,3640
9
+ tesserae_utils-0.2.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
10
+ tesserae_utils-0.2.1.dist-info/licenses/LICENSE,sha256=srxrPcyTjFUDbl2eWK_4QEPABcKrhKib0BfGxvj8af4,1072
11
+ tesserae_utils-0.2.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.33.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Mind Derivative
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.