abstractavatar 0.1.0__py3-none-win_amd64.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.
@@ -0,0 +1,223 @@
1
+ """AbstractAvatar: deterministic procedural frames through the bounded native ABI."""
2
+ from __future__ import annotations
3
+
4
+ import ctypes as C
5
+ import json
6
+ import math
7
+ from pathlib import Path
8
+ import sys
9
+ import threading
10
+ from typing import Any
11
+
12
+ __version__ = "0.1.0"
13
+ __all__ = ["Renderer", "catalog", "validate_descriptor", "__version__"]
14
+ _STATES = ("ready", "thinking", "working", "listening", "speaking", "waiting", "error")
15
+ _LIBRARIES: dict[str, Any] = {}
16
+ _LIBRARY_LOCK = threading.RLock()
17
+ _NAMES = {"darwin": "libabstractavatar.dylib", "win32": "abstractavatar.dll"}
18
+
19
+
20
+ def _library(library_path: str | Path | None = None):
21
+ path = Path(library_path).expanduser().resolve() if library_path is not None else Path(__file__).parent / "_native" / _NAMES.get(sys.platform, "libabstractavatar.so")
22
+ if not path.is_file():
23
+ raise RuntimeError("AbstractAvatar native library is unavailable. Install a built AbstractAvatar wheel or supply library_path explicitly.")
24
+ key = str(path)
25
+ with _LIBRARY_LOCK:
26
+ if key in _LIBRARIES:
27
+ return _LIBRARIES[key]
28
+ lib = C.CDLL(key)
29
+ signatures = {
30
+ "avatar_abi_version": ([], C.c_uint32),
31
+ "avatar_style_count": ([], C.c_uint32),
32
+ "avatar_style_field_ptr": ([C.c_uint32] * 2, C.c_void_p),
33
+ "avatar_style_field_len": ([C.c_uint32] * 2, C.c_size_t),
34
+ "avatar_create": ([C.c_uint32] * 2, C.c_uint32),
35
+ "avatar_set_shade": ([C.c_uint32] * 4, C.c_int32),
36
+ "avatar_set_ground": ([C.c_uint32] * 2, C.c_int32),
37
+ "avatar_set_gaze": ([C.c_uint32, C.c_float, C.c_float], C.c_int32),
38
+ "avatar_set_bands": ([C.c_uint32] + [C.c_float] * 8, C.c_int32),
39
+ "avatar_clear_bands": ([C.c_uint32], C.c_int32),
40
+ "avatar_render_copy": ([C.c_uint32] * 3 + [C.c_float] * 2 + [C.c_uint32, C.c_void_p, C.c_size_t], C.c_int32),
41
+ "avatar_destroy": ([C.c_uint32], C.c_int32),
42
+ }
43
+ try:
44
+ for name, (args, result) in signatures.items():
45
+ fn = getattr(lib, name)
46
+ fn.argtypes, fn.restype = args, result
47
+ except AttributeError as exc:
48
+ raise RuntimeError("AbstractAvatar native library is missing a required ABI function") from exc
49
+ if lib.avatar_abi_version() != 1:
50
+ raise RuntimeError("Unsupported AbstractAvatar native ABI")
51
+ _LIBRARIES[key] = lib
52
+ return lib
53
+
54
+
55
+ def catalog(library_path: str | Path | None = None) -> list[dict[str, Any]]:
56
+ """Return runtime catalog records. Persist ``id`` rather than numeric ``code``."""
57
+ lib = _library(library_path)
58
+ count = int(lib.avatar_style_count())
59
+ if not 1 <= count <= 256:
60
+ raise RuntimeError("AbstractAvatar catalog exceeds the supported bounds")
61
+ out: list[dict[str, Any]] = []
62
+ seen: set[str] = set()
63
+ for code in range(count):
64
+ record: dict[str, Any] = {"code": code}
65
+ for field, name in enumerate(("id", "name", "description", "watch_code", "family")):
66
+ length = int(lib.avatar_style_field_len(code, field))
67
+ pointer = lib.avatar_style_field_ptr(code, field)
68
+ if length > 512 or (length and not pointer):
69
+ raise RuntimeError("Invalid AbstractAvatar catalog field")
70
+ record[name] = C.string_at(pointer, length).decode("utf-8") if length else ""
71
+ if not record["id"] or record["id"] in seen:
72
+ raise RuntimeError("Invalid or duplicated AbstractAvatar style identifier")
73
+ record["reference"] = record["watch_code"]
74
+ seen.add(record["id"])
75
+ out.append(record)
76
+ return out
77
+
78
+
79
+ def _number(value: Any, lo: float, hi: float, name: str) -> float:
80
+ try:
81
+ valid = not isinstance(value, bool) and isinstance(value, (int, float)) and math.isfinite(value) and lo <= value <= hi
82
+ except (OverflowError, TypeError, ValueError):
83
+ valid = False
84
+ if not valid:
85
+ raise ValueError(f"{name} must be finite and in {lo:g}..{hi:g}")
86
+ return float(value)
87
+
88
+
89
+ def _vector(value: Any, count: int, lo: float, hi: float, name: str) -> tuple[float, ...]:
90
+ if not isinstance(value, (list, tuple)) or len(value) != count:
91
+ raise ValueError(f"{name} must contain exactly {count} values")
92
+ return tuple(_number(v, lo, hi, name) for v in value)
93
+
94
+
95
+ def _unique_object(pairs):
96
+ result = {}
97
+ for key, value in pairs:
98
+ if key in result:
99
+ raise ValueError(f"Duplicated avatar field: {key}")
100
+ result[key] = value
101
+ return result
102
+
103
+
104
+ def validate_descriptor(value: dict[str, Any] | str, *, styles: set[str] | None = None) -> dict[str, Any]:
105
+ """Validate an inert schema-version-1 descriptor; no file or URL is evaluated."""
106
+ if isinstance(value, str):
107
+ if len(value.encode("utf-8")) > 4096:
108
+ raise ValueError("Avatar descriptor exceeds 4096 bytes")
109
+ try:
110
+ value = json.loads(value, object_pairs_hook=_unique_object)
111
+ except (ValueError, RecursionError) as exc:
112
+ raise ValueError(f"Invalid avatar descriptor: {exc}") from exc
113
+ if not isinstance(value, dict):
114
+ raise ValueError("Avatar descriptor must be an object")
115
+ required = {"schema_version", "style", "state", "time", "level"}
116
+ if set(value) - required - {"gaze", "bands"} or required - set(value):
117
+ raise ValueError("Avatar descriptor has unknown or missing fields")
118
+ if isinstance(value["schema_version"], bool) or not isinstance(value["schema_version"], (int, float)) or value["schema_version"] != 1:
119
+ raise ValueError("Unsupported avatar schema_version")
120
+ if not isinstance(value["style"], str) or not value["style"] or len(value["style"]) > 64:
121
+ raise ValueError("Avatar style must be a nonempty identifier of at most 64 characters")
122
+ if styles is not None and value["style"] not in styles:
123
+ raise ValueError("Unknown avatar style")
124
+ if value["state"] not in _STATES:
125
+ raise ValueError("Unknown avatar state")
126
+ out = dict(value)
127
+ out["time"] = _number(value["time"], 0, 86400, "time")
128
+ out["level"] = _number(value["level"], 0, 1, "level")
129
+ if "gaze" in out:
130
+ out["gaze"] = _vector(out["gaze"], 2, -1, 1, "gaze")
131
+ if "bands" in out:
132
+ out["bands"] = _vector(out["bands"], 8, 0, 1, "bands")
133
+ return out
134
+
135
+
136
+ def _color(value: Any, count: int, name: str) -> tuple[int, ...]:
137
+ if not isinstance(value, (list, tuple)) or len(value) != count or any(type(v) is not int or not 0 <= v <= 255 for v in value):
138
+ raise ValueError(f"{name} must contain {count} integer channels in 0..255")
139
+ return tuple(value)
140
+
141
+
142
+ class Renderer:
143
+ """Own one reusable bounded native RGBA8 buffer; close it when the host closes."""
144
+ def __init__(self, width: int = 128, height: int = 128, library_path: str | Path | None = None):
145
+ if type(width) is not int or type(height) is not int or not 1 <= width <= 512 or not 1 <= height <= 512:
146
+ raise ValueError("Avatar dimensions must be integers in 1..512")
147
+ self.width, self.height = width, height
148
+ self._lock = threading.RLock()
149
+ self._library = _library(library_path)
150
+ self._styles = {r["id"]: r["code"] for r in catalog(library_path)}
151
+ self._handle = int(self._library.avatar_create(width, height))
152
+ if not self._handle:
153
+ raise RuntimeError("AbstractAvatar renderer capacity exceeded (at most 16 live renderers)")
154
+ self._buffer = C.create_string_buffer(width * height * 4)
155
+ try:
156
+ self.set_palette()
157
+ except BaseException:
158
+ self.close()
159
+ raise
160
+
161
+ def _check(self, status: int):
162
+ if status:
163
+ raise RuntimeError(f"AbstractAvatar operation refused (code {status})")
164
+
165
+ def _open(self):
166
+ if not self._handle:
167
+ raise RuntimeError("AbstractAvatar renderer is closed")
168
+
169
+ def set_palette(self, *, warm=(211, 158, 57), eye=(225, 70, 95), dim=(80, 90, 105), ground=(0, 0, 0, 0)):
170
+ """Set three host theme color anchors and an RGBA background."""
171
+ anchors = [_color(v, 3, n) for v, n in [(warm, "warm"), (eye, "eye"), (dim, "dim")]]
172
+ ground = _color(ground, 4, "ground")
173
+ with self._lock:
174
+ self._open()
175
+ self._check(self._library.avatar_set_ground(self._handle, int.from_bytes(bytes(ground), "big")))
176
+ for material, mid in enumerate(anchors):
177
+ for shade in range(256):
178
+ t = shade / 255
179
+ left, right, amount = (ground[:3], mid, t / .65) if t < .65 else (mid, (255, 255, 255), (t - .65) / .35)
180
+ rgb = tuple(int(a + (b - a) * amount + .5) for a, b in zip(left, right))
181
+ self._check(self._library.avatar_set_shade(self._handle, material, shade, int.from_bytes(bytes((*rgb, 255)), "big")))
182
+
183
+ def render(self, style="halo", state="ready", level=0.0, time=0.0, gaze=(0, 0), transparent=True, bands=None) -> bytes:
184
+ """Return owned, tightly packed, straight-alpha RGBA8 bytes."""
185
+ desc = {"schema_version": 1, "style": style, "state": state, "time": time, "level": level, "gaze": gaze}
186
+ if bands is not None:
187
+ desc["bands"] = bands
188
+ frame = validate_descriptor(desc, styles=set(self._styles))
189
+ if type(transparent) is not bool:
190
+ raise ValueError("transparent must be a boolean")
191
+ with self._lock:
192
+ self._open()
193
+ self._check(self._library.avatar_set_gaze(self._handle, *frame["gaze"]))
194
+ if "bands" in frame:
195
+ self._check(self._library.avatar_set_bands(self._handle, *frame["bands"]))
196
+ else:
197
+ self._check(self._library.avatar_clear_bands(self._handle))
198
+ self._check(self._library.avatar_render_copy(self._handle, self._styles[style], _STATES.index(state), frame["level"], frame["time"], int(transparent), self._buffer, len(self._buffer)))
199
+ return self._buffer.raw
200
+
201
+ def render_descriptor(self, descriptor: dict[str, Any] | str, *, transparent: bool = True) -> bytes:
202
+ frame = validate_descriptor(descriptor, styles=set(self._styles))
203
+ return self.render(style=frame["style"], state=frame["state"], time=frame["time"], level=frame["level"], gaze=frame.get("gaze", (0, 0)), bands=frame.get("bands"), transparent=transparent)
204
+
205
+ def close(self):
206
+ with self._lock:
207
+ if self._handle:
208
+ self._check(self._library.avatar_destroy(self._handle))
209
+ self._handle = 0
210
+
211
+ def __enter__(self):
212
+ self._open()
213
+ return self
214
+
215
+ def __exit__(self, *_):
216
+ self.close()
217
+
218
+ def __del__(self):
219
+ if getattr(self, "_handle", 0):
220
+ try:
221
+ self.close()
222
+ except Exception:
223
+ pass
@@ -0,0 +1,43 @@
1
+ """Catalog inspection and deterministic PNG rendering, without a GUI dependency."""
2
+ import argparse
3
+ import json
4
+ from pathlib import Path
5
+ import struct
6
+ import zlib
7
+ from . import Renderer, catalog
8
+
9
+
10
+ def png(width, height, pixels):
11
+ def chunk(kind, data):
12
+ return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data))
13
+ stride = width * 4
14
+ rows = b"".join(b"\0" + pixels[y * stride:(y + 1) * stride] for y in range(height))
15
+ return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)) + chunk(b"IDAT", zlib.compress(rows)) + chunk(b"IEND", b"")
16
+
17
+
18
+ def main():
19
+ parser = argparse.ArgumentParser(description="Inspect and render AbstractAvatar procedural designs")
20
+ parser.add_argument("--library", help="Explicit trusted native library path")
21
+ commands = parser.add_subparsers(dest="command", required=True)
22
+ commands.add_parser("catalog", help="Print the native style catalog as JSON")
23
+ render = commands.add_parser("render", help="Render an RGBA PNG frame")
24
+ render.add_argument("--style", default="halo")
25
+ render.add_argument("--state", default="ready")
26
+ render.add_argument("--time", type=float, default=0.0)
27
+ render.add_argument("--level", type=float, default=0.0)
28
+ render.add_argument("--size", type=int, default=128)
29
+ render.add_argument("--output", type=Path, required=True)
30
+ args = parser.parse_args()
31
+ try:
32
+ if args.command == "catalog":
33
+ print(json.dumps(catalog(args.library), indent=2))
34
+ else:
35
+ with Renderer(args.size, args.size, args.library) as renderer:
36
+ data = renderer.render(style=args.style, state=args.state, time=args.time, level=args.level)
37
+ args.output.write_bytes(png(args.size, args.size, data))
38
+ except (ValueError, RuntimeError, OSError) as exc:
39
+ parser.exit(2, f"abstractavatar: {exc}\n")
40
+
41
+
42
+ if __name__ == "__main__":
43
+ main()
@@ -0,0 +1,91 @@
1
+ Metadata-Version: 2.4
2
+ Name: abstractavatar
3
+ Version: 0.1.0
4
+ Summary: Shared procedural avatar generation for native, terminal and web platforms
5
+ Author: Laurent-Philippe Albou
6
+ License-Expression: MIT
7
+ Project-URL: Repository, https://github.com/lpalbou/AbstractAvatar
8
+ Requires-Python: >=3.10
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Dynamic: license-file
12
+
13
+ # AbstractAvatar
14
+
15
+ [![crates.io](https://img.shields.io/crates/v/abstractavatar.svg)](https://crates.io/crates/abstractavatar)
16
+ [![docs.rs](https://img.shields.io/docsrs/abstractavatar)](https://docs.rs/abstractavatar)
17
+ [![CI](https://github.com/lpalbou/AbstractAvatar/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/lpalbou/AbstractAvatar/actions/workflows/ci.yml)
18
+
19
+ AbstractAvatar generates procedural avatars from explicit activity state, time, audio level and
20
+ gaze. One Rust implementation supplies terminal, browser and native applications with a common
21
+ catalog and rendering behavior.
22
+
23
+ Use it for an assistant portrait, an activity indicator or a procedural character that responds
24
+ to your application's state. The host supplies state and presentation; AbstractAvatar generates
25
+ the picture locally.
26
+
27
+ ![Procedural avatar catalog](docs/media/catalog.png)
28
+
29
+ **What's new in 0.1.0:** the first release of the `abstractavatar` crate. See the
30
+ [changelog](CHANGELOG.md#010---2026-11-02).
31
+
32
+ ## Start with Rust
33
+
34
+ Add the crate from crates.io (Rust 1.87+):
35
+
36
+ ```sh
37
+ cargo add abstractavatar
38
+ ```
39
+
40
+ ```rust
41
+ use abstractavatar::{AvatarPose, AvatarStyle, Frame, Gaze, Palette};
42
+
43
+ let frame = Frame::new(AvatarStyle::Halo, AvatarPose::Speaking, 0.6, 1.2, Gaze::default());
44
+ let palette: Palette = [[0xffc060ff; 256], [0xff7070ff; 256], [0xd8e0ffff; 256]];
45
+ let rgba = frame.rgba(0.2, -0.1, 2.0 / 128.0, &palette);
46
+ ```
47
+
48
+ Enable the `ffi` feature for the C ABI and WebAssembly exports, and `json` for the versioned
49
+ parameter descriptor.
50
+
51
+ ## Start with Python
52
+
53
+ Build from the repository with Python 3.10+ and Rust 1.87+:
54
+
55
+ ```sh
56
+ git clone https://github.com/lpalbou/AbstractAvatar.git
57
+ cd AbstractAvatar
58
+ python -m pip install .
59
+ python -m abstractavatar catalog
60
+ python -m abstractavatar render --style halo --state speaking --level 0.6 --size 128 --output avatar.png
61
+ ```
62
+
63
+ The Python distribution includes the compiled native library. A source installation builds it
64
+ with Cargo. See [getting started](docs/getting-started.md) for library use and platform builds.
65
+
66
+ ## Integrate a player
67
+
68
+ - **Rust:** create a `Frame` and sample composited RGBA through your theme's material ramps.
69
+ - **Browser:** run the bundled WebAssembly generator and present RGBA pixels on Canvas.
70
+ - **Python/native:** request RGBA pixels through the binding or the C interface and present them
71
+ with your UI toolkit.
72
+
73
+ Store catalog style identifiers, rather than numeric indices. Supply time explicitly, stop
74
+ animation while hidden, and use a static frame when reduced motion is enabled. Platform adapters
75
+ do not need their own geometry implementations.
76
+
77
+ The catalog includes shaded characters, particle orbs, forms, portraits, machines, nature scenes
78
+ and a woven orb. [Catalog guidance](docs/catalog.md) explains source variants and stable keys.
79
+
80
+ ## Documentation
81
+
82
+ [Documentation index](docs/README.md) · [Architecture](docs/architecture.md) ·
83
+ [API](docs/api.md) · [Frame contract](docs/frame-contract.md) · [FAQ](docs/faq.md) ·
84
+ [Troubleshooting](docs/troubleshooting.md) · [Contributing](CONTRIBUTING.md) ·
85
+ [Security](SECURITY.md) · [Changelog](CHANGELOG.md)
86
+
87
+ ## For AI agents
88
+
89
+ Use the [AbstractAvatar skill](skills/abstractavatar/SKILL.md) for the rendering workflow,
90
+ descriptor constraints and platform integration rules. The [LLM index](llms.txt) maps the public
91
+ documentation.
@@ -0,0 +1,8 @@
1
+ abstractavatar/__init__.py,sha256=UdxcDTXBNfdw2AweKZYKFqFvbrM4KxFx_aS2hxXuSlk,11036
2
+ abstractavatar/__main__.py,sha256=z9P9fUjT90Q-6MoOwaSCAifyw2AlDyKH0YkHJc6t3Xk,1999
3
+ abstractavatar/_native/abstractavatar.dll,sha256=rE5NRmYSKiaYMoqj1kNdSSIcbrU63RMC7a6Ov1dmKUw,282112
4
+ abstractavatar-0.1.0.dist-info/licenses/LICENSE,sha256=Ul_qU6NR2oU4jRajphulxe86_G6ch4VONAF7P1sARBs,1131
5
+ abstractavatar-0.1.0.dist-info/METADATA,sha256=xAVNGX5Eddh_AvOyh03s7v612DUqR2X4AsFOWHOqxBw,3817
6
+ abstractavatar-0.1.0.dist-info/WHEEL,sha256=79BCzrXBJOa2YV6ugKrK59dqWifMGjAkgVd_6AQrqbU,98
7
+ abstractavatar-0.1.0.dist-info/top_level.txt,sha256=_-TqyggTTxJ_BnrTtYd5bAB9NEDSaVR-WBzm2RchnSY,15
8
+ abstractavatar-0.1.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_amd64
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Laurent-Philippe Albou <contact@abstractframework.ai>
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.
@@ -0,0 +1 @@
1
+ abstractavatar