led-controller-version-3-effect-creation 3.0.2__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.
@@ -0,0 +1,263 @@
1
+ """Source validation and the smoke render.
2
+
3
+ The build is a quality gate, not a zip step. A source that reaches the packer
4
+ has already been proven to import cleanly on its own, to declare exactly one
5
+ definition, to keep its presets inside its own schema, and to render a frame
6
+ that satisfies the contract it declared — at more than one ring size, because a
7
+ package that only works at twelve LEDs has hardcoded something it should not.
8
+ """
9
+
10
+ from __future__ import annotations
11
+
12
+ import importlib.util
13
+ import sys
14
+ from dataclasses import dataclass, field
15
+ from pathlib import Path
16
+ from typing import Any
17
+
18
+ from lefx.engine import check_frame
19
+ from lefx.sdk import (
20
+ BaseEffect,
21
+ DefinitionBase,
22
+ ParameterValidationError,
23
+ RenderContext,
24
+ initial_runtime_inputs,
25
+ resolve_configuration,
26
+ )
27
+
28
+ from .imports import ImportViolation, check_imports, find_effect_classes
29
+ from .source import EffectSetSource, EffectSource, SourceError
30
+
31
+ SMOKE_LED_COUNTS: tuple[int, ...] = (5, 12, 24)
32
+
33
+ _module_counter = 0
34
+
35
+
36
+ @dataclass(slots=True)
37
+ class ValidationReport:
38
+ ok: bool
39
+ kind: str
40
+ identifier: str
41
+ source_id: str
42
+ details: dict[str, Any] = field(default_factory=dict)
43
+ warnings: list[str] = field(default_factory=list)
44
+ errors: list[str] = field(default_factory=list)
45
+
46
+ def to_dict(self) -> dict[str, Any]:
47
+ return {
48
+ "ok": self.ok,
49
+ "kind": self.kind,
50
+ "id": self.identifier,
51
+ "source_id": self.source_id,
52
+ "details": self.details,
53
+ "warnings": self.warnings,
54
+ "errors": self.errors,
55
+ }
56
+
57
+
58
+ def import_effect_class(source: EffectSource) -> type[BaseEffect]:
59
+ """Import the source in isolation and return its single definition class."""
60
+ declared = find_effect_classes(source.entry_path)
61
+ if not declared:
62
+ raise SourceError(
63
+ f"{source.entry_path} defines no BaseEffect subclass; a source ships "
64
+ "exactly one definition"
65
+ )
66
+ if source.entry_class is None and len(declared) > 1:
67
+ raise SourceError(
68
+ f"{source.entry_path} defines several definitions ({', '.join(declared)}); "
69
+ "a source ships exactly one, or the manifest must name entry_class"
70
+ )
71
+ wanted = source.entry_class or declared[0]
72
+ if wanted not in declared:
73
+ raise SourceError(
74
+ f"{source.manifest_path} names entry_class {wanted!r}, which "
75
+ f"{source.entry_path.name} does not define"
76
+ )
77
+
78
+ global _module_counter
79
+ _module_counter += 1
80
+ alias = f"_lefx_src_{source.root.name}_{_module_counter}"
81
+
82
+ init_path = source.root / "__init__.py"
83
+ created_init = not init_path.exists()
84
+ if created_init:
85
+ init_path.write_text("", encoding="utf-8")
86
+ try:
87
+ spec = importlib.util.spec_from_file_location(
88
+ alias, init_path, submodule_search_locations=[str(source.root)]
89
+ )
90
+ if spec is None or spec.loader is None:
91
+ raise SourceError(f"Cannot import {source.root}")
92
+ package = importlib.util.module_from_spec(spec)
93
+ sys.modules[alias] = package
94
+ spec.loader.exec_module(package)
95
+ module = importlib.import_module(f"{alias}.{source.entry_module}")
96
+ except SourceError:
97
+ raise
98
+ except Exception as exc:
99
+ raise SourceError(f"Importing {source.entry_path} failed: {exc}") from exc
100
+ finally:
101
+ sys.modules.pop(alias, None)
102
+ if created_init:
103
+ init_path.unlink(missing_ok=True)
104
+
105
+ effect_class = getattr(module, wanted, None)
106
+ if not isinstance(effect_class, type) or not issubclass(effect_class, BaseEffect):
107
+ raise SourceError(f"{wanted} in {source.entry_path.name} is not a BaseEffect subclass")
108
+ if not isinstance(getattr(effect_class, "definition", None), DefinitionBase):
109
+ raise SourceError(f"{wanted} declares no LEFX V3 definition")
110
+ return effect_class
111
+
112
+
113
+ def smoke_render(
114
+ effect_class: type[BaseEffect], *, led_counts: tuple[int, ...] = SMOKE_LED_COUNTS
115
+ ) -> None:
116
+ """Render one frame per ring size and hold it to the declared contract.
117
+
118
+ This catches integration mistakes, not visual ones. It does not replace
119
+ deliberate animation or boundary tests.
120
+ """
121
+ definition = effect_class.get_definition()
122
+ params = resolve_configuration(definition)
123
+ inputs = initial_runtime_inputs(definition)
124
+ for led_count in led_counts:
125
+ instance = effect_class()
126
+ context = RenderContext(
127
+ now=1.0,
128
+ started_at=0.0,
129
+ led_count=led_count,
130
+ definition=definition,
131
+ params=params,
132
+ inputs=inputs,
133
+ )
134
+ try:
135
+ frame = instance.render(context)
136
+ except Exception as exc:
137
+ raise SourceError(
138
+ f"{definition.id!r} failed to render at {led_count} LEDs: {exc}"
139
+ ) from exc
140
+ check_frame(frame, definition, led_count)
141
+
142
+
143
+ def validate_effect_source(directory: str | Path) -> ValidationReport:
144
+ """Everything a source must satisfy before it may be packed."""
145
+ from .source import load_effect_source
146
+
147
+ source = load_effect_source(directory)
148
+ report = ValidationReport(
149
+ ok=False, kind="effect", identifier="", source_id=source.source_id
150
+ )
151
+
152
+ violations: list[ImportViolation] = check_imports(source.root)
153
+ if violations:
154
+ report.errors.extend(str(item) for item in violations)
155
+ return report
156
+
157
+ try:
158
+ effect_class = import_effect_class(source)
159
+ except SourceError as exc:
160
+ report.errors.append(str(exc))
161
+ return report
162
+
163
+ definition = effect_class.get_definition()
164
+ report.identifier = definition.id
165
+
166
+ if source.root.name != definition.id:
167
+ report.warnings.append(
168
+ f"directory is {source.root.name!r} but the definition is {definition.id!r}; "
169
+ "keeping them equal makes the catalogue navigable"
170
+ )
171
+
172
+ presets = source.presets()
173
+ for preset_id, entry in presets.items():
174
+ if not isinstance(entry, dict):
175
+ report.errors.append(f"preset {preset_id!r} is not an object")
176
+ continue
177
+ unknown = set(entry) - {"title", "description", "tags", "params"}
178
+ if unknown:
179
+ report.errors.append(
180
+ f"preset {preset_id!r} has unknown keys: {', '.join(sorted(unknown))}. "
181
+ "A preset carries configuration only."
182
+ )
183
+ continue
184
+ try:
185
+ resolve_configuration(definition, preset=entry.get("params", {}))
186
+ except ParameterValidationError as exc:
187
+ report.errors.append(f"preset {preset_id!r} does not satisfy the schema: {exc}")
188
+
189
+ try:
190
+ smoke_render(effect_class)
191
+ except SourceError as exc:
192
+ report.errors.append(str(exc))
193
+ except Exception as exc:
194
+ report.errors.append(f"smoke render failed: {exc}")
195
+
196
+ report.details = {
197
+ "kind": definition.kind.value,
198
+ "type": definition.definition_type.value,
199
+ "package_id": source.package_id or f"{source.source_id}.{definition.id}",
200
+ "entry_class": effect_class.__name__,
201
+ "entry_module": source.entry_module,
202
+ "preset_count": len(presets),
203
+ "led_counts": list(SMOKE_LED_COUNTS),
204
+ }
205
+ report.ok = not report.errors
206
+ return report
207
+
208
+
209
+ def validate_effect_set_source(directory: str | Path) -> ValidationReport:
210
+ """A set is checked as a whole: members, namespace and id collisions."""
211
+ from lefx.engine import load_source as load_package
212
+
213
+ from .source import load_effect_set_source
214
+
215
+ source: EffectSetSource = load_effect_set_source(directory)
216
+ report = ValidationReport(
217
+ ok=False, kind="set", identifier=source.set_id, source_id=source.source_id
218
+ )
219
+
220
+ seen: dict[str, str] = {}
221
+ effect_count = 0
222
+ preset_count = 0
223
+ for member in source.members:
224
+ path = source.effects_dir / member
225
+ try:
226
+ loaded = load_package(path)
227
+ except Exception as exc:
228
+ report.errors.append(f"{member}: {exc}")
229
+ continue
230
+ if loaded.source_id != source.source_id:
231
+ report.errors.append(
232
+ f"{member} declares source {loaded.source_id!r} but the set is "
233
+ f"{source.source_id!r}; every member shares the set's namespace"
234
+ )
235
+ for package in loaded.packages:
236
+ effect_count += 1
237
+ preset_count += len(package.presets)
238
+ for identifier in (package.effect_id, *(p.preset_id for p in package.presets)):
239
+ previous = seen.get(identifier)
240
+ if previous is not None:
241
+ report.errors.append(
242
+ f"{identifier!r} is declared by both {previous} and {member}"
243
+ )
244
+ seen[identifier] = member
245
+
246
+ report.details = {
247
+ "title": source.title,
248
+ "members": list(source.members),
249
+ "effect_count": effect_count,
250
+ "preset_count": preset_count,
251
+ }
252
+ report.ok = not report.errors
253
+ return report
254
+
255
+
256
+ __all__ = [
257
+ "SMOKE_LED_COUNTS",
258
+ "ValidationReport",
259
+ "import_effect_class",
260
+ "smoke_render",
261
+ "validate_effect_set_source",
262
+ "validate_effect_source",
263
+ ]