idotmatrix-api-client 0.2.3__tar.gz → 0.3.0__tar.gz

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 (67) hide show
  1. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/PKG-INFO +6 -1
  2. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/README.md +5 -0
  3. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/gif.py +182 -23
  4. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/image.py +34 -11
  5. idotmatrix_api_client-0.3.0/idotmatrix/modules/materials.py +213 -0
  6. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/util/image_utils.py +37 -2
  7. idotmatrix_api_client-0.3.0/idotmatrix/util/overlay.py +95 -0
  8. idotmatrix_api_client-0.3.0/idotmatrix/util/quality.py +50 -0
  9. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/pyproject.toml +1 -1
  10. idotmatrix_api_client-0.2.3/idotmatrix/modules/materials.py +0 -120
  11. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/LICENSE +0 -0
  12. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/__init__.py +0 -0
  13. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/apps/__init__.py +0 -0
  14. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/apps/digital_picture_frame.py +0 -0
  15. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/client.py +0 -0
  16. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/connection_manager.py +0 -0
  17. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/const.py +0 -0
  18. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-ErbosDraco1StOpenNbpRegular-l5wX.ttf +0 -0
  19. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-MinecraftStandard.otf +0 -0
  20. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-MinecraftStandardBoldOblique.otf +0 -0
  21. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-PixelOperator8-Bold.ttf +0 -0
  22. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-PixelOperator8.ttf +0 -0
  23. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-PixelifySans-Regular.ttf +0 -0
  24. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-PressStart2P-Regular.ttf +0 -0
  25. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-dogica.ttf +0 -0
  26. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-dogicabold.ttf +0 -0
  27. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-dogicapixel.ttf +0 -0
  28. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16-dogicapixelbold.ttf +0 -0
  29. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16_32-HomeVideo-BLG6G.ttf +0 -0
  30. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16_32-HomeVideoBold-R90Dv.ttf +0 -0
  31. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/16_32-MayfairNbpBold-gAA4.ttf +0 -0
  32. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/32-Jersey10-Regular.ttf +0 -0
  33. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/CC-BY-SA-4.0-License.txt +0 -0
  34. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/ErbosDraco-License.txt +0 -0
  35. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/HomeVideo-License.txt +0 -0
  36. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/Jersey10-Regular-License.txt +0 -0
  37. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/MayfairNbpBold-License.txt +0 -0
  38. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/MinecraftStandard-License.txt +0 -0
  39. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/PixelOperator-License.txt +0 -0
  40. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/PixelifySans-License.txt +0 -0
  41. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/PressStart2P-Regular-License.txt +0 -0
  42. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/Rain-DRM3-License.txt +0 -0
  43. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/Rain-DRM3.otf +0 -0
  44. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/fonts/dogica_license.txt +0 -0
  45. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/__init__.py +0 -0
  46. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/chronograph.py +0 -0
  47. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/clock.py +0 -0
  48. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/common.py +0 -0
  49. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/countdown.py +0 -0
  50. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/eco.py +0 -0
  51. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/effect.py +0 -0
  52. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/fullscreen_color.py +0 -0
  53. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/graffiti.py +0 -0
  54. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/music_sync.py +0 -0
  55. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/scoreboard.py +0 -0
  56. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/system.py +0 -0
  57. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/modules/text.py +0 -0
  58. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/protocol.py +0 -0
  59. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/screensize.py +0 -0
  60. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/transport.py +0 -0
  61. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/util/__init__.py +0 -0
  62. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/util/color_utils.py +0 -0
  63. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/util/command_ack.py +0 -0
  64. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/util/device_info.py +0 -0
  65. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/util/device_material.py +0 -0
  66. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/util/file_watch.py +0 -0
  67. {idotmatrix_api_client-0.2.3 → idotmatrix_api_client-0.3.0}/idotmatrix/util/upload_ack.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: idotmatrix-api-client
3
- Version: 0.2.3
3
+ Version: 0.3.0
4
4
  Summary: A library for controlling iDotMatrix displays.
5
5
  License-Expression: GPL-3.0-or-later
6
6
  License-File: LICENSE
@@ -152,8 +152,13 @@ await client.image.show_image_file("photo.jpg", resize_mode=ResizeMode.FILL)
152
152
  # show an animated GIF
153
153
  await client.gif.upload_gif_file("animation.gif")
154
154
 
155
+ # label a picture or every frame of a GIF (the text is drawn at the size of the screen, before the colors are reduced)
156
+ from idotmatrix.util.overlay import TextOverlay
157
+ await client.gif.upload_gif_file("animation.gif", overlay=TextOverlay("64c", position="top-right"))
158
+
155
159
  # store files in the slots of the device, which then cycles through them on its own (no uploads during the show)
156
160
  await client.materials.store(["a.gif", "b.png", "c.gif"], slots=[1, 2, 3], display_time=30)
161
+ # the module remembers what is in which slot: storing again only transfers what is new, in any order
157
162
  ```
158
163
 
159
164
  Both can be mixed freely, no mode switching is needed in between. They work like the official app, which waits
@@ -134,8 +134,13 @@ await client.image.show_image_file("photo.jpg", resize_mode=ResizeMode.FILL)
134
134
  # show an animated GIF
135
135
  await client.gif.upload_gif_file("animation.gif")
136
136
 
137
+ # label a picture or every frame of a GIF (the text is drawn at the size of the screen, before the colors are reduced)
138
+ from idotmatrix.util.overlay import TextOverlay
139
+ await client.gif.upload_gif_file("animation.gif", overlay=TextOverlay("64c", position="top-right"))
140
+
137
141
  # store files in the slots of the device, which then cycles through them on its own (no uploads during the show)
138
142
  await client.materials.store(["a.gif", "b.png", "c.gif"], slots=[1, 2, 3], display_time=30)
143
+ # the module remembers what is in which slot: storing again only transfers what is new, in any order
139
144
  ```
140
145
 
141
146
  Both can be mixed freely, no mode switching is needed in between. They work like the official app, which waits
@@ -16,13 +16,18 @@ from idotmatrix.util import image_utils, color_utils
16
16
  from idotmatrix.util.device_material import (
17
17
  DEFAULT_DISPLAY_TIME_SECONDS, INDEX_SHOW_NOW, convert_display_time, validate_display_time, validate_slot,
18
18
  )
19
- from idotmatrix.util.image_utils import ResizeMode
19
+ from idotmatrix.util.image_utils import ResizeMode, validate_colors
20
+ from idotmatrix.util.overlay import TextOverlay
21
+ from idotmatrix.util.quality import DEFAULT_MAX_COLOR_ERROR, color_error, color_score
20
22
 
21
23
  ANIMATION_MAX_FRAME_COUNT = 64 # Maximum number of frames in a GIF animation
22
24
  DEFAULT_DURATION_PER_FRAME_MS = 200 # Default duration per frame in milliseconds if not specified in the GIF file
23
25
  ANIMATION_TOTAL_DURATION_LIMIT_MS = 2000
24
26
  DEFAULT_ANIMATION_TOTAL_DURATION_MS = ANIMATION_TOTAL_DURATION_LIMIT_MS
25
27
 
28
+ AUTO_COLORS = "auto"
29
+ AUTO_COLOR_STEPS = (256, 128, 64, 32, 16)
30
+
26
31
  # --- Constants based on the Java code ---
27
32
  CHUNK_SIZE_4096 = 4096
28
33
  HEADER_SIZE_GIF = 16 # As per sendImageData logic in GifAgreement.java
@@ -51,6 +56,11 @@ class GifModule(IDotMatrixModule):
51
56
  duration_per_frame_in_ms: int = None,
52
57
  slot: int | None = None,
53
58
  display_time: int = DEFAULT_DISPLAY_TIME_SECONDS,
59
+ colors: int | str = 256,
60
+ max_size_kb: int | None = None,
61
+ overlay: TextOverlay | None = None,
62
+ shared_palette: bool = False,
63
+ max_color_error: float = DEFAULT_MAX_COLOR_ERROR,
54
64
  ):
55
65
  """
56
66
  Uploads a GIF file to the device. It is shown right away, unless a slot is given.
@@ -65,7 +75,29 @@ class GifModule(IDotMatrixModule):
65
75
  slot (int, optional): If given (0 to 11), the GIF is stored in that slot of the device instead of being shown
66
76
  right away. The device cycles through the stored items by itself, see `MaterialsModule`.
67
77
  display_time (int): Seconds the stored item stays on screen in that cycle. Only used with a slot.
78
+ colors (int | str): The number of colors of the palette (2 to 256), or "auto". Fewer colors make the
79
+ upload smaller and
80
+ faster (16 colors are about a third of the size of 256 for a photo-like animation), at the price of
81
+ rougher colors. Less than 256 reduces the colors even if `palletize` is off.
82
+ max_size_kb (int, optional): The most the converted GIF may have, which is what is transferred (a large
83
+ one takes 10 s or more). If it is bigger, quality is given up until it fits, in this order: colors
84
+ (down to 32), frames (every 2nd, 3rd, ... frame, the animation takes as long as before), then colors
85
+ down to 8 and frames again. If it still does not fit the smallest version is used and a warning is
86
+ logged.
87
+ overlay (TextOverlay, optional): A text that is drawn on top of every frame, f.e. to label it.
88
+ shared_palette (bool): One palette for all frames instead of one for each, which can flicker when the
89
+ colors differ from frame to frame (it also changes the colors a little more). Not for "auto".
90
+ max_color_error (float): With colors="auto": the GIF with the fewest bytes whose color error is at most
91
+ this is used. The error is the mean color difference to the GIF with 256 colors (delta E) plus 8 times the
92
+ flicker. On a 64x64 up to 5 looks good, up to 9 is still acceptable but duller, more looks broken
93
+ (about 3 is nearly lossless). The palette sizes 256 to 16 are tried, with a palette for each frame
94
+ and with a shared one.
68
95
  """
96
+ if colors != AUTO_COLORS:
97
+ validate_colors(colors)
98
+ if max_size_kb is not None and (isinstance(max_size_kb, bool) or not isinstance(max_size_kb, int)
99
+ or max_size_kb < 1):
100
+ raise ValueError(f"max_size_kb must be a positive number, got: {max_size_kb!r}")
69
101
  if slot is not None:
70
102
  validate_slot(slot)
71
103
  validate_display_time(display_time)
@@ -81,6 +113,11 @@ class GifModule(IDotMatrixModule):
81
113
  palletize=palletize,
82
114
  background_color=background_color,
83
115
  duration_per_frame_in_ms=duration_per_frame_in_ms,
116
+ colors=colors,
117
+ max_size_kb=max_size_kb,
118
+ overlay=overlay,
119
+ shared_palette=shared_palette,
120
+ max_color_error=max_color_error,
84
121
  )
85
122
 
86
123
  # If the device already has the exact same GIF stored, it answers the first chunk with "finished"
@@ -116,6 +153,11 @@ class GifModule(IDotMatrixModule):
116
153
  palletize: bool = True,
117
154
  background_color: Tuple[int, int, int] = (0, 0, 0),
118
155
  duration_per_frame_in_ms: int = None,
156
+ colors: int | str = 256,
157
+ max_size_kb: int | None = None,
158
+ overlay: TextOverlay | None = None,
159
+ shared_palette: bool = False,
160
+ max_color_error: float = DEFAULT_MAX_COLOR_ERROR,
119
161
  ) -> bytes:
120
162
  """
121
163
  Loads a GIF file and adapts it to the pixel size of the device's canvas.
@@ -131,6 +173,11 @@ class GifModule(IDotMatrixModule):
131
173
  palletize (bool): Whether to convert the image to a color palette. Defaults to True.
132
174
  background_color (Tuple[int, int, int]): Background color to fill transparent pixels.
133
175
  duration_per_frame_in_ms (int, optional): Duration of each frame in milliseconds. If not provided, defaults to the duration specified in the GIF file, or 200ms if not set.
176
+ colors (int): The number of colors of the palette (2 to 256).
177
+ max_size_kb (int, optional): The size the GIF may have at most, see `upload_gif_file`.
178
+ overlay (TextOverlay, optional): A text that is drawn on top of every frame.
179
+ shared_palette (bool): One palette for all frames.
180
+ max_color_error (float): The limit for colors="auto", see `upload_gif_file`.
134
181
  Returns:
135
182
  bytes: A byte representation of the GIF file, adapted to fit the pixel size.
136
183
  """
@@ -156,8 +203,8 @@ class GifModule(IDotMatrixModule):
156
203
  background_color=background_color,
157
204
  mode="RGBA",
158
205
  )
159
- if palletize:
160
- frame = image_utils.palettize(frame)
206
+ if overlay is not None:
207
+ frame = overlay.apply(frame)
161
208
 
162
209
  frames.append(frame.copy())
163
210
  img.seek(img.tell() + 1)
@@ -168,26 +215,138 @@ class GifModule(IDotMatrixModule):
168
215
  img, frames, duration_per_frame_in_ms
169
216
  )
170
217
 
171
- # TODO: there are still some cases where
172
- # - the GIF is not animating all frames
173
-
174
- # all frames need color tables of the same size, or the device garbles / drops frames
175
- frames = [image_utils.pad_palette(frame) for frame in frames]
176
-
177
- gif_buffer = io.BytesIO()
178
- # take the first frame, append the rest as additional frames and save as GIF into gif_buffer
179
- frames[0].save(
180
- gif_buffer,
181
- format="GIF",
182
- save_all=True,
183
- optimize=False, # True would shrink the color tables to the number of used colors again
184
- append_images=frames[1:],
185
- loop=0, # loop forever
186
- duration=duration_per_frame_in_ms,
187
- disposal=2, # Restore to background color after each frame
188
- )
189
- gif_buffer.seek(0)
190
- return gif_buffer.getvalue()
218
+ # TODO: there are still some cases where
219
+ # - the GIF is not animating all frames
220
+
221
+ shared = shared_palette
222
+ if colors == AUTO_COLORS:
223
+ data, colors, shared = self._encode_gif_auto(frames, duration_per_frame_in_ms, max_color_error)
224
+ if max_size_kb is None or len(data) <= max_size_kb * 1024:
225
+ return data
226
+ palletize = True
227
+ if max_size_kb is None:
228
+ return self._encode_gif(frames, duration_per_frame_in_ms, colors, palletize, shared)
229
+ return self._encode_gif_within(frames, duration_per_frame_in_ms, colors, palletize, max_size_kb, shared)
230
+
231
+ @staticmethod
232
+ def _reduce_colors(
233
+ frames: List[PILImage.Image], colors: int, palletize: bool, shared: bool = False
234
+ ) -> List[PILImage.Image]:
235
+ """Gives the frames a palette of `colors` colors, one for each frame or a shared one."""
236
+ if shared:
237
+ return image_utils.palettize_together(frames, colors=colors)
238
+ if palletize or colors < 256:
239
+ return [image_utils.palettize(frame, colors=colors) for frame in frames]
240
+ return frames
241
+
242
+ @staticmethod
243
+ def _save_gif(frames: List[PILImage.Image], duration_per_frame_in_ms: int, colors: int) -> bytes:
244
+ """Writes the frames as a GIF whose frames all have a color table of the same size."""
245
+ # all frames need color tables of the same size, or the device garbles / drops frames
246
+ table_size = image_utils.palette_table_size(colors)
247
+ frames = [image_utils.pad_palette(frame, table_size) for frame in frames]
248
+
249
+ gif_buffer = io.BytesIO()
250
+ # take the first frame, append the rest as additional frames and save as GIF into gif_buffer
251
+ frames[0].save(
252
+ gif_buffer,
253
+ format="GIF",
254
+ save_all=True,
255
+ optimize=False, # True would shrink the color tables to the number of used colors again
256
+ append_images=frames[1:],
257
+ loop=0, # loop forever
258
+ duration=duration_per_frame_in_ms,
259
+ disposal=2, # Restore to background color after each frame
260
+ )
261
+ gif_buffer.seek(0)
262
+ return gif_buffer.getvalue()
263
+
264
+ def _encode_gif(
265
+ self, frames: List[PILImage.Image], duration_per_frame_in_ms: int, colors: int, palletize: bool,
266
+ shared: bool = False
267
+ ) -> bytes:
268
+ """Encodes the frames as a GIF whose frames all have a color table of the same size."""
269
+ return self._save_gif(self._reduce_colors(frames, colors, palletize, shared), duration_per_frame_in_ms, colors)
270
+
271
+ def _encode_gif_auto(
272
+ self, frames: List[PILImage.Image], duration_per_frame_in_ms: int, max_color_error: float
273
+ ) -> Tuple[bytes, int, bool]:
274
+ """
275
+ Finds the GIF with the fewest bytes whose color error (compared to the same GIF with 256 colors for each
276
+ frame) is at most `max_color_error`, among palettes of 256 to 16 colors, for each frame or shared. If none is
277
+ good enough the one with the lowest error is used.
278
+ Returns the GIF, its number of colors and whether the palette is shared.
279
+ """
280
+ # compared to the GIF with all colors, which is what the limit was calibrated on
281
+ reference = [frame.convert("RGB") for frame in self._reduce_colors(frames, 256, True)]
282
+ best = None # (size, data, colors, shared) of the smallest that is good enough
283
+ closest = None # (score, data, colors, shared)
284
+ for colors in AUTO_COLOR_STEPS:
285
+ for shared in (False, True):
286
+ reduced = self._reduce_colors(frames, colors, True, shared)
287
+ data = self._save_gif(reduced, duration_per_frame_in_ms, colors)
288
+ score = color_score(*color_error(reference, [frame.convert("RGB") for frame in reduced]))
289
+ if score <= max_color_error and (best is None or len(data) < best[0]):
290
+ best = (len(data), data, colors, shared)
291
+ if closest is None or score < closest[0]:
292
+ closest = (score, data, colors, shared)
293
+ if best is not None:
294
+ _, data, colors, shared = best
295
+ else:
296
+ score, data, colors, shared = closest
297
+ self.logging.warning(
298
+ f"no palette is within the color error {max_color_error}, using the best ({score:.1f})")
299
+ self.logging.info(f"{colors} colors{', shared palette' if shared else ''} ({len(data) / 1024:.0f} KB)")
300
+ return data, colors, shared
301
+
302
+ def _encode_gif_within(
303
+ self,
304
+ frames: List[PILImage.Image],
305
+ duration_per_frame_in_ms: int,
306
+ colors: int,
307
+ palletize: bool,
308
+ max_size_kb: int,
309
+ shared: bool = False,
310
+ ) -> bytes:
311
+ """
312
+ Encodes the frames as a GIF of at most `max_size_kb` KB if that is possible, by taking the first of
313
+ `_size_reductions` that fits, and the smallest one otherwise.
314
+ """
315
+ limit = max_size_kb * 1024
316
+ smallest = None
317
+ for step_colors, every in self._size_reductions(colors, len(frames)):
318
+ kept = frames[::every]
319
+ if every > 1 and frames[-1] is not kept[-1] and len(kept) > 1:
320
+ kept[-1] = frames[-1] # the animation still ends where it did
321
+ data = self._encode_gif(kept, duration_per_frame_in_ms * every, step_colors, palletize, shared)
322
+ if len(data) <= limit:
323
+ if (step_colors, every) != (colors, 1):
324
+ self.logging.info(
325
+ f"GIF reduced to {step_colors} colors and every {every}. frame to fit {max_size_kb} KB "
326
+ f"({len(data) / 1024:.0f} KB)")
327
+ return data
328
+ if smallest is None or len(data) < len(smallest):
329
+ smallest = data
330
+ self.logging.warning(f"GIF does not fit {max_size_kb} KB, using the smallest version ({len(smallest) / 1024:.0f} KB)")
331
+ return smallest
332
+
333
+ @staticmethod
334
+ def _size_reductions(colors: int, frame_count: int) -> List[Tuple[int, int]]:
335
+ """
336
+ What to give up to make a GIF smaller, from the least to the most visible: first colors down to 32, then every
337
+ second, third, ... frame (the duration of the animation stays the same), then fewer colors with all frames
338
+ again. Returns (colors, keep every n-th frame), starting with what was asked for.
339
+ """
340
+ steps = [(c, 1) for c in (256, 128, 64, 32) if c <= colors]
341
+ if not steps or steps[0][0] != colors:
342
+ steps.insert(0, (colors, 1))
343
+ floor = min(colors, 32)
344
+ every_steps = [n for n in (2, 3, 4, 6, 8) if frame_count // n >= 2]
345
+ steps += [(floor, n) for n in every_steps]
346
+ for fewer in (16, 8):
347
+ if fewer < floor:
348
+ steps += [(fewer, 1)] + [(fewer, n) for n in every_steps]
349
+ return steps
191
350
 
192
351
  def _int_to_bytes_le(self, value: int, length: int = 4) -> bytearray:
193
352
  """Converts an integer to a little-endian bytearray of specified length."""
@@ -16,6 +16,8 @@ from idotmatrix.util import image_utils, color_utils
16
16
  from idotmatrix.util.device_material import (
17
17
  DEFAULT_DISPLAY_TIME_SECONDS, INDEX_SHOW_NOW, convert_display_time, validate_display_time, validate_slot,
18
18
  )
19
+ from idotmatrix.util.image_utils import validate_colors
20
+ from idotmatrix.util.overlay import TextOverlay
19
21
 
20
22
  MTU_SIZE_IF_ENABLED = 509
21
23
  MTU_SIZE_IF_DISABLED = 18
@@ -96,6 +98,8 @@ class ImageModule(IDotMatrixModule):
96
98
  resize_mode: image_utils.ResizeMode,
97
99
  palletize: bool,
98
100
  background_color: Tuple[int, int, int],
101
+ colors: int = 256,
102
+ overlay: TextOverlay | None = None,
99
103
  ) -> bytearray:
100
104
  """
101
105
  Loads an image from a file, resizes it to fit within a square canvas of pixel_size x pixel_size,
@@ -105,6 +109,8 @@ class ImageModule(IDotMatrixModule):
105
109
  canvas_size (int): Size of the square canvas in pixels.
106
110
  palletize (bool): If True, the image will be converted to a palette-based image.
107
111
  background_color (Tuple[int, int, int]): RGB color for the background, which is only visible if the input
112
+ colors (int): The number of colors of the palette that `palletize` reduces the image to.
113
+ overlay (TextOverlay, optional): A text that is drawn on top of the image.
108
114
  Returns:
109
115
  bytearray: A bytearray containing the raw pixel data of the processed image in RGB format.
110
116
  """
@@ -123,11 +129,15 @@ class ImageModule(IDotMatrixModule):
123
129
  canvas_size=canvas_size,
124
130
  resize_mode=resize_mode,
125
131
  resample_mode=resample_mode,
132
+ background_color=background_color,
126
133
  mode="RGB", # ensure the image is in RGB mode
127
134
  )
128
135
 
136
+ if overlay is not None:
137
+ img = overlay.apply(img).convert("RGB")
138
+
129
139
  if palletize:
130
- img = image_utils.palettize(img)
140
+ img = image_utils.palettize(img, colors=colors)
131
141
 
132
142
  # Convert to RGB if not already in that mode, to get the pixel data in RGB format
133
143
  mode = "RGB"
@@ -143,9 +153,11 @@ class ImageModule(IDotMatrixModule):
143
153
  resize_mode: image_utils.ResizeMode = image_utils.ResizeMode.FIT,
144
154
  palletize: bool = False,
145
155
  background_color: Tuple[int, int, int] | int | str = (0, 0, 0),
146
- png: bool = False,
156
+ png: bool = True,
147
157
  slot: int | None = None,
148
158
  display_time: int = DEFAULT_DISPLAY_TIME_SECONDS,
159
+ colors: int = 256,
160
+ overlay: TextOverlay | None = None,
149
161
  ) -> None:
150
162
  """
151
163
  Shows an image file on the device, the way the official app does it for photos. It is shown right away, unless
@@ -162,12 +174,19 @@ class ImageModule(IDotMatrixModule):
162
174
  background_color (Tuple[int, int, int]): RGB color for the background, which is only visible if the input
163
175
  image doesn't match the devices aspect ratio. Defaults to black (0, 0, 0).
164
176
  png (bool): If True, the image is sent as a PNG file instead of raw RGB data. That is smaller (about 25-45%
165
- for photos, more for pixel-art, and a palette PNG with `palletize`), which saves a little upload time.
166
- Experimental: tested on a 64x64 device only, the official app sends raw RGB. Defaults to False.
177
+ for photos, more for pixel-art, and a palette PNG with `palletize`), which saves a little upload time,
178
+ and it avoids a stray dark red pixel in the top row that the device draws after a raw upload. Tested
179
+ on a 64x64 device only, the official app sends raw RGB. Defaults to True.
167
180
  slot (int, optional): If given (0 to 11), the image is stored in that slot of the device instead of being
168
181
  shown right away. The device cycles through the stored items by itself, see `MaterialsModule`.
169
182
  display_time (int): Seconds the stored item stays on screen in that cycle. Only used with a slot.
183
+ colors (int): The number of colors of the palette (2 to 256) that `palletize` reduces the image to. The
184
+ raw upload has the same size either way, with `png` fewer colors make it smaller. Less than 256 reduces
185
+ the colors even if `palletize` is off.
186
+ overlay (TextOverlay, optional): A text that is drawn on top of the image, f.e. to label it.
170
187
  """
188
+ validate_colors(colors)
189
+ palletize = palletize or colors < 256
171
190
  if slot is not None:
172
191
  validate_slot(slot)
173
192
  validate_display_time(display_time)
@@ -180,23 +199,26 @@ class ImageModule(IDotMatrixModule):
180
199
  resize_mode=resize_mode,
181
200
  palletize=palletize,
182
201
  background_color=background_color,
202
+ colors=colors,
203
+ overlay=overlay,
183
204
  )
184
- await self._send_static_image_data(pixel_data, png=png, palette=palletize, slot=slot, display_time=display_time)
205
+ await self._send_static_image_data(
206
+ pixel_data, png=png, palette=palletize, slot=slot, display_time=display_time, colors=colors)
185
207
 
186
208
  async def show_image_pixeldata(
187
209
  self,
188
210
  pixel_colors: List[Tuple[int, int, int] | int | str],
189
- png: bool = False,
211
+ png: bool = True,
190
212
  ) -> None:
191
213
  """
192
214
  Shows pixel data on the device, the way the official app does it for photos. See `show_image_file`.
193
215
  Args:
194
216
  pixel_colors: One color for each pixel of the screen, row by row.
195
- png (bool): If True, the pixels are sent as a PNG file. See `show_image_file`.
217
+ png (bool): If True (the default), the pixels are sent as a PNG file. See `show_image_file`.
196
218
  """
197
219
  await self._send_static_image_data(self._pixel_colors_to_bytes(pixel_colors), png=png)
198
220
 
199
- def _encode_png(self, pixel_data: bytearray, palette: bool = False) -> bytearray:
221
+ def _encode_png(self, pixel_data: bytearray, palette: bool = False, colors: int = 256) -> bytearray:
200
222
  """
201
223
  Encodes raw RGB pixel data of the whole screen as a PNG file.
202
224
 
@@ -208,7 +230,7 @@ class ImageModule(IDotMatrixModule):
208
230
  size = self.screen_size.value[0]
209
231
  img = PILImage.frombytes("RGB", (size, size), bytes(pixel_data))
210
232
  if palette:
211
- img = img.quantize(256, dither=PILImage.Dither.NONE)
233
+ img = img.quantize(colors, dither=PILImage.Dither.NONE)
212
234
  buffer = io.BytesIO()
213
235
  img.save(buffer, "PNG", optimize=True)
214
236
  return bytearray(buffer.getvalue())
@@ -216,13 +238,14 @@ class ImageModule(IDotMatrixModule):
216
238
  async def _send_static_image_data(
217
239
  self,
218
240
  pixel_data: bytearray,
219
- png: bool = False,
241
+ png: bool = True,
220
242
  palette: bool = False,
221
243
  slot: int | None = None,
222
244
  display_time: int = DEFAULT_DISPLAY_TIME_SECONDS,
245
+ colors: int = 256,
223
246
  ) -> None:
224
247
  if png:
225
- pixel_data = self._encode_png(pixel_data, palette=palette)
248
+ pixel_data = self._encode_png(pixel_data, palette=palette, colors=colors)
226
249
  packets = self._create_static_image_data_packets(
227
250
  pixel_data,
228
251
  index=INDEX_SHOW_NOW if slot is None else slot,
@@ -0,0 +1,213 @@
1
+ import asyncio
2
+ import hashlib
3
+ import logging
4
+ from os import PathLike
5
+ from typing import Callable, Iterable, Sequence, Tuple
6
+
7
+ from PIL import Image as PILImage
8
+
9
+ from idotmatrix import protocol
10
+ from idotmatrix.connection_manager import ConnectionManager
11
+ from idotmatrix.modules import IDotMatrixModule
12
+ from idotmatrix.modules.gif import AUTO_COLORS, GifModule
13
+ from idotmatrix.modules.image import ImageModule
14
+ from idotmatrix.protocol import build_command
15
+ from idotmatrix.util import image_utils
16
+ from idotmatrix.util.image_utils import validate_colors
17
+ from idotmatrix.util.overlay import TextOverlay
18
+ from idotmatrix.util.quality import DEFAULT_MAX_COLOR_ERROR
19
+ from idotmatrix.util.device_material import (
20
+ DEFAULT_DISPLAY_TIME_SECONDS, SLOTS, validate_display_time, validate_slot,
21
+ )
22
+
23
+
24
+ class MaterialsModule(IDotMatrixModule):
25
+ """
26
+ The slots of the device ("device materials" in the official app). The device keeps the items in its slots and
27
+ cycles through them by itself, in the order of the slots, so after the upload no Bluetooth traffic is needed and the
28
+ animation is not interrupted by an upload, which takes seconds for a GIF. Based on `DeviceMaterialChildFragment` of
29
+ the official app, which deletes the slots and then sends its items one after another.
30
+
31
+ The module remembers what it stored in which slot (as long as it lives), so storing again only transfers what is new.
32
+ """
33
+ logging = logging.getLogger(__name__)
34
+
35
+ def __init__(self, connection_manager: ConnectionManager, gif: GifModule, image: ImageModule) -> None:
36
+ super().__init__(connection_manager=connection_manager)
37
+ self._gif = gif
38
+ self._image = image
39
+ # slot -> what is in it: None for empty, a fingerprint of the stored item, or missing if it is not known
40
+ self._contents: dict[int, tuple | None] = {}
41
+
42
+ async def clear(self, slots: Iterable[int] | None = None) -> None:
43
+ """
44
+ Deletes the items in the given slots.
45
+
46
+ Args:
47
+ slots: The slots to empty (0 to 11). All of them if not given.
48
+ """
49
+ slots = self._validate_slots(slots)
50
+ for slot in slots:
51
+ self._contents.pop(slot, None)
52
+ # `11 00 02 01 <number of slots> <slot>...`, acknowledged with `05 00 02 01 01` (verified on a 64x64)
53
+ await self._send_bytes(data=build_command(protocol.DELETE_MATERIALS, len(slots), *slots), response=True)
54
+ for slot in slots:
55
+ self._contents[slot] = None
56
+
57
+ async def store(
58
+ self,
59
+ files: Sequence[PathLike | str],
60
+ slots: Iterable[int] | None = None,
61
+ display_time: int = DEFAULT_DISPLAY_TIME_SECONDS,
62
+ resize_mode: image_utils.ResizeMode = image_utils.ResizeMode.FIT,
63
+ palletize: bool | None = None,
64
+ background_color: Tuple[int, int, int] | int | str = (0, 0, 0),
65
+ clear_unused: bool = True,
66
+ keep_order: bool = False,
67
+ verify: bool = False,
68
+ colors: int | str = 256,
69
+ max_size_kb: int | None = None,
70
+ overlay: TextOverlay | Callable[[str], TextOverlay | None] | None = None,
71
+ shared_palette: bool = False,
72
+ max_color_error: float = DEFAULT_MAX_COLOR_ERROR,
73
+ ) -> list[int]:
74
+ """
75
+ Stores image and GIF files in the slots of the device, one file per slot, and ends up with the device cycling
76
+ through them. Other slots are not touched, so a list of slots protects the others.
77
+
78
+ Only what is new is transferred: a file that this module stored in one of the allowed slots earlier (same
79
+ content, options and display time) stays where it is and costs nothing. The rest goes into the other allowed
80
+ slots, which are overwritten, no delete is needed. A transfer of an item the device holds anyway takes about
81
+ 0.8 s instead of seconds, also in another slot, so reordering is cheap, too. (verified on a 64x64)
82
+
83
+ Args:
84
+ files: The files. Animated GIFs are stored as GIFs, the rest as images.
85
+ slots: The slots the device may use (0 to 11), all of them if not given.
86
+ display_time: Seconds each item stays on screen.
87
+ resize_mode: How the files are scaled to the screen.
88
+ palletize: Reduce the colors to a palette. The default is on for GIFs and off for images.
89
+ background_color: Color of the bars if a file does not have the shape of the screen.
90
+ colors: The number of colors of the palette (2 to 256), fewer make GIFs smaller and faster to upload, or
91
+ "auto" to let each GIF get as few as still look fine (see `GifModule.upload_gif_file`, `max_color_error`
92
+ and `shared_palette`). Images use all 256 colors with "auto".
93
+ max_size_kb: The most a converted GIF may have, quality is given up until it fits, see
94
+ `GifModule.upload_gif_file`. Keeps the upload of each GIF short.
95
+ overlay: A text that is drawn on top of every file, or a function that gets the path of a file and returns
96
+ the text for it (or None), f.e. to label each file with its name.
97
+ clear_unused: Delete the allowed slots that get no file, so that nothing stale keeps cycling.
98
+ keep_order: Put the files into the slots in the order of the slot numbers, which is the order of the cycle,
99
+ instead of keeping what is stored where it is. That can transfer many files again, because writing a
100
+ slot destroys the item that is in it.
101
+ verify: Do not trust what this module remembers about the slots, send all files again (which takes about
102
+ 0.8 s for each item the device holds). Use it if something else (the app) may have changed the slots.
103
+
104
+ Returns:
105
+ The slot of each file, in the order of the files. The device cycles in the order of the slots.
106
+
107
+ Raises:
108
+ ValueError: If there are more files than slots, or a slot or the display time is invalid.
109
+ """
110
+ slots = self._validate_slots(slots)
111
+ validate_display_time(display_time)
112
+ if colors != AUTO_COLORS:
113
+ validate_colors(colors)
114
+ if len(files) > len(slots):
115
+ raise ValueError(f"{len(files)} files do not fit into {len(slots)} slots")
116
+ if not files:
117
+ return []
118
+
119
+ overlays = [overlay(str(file)) if callable(overlay) else overlay for file in files]
120
+ items = [
121
+ await asyncio.to_thread(
122
+ self._fingerprint, file, display_time, resize_mode, palletize, background_color, colors, max_size_kb,
123
+ file_overlay, shared_palette, max_color_error)
124
+ for file, file_overlay in zip(files, overlays)
125
+ ]
126
+ keys = [key for key, _ in items]
127
+ stored = {} if verify else self._contents
128
+ assignment = self._plan(keys, slots, stored, keep_order)
129
+
130
+ unused = [slot for slot in slots if slot not in assignment.values()]
131
+ if clear_unused:
132
+ unused = [slot for slot in unused if self._contents.get(slot, False) is not None]
133
+ if unused:
134
+ await self.clear(unused)
135
+
136
+ for index, file in enumerate(files):
137
+ slot = assignment[index]
138
+ if stored.get(slot) == keys[index]:
139
+ continue
140
+ self._contents.pop(slot, None) # not known anymore, in case the upload fails
141
+ if items[index][1]:
142
+ await self._gif.upload_gif_file(
143
+ file_path=file,
144
+ resize_mode=resize_mode,
145
+ palletize=True if palletize is None else palletize,
146
+ background_color=background_color,
147
+ slot=slot,
148
+ display_time=display_time,
149
+ colors=colors,
150
+ max_size_kb=max_size_kb,
151
+ overlay=overlays[index],
152
+ shared_palette=shared_palette,
153
+ max_color_error=max_color_error,
154
+ )
155
+ else:
156
+ await self._image.show_image_file(
157
+ file_path=file,
158
+ resize_mode=resize_mode,
159
+ palletize=bool(palletize),
160
+ background_color=background_color,
161
+ slot=slot,
162
+ display_time=display_time,
163
+ colors=256 if colors == AUTO_COLORS else colors,
164
+ overlay=overlays[index],
165
+ )
166
+ self._contents[slot] = keys[index]
167
+ return [assignment[index] for index in range(len(files))]
168
+
169
+ @staticmethod
170
+ def _plan(keys: list[tuple], slots: list[int], stored: dict[int, tuple | None], keep_order: bool) -> dict[int, int]:
171
+ """Decides which file goes into which slot: the index of each file -> its slot."""
172
+ if keep_order:
173
+ return dict(enumerate(slots[:len(keys)]))
174
+ free = list(slots)
175
+ assignment: dict[int, int] = {}
176
+ for index, key in enumerate(keys):
177
+ for slot in free:
178
+ if stored.get(slot) == key:
179
+ assignment[index] = slot
180
+ free.remove(slot)
181
+ break
182
+ for index in range(len(keys)):
183
+ if index not in assignment:
184
+ assignment[index] = free.pop(0)
185
+ return assignment
186
+
187
+ @staticmethod
188
+ def _fingerprint(
189
+ file: PathLike | str, display_time: int, resize_mode, palletize, background_color, colors: int,
190
+ max_size_kb: int | None,
191
+ overlay: TextOverlay | None,
192
+ shared_palette: bool,
193
+ max_color_error: float,
194
+ ) -> tuple:
195
+ """What identifies an item: the content of the file and everything that changes what is sent."""
196
+ with open(file, "rb") as handle:
197
+ digest = hashlib.sha1(handle.read()).hexdigest()
198
+ with PILImage.open(file) as img:
199
+ animated = getattr(img, "n_frames", 1) > 1
200
+ options = (display_time, resize_mode, palletize, str(background_color), colors, max_size_kb, overlay,
201
+ shared_palette, max_color_error)
202
+ return (digest, animated, *options), animated
203
+
204
+ @staticmethod
205
+ def _validate_slots(slots: Iterable[int] | None) -> list[int]:
206
+ if slots is None:
207
+ return list(SLOTS)
208
+ slots = sorted(validate_slot(slot) for slot in slots)
209
+ if len(set(slots)) != len(slots):
210
+ raise ValueError(f"slots must not contain duplicates, got: {slots}")
211
+ if not slots:
212
+ raise ValueError("slots must not be empty")
213
+ return slots
@@ -28,6 +28,33 @@ def palettize(
28
28
  )
29
29
 
30
30
 
31
+ def validate_colors(colors: int) -> int:
32
+ """Raises a ValueError for a number of palette colors that cannot be used (2 to 256)."""
33
+ if isinstance(colors, bool) or not isinstance(colors, int) or not 2 <= colors <= 256:
34
+ raise ValueError(f"colors must be between 2 and 256, got: {colors!r}")
35
+ return colors
36
+
37
+
38
+ def palette_table_size(colors: int) -> int:
39
+ """
40
+ The size of the color table of a GIF for that many colors: a power of 2 entries, and PIL writes at least 4.
41
+ """
42
+ return max(4, 1 << (validate_colors(colors) - 1).bit_length())
43
+
44
+
45
+ def palettize_together(images: list[PILImage.Image], colors: int = 256) -> list[PILImage.Image]:
46
+ """
47
+ Converts the images to one common palette, built from all of them. In an animation that keeps a color the
48
+ same from frame to frame, where a palette for each frame makes colors jump (flicker).
49
+ """
50
+ rgb = [image.convert("RGB") for image in images]
51
+ montage = PILImage.new("RGB", (rgb[0].width, rgb[0].height * len(rgb)))
52
+ for index, image in enumerate(rgb):
53
+ montage.paste(image, (0, index * image.height))
54
+ palette = montage.quantize(colors=colors, dither=PILImage.Dither.NONE)
55
+ return [image.quantize(palette=palette, dither=PILImage.Dither.NONE) for image in rgb]
56
+
57
+
31
58
  def pad_palette(image: PILImage.Image, size: int = 256) -> PILImage.Image:
32
59
  """
33
60
  Makes sure an image is palettized and its palette has exactly `size` entries.
@@ -83,7 +110,11 @@ def resize_image(
83
110
  # if the dimensions of the frame are not equal to the pixel size, resize it while maintaining the aspect ratio
84
111
  # and adding a black background if necessary.
85
112
  ratio = min(canvas_size / image.width, canvas_size / image.height)
86
- new_size = (int(image.width * ratio), int(image.height * ratio))
113
+ # at least one pixel, a very wide or tall picture would be 0 pixels high on a small screen
114
+ new_size = (
115
+ min(canvas_size, max(1, round(image.width * ratio))),
116
+ min(canvas_size, max(1, round(image.height * ratio))),
117
+ )
87
118
  image = image.resize(
88
119
  size=new_size,
89
120
  resample=resample_mode,
@@ -92,7 +123,11 @@ def resize_image(
92
123
  # if the dimensions of the frame are not equal to the pixel size, resize it to fill the canvas
93
124
  # this might crop the image, but maintains aspect ratio
94
125
  ratio = max(canvas_size / image.width, canvas_size / image.height)
95
- new_size = (int(image.width * ratio), int(image.height * ratio))
126
+ # never smaller than the canvas, rounding down would leave a stripe of background
127
+ new_size = (
128
+ max(canvas_size, round(image.width * ratio)),
129
+ max(canvas_size, round(image.height * ratio)),
130
+ )
96
131
  image = image.resize(
97
132
  size=new_size,
98
133
  resample=resample_mode,
@@ -0,0 +1,95 @@
1
+ import os
2
+ from dataclasses import dataclass
3
+ from functools import lru_cache
4
+ from typing import Tuple
5
+
6
+ from PIL import Image, ImageDraw, ImageFont
7
+
8
+ from idotmatrix.util import color_utils
9
+
10
+ # a pixel font that is crisp at 8 px (bundled, its license is PixelOperator-License.txt in the same folder)
11
+ DEFAULT_FONT = os.path.normpath(
12
+ os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "fonts", "16-PixelOperator8.ttf"))
13
+
14
+ POSITIONS = (
15
+ "top-left", "top-center", "top-right",
16
+ "center",
17
+ "bottom-left", "bottom-center", "bottom-right",
18
+ )
19
+
20
+
21
+ @lru_cache(maxsize=16)
22
+ def _font(path: str, size: int) -> ImageFont.FreeTypeFont:
23
+ return ImageFont.truetype(path, size)
24
+
25
+
26
+ @dataclass(frozen=True)
27
+ class TextOverlay:
28
+ """
29
+ A text that is drawn on top of a picture or of every frame of an animation, at the size of the screen, before the
30
+ colors are reduced. It does not change over time: for a clock or an album title upload again when it changes.
31
+
32
+ Attributes:
33
+ text: What to write.
34
+ position: Where the text goes: one of `POSITIONS`.
35
+ color: The color of the text, anything `color_utils.parse_color_rgb` accepts.
36
+ background: A box behind the text so that it is readable on any picture, (R, G, B, alpha) with alpha from 0
37
+ (invisible) to 255, or None for no box.
38
+ font_size: The size of the font in pixels. The default font is made for 8, which fits about 10 characters on
39
+ a 64 pixel wide screen, a longer text is cut.
40
+ font: The path of a font file, a pixel font that is bundled is used if not given.
41
+ margin: The distance to the border of the screen in pixels.
42
+ """
43
+ text: str
44
+ position: str = "bottom-left"
45
+ color: Tuple[int, int, int] | int | str = (255, 255, 255)
46
+ background: Tuple[int, int, int, int] | None = (0, 0, 0, 160)
47
+ font_size: int = 8
48
+ font: str | None = None
49
+ margin: int = 1
50
+
51
+ def __post_init__(self):
52
+ if not self.text:
53
+ raise ValueError("text must not be empty")
54
+ if self.position not in POSITIONS:
55
+ raise ValueError(f"position must be one of {', '.join(POSITIONS)}, got: {self.position!r}")
56
+ if not isinstance(self.font_size, int) or isinstance(self.font_size, bool) or self.font_size < 4:
57
+ raise ValueError(f"font_size must be at least 4, got: {self.font_size!r}")
58
+ if self.background is not None and (len(self.background) != 4 or not all(0 <= v <= 255 for v in self.background)):
59
+ raise ValueError(f"background must be (R, G, B, alpha) with values from 0 to 255, got: {self.background!r}")
60
+ if not isinstance(self.margin, int) or isinstance(self.margin, bool) or self.margin < 0:
61
+ raise ValueError(f"margin must not be negative, got: {self.margin!r}")
62
+ color_utils.parse_color_rgb(self.color)
63
+
64
+ def apply(self, frame: Image.Image) -> Image.Image:
65
+ """Returns the frame (any mode, as large as the screen) with the text on top, as RGBA."""
66
+ frame = frame.convert("RGBA")
67
+ font = _font(self.font or DEFAULT_FONT, self.font_size)
68
+ measure = ImageDraw.Draw(frame)
69
+ pad = 1 if self.background else 0
70
+ room = frame.width - 2 * self.margin - 2 * pad
71
+
72
+ # a text that is too wide for the screen is cut, there is nothing to scroll
73
+ text = self.text
74
+ left, top, right, bottom = measure.textbbox((0, 0), text, font=font)
75
+ while right - left > room and len(text) > 1:
76
+ text = text[:-1]
77
+ left, top, right, bottom = measure.textbbox((0, 0), text, font=font)
78
+ box_width, box_height = right - left + 2 * pad, bottom - top + 2 * pad
79
+
80
+ if self.position == "center":
81
+ vertical, horizontal = "center", "center"
82
+ else:
83
+ vertical, horizontal = self.position.split("-")
84
+ x = {"left": self.margin, "center": (frame.width - box_width) // 2,
85
+ "right": frame.width - box_width - self.margin}[horizontal]
86
+ y = {"top": self.margin, "center": (frame.height - box_height) // 2,
87
+ "bottom": frame.height - box_height - self.margin}[vertical]
88
+
89
+ layer = Image.new("RGBA", frame.size, (0, 0, 0, 0))
90
+ draw = ImageDraw.Draw(layer)
91
+ if self.background:
92
+ draw.rectangle((x, y, x + box_width - 1, y + box_height - 1), fill=self.background)
93
+ draw.fontmode = "1" # no anti-aliasing, the pixels of a pixel font stay sharp
94
+ draw.text((x + pad - left, y + pad - top), text, font=font, fill=color_utils.parse_color_rgb(self.color))
95
+ return Image.alpha_composite(frame, layer)
@@ -0,0 +1,50 @@
1
+ import math
2
+ from typing import List, Sequence, Tuple
3
+
4
+ from PIL import Image, ImageChops, ImageCms, ImageStat
5
+
6
+ # Calibrated by eye on a 64x64 display with 6 real animations. Every version that looked acceptable scored up to
7
+ # 8.3 (one that "flickers but is ok" 9.7), every one that looked broken or muted scored 11 or more: 9 is the limit of
8
+ # what is still fine. What was preferred when there was a choice scored 0 to 4 (for 8351169 the preferred version
9
+ # had 128 colors with a score of 0, the one with a shared 64 color palette that scored 7.5 looked as smooth, but
10
+ # duller), so the default favors that.
11
+ DEFAULT_MAX_COLOR_ERROR = 5.0
12
+ # a color that jumps between frames is much more noticeable than a constant error
13
+ FLICKER_WEIGHT = 8.0
14
+
15
+ _SRGB = ImageCms.createProfile("sRGB")
16
+ _LAB = ImageCms.createProfile("LAB")
17
+ _TO_LAB = ImageCms.buildTransform(_SRGB, _LAB, "RGB", "LAB")
18
+
19
+
20
+ def color_difference(a: Image.Image, b: Image.Image) -> float:
21
+ """
22
+ The root mean square of the color difference between two pictures of the same size, in CIE76 delta E (the
23
+ distance of two colors as the eye sees it: below 2 is hardly noticeable, 5 clearly visible).
24
+ """
25
+ diff = ImageChops.difference(
26
+ ImageCms.applyTransform(a.convert("RGB"), _TO_LAB), ImageCms.applyTransform(b.convert("RGB"), _TO_LAB))
27
+ lightness, green_red, blue_yellow = ImageStat.Stat(diff).rms
28
+ return math.sqrt((lightness * 100 / 255) ** 2 + green_red ** 2 + blue_yellow ** 2)
29
+
30
+
31
+ def color_error(reference: Sequence[Image.Image], reduced: Sequence[Image.Image]) -> Tuple[float, float]:
32
+ """
33
+ How far an animation with fewer colors is from the original: (the mean color difference of the frames, the
34
+ flicker). The flicker is how much more the colors jump from one frame to the next than in the original, which
35
+ happens when every frame gets its own palette.
36
+ """
37
+ errors: List[float] = [color_difference(a, b) for a, b in zip(reference, reduced)]
38
+ mean = sum(errors) / len(errors)
39
+ if len(reference) < 2:
40
+ return mean, 0.0
41
+ jumps = [
42
+ abs(color_difference(reduced[i], reduced[i + 1]) - color_difference(reference[i], reference[i + 1]))
43
+ for i in range(len(reference) - 1)
44
+ ]
45
+ return mean, sum(jumps) / len(jumps)
46
+
47
+
48
+ def color_score(mean: float, flicker: float) -> float:
49
+ """One number for how much worse an animation looks: the lower the better, `DEFAULT_MAX_COLOR_ERROR` is still fine."""
50
+ return mean + FLICKER_WEIGHT * flicker
@@ -4,7 +4,7 @@ description = "A library for controlling iDotMatrix displays."
4
4
  license = "GPL-3.0-or-later"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.12,<3.15"
7
- version = "0.2.3"
7
+ version = "0.3.0"
8
8
  classifiers = [
9
9
  "Intended Audience :: Developers",
10
10
  ]
@@ -1,120 +0,0 @@
1
- import asyncio
2
- import logging
3
- from os import PathLike
4
- from typing import Iterable, Sequence, Tuple
5
-
6
- from PIL import Image as PILImage
7
-
8
- from idotmatrix import protocol
9
- from idotmatrix.connection_manager import ConnectionManager
10
- from idotmatrix.modules import IDotMatrixModule
11
- from idotmatrix.modules.gif import GifModule
12
- from idotmatrix.modules.image import ImageModule
13
- from idotmatrix.protocol import build_command
14
- from idotmatrix.util import image_utils
15
- from idotmatrix.util.device_material import (
16
- DEFAULT_DISPLAY_TIME_SECONDS, SLOTS, validate_display_time, validate_slot,
17
- )
18
-
19
-
20
- class MaterialsModule(IDotMatrixModule):
21
- """
22
- The slots of the device ("device materials" in the official app). The device keeps the items in its slots and
23
- cycles through them by itself, in the order of the slots, so after the upload no Bluetooth traffic is needed and the
24
- animation is not interrupted by an upload, which takes seconds for a GIF. Based on `DeviceMaterialChildFragment` of
25
- the official app, which deletes the slots and then sends the items one after another.
26
- """
27
- logging = logging.getLogger(__name__)
28
-
29
- def __init__(self, connection_manager: ConnectionManager, gif: GifModule, image: ImageModule) -> None:
30
- super().__init__(connection_manager=connection_manager)
31
- self._gif = gif
32
- self._image = image
33
-
34
- async def clear(self, slots: Iterable[int] | None = None) -> None:
35
- """
36
- Deletes the items in the given slots.
37
-
38
- Args:
39
- slots: The slots to empty (0 to 11). All of them if not given.
40
- """
41
- slots = self._validate_slots(slots)
42
- # `11 00 02 01 <number of slots> <slot>...`, acknowledged with `05 00 02 01 01` (verified on a 64x64)
43
- await self._send_bytes(data=build_command(protocol.DELETE_MATERIALS, len(slots), *slots), response=True)
44
-
45
- async def store(
46
- self,
47
- files: Sequence[PathLike | str],
48
- slots: Iterable[int] | None = None,
49
- display_time: int = DEFAULT_DISPLAY_TIME_SECONDS,
50
- resize_mode: image_utils.ResizeMode = image_utils.ResizeMode.FIT,
51
- palletize: bool | None = None,
52
- background_color: Tuple[int, int, int] | int | str = (0, 0, 0),
53
- clear: bool = True,
54
- ) -> list[int]:
55
- """
56
- Stores image and GIF files in the slots of the device, one file per slot, and ends up with the device cycling
57
- through them. Other slots are not touched, so a list of slots protects the others.
58
-
59
- Args:
60
- files: The files, in the order they should be shown in. Animated GIFs are stored as GIFs, the rest as images.
61
- slots: The slots the device may use (0 to 11), all of them if not given. The files go into them in the order
62
- of the slot numbers, which is the order of the cycle.
63
- display_time: Seconds each item stays on screen.
64
- resize_mode: How the files are scaled to the screen.
65
- palletize: Reduce the colors to a palette. The default is on for GIFs and off for images.
66
- background_color: Color of the bars if a file does not have the shape of the screen.
67
- clear: Delete the used slots before the upload, like the official app does.
68
-
69
- Returns:
70
- The slots that were used, one for each file.
71
-
72
- Raises:
73
- ValueError: If there are more files than slots, or a slot or the display time is invalid.
74
- """
75
- slots = self._validate_slots(slots)
76
- validate_display_time(display_time)
77
- if len(files) > len(slots):
78
- raise ValueError(f"{len(files)} files do not fit into {len(slots)} slots")
79
- used = slots[:len(files)]
80
- if not used:
81
- return []
82
-
83
- if clear:
84
- await self.clear(used)
85
- for slot, file in zip(used, files):
86
- if await asyncio.to_thread(self._is_animated, file):
87
- await self._gif.upload_gif_file(
88
- file_path=file,
89
- resize_mode=resize_mode,
90
- palletize=True if palletize is None else palletize,
91
- background_color=background_color,
92
- slot=slot,
93
- display_time=display_time,
94
- )
95
- else:
96
- await self._image.show_image_file(
97
- file_path=file,
98
- resize_mode=resize_mode,
99
- palletize=bool(palletize),
100
- background_color=background_color,
101
- slot=slot,
102
- display_time=display_time,
103
- )
104
- return used
105
-
106
- @staticmethod
107
- def _validate_slots(slots: Iterable[int] | None) -> list[int]:
108
- if slots is None:
109
- return list(SLOTS)
110
- slots = sorted(validate_slot(slot) for slot in slots)
111
- if len(set(slots)) != len(slots):
112
- raise ValueError(f"slots must not contain duplicates, got: {slots}")
113
- if not slots:
114
- raise ValueError("slots must not be empty")
115
- return slots
116
-
117
- @staticmethod
118
- def _is_animated(file: PathLike | str) -> bool:
119
- with PILImage.open(file) as img:
120
- return getattr(img, "n_frames", 1) > 1