aether-mobile 0.8.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.
aether/__init__.py ADDED
@@ -0,0 +1,16 @@
1
+ """Build and run a pipeline for Aether."""
2
+
3
+ from .bundle import read_manifest
4
+ from .models import LiteRTModel, OnnxModel, SklearnModel
5
+ from .native_ops import (
6
+ AffineValues, AudioPreprocess, Classify, DetectBoxes, ExtractScalar, ImagePreprocess,
7
+ MathTransform, OneHotEncode, TabularFeatures, TextTokenize,
8
+ )
9
+ from .pipeline import Asset, Example, Pipeline, Step
10
+ from .schema import Input, Output, PipelineError
11
+
12
+ __all__ = [
13
+ "AffineValues", "Asset", "AudioPreprocess", "Classify", "DetectBoxes", "Example", "ExtractScalar",
14
+ "ImagePreprocess", "Input", "LiteRTModel", "MathTransform", "OneHotEncode", "OnnxModel", "Output",
15
+ "Pipeline", "PipelineError", "SklearnModel", "Step", "TabularFeatures", "TextTokenize", "read_manifest",
16
+ ]
aether/__main__.py ADDED
@@ -0,0 +1,3 @@
1
+ from .cli import main
2
+
3
+ raise SystemExit(main())
@@ -0,0 +1,107 @@
1
+ {
2
+ "contract_version": 2,
3
+ "target": "android-0.8",
4
+ "previous_bundle_targets": [],
5
+ "app_version": "0.8",
6
+ "app_version_code": 7,
7
+ "bundle_schemas": [2],
8
+ "bundle_limits": {
9
+ "download_bytes": 134217728,
10
+ "manifest_bytes": 1048576,
11
+ "expanded_asset_bytes": 134217728
12
+ },
13
+ "platform": {
14
+ "os": "android",
15
+ "min_api": 24,
16
+ "abis": ["arm64-v8a"]
17
+ },
18
+ "model_formats": {
19
+ "tflite": {
20
+ "version": "1.0",
21
+ "families": ["generic-tflite"],
22
+ "availability": "required",
23
+ "dtypes": ["float32", "uint8", "int8", "int32", "int64"]
24
+ },
25
+ "onnx": {
26
+ "version": "1.0",
27
+ "families": ["generic-onnx"],
28
+ "availability": "required",
29
+ "dtypes": ["float32", "int32", "int64", "uint8", "int8", "string"]
30
+ },
31
+ "executorch-pte": {
32
+ "version": null,
33
+ "families": [],
34
+ "availability": "unavailable"
35
+ }
36
+ },
37
+ "capabilities": {
38
+ "image-preprocess": {"version": "1.0", "availability": "required"},
39
+ "audio-preprocess": {"version": "1.0", "availability": "required"},
40
+ "tabular-features": {"version": "1.0", "availability": "required"},
41
+ "affine-values": {"version": "1.0", "availability": "required"},
42
+ "math-transform": {"version": "1.0", "availability": "required"},
43
+ "one-hot-encode": {"version": "1.0", "availability": "required"},
44
+ "text-tokenize": {"version": "1.0", "availability": "required"},
45
+ "classify": {"version": "1.0", "availability": "required"},
46
+ "detect-boxes": {"version": "1.0", "availability": "required"},
47
+ "extract-scalar": {"version": "1.0", "availability": "required"},
48
+ "litert-inference": {"version": "1.0", "availability": "required"},
49
+ "onnx-inference": {"version": "1.0", "availability": "required"},
50
+ "downloaded-python": {"version": null, "availability": "unavailable"}
51
+ },
52
+ "runtimes": {
53
+ "litert": {
54
+ "version": "1.4.2",
55
+ "availability": "required",
56
+ "validator": "native",
57
+ "since": "android-0.8",
58
+ "summary": "Generic LiteRT (.tflite) inference with native image, audio, text, and tabular preprocessing.",
59
+ "execution": "native-pipeline-v1",
60
+ "inputs": ["image", "audio", "integer", "number", "choice", "toggle", "text"],
61
+ "outputs": ["label", "score", "scores", "boxes", "text", "json"],
62
+ "optional_capabilities": [],
63
+ "operations": {
64
+ "image_preprocess": {"capability": "image-preprocess"},
65
+ "audio_preprocess": {"capability": "audio-preprocess"},
66
+ "tabular_features": {"capability": "tabular-features"},
67
+ "affine_values": {"capability": "affine-values"},
68
+ "math_transform": {"capability": "math-transform"},
69
+ "one_hot_encode": {"capability": "one-hot-encode"},
70
+ "text_tokenize": {"capability": "text-tokenize"},
71
+ "classify": {"capability": "classify"},
72
+ "detect_boxes": {"capability": "detect-boxes"},
73
+ "extract_scalar": {"capability": "extract-scalar"},
74
+ "litert": {"capability": "litert-inference", "format": "tflite", "family": "generic-tflite"}
75
+ }
76
+ },
77
+ "onnx": {
78
+ "version": "1.20.0",
79
+ "availability": "required",
80
+ "validator": "native",
81
+ "since": "android-0.8",
82
+ "summary": "Generic ONNX Runtime (.onnx) inference including ai.onnx.ml models and native preprocessing.",
83
+ "execution": "native-pipeline-v1",
84
+ "inputs": ["image", "audio", "integer", "number", "choice", "toggle", "text"],
85
+ "outputs": ["label", "score", "scores", "boxes", "text", "json"],
86
+ "optional_capabilities": [],
87
+ "operations": {
88
+ "image_preprocess": {"capability": "image-preprocess"},
89
+ "audio_preprocess": {"capability": "audio-preprocess"},
90
+ "tabular_features": {"capability": "tabular-features"},
91
+ "affine_values": {"capability": "affine-values"},
92
+ "math_transform": {"capability": "math-transform"},
93
+ "one_hot_encode": {"capability": "one-hot-encode"},
94
+ "text_tokenize": {"capability": "text-tokenize"},
95
+ "classify": {"capability": "classify"},
96
+ "detect_boxes": {"capability": "detect-boxes"},
97
+ "extract_scalar": {"capability": "extract-scalar"},
98
+ "onnx": {"capability": "onnx-inference", "format": "onnx", "family": "generic-onnx"}
99
+ }
100
+ },
101
+ "executorch": {
102
+ "version": null,
103
+ "availability": "unavailable",
104
+ "reason": "ExecuTorch is not installed in this Android app release."
105
+ }
106
+ }
107
+ }
@@ -0,0 +1,44 @@
1
+ """Manifest integrity parsing and content fingerprinting shared across Aether."""
2
+
3
+ import hashlib
4
+ import json
5
+ import math
6
+
7
+
8
+ BUNDLE_LIMIT = 128 * 1024 * 1024
9
+ MANIFEST_LIMIT = 1024 * 1024
10
+
11
+
12
+ def parse_manifest(data):
13
+ def unique_object(pairs):
14
+ result = {}
15
+ for key, value in pairs:
16
+ if key in result:
17
+ raise ValueError("Duplicate JSON keys are not allowed in a bundle.")
18
+ result[key] = value
19
+ return result
20
+
21
+ def reject_constant(_):
22
+ raise ValueError("Bundle numbers must be finite.")
23
+
24
+ manifest = json.loads(data, object_pairs_hook=unique_object, parse_constant=reject_constant)
25
+
26
+ def check(value, depth):
27
+ if isinstance(value, (list, dict)):
28
+ if depth > 20:
29
+ raise ValueError("The bundle manifest is nested too deeply.")
30
+ for item in (value.values() if isinstance(value, dict) else value):
31
+ check(item, depth + 1)
32
+ elif isinstance(value, float) and not math.isfinite(value):
33
+ raise ValueError("Bundle numbers must be finite.")
34
+
35
+ check(manifest, 1)
36
+ return manifest
37
+
38
+
39
+ def content_fingerprint(manifest):
40
+ canonical = dict(manifest)
41
+ canonical.pop("compatibility", None)
42
+ canonical["files"] = sorted(manifest["files"], key=lambda entry: entry["path"])
43
+ payload = json.dumps(canonical, sort_keys=True, separators=(",", ":"), ensure_ascii=True, allow_nan=False)
44
+ return hashlib.sha256(payload.encode("ascii")).hexdigest()
aether/bundle.py ADDED
@@ -0,0 +1,260 @@
1
+ """Write and verify Aether bundles without importing their Python code."""
2
+
3
+ from contextlib import contextmanager, nullcontext
4
+ import hashlib
5
+ import json
6
+ import os
7
+ from pathlib import Path
8
+ import tempfile
9
+ from zipfile import BadZipFile, ZIP_DEFLATED, ZipFile
10
+ import zlib
11
+
12
+ from .android_profile import BUNDLE_LIMIT, MANIFEST_LIMIT, parse_manifest
13
+ from .compatibility import MOBILE_BUNDLE_SCHEMA, TARGET
14
+ from .native_ops import NATIVE_EXECUTION, validate_native_manifest
15
+ from .schema import (
16
+ Input, Output, PipelineError, check_json, check_key, check_project_id, finite_number, portable_path,
17
+ )
18
+
19
+
20
+ def _entry_name(name):
21
+ portable_path(name)
22
+ if not name.startswith(("source/", "assets/")):
23
+ raise PipelineError(f"Invalid bundle entry '{name}'.")
24
+ return name.casefold()
25
+
26
+
27
+ def verify_model_headers(manifest, open_asset):
28
+ for step in manifest["steps"]:
29
+ kind = step.get("kind")
30
+ if kind == "litert":
31
+ with open_asset(step["model"]) as model:
32
+ if model.read(8)[4:] != b"TFL3":
33
+ raise PipelineError(
34
+ "The model file is missing its LiteRT flatbuffer identifier.",
35
+ compatibility_code="model.invalid_file",
36
+ )
37
+ elif kind == "onnx":
38
+ with open_asset(step["model"]) as model:
39
+ header = model.read(64)
40
+ if not header or header.lstrip().startswith((b"{", b"[", b"<", b"PK")):
41
+ raise PipelineError(
42
+ "The model file does not appear to be a binary ONNX protobuf.",
43
+ compatibility_code="model.invalid_file",
44
+ )
45
+
46
+
47
+ def build_bundle(pipeline, output, *, target=TARGET):
48
+ output = Path(output).resolve()
49
+ if output.suffix.lower() != ".aether":
50
+ raise PipelineError("Use a .aether filename for the bundle.")
51
+ with tempfile.TemporaryDirectory() as directory:
52
+ if target is None and any(pipeline.mobile_requirements.values()):
53
+ raise PipelineError("Declared runtime and capability requirements need an Android packaging target.")
54
+ manifest, files = pipeline._bundle_contents(Path(directory), assess_runtime=target is not None)
55
+ if output in files.values():
56
+ raise PipelineError("Save the bundle to a different file from its inputs.")
57
+ names = [_entry_name(name) for name in files]
58
+ if len(set(names)) != len(names):
59
+ raise PipelineError("Bundle paths must remain unique when compared without letter case.")
60
+ output.parent.mkdir(parents=True, exist_ok=True)
61
+ temporary = None
62
+ try:
63
+ with tempfile.NamedTemporaryFile(dir=output.parent, suffix=".tmp", delete=False) as handle:
64
+ temporary = Path(handle.name)
65
+ with ZipFile(handle, mode="w", compression=ZIP_DEFLATED) as archive:
66
+ records = []
67
+ total = 0
68
+ for name, path in sorted(files.items()):
69
+ if target is not None and path.stat().st_size > BUNDLE_LIMIT - total:
70
+ raise PipelineError("The project exceeds the Android expanded asset size limit.")
71
+ digest = hashlib.sha256()
72
+ size = 0
73
+ with path.open("rb") as source, archive.open(name, "w", force_zip64=True) as destination:
74
+ while chunk := source.read(1024 * 1024):
75
+ total += len(chunk)
76
+ if target is not None and total > BUNDLE_LIMIT:
77
+ raise PipelineError("The project exceeds the Android expanded asset size limit.")
78
+ destination.write(chunk)
79
+ digest.update(chunk)
80
+ size += len(chunk)
81
+ records.append({"path": name, "bytes": size, "sha256": digest.hexdigest()})
82
+ manifest["files"] = records
83
+ check_json(manifest, "The bundle manifest")
84
+ if target is not None:
85
+ from .targets import check_manifest, require_supported
86
+
87
+ manifest["schema_version"] = MOBILE_BUNDLE_SCHEMA
88
+ report, plan = check_manifest(manifest, target, declarations=pipeline.mobile_requirements)
89
+ require_supported(report)
90
+ verify_model_headers(manifest, archive.open)
91
+ manifest["compatibility"] = plan
92
+ _verify_references(manifest, files)
93
+ payload = json.dumps(manifest, indent=2, allow_nan=False).encode("utf-8")
94
+ if target is not None and (len(payload) > MANIFEST_LIMIT or handle.tell() > BUNDLE_LIMIT):
95
+ raise PipelineError("This project exceeds the Android manifest or download size limit.")
96
+ archive.writestr("manifest.json", payload)
97
+ if target is not None and handle.tell() > BUNDLE_LIMIT:
98
+ raise PipelineError("This project exceeds the Android download size limit.")
99
+ os.replace(temporary, output)
100
+ finally:
101
+ if temporary is not None:
102
+ temporary.unlink(missing_ok=True)
103
+ return output
104
+
105
+
106
+ @contextmanager
107
+ def open_bundle(bundle, max_bytes):
108
+ source = nullcontext(bundle) if hasattr(bundle, "read") else Path(bundle).open("rb")
109
+ with source as stream:
110
+ position = stream.tell()
111
+ try:
112
+ if stream.seek(0, os.SEEK_END) > max_bytes:
113
+ raise PipelineError("The archive exceeds the inspection size limit.")
114
+ with ZipFile(stream) as archive:
115
+ yield archive
116
+ finally:
117
+ stream.seek(position)
118
+
119
+
120
+ def _verify(archive, *, verify_project=True, max_bytes=BUNDLE_LIMIT):
121
+ names = archive.namelist()
122
+ if names.count("manifest.json") != 1 or len(names) != len(set(names)):
123
+ raise PipelineError("Expected one manifest and unique file names in the bundle.")
124
+ if archive.getinfo("manifest.json").file_size > MANIFEST_LIMIT:
125
+ raise PipelineError("The bundle manifest exceeds its size limit.")
126
+ if sum(entry.file_size for entry in archive.infolist() if entry.filename != "manifest.json") > max_bytes:
127
+ raise PipelineError("The expanded bundle exceeds the inspection size limit.")
128
+ manifest = parse_manifest(archive.read("manifest.json").decode("utf-8"))
129
+ if not isinstance(manifest, dict):
130
+ raise PipelineError("Expected an Aether manifest object.")
131
+ if verify_project and (type(manifest.get("schema_version")) is not int
132
+ or manifest["schema_version"] not in (1, MOBILE_BUNDLE_SCHEMA)):
133
+ raise PipelineError("Unsupported Aether bundle format version.")
134
+ check_json(manifest, "The bundle manifest")
135
+ if not isinstance(manifest.get("files"), list):
136
+ raise PipelineError("The bundle has no file inventory.")
137
+ inventory = {}
138
+ normalized = set()
139
+ for record in manifest["files"]:
140
+ if not isinstance(record, dict) or not isinstance(record.get("path"), str):
141
+ raise PipelineError("The bundle has an invalid file record.")
142
+ name = record["path"]
143
+ folded = _entry_name(name)
144
+ if folded in normalized:
145
+ raise PipelineError(f"Duplicate bundle path '{name}'.")
146
+ normalized.add(folded)
147
+ inventory[name] = record
148
+ if set(names) != {"manifest.json", *inventory}:
149
+ raise PipelineError("The bundle file list differs from its manifest.")
150
+ for name, record in inventory.items():
151
+ info = archive.getinfo(name)
152
+ if type(record.get("bytes")) is not int or info.file_size != record["bytes"]:
153
+ raise PipelineError(f"Bundle file '{name}' has the wrong size.")
154
+ with archive.open(info) as contents:
155
+ actual = hashlib.file_digest(contents, "sha256").hexdigest()
156
+ if actual != record.get("sha256"):
157
+ raise PipelineError(f"Checksum mismatch for bundle file '{name}'.")
158
+ if verify_project:
159
+ _verify_references(manifest, inventory)
160
+ return manifest
161
+
162
+
163
+ def _verify_references(manifest, inventory):
164
+ if manifest.get("execution") == NATIVE_EXECUTION:
165
+ try:
166
+ validate_native_manifest(manifest, inventory=inventory)
167
+ except (ValueError, TypeError, KeyError, AttributeError) as error:
168
+ raise PipelineError(str(error)) from error
169
+ return
170
+ try:
171
+ project = manifest["project"]
172
+ if not all(isinstance(project[key], str) and project[key] for key in ("name", "version")):
173
+ raise ValueError
174
+ check_project_id(project["id"])
175
+ if not isinstance(manifest["requirements"], list) or manifest["execution"] != "trusted-python":
176
+ raise ValueError
177
+ if any(not isinstance(manifest[key], list) for key in ("inputs", "outputs", "steps", "examples")):
178
+ raise ValueError
179
+ inputs = []
180
+ for control in manifest["inputs"]:
181
+ fields = dict(control)
182
+ fields["kind"] = fields.pop("type")
183
+ inputs.append(Input(**fields))
184
+ outputs = [Output(**control) for control in manifest["outputs"]]
185
+ known = {control.name for control in inputs}
186
+ output_names = {control.name for control in outputs}
187
+ if (not inputs or not outputs or not manifest["steps"]
188
+ or len(known) != len(inputs) or len(output_names) != len(outputs)):
189
+ raise ValueError
190
+ for step in manifest["steps"]:
191
+ if not isinstance(step["name"], str) or not isinstance(step["inputs"], dict):
192
+ raise ValueError
193
+ if not isinstance(step["outputs"], list) or not step["outputs"]:
194
+ raise ValueError
195
+ if step["kind"] == "python":
196
+ source = step["source"]
197
+ parts = step["module"].split(".")
198
+ for part in (*parts, step["function"]):
199
+ check_key(part)
200
+ module_path = "source/" + "/".join(parts)
201
+ if source not in (f"{module_path}.py", f"{module_path}/__init__.py") or source not in inventory:
202
+ raise ValueError
203
+ elif step["kind"] in ("sklearn", "litert", "onnx"):
204
+ asset = step["model"]
205
+ if not asset.startswith("assets/") or asset not in inventory:
206
+ raise ValueError
207
+ else:
208
+ raise ValueError
209
+ for argument, binding in step["inputs"].items():
210
+ check_key(argument)
211
+ if binding.keys() == {"asset"}:
212
+ if not binding["asset"].startswith("assets/") or binding["asset"] not in inventory:
213
+ raise ValueError
214
+ elif binding.keys() != {"value"} or binding["value"] not in known:
215
+ raise ValueError
216
+ for output in step["outputs"]:
217
+ check_key(output)
218
+ if output in known:
219
+ raise ValueError
220
+ known.add(output)
221
+ if not output_names <= known:
222
+ raise ValueError
223
+ example_names = set()
224
+ input_names = {control.name for control in inputs}
225
+ for example in manifest["examples"]:
226
+ name = example["name"]
227
+ tolerance = example["tolerance"]
228
+ if (not isinstance(name, str) or not name.strip() or name in example_names
229
+ or not finite_number(tolerance) or tolerance < 0):
230
+ raise ValueError
231
+ example_names.add(name)
232
+ values = example["inputs"]
233
+ if values.keys() != input_names:
234
+ raise ValueError
235
+ for control in inputs:
236
+ value = values[control.name]
237
+ if control.kind in ("image", "audio") and value is not None:
238
+ if value.keys() != {"asset"} or not value["asset"].startswith("assets/") or value["asset"] not in inventory:
239
+ raise ValueError
240
+ else:
241
+ control.validate(value)
242
+ expected = example["expected"]
243
+ if expected is not None:
244
+ if expected.keys() != output_names:
245
+ raise ValueError
246
+ for output in outputs:
247
+ output.validate(expected[output.name])
248
+ except (KeyError, TypeError, AttributeError, ValueError) as error:
249
+ raise PipelineError("Invalid pipeline bindings or missing files in the bundle manifest.") from error
250
+
251
+
252
+ def read_manifest(bundle, *, max_bytes=BUNDLE_LIMIT):
253
+ """Check file hashes and return the manifest. Source and models are only read as bytes."""
254
+ try:
255
+ with open_bundle(bundle, max_bytes) as archive:
256
+ return _verify(archive, max_bytes=max_bytes)
257
+ except PipelineError:
258
+ raise
259
+ except (OSError, BadZipFile, ValueError, OverflowError, RuntimeError, zlib.error) as error:
260
+ raise PipelineError("Could not read the Aether bundle. Check its format and JSON metadata.") from error