pyvisionect 0.1.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.
Files changed (58) hide show
  1. pyvisionect/__init__.py +120 -0
  2. pyvisionect/devices/__init__.py +92 -0
  3. pyvisionect/devices/enums.py +403 -0
  4. pyvisionect/devices/panels.py +242 -0
  5. pyvisionect/devices/tclv.py +460 -0
  6. pyvisionect/imaging/README.md +175 -0
  7. pyvisionect/imaging/__init__.py +181 -0
  8. pyvisionect/imaging/checksum.py +114 -0
  9. pyvisionect/imaging/constants.py +131 -0
  10. pyvisionect/imaging/data/blue_noise_64.npy +0 -0
  11. pyvisionect/imaging/decode.py +172 -0
  12. pyvisionect/imaging/dither.py +357 -0
  13. pyvisionect/imaging/encoder.py +594 -0
  14. pyvisionect/imaging/geometry.py +129 -0
  15. pyvisionect/imaging/grey.py +104 -0
  16. pyvisionect/imaging/interlace.py +244 -0
  17. pyvisionect/imaging/pack.py +142 -0
  18. pyvisionect/imaging/panel.py +339 -0
  19. pyvisionect/imaging/partial.py +931 -0
  20. pyvisionect/imaging/rects.py +466 -0
  21. pyvisionect/io/__init__.py +33 -0
  22. pyvisionect/io/tcp.py +795 -0
  23. pyvisionect/io/usb/__init__.py +237 -0
  24. pyvisionect/io/usb/cli.py +278 -0
  25. pyvisionect/io/usb/commands.py +781 -0
  26. pyvisionect/io/usb/console.py +730 -0
  27. pyvisionect/io/usb/device.py +914 -0
  28. pyvisionect/io/usb/discovery.py +260 -0
  29. pyvisionect/io/usb/encryption.py +262 -0
  30. pyvisionect/io/usb/errors.py +175 -0
  31. pyvisionect/io/usb/fake.py +292 -0
  32. pyvisionect/io/usb/parsers.py +1464 -0
  33. pyvisionect/io/usb/provisioning.py +502 -0
  34. pyvisionect/packets/__init__.py +135 -0
  35. pyvisionect/packets/control.py +95 -0
  36. pyvisionect/packets/file.py +325 -0
  37. pyvisionect/packets/image.py +234 -0
  38. pyvisionect/packets/misc.py +202 -0
  39. pyvisionect/packets/param.py +284 -0
  40. pyvisionect/packets/status.py +518 -0
  41. pyvisionect/packets/stored.py +217 -0
  42. pyvisionect/py.typed +0 -0
  43. pyvisionect/session/__init__.py +100 -0
  44. pyvisionect/session/connection.py +1043 -0
  45. pyvisionect/session/device.py +587 -0
  46. pyvisionect/session/events.py +196 -0
  47. pyvisionect/session/filetransfer.py +251 -0
  48. pyvisionect/session/pending.py +425 -0
  49. pyvisionect/wire/__init__.py +91 -0
  50. pyvisionect/wire/blocks.py +350 -0
  51. pyvisionect/wire/checksum.py +115 -0
  52. pyvisionect/wire/errors.py +176 -0
  53. pyvisionect/wire/framing.py +334 -0
  54. pyvisionect-0.1.0.dist-info/METADATA +1030 -0
  55. pyvisionect-0.1.0.dist-info/RECORD +58 -0
  56. pyvisionect-0.1.0.dist-info/WHEEL +4 -0
  57. pyvisionect-0.1.0.dist-info/entry_points.txt +3 -0
  58. pyvisionect-0.1.0.dist-info/licenses/LICENSE +21 -0
@@ -0,0 +1,357 @@
1
+ """Quantisation and dithering. Spec §3.
2
+
3
+ **Nothing about grey-level reduction happens on the device.** The panel
4
+ receives already-quantised 1 bpp or 4 bpp data and only drives the waveform
5
+ (spec §3.3). So every mode here is a purely library-side choice with zero
6
+ protocol impact -- the ``DitheringType`` number never leaves the process.
7
+
8
+ Output levels
9
+ -------------
10
+ A quantised buffer always lands on the encoding's uniform ramp:
11
+
12
+ * 4 bpp -> 16 levels, ``n * 17`` for ``n`` in 0..15
13
+ * 1 bpp -> 2 levels, ``0`` and ``255``
14
+
15
+ so that :func:`pyvisionect.imaging.pack.pack` is afterwards exact (its nibble
16
+ is ``pix >> 4`` and its bit is ``pix >= 0x80``).
17
+
18
+ Where each mode is applied
19
+ --------------------------
20
+ ``none``, ``bayer`` and ``blue-noise`` are **pixel-local**: the output for a
21
+ pixel depends only on that pixel and on its *canvas* coordinate. The encoder
22
+ therefore runs them **once over the whole session canvas, in canvas
23
+ coordinates**, before cropping to displays. Two consequences, both deliberate:
24
+
25
+ * an ordered pattern never seams at a rectangle boundary -- two partial
26
+ updates that happen to abut produce exactly the pixels one combined update
27
+ would have;
28
+ * the result is invariant under the subsequent crop / rotate / mirror, so the
29
+ state image and the wire data agree trivially.
30
+
31
+ ``floyd-steinberg`` diffuses error and is **not** pixel-local, so it is run
32
+ per encoded rectangle in display-local (post-rotate, post-mirror) space, which
33
+ is where the vendor runs it (``eink-generic.go:135-137``, called from
34
+ ``cache.CheckCache`` on the already-cut, already-rotated sub-image). Error
35
+ diffusion is inherently seam-prone; that is a property of the algorithm, not a
36
+ bug here.
37
+
38
+ Divergence from GraphicsMagick -- read this before claiming bit-exactness
39
+ -------------------------------------------------------------------------
40
+ The vendor calls into GraphicsMagick (``bill.vnct.xyz/vss/imgproc``):
41
+
42
+ * ``bayer`` -> ``GmOrderedDither`` -> GM's ``OrderedDitherImage()``, which
43
+ takes **no level parameter** and is a fixed ordered dither **to bi-level**.
44
+ With ``Encoding: 4`` the vendor therefore still produces a 2-level image
45
+ which then gets nibble-packed as ``0x0``/``0xF`` (spec §3.2, marked
46
+ **[INFERRED]** there). **We deliberately differ**: our ``bayer`` is a
47
+ multi-level ordered dither to the encoding's level count, because that is
48
+ what the 4 bpp wire format can actually carry. Pass
49
+ ``bayer_levels_override=2`` if you want the vendor's behaviour.
50
+ GM's internal matrix is also not published in the report, so even the
51
+ bi-level output would not be pixel-identical. **This makes blue-noise
52
+ (mode 4) the only good ordered dither at 4 bpp.**
53
+ * ``floyd-steinberg`` -> ``GmFloydSteinbergDither`` ->
54
+ ``QuantizeImage(number_colors=encodingLevels, dither=1)``. GM *builds its
55
+ palette from the image histogram*, so at 16 colours it produces 16
56
+ **image-derived** greys which the packer then truncates to nibbles -- lossy
57
+ and content-dependent. We quantise to the uniform ``n*17`` ramp instead,
58
+ which is what the wire format encodes, and we use Pillow's
59
+ Floyd-Steinberg error diffusion.
60
+ **This is not bit-exact to GraphicsMagick and has not been claimed to be.**
61
+ No GM output was available to diff against.
62
+
63
+ What *is* verified against real device bytes is the ``none`` path: see
64
+ ``tests/imaging/test_golden_capture.py``.
65
+ """
66
+
67
+ from __future__ import annotations
68
+
69
+ import functools
70
+ import importlib.resources
71
+ import warnings
72
+ from typing import Optional
73
+
74
+ import numpy as np
75
+ from PIL import Image
76
+
77
+ from .constants import ENCODING_LEVELS, LEVEL_STEP, Dithering, Encoding
78
+
79
+ __all__ = [
80
+ "bayer_matrix",
81
+ "BAYER_8",
82
+ "blue_noise_matrix",
83
+ "quantise",
84
+ "quantise_none",
85
+ "quantise_ordered",
86
+ "quantise_floyd_steinberg",
87
+ "tile_matrix",
88
+ "is_pixel_local",
89
+ ]
90
+
91
+
92
+ # --------------------------------------------------------------------------
93
+ # threshold matrices
94
+ # --------------------------------------------------------------------------
95
+
96
+ def bayer_matrix(size: int = 8) -> np.ndarray:
97
+ """Recursive Bayer (ordered) threshold matrix, uint8 in ``[0, 255]``.
98
+
99
+ ``size`` must be a power of two. The classic recursion is
100
+
101
+ .. code-block:: text
102
+
103
+ M_1 = [0]
104
+ M_2n = [[4M+0, 4M+2],
105
+ [4M+3, 4M+1]]
106
+
107
+ which yields ``[[0,2],[3,1]]`` at 2x2. The integer ranks ``0..size^2-1``
108
+ are rescaled to bin-centre thresholds ``floor((r + 0.5) / size^2 * 256)``,
109
+ so the matrix mean is 127.5 and the dither is unbiased.
110
+ """
111
+ if size < 1 or size & (size - 1):
112
+ raise ValueError(f"bayer matrix size must be a power of two, got {size}")
113
+ m = np.zeros((1, 1), dtype=np.int64)
114
+ while m.shape[0] < size:
115
+ m = np.block([[4 * m, 4 * m + 2], [4 * m + 3, 4 * m + 1]])
116
+ n = size * size
117
+ return np.floor((m + 0.5) / n * 256.0).clip(0, 255).astype(np.uint8)
118
+
119
+
120
+ #: The default ordered-dither matrix.
121
+ BAYER_8 = bayer_matrix(8)
122
+
123
+
124
+ @functools.lru_cache(maxsize=1)
125
+ def blue_noise_matrix() -> np.ndarray:
126
+ """The shipped 64x64 blue-noise threshold matrix, uint8 in ``[0, 255]``.
127
+
128
+ Generated once by ``tools/gen_blue_noise.py`` with Ulichney's
129
+ void-and-cluster algorithm (sigma 1.5, fixed seed) and **committed** as
130
+ ``data/blue_noise_64.npy``. Nothing is generated at import time, so the
131
+ output of :func:`quantise` is reproducible across runs and machines.
132
+
133
+ Why blue noise is the right default for an e-ink sign: it is *spatially
134
+ stable*. A small content change perturbs only the pixels underneath it,
135
+ whereas Floyd-Steinberg propagates error across the rest of the image, so a
136
+ one-word text change can dirty a huge area. That directly inflates the
137
+ change-detect rectangle list, defeats the <=15-region merge (spec §4.1) and
138
+ causes more panel flashing. Ordered dithers keep dirty regions tight, and
139
+ blue noise gets that stability without Bayer's visible cross-hatch.
140
+ ``tests/imaging/test_dither.py::test_spatial_stability_ranking`` measures
141
+ exactly this.
142
+ """
143
+ with importlib.resources.as_file(
144
+ importlib.resources.files(__package__) / "data" / "blue_noise_64.npy"
145
+ ) as path:
146
+ m = np.load(path)
147
+ if m.dtype != np.uint8 or m.ndim != 2:
148
+ raise ValueError("blue-noise matrix must be a 2-D uint8 array")
149
+ return m
150
+
151
+
152
+ def tile_matrix(matrix: np.ndarray, shape: tuple[int, int],
153
+ origin: tuple[int, int] = (0, 0)) -> np.ndarray:
154
+ """Tile a threshold matrix over ``shape``, phased by an absolute ``origin``.
155
+
156
+ ``origin`` is ``(y, x)`` in **canvas** coordinates. Phasing on the
157
+ absolute position is what makes an ordered dither seam-free across
158
+ independently-encoded rectangles.
159
+ """
160
+ h, w = shape
161
+ oy, ox = origin
162
+ mh, mw = matrix.shape
163
+ ys = (np.arange(oy, oy + h) % mh)
164
+ xs = (np.arange(ox, ox + w) % mw)
165
+ return matrix[np.ix_(ys, xs)]
166
+
167
+
168
+ # --------------------------------------------------------------------------
169
+ # quantisers
170
+ # --------------------------------------------------------------------------
171
+
172
+ def _levels_and_step(encoding: int, levels: int | None = None) -> tuple[int, int]:
173
+ """Resolve ``(levels, step)`` so that output values are ``n * step``.
174
+
175
+ ``step`` is derived from the *level count actually used*, not from the
176
+ encoding, so that a reduced level count (e.g. bi-level Bayer at 4 bpp)
177
+ still lands on values the encoding can carry: 2 levels -> ``0``/``255``,
178
+ which nibble-pack to ``0x0``/``0xF``.
179
+ """
180
+ try:
181
+ default_levels = ENCODING_LEVELS[int(encoding)]
182
+ default_step = LEVEL_STEP[int(encoding)]
183
+ except KeyError:
184
+ raise ValueError(
185
+ f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)"
186
+ ) from None
187
+ if levels is None:
188
+ return default_levels, default_step
189
+ if levels < 2:
190
+ raise ValueError("levels must be >= 2")
191
+ if levels > default_levels:
192
+ raise ValueError(
193
+ f"encoding {int(encoding)} carries at most {default_levels} levels, "
194
+ f"got {levels}"
195
+ )
196
+ if 255 % (levels - 1):
197
+ raise ValueError(
198
+ f"{levels} levels do not divide the 0..255 range evenly; the wire "
199
+ "format only has uniform ramps (spec §2.3)"
200
+ )
201
+ return levels, 255 // (levels - 1)
202
+
203
+
204
+ def quantise_none(grey: np.ndarray, encoding: int) -> np.ndarray:
205
+ """``DitheringType 1`` -- no dithering.
206
+
207
+ 4 bpp: plain truncation of the top nibble, ``(pix >> 4) * 17``.
208
+ 1 bpp: MSB threshold, ``(pix >= 0x80) * 255``.
209
+
210
+ Exactly what :func:`pyvisionect.imaging.pack.pack` would do on its own, so
211
+ a buffer that is already on the ``n * 17`` ramp survives **unchanged**
212
+ (``(n*17) >> 4 == n`` for all ``n`` in 0..15). That losslessness is the
213
+ property the user's pre-dithered Home Assistant content depends on.
214
+ """
215
+ g = np.asarray(grey, dtype=np.uint8)
216
+ if encoding == Encoding.FOUR_BIT:
217
+ return ((g >> 4) * np.uint8(17)).astype(np.uint8)
218
+ if encoding == Encoding.ONE_BIT:
219
+ return np.where(g >= 0x80, np.uint8(255), np.uint8(0)).astype(np.uint8)
220
+ raise ValueError(f"bad encoding {encoding!r}; only 1 and 4 exist (spec §2.1)")
221
+
222
+
223
+ def quantise_ordered(grey: np.ndarray, encoding: int, matrix: np.ndarray,
224
+ origin: tuple[int, int] = (0, 0),
225
+ levels: int | None = None) -> np.ndarray:
226
+ """Ordered (point) dither against a tiled uint8 threshold matrix.
227
+
228
+ The quantiser is integer-exact and unbiased::
229
+
230
+ n = (pix * (L-1) * 256 + threshold * 255) // (255 * 256)
231
+ out = clip(n, 0, L-1) * step
232
+
233
+ Scaling the pixel by 256 and the threshold by 255 (rather than mixing the
234
+ two scales) makes the result **idempotent on the output ramp**: a pixel
235
+ that is already exactly ``n * step`` quantises back to ``n`` for every
236
+ threshold value, so re-dithering never shifts already-quantised content.
237
+
238
+ :param origin: ``(y, x)`` canvas coordinate of ``grey[0, 0]``; the matrix
239
+ phase follows it, which is what keeps independently-encoded rectangles
240
+ seam-free.
241
+ """
242
+ g = np.asarray(grey, dtype=np.uint8)
243
+ nlevels, step = _levels_and_step(encoding, levels)
244
+ thr = tile_matrix(matrix, g.shape, origin).astype(np.int32)
245
+ num = g.astype(np.int32) * (nlevels - 1) * 256 + thr * 255
246
+ n = np.clip(num // (255 * 256), 0, nlevels - 1)
247
+ return (n * step).astype(np.uint8)
248
+
249
+
250
+ def quantise_floyd_steinberg(grey: np.ndarray, encoding: int,
251
+ levels: int | None = None) -> np.ndarray:
252
+ """Floyd-Steinberg error diffusion onto the encoding's uniform ramp.
253
+
254
+ Implemented with Pillow's palette quantiser
255
+ (``Image.quantize(palette=..., dither=FLOYDSTEINBERG)``), with the palette
256
+ pinned to the ``step * n`` ramp so the result is exactly representable on
257
+ the wire. See the module docstring for the divergence from
258
+ GraphicsMagick's ``QuantizeImage``.
259
+ """
260
+ g = np.ascontiguousarray(np.asarray(grey, dtype=np.uint8))
261
+ nlevels, step = _levels_and_step(encoding, levels)
262
+ if g.size == 0:
263
+ return g.copy()
264
+ pal = Image.new("P", (1, 1))
265
+ entries: list[int] = []
266
+ for n in range(nlevels):
267
+ v = min(255, n * step)
268
+ entries += [v, v, v]
269
+ pal.putpalette(entries)
270
+ # Pillow's palette quantiser ignores `palette=` for mode-"L" input (it
271
+ # returns an identity mapping), so the source must be RGB.
272
+ src = Image.fromarray(g, "L").convert("RGB")
273
+ idx = np.array(src.quantize(palette=pal, dither=Image.Dither.FLOYDSTEINBERG))
274
+ return np.minimum(idx.astype(np.int32) * step, 255).astype(np.uint8)
275
+
276
+
277
+ #: Modes whose output for a pixel depends only on that pixel and its canvas
278
+ #: coordinate. The encoder runs these once over the whole canvas; everything
279
+ #: else is run per encoded rectangle.
280
+ _PIXEL_LOCAL = frozenset({Dithering.NONE, Dithering.BAYER, Dithering.BLUE_NOISE})
281
+
282
+
283
+ def is_pixel_local(dithering: int) -> bool:
284
+ """Whether ``dithering`` can be applied canvas-wide (see module docstring)."""
285
+ return int(dithering) in _PIXEL_LOCAL
286
+
287
+
288
+ def _bayer_levels(encoding: int, levels: int | None) -> int:
289
+ """Resolve the level count for ``DitheringType 2`` -- bi-level, loudly.
290
+
291
+ The vendor's ``bayer`` is ``imgproc.GmOrderedDither`` ->
292
+ GraphicsMagick ``OrderedDitherImage()``, which **takes no level
293
+ parameter and is a fixed ordered dither to bi-level** (spec §3.2). With
294
+ ``Encoding: 4`` the vendor therefore still emits a 2-level image, which
295
+ then gets nibble-packed as ``0x0``/``0xF``.
296
+
297
+ We reproduce that -- silently inventing a 16-level "bayer" would not match
298
+ any real server -- but warn, because at 4 bpp it throws away 14 of the 16
299
+ levels the panel can show. **Blue-noise (mode 4) is the only good ordered
300
+ dither at 4 bpp**; prefer it. Pass ``levels=16`` explicitly to opt into a
301
+ multi-level ordered dither with the Bayer matrix.
302
+ """
303
+ if levels is not None:
304
+ return levels
305
+ if int(encoding) == Encoding.FOUR_BIT:
306
+ warnings.warn(
307
+ "DitheringType 2 (bayer) is bi-level only: GraphicsMagick's "
308
+ "OrderedDitherImage() takes no level parameter, so a 4 bpp bayer "
309
+ "rectangle degenerates to 2 of the 16 available grey levels "
310
+ "(packed as 0x0/0xF). Use DitheringType 4 (blue-noise) for a "
311
+ "16-level ordered dither, or pass levels=16 to force one.",
312
+ stacklevel=3,
313
+ )
314
+ return 2
315
+
316
+
317
+ def quantise(grey: np.ndarray, encoding: int, dithering: int,
318
+ origin: tuple[int, int] = (0, 0),
319
+ bayer: Optional[np.ndarray] = None,
320
+ blue_noise: Optional[np.ndarray] = None,
321
+ levels: int | None = None) -> np.ndarray:
322
+ """Quantise an 8-bit grey buffer for ``encoding`` using ``dithering``.
323
+
324
+ :param dithering: a :class:`~pyvisionect.imaging.constants.Dithering`
325
+ value. ``0`` (``DEFAULT``) is rejected, matching the vendor's
326
+ ``updateDefaultRectUnlocked`` (``image-state.go:754``).
327
+ :param origin: canvas coordinate of ``grey[0, 0]``; only used by the
328
+ ordered modes.
329
+ :param bayer: threshold matrix overriding :data:`BAYER_8`.
330
+ :param blue_noise: threshold matrix overriding
331
+ :func:`blue_noise_matrix` -- drop in the exact matrix your renderer
332
+ uses to get identical output.
333
+ """
334
+ d = int(dithering)
335
+ if d == Dithering.DEFAULT:
336
+ raise ValueError(
337
+ "DitheringType 0 ('default') is invalid at the encoder; the vendor "
338
+ "rejects it with render.ErrDithering (image-state.go:754). "
339
+ "Pass 1 (none), 2 (bayer), 3 (floyd-steinberg) or 4 (blue-noise)."
340
+ )
341
+ if d == Dithering.NONE:
342
+ return quantise_none(grey, encoding)
343
+ if d == Dithering.BAYER:
344
+ return quantise_ordered(grey, encoding,
345
+ BAYER_8 if bayer is None else bayer,
346
+ origin, _bayer_levels(encoding, levels))
347
+ if d == Dithering.FLOYD_STEINBERG:
348
+ return quantise_floyd_steinberg(grey, encoding, levels)
349
+ if d == Dithering.BLUE_NOISE:
350
+ return quantise_ordered(grey, encoding,
351
+ blue_noise_matrix() if blue_noise is None else blue_noise,
352
+ origin, levels)
353
+ raise ValueError(
354
+ f"unknown DitheringType {dithering!r}; known values are "
355
+ "0 default (invalid), 1 none, 2 bayer, 3 floyd-steinberg, "
356
+ "4 blue-noise (library extension)"
357
+ )