valetudo-map-parser 0.1.9b52__py3-none-any.whl → 0.1.9b54__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.
@@ -15,13 +15,13 @@ from .config.types import (
15
15
  TrimCropData,
16
16
  UserLanguageStore,
17
17
  )
18
- from .hypfer_rooms_handler import HypferRoomsHandler
19
18
  from .hypfer_handler import HypferMapImageHandler
20
19
  from .rand25_handler import ReImageHandler
20
+ from .rooms_handler import RoomsHandler
21
21
 
22
22
 
23
23
  __all__ = [
24
- "HypferRoomsHandler",
24
+ "RoomsHandler",
25
25
  "HypferMapImageHandler",
26
26
  "ReImageHandler",
27
27
  "RRMapParser",
@@ -125,7 +125,7 @@ class AutoCrop:
125
125
  if self.auto_crop:
126
126
  self.auto_crop_offset()
127
127
  else:
128
- self.handler.max_frames = 5
128
+ self.handler.max_frames = 1205
129
129
 
130
130
  # Fallback: Ensure auto_crop is valid
131
131
  if not self.auto_crop or any(v < 0 for v in self.auto_crop):
@@ -137,12 +137,32 @@ class AutoCrop:
137
137
  async def async_image_margins(
138
138
  self, image_array: NumpyArray, detect_colour: Color
139
139
  ) -> tuple[int, int, int, int]:
140
- """Crop the image based on the auto crop area."""
141
- nonzero_coords = np.column_stack(np.where(image_array != list(detect_colour)))
142
- # Calculate the trim box based on the first and last occurrences
143
- min_y, min_x, _ = NumpyArray.min(nonzero_coords, axis=0)
144
- max_y, max_x, _ = NumpyArray.max(nonzero_coords, axis=0)
145
- del nonzero_coords
140
+ """Crop the image based on the auto crop area using scipy.ndimage for better performance."""
141
+ # Import scipy.ndimage here to avoid import at module level
142
+ from scipy import ndimage
143
+
144
+ # Create a binary mask where True = non-background pixels
145
+ # This is much more memory efficient than storing coordinates
146
+ mask = ~np.all(image_array == list(detect_colour), axis=2)
147
+
148
+ # Use scipy.ndimage.find_objects to efficiently find the bounding box
149
+ # This returns a list of slice objects that define the bounding box
150
+ # Label the mask with a single label (1) and find its bounding box
151
+ labeled_mask = mask.astype(np.int8) # Convert to int8 (smallest integer type)
152
+ objects = ndimage.find_objects(labeled_mask)
153
+
154
+ if not objects: # No objects found
155
+ _LOGGER.warning(
156
+ "%s: No non-background pixels found in image", self.handler.file_name
157
+ )
158
+ # Return full image dimensions as fallback
159
+ return 0, 0, image_array.shape[1], image_array.shape[0]
160
+
161
+ # Extract the bounding box coordinates from the slice objects
162
+ y_slice, x_slice = objects[0]
163
+ min_y, max_y = y_slice.start, y_slice.stop - 1
164
+ min_x, max_x = x_slice.start, x_slice.stop - 1
165
+
146
166
  _LOGGER.debug(
147
167
  "%s: Found trims max and min values (y,x) (%s, %s) (%s, %s)...",
148
168
  self.handler.file_name,
@@ -1,9 +1,9 @@
1
1
  """Utility functions for color operations in the map parser."""
2
2
 
3
- from typing import Tuple, Optional
3
+ from typing import Optional, Tuple
4
4
 
5
5
  from .colors import ColorsManagement
6
- from .types import NumpyArray, Color
6
+ from .types import Color, NumpyArray
7
7
 
8
8
 
9
9
  def get_blended_color(
@@ -63,6 +63,7 @@ from .types import (
63
63
  Color,
64
64
  )
65
65
 
66
+
66
67
  color_transparent = (0, 0, 0, 0)
67
68
  color_charger = (0, 128, 0, 255)
68
69
  color_move = (238, 247, 255, 255)
@@ -492,10 +493,20 @@ class ColorsManagement:
492
493
  background = tuple(map(int, array[y, x]))
493
494
 
494
495
  # Update cache (with simple LRU-like behavior)
495
- if len(cache) >= ColorsManagement._cache_size:
496
- # Remove a random entry if cache is full
497
- cache.pop(next(iter(cache)))
498
- cache[cache_key] = background
496
+ try:
497
+ if len(cache) >= ColorsManagement._cache_size:
498
+ # Remove a random entry if cache is full
499
+ if cache: # Make sure cache is not empty
500
+ cache.pop(next(iter(cache)))
501
+ else:
502
+ # If cache is somehow empty but len reported >= _cache_size
503
+ # This is an edge case that shouldn't happen but we handle it
504
+ pass
505
+ cache[cache_key] = background
506
+ except KeyError:
507
+ # If we encounter a KeyError, reset the cache
508
+ # This is a rare edge case that might happen in concurrent access
509
+ ColorsManagement._bg_color_cache = {cache_key: background}
499
510
 
500
511
  except (IndexError, ValueError):
501
512
  return foreground
@@ -10,15 +10,14 @@ Optimized with NumPy and SciPy for better performance.
10
10
 
11
11
  from __future__ import annotations
12
12
 
13
-
14
13
  import logging
15
14
  import math
16
15
 
17
16
  import numpy as np
18
17
  from PIL import ImageDraw, ImageFont
19
18
 
20
- from .colors import ColorsManagement
21
19
  from .color_utils import get_blended_color
20
+ from .colors import ColorsManagement
22
21
  from .types import Color, NumpyArray, PilPNG, Point, Tuple, Union
23
22
 
24
23
 
@@ -57,9 +56,6 @@ class Drawable:
57
56
  # Extract alpha from color
58
57
  alpha = color[3] if len(color) == 4 else 255
59
58
 
60
- # For debugging
61
- _LOGGER.debug("Drawing with color %s and alpha %s", color, alpha)
62
-
63
59
  # Create the full color with alpha
64
60
  full_color = color if len(color) == 4 else (*color, 255)
65
61
 
@@ -8,10 +8,12 @@ from __future__ import annotations
8
8
 
9
9
  from enum import IntEnum
10
10
  from typing import Dict, List, Tuple, Union
11
+
11
12
  import numpy as np
12
- from .types import LOGGER
13
13
 
14
14
  from .colors import DefaultColors, SupportedColor
15
+ from .types import LOGGER
16
+
15
17
 
16
18
  # Type aliases
17
19
  Color = Tuple[int, int, int, int] # RGBA color
@@ -170,13 +172,7 @@ class DrawingConfig:
170
172
 
171
173
  def is_enabled(self, element_code: DrawableElement) -> bool:
172
174
  """Check if an element is enabled for drawing."""
173
- enabled = self._enabled_elements.get(element_code, False)
174
- LOGGER.debug(
175
- "Checking if element %s is enabled: %s",
176
- element_code.name if hasattr(element_code, "name") else element_code,
177
- enabled,
178
- )
179
- return enabled
175
+ return self._enabled_elements.get(element_code, False)
180
176
 
181
177
  def set_property(
182
178
  self, element_code: DrawableElement, property_name: str, value
@@ -238,10 +234,6 @@ class DrawingConfig:
238
234
  self.set_property(room_element, "color", rgba)
239
235
  self.set_property(room_element, "opacity", alpha / 255.0)
240
236
 
241
- LOGGER.debug(
242
- "Updated room %d color to %s with alpha %s", room_id, rgb, alpha
243
- )
244
-
245
237
  # Update other element colors
246
238
  for element, color_key in element_color_mapping.items():
247
239
  if color_key in device_info:
@@ -265,13 +257,6 @@ class DrawingConfig:
265
257
  self.set_property(element, "color", rgba)
266
258
  self.set_property(element, "opacity", alpha / 255.0)
267
259
 
268
- LOGGER.debug(
269
- "Updated element %s color to %s with alpha %s",
270
- element.name,
271
- rgb,
272
- alpha,
273
- )
274
-
275
260
  # Check for disabled elements using specific boolean flags
276
261
  # Map element disable flags to DrawableElement enum values
277
262
  element_disable_mapping = {
@@ -13,12 +13,12 @@ from typing import Optional, Tuple
13
13
 
14
14
  import numpy as np
15
15
 
16
+ from .colors import ColorsManagement
16
17
  from .drawable import Drawable
17
18
  from .drawable_elements import (
18
19
  DrawableElement,
19
20
  DrawingConfig,
20
21
  )
21
- from .colors import ColorsManagement
22
22
 
23
23
 
24
24
  # Type aliases
@@ -247,26 +247,6 @@ class CameraSharedManager:
247
247
  )
248
248
  instance.trims = TrimsData.from_dict(trim_data)
249
249
 
250
- # Log disable_obstacles and disable_path settings
251
- if "disable_obstacles" in device_info:
252
- _LOGGER.info(
253
- "%s: device_info contains disable_obstacles: %s",
254
- instance.file_name,
255
- device_info["disable_obstacles"],
256
- )
257
- if "disable_path" in device_info:
258
- _LOGGER.info(
259
- "%s: device_info contains disable_path: %s",
260
- instance.file_name,
261
- device_info["disable_path"],
262
- )
263
- if "disable_elements" in device_info:
264
- _LOGGER.info(
265
- "%s: device_info contains disable_elements: %s",
266
- instance.file_name,
267
- device_info["disable_elements"],
268
- )
269
-
270
250
  except TypeError as ex:
271
251
  _LOGGER.error("Shared data can't be initialized due to a TypeError! %s", ex)
272
252
  except AttributeError as ex:
@@ -8,7 +8,7 @@ import json
8
8
  import logging
9
9
  import threading
10
10
  from dataclasses import asdict, dataclass
11
- from typing import Any, Dict, Optional, Tuple, Union, TypedDict
11
+ from typing import Any, Dict, Optional, Tuple, TypedDict, Union
12
12
 
13
13
  import numpy as np
14
14
  from PIL import Image
@@ -639,7 +639,3 @@ class TrimsData:
639
639
  self.trim_down = 0
640
640
  self.trim_right = 0
641
641
  return asdict(self)
642
-
643
- def self_instance(self):
644
- """Return self instance."""
645
- return self.self_instance()
@@ -550,58 +550,8 @@ def initialize_drawing_config(handler):
550
550
  hasattr(handler.shared, "device_info")
551
551
  and handler.shared.device_info is not None
552
552
  ):
553
- LOGGER.info(
554
- "%s: Initializing drawing config from device_info", handler.file_name
555
- )
556
- LOGGER.info(
557
- "%s: device_info contains disable_obstacles: %s",
558
- handler.file_name,
559
- "disable_obstacles" in handler.shared.device_info,
560
- )
561
- LOGGER.info(
562
- "%s: device_info contains disable_path: %s",
563
- handler.file_name,
564
- "disable_path" in handler.shared.device_info,
565
- )
566
- LOGGER.info(
567
- "%s: device_info contains disable_elements: %s",
568
- handler.file_name,
569
- "disable_elements" in handler.shared.device_info,
570
- )
571
-
572
- if "disable_obstacles" in handler.shared.device_info:
573
- LOGGER.info(
574
- "%s: disable_obstacles value: %s",
575
- handler.file_name,
576
- handler.shared.device_info["disable_obstacles"],
577
- )
578
- if "disable_path" in handler.shared.device_info:
579
- LOGGER.info(
580
- "%s: disable_path value: %s",
581
- handler.file_name,
582
- handler.shared.device_info["disable_path"],
583
- )
584
- if "disable_elements" in handler.shared.device_info:
585
- LOGGER.info(
586
- "%s: disable_elements value: %s",
587
- handler.file_name,
588
- handler.shared.device_info["disable_elements"],
589
- )
590
-
591
553
  drawing_config.update_from_device_info(handler.shared.device_info)
592
554
 
593
- # Verify elements are disabled
594
- LOGGER.info(
595
- "%s: After initialization, PATH enabled: %s",
596
- handler.file_name,
597
- drawing_config.is_enabled(DrawableElement.PATH),
598
- )
599
- LOGGER.info(
600
- "%s: After initialization, OBSTACLE enabled: %s",
601
- handler.file_name,
602
- drawing_config.is_enabled(DrawableElement.OBSTACLE),
603
- )
604
-
605
555
  # Initialize both drawable systems for backward compatibility
606
556
  draw = Drawable() # Legacy drawing utilities
607
557
  enhanced_draw = EnhancedDrawable(drawing_config) # New enhanced drawing system
@@ -632,7 +582,7 @@ def blend_colors(base_color, overlay_color):
632
582
 
633
583
  # Avoid division by zero
634
584
  if a_out < 0.0001:
635
- return (0, 0, 0, 0)
585
+ return [0, 0, 0, 0]
636
586
 
637
587
  # Calculate blended RGB components
638
588
  r_out = (r1 * a1 + r2 * a2 * (1 - a1)) / a_out
@@ -142,12 +142,6 @@ class ImageDraw:
142
142
  room_element = getattr(DrawableElement, f"ROOM_{current_room_id}", None)
143
143
  if room_element and hasattr(self.img_h.drawing_config, "is_enabled"):
144
144
  draw_room = self.img_h.drawing_config.is_enabled(room_element)
145
- _LOGGER.debug(
146
- "%s: Room %d is %s",
147
- self.file_name,
148
- current_room_id,
149
- "enabled" if draw_room else "disabled",
150
- )
151
145
 
152
146
  # Get the room color
153
147
  room_color = self.img_h.shared.rooms_colors[room_id]
@@ -170,13 +164,6 @@ class ImageDraw:
170
164
  except IndexError as e:
171
165
  _LOGGER.warning("%s: Image Draw Error: %s", self.file_name, str(e))
172
166
 
173
- _LOGGER.debug(
174
- "%s Active Zones: %s and Room ID: %s",
175
- self.file_name,
176
- str(self.img_h.active_zones),
177
- str(room_id),
178
- )
179
-
180
167
  return img_np_array, room_id
181
168
 
182
169
  def _get_active_room_color(self, room_id, room_color, color_zone_clean):
@@ -20,6 +20,7 @@ from .config.types import (
20
20
  CalibrationPoints,
21
21
  Colors,
22
22
  RoomsProperties,
23
+ RoomStore,
23
24
  )
24
25
  from .config.utils import (
25
26
  BaseHandler,
@@ -28,8 +29,8 @@ from .config.utils import (
28
29
  prepare_resize_params,
29
30
  )
30
31
  from .hypfer_draw import ImageDraw as ImDraw
31
- from .hypfer_rooms_handler import HypferRoomsHandler
32
32
  from .map_data import ImageData
33
+ from .rooms_handler import RoomsHandler
33
34
 
34
35
 
35
36
  class HypferMapImageHandler(BaseHandler, AutoCrop):
@@ -57,7 +58,7 @@ class HypferMapImageHandler(BaseHandler, AutoCrop):
57
58
  self.imd = ImDraw(self) # Image Draw class.
58
59
  self.color_grey = (128, 128, 128, 255)
59
60
  self.file_name = self.shared.file_name # file name of the vacuum.
60
- self.rooms_handler = HypferRoomsHandler(
61
+ self.rooms_handler = RoomsHandler(
61
62
  self.file_name, self.drawing_config
62
63
  ) # Room data handler
63
64
 
@@ -68,51 +69,24 @@ class HypferMapImageHandler(BaseHandler, AutoCrop):
68
69
 
69
70
  async def async_extract_room_properties(self, json_data) -> RoomsProperties:
70
71
  """Extract room properties from the JSON data."""
71
-
72
- return await self.rooms_handler.async_extract_room_properties(json_data)
73
- # room_properties = {}
74
- # self.rooms_pos = []
75
- # pixel_size = json_data.get("pixelSize", [])
76
- #
77
- # for layer in json_data.get("layers", []):
78
- # if layer["__class"] == "MapLayer":
79
- # meta_data = layer.get("metaData", {})
80
- # segment_id = meta_data.get("segmentId")
81
- # if segment_id is not None:
82
- # name = meta_data.get("name")
83
- # compressed_pixels = layer.get("compressedPixels", [])
84
- # pixels = self.data.sublist(compressed_pixels, 3)
85
- # # Calculate x and y min/max from compressed pixels
86
- # (
87
- # x_min,
88
- # y_min,
89
- # x_max,
90
- # y_max,
91
- # ) = await self.data.async_get_rooms_coordinates(pixels, pixel_size)
92
- # corners = self.get_corners(x_max, x_min, y_max, y_min)
93
- # room_id = str(segment_id)
94
- # self.rooms_pos.append(
95
- # {
96
- # "name": name,
97
- # "corners": corners,
98
- # }
99
- # )
100
- # room_properties[room_id] = {
101
- # "number": segment_id,
102
- # "outline": corners,
103
- # "name": name,
104
- # "x": ((x_min + x_max) // 2),
105
- # "y": ((y_min + y_max) // 2),
106
- # }
107
- # if room_properties:
108
- # rooms = RoomStore(self.file_name, room_properties)
109
- # LOGGER.debug(
110
- # "%s: Rooms data extracted! %s", self.file_name, rooms.get_rooms()
111
- # )
112
- # else:
113
- # LOGGER.debug("%s: Rooms data not available!", self.file_name)
114
- # self.rooms_pos = None
115
- # return room_properties
72
+ room_properties = await self.rooms_handler.async_extract_room_properties(
73
+ json_data
74
+ )
75
+ if room_properties:
76
+ rooms = RoomStore(self.file_name, room_properties)
77
+ LOGGER.debug(
78
+ "%s: Rooms data extracted! %s", self.file_name, rooms.get_rooms()
79
+ )
80
+ # Convert room_properties to the format expected by async_get_robot_in_room
81
+ self.rooms_pos = []
82
+ for room_id, room_data in room_properties.items():
83
+ self.rooms_pos.append(
84
+ {"name": room_data["name"], "outline": room_data["outline"]}
85
+ )
86
+ else:
87
+ LOGGER.debug("%s: Rooms data not available!", self.file_name)
88
+ self.rooms_pos = None
89
+ return room_properties
116
90
 
117
91
  # noinspection PyUnresolvedReferences,PyUnboundLocalVariable
118
92
  async def async_get_image_from_json(
@@ -164,9 +138,6 @@ class HypferMapImageHandler(BaseHandler, AutoCrop):
164
138
  img_np_array = await self.draw.create_empty_image(
165
139
  size_x, size_y, colors["background"]
166
140
  )
167
-
168
- LOGGER.info("%s: Drawing map with color blending", self.file_name)
169
-
170
141
  # Draw layers and segments if enabled
171
142
  room_id = 0
172
143
  # Keep track of disabled rooms to skip their walls later
@@ -218,25 +189,13 @@ class HypferMapImageHandler(BaseHandler, AutoCrop):
218
189
  room_element = getattr(
219
190
  DrawableElement, f"ROOM_{current_room_id}", None
220
191
  )
221
- if room_element:
222
- # Log the room check for debugging
223
- LOGGER.debug(
224
- "%s: Checking if room %d is enabled: %s",
225
- self.file_name,
226
- current_room_id,
227
- self.drawing_config.is_enabled(
228
- room_element
229
- ),
230
- )
231
192
 
232
- # Skip this room if it's disabled
233
- if not self.drawing_config.is_enabled(
234
- room_element
235
- ):
236
- room_id = (
237
- room_id + 1
238
- ) % 16 # Increment room_id even if we skip
239
- continue
193
+ # Skip this room if it's disabled
194
+ if not self.drawing_config.is_enabled(room_element):
195
+ room_id = (
196
+ room_id + 1
197
+ ) % 16 # Increment room_id even if we skip
198
+ continue
240
199
 
241
200
  # Check if this is a wall layer and if walls are enabled
242
201
  is_wall_layer = layer_type == "wall"
@@ -244,22 +203,7 @@ class HypferMapImageHandler(BaseHandler, AutoCrop):
244
203
  if not self.drawing_config.is_enabled(
245
204
  DrawableElement.WALL
246
205
  ):
247
- LOGGER.info(
248
- "%s: Skipping wall layer because WALL element is disabled",
249
- self.file_name,
250
- )
251
- continue
252
-
253
- # Filter out walls for disabled rooms
254
- if disabled_rooms:
255
- # Need to modify compressed_pixels_list to exclude walls of disabled rooms
256
- # This requires knowledge of which walls belong to which rooms
257
- # For now, we'll just log that we're drawing walls for all rooms
258
- LOGGER.debug(
259
- "%s: Drawing walls for all rooms (including disabled ones)",
260
- self.file_name,
261
- )
262
- # In a real implementation, we would filter the walls here
206
+ pass
263
207
 
264
208
  # Draw the layer
265
209
  (
@@ -281,10 +225,6 @@ class HypferMapImageHandler(BaseHandler, AutoCrop):
281
225
  room_element = getattr(
282
226
  DrawableElement, f"ROOM_{room_id}", None
283
227
  )
284
- if room_element:
285
- # This is a simplification - in a real implementation we would
286
- # need to identify the exact pixels that belong to this room
287
- pass
288
228
 
289
229
  # Draw the virtual walls if enabled
290
230
  if self.drawing_config.is_enabled(DrawableElement.VIRTUAL_WALL):