code-loader 1.0.139.dev5__py3-none-any.whl → 1.0.153.dev3__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.

Potentially problematic release.


This version of code-loader might be problematic. Click here for more details.

code_loader/leaploader.py CHANGED
@@ -163,7 +163,7 @@ class LeapLoader(LeapLoaderBase):
163
163
  if state == DataStateEnum.unlabeled and sample_id not in preprocess_result[state].sample_ids:
164
164
  self._preprocess_result(update_unlabeled_preprocess=True)
165
165
 
166
- metadata, metadata_is_none = self._get_metadata(state, sample_id)
166
+ metadata, metadata_is_none = self.get_metadata(state, sample_id)
167
167
 
168
168
  custom_latent_space = None
169
169
  if global_leap_binder.setup_container.custom_latent_space is not None:
@@ -521,21 +521,38 @@ class LeapLoader(LeapLoaderBase):
521
521
 
522
522
  return converted_value, is_none
523
523
 
524
- def _get_metadata(self, state: DataStateEnum, sample_id: Union[int, str]) -> Tuple[
524
+ def get_metadata(self, state: DataStateEnum, sample_id: Union[int, str], requested_metadata_names: Optional[List[str]] = None) -> Tuple[
525
525
  Dict[str, Union[str, int, bool, float]], Dict[str, bool]]:
526
+
527
+ def is_metadata_name_starts_with_handler_name(_handler):
528
+ for metadata_name in requested_metadata_names:
529
+ if metadata_name.startswith(_handler.name + '_') or metadata_name == _handler.name:
530
+ return True
531
+ return False
532
+
526
533
  result_agg = {}
527
534
  is_none = {}
528
535
  preprocess_result = self._preprocess_result()
529
536
  preprocess_state = preprocess_result[state]
530
537
  for handler in global_leap_binder.setup_container.metadata:
538
+ if requested_metadata_names:
539
+ if not is_metadata_name_starts_with_handler_name(handler):
540
+ continue
541
+
531
542
  handler_result = handler.function(sample_id, preprocess_state)
532
543
  if isinstance(handler_result, dict):
533
544
  for single_metadata_name, single_metadata_result in handler_result.items():
534
545
  handler_name = f'{handler.name}_{single_metadata_name}'
546
+ if requested_metadata_names:
547
+ if handler_name not in requested_metadata_names:
548
+ continue
535
549
  result_agg[handler_name], is_none[handler_name] = self._convert_metadata_to_correct_type(
536
550
  handler_name, single_metadata_result)
537
551
  else:
538
552
  handler_name = handler.name
553
+ if requested_metadata_names:
554
+ if handler_name not in requested_metadata_names:
555
+ continue
539
556
  result_agg[handler_name], is_none[handler_name] = self._convert_metadata_to_correct_type(
540
557
  handler_name, handler_result)
541
558
 
@@ -68,6 +68,24 @@ class LeapLoaderBase:
68
68
  def get_instances_data(self, state: DataStateEnum) -> Tuple[Dict[str, List[str]], Dict[str, str]]:
69
69
  pass
70
70
 
71
+ def get_metadata_multiple_samples(self, state: DataStateEnum, sample_ids: Union[List[int], List[str]],
72
+ requested_metadata_names: Optional[List[str]] = None
73
+ ) -> Tuple[Dict[str, Union[List[str], List[int], List[bool],
74
+ List[float]]], Dict[str, List[bool]]]:
75
+ aggregated_results: Dict[str, List[Union[str, int, bool, float]]] = {}
76
+ aggregated_is_none: Dict[str, List[bool]] = {}
77
+ sample_id_type = self.get_sample_id_type()
78
+ for sample_id in sample_ids:
79
+ sample_id = sample_id_type(sample_id)
80
+ metadata_result, is_none_result = self.get_metadata(state, sample_id, requested_metadata_names)
81
+ for metadata_name, metadata_value in metadata_result.items():
82
+ if metadata_name not in aggregated_results:
83
+ aggregated_results[metadata_name] = []
84
+ aggregated_is_none[metadata_name] = []
85
+ aggregated_results[metadata_name].append(metadata_value)
86
+ aggregated_is_none[metadata_name].append(is_none_result[metadata_name])
87
+ return aggregated_results, aggregated_is_none
88
+
71
89
  @abstractmethod
72
90
  def check_dataset(self) -> DatasetIntegParseResult:
73
91
  pass
@@ -87,6 +105,13 @@ class LeapLoaderBase:
87
105
  input_tensors_by_arg_name: Dict[str, npt.NDArray[np.float32]]):
88
106
  pass
89
107
 
108
+ @abstractmethod
109
+ def get_metadata(
110
+ self, state: DataStateEnum, sample_id: Union[int, str],
111
+ requested_metadata_names: Optional[List[str]] = None
112
+ ) -> Tuple[Dict[str, Union[str, int, bool, float]], Dict[str, bool]]:
113
+ pass
114
+
90
115
  @abstractmethod
91
116
  def run_heatmap_visualizer(self, visualizer_name: str, sample_ids: np.array, state: DataStateEnum,
92
117
  input_tensors_by_arg_name: Dict[str, npt.NDArray[np.float32]]
@@ -5,12 +5,53 @@ import os
5
5
  import sys
6
6
  import getpass
7
7
  import uuid
8
- from typing import Optional, Dict, Any
8
+ import logging
9
+ from enum import Enum
10
+ from typing import Optional, Dict, Any, Set, Union, TypedDict
9
11
  import mixpanel # type: ignore[import]
10
12
 
13
+ logger = logging.getLogger(__name__)
14
+
11
15
  TRACKING_VERSION = '1'
12
16
 
13
17
 
18
+ class AnalyticsEvent(str, Enum):
19
+ """Enumeration of all tracked analytics events."""
20
+ CODE_LOADER_LOADED = "code_loader_loaded"
21
+ LOAD_MODEL_INTEGRATION_TEST = "load_model_integration_test"
22
+ PREPROCESS_INTEGRATION_TEST = "preprocess_integration_test"
23
+ INPUT_ENCODER_INTEGRATION_TEST = "input_encoder_integration_test"
24
+ GT_ENCODER_INTEGRATION_TEST = "gt_encoder_integration_test"
25
+
26
+
27
+ class CodeLoaderLoadedProps(TypedDict, total=False):
28
+ """Properties for code_loader_loaded event."""
29
+ event_type: str
30
+ code_path: str
31
+ code_entry_name: str
32
+
33
+
34
+ class LoadModelEventProps(TypedDict, total=False):
35
+ """Properties for load_model_integration_test event."""
36
+ prediction_types_count: int
37
+
38
+
39
+ class PreprocessEventProps(TypedDict, total=False):
40
+ """Properties for preprocess_integration_test event."""
41
+ preprocess_responses_count: int
42
+
43
+
44
+ class InputEncoderEventProps(TypedDict, total=False):
45
+ """Properties for input_encoder_integration_test event."""
46
+ encoder_name: str
47
+ channel_dim: int
48
+
49
+
50
+ class GtEncoderEventProps(TypedDict, total=False):
51
+ """Properties for gt_encoder_integration_test event."""
52
+ encoder_name: str
53
+
54
+
14
55
  class MixpanelTracker:
15
56
  """Handles Mixpanel event tracking for code-loader."""
16
57
 
@@ -28,7 +69,8 @@ class MixpanelTracker:
28
69
  if self._user_id is None:
29
70
  try:
30
71
  self._user_id = getpass.getuser()
31
- except Exception:
72
+ except Exception as e:
73
+ logger.debug(f"Failed to get username via getpass: {e}")
32
74
  # Fallback to environment variables or default
33
75
  self._user_id = os.environ.get('USER', os.environ.get('USERNAME', 'unknown'))
34
76
  return self._user_id or 'unknown'
@@ -43,8 +85,8 @@ class MixpanelTracker:
43
85
  user_id = f.read().strip()
44
86
  if user_id:
45
87
  return user_id
46
- except Exception:
47
- pass
88
+ except Exception as e:
89
+ logger.debug(f"Failed to read TensorLeap user ID: {e}")
48
90
  return None
49
91
 
50
92
  def _get_or_create_device_id(self) -> str:
@@ -73,7 +115,8 @@ class MixpanelTracker:
73
115
  f.write(device_id)
74
116
 
75
117
  return device_id
76
- except Exception:
118
+ except Exception as e:
119
+ logger.debug(f"Failed to read/write device ID file: {e}")
77
120
  # Fallback to generating a new UUID if file operations fail
78
121
  return str(uuid.uuid4())
79
122
 
@@ -90,10 +133,11 @@ class MixpanelTracker:
90
133
 
91
134
  return self._get_or_create_device_id()
92
135
 
93
- def track_code_loader_loaded(self, event_properties: Optional[Dict[str, Any]] = None) -> None:
94
- """Track code loader loaded event with device identification.
136
+ def _track_event(self, event_name: Union[str, AnalyticsEvent], event_properties: Optional[Dict[str, Any]] = None) -> None:
137
+ """Internal method to track any event with device identification.
95
138
 
96
139
  Args:
140
+ event_name: The name of the event to track (string or AnalyticsEvent enum)
97
141
  event_properties: Optional additional properties to include in the event
98
142
  """
99
143
  # Skip tracking if IS_TENSORLEAP_PLATFORM environment variable is set to 'true'
@@ -122,9 +166,26 @@ class MixpanelTracker:
122
166
  if event_properties:
123
167
  properties.update(event_properties)
124
168
 
125
- self.mp.track(distinct_id, 'code_loader_loaded', properties)
169
+ self.mp.track(distinct_id, str(event_name), properties)
126
170
  except Exception as e:
127
- pass
171
+ logger.debug(f"Failed to track event '{event_name}': {e}")
172
+
173
+ def track_code_loader_loaded(self, event_properties: Optional[Dict[str, Any]] = None) -> None:
174
+ """Track code loader loaded event with device identification.
175
+
176
+ Args:
177
+ event_properties: Optional additional properties to include in the event
178
+ """
179
+ self._track_event(AnalyticsEvent.CODE_LOADER_LOADED, event_properties)
180
+
181
+ def track_integration_test_event(self, event_name: Union[str, AnalyticsEvent], event_properties: Optional[Dict[str, Any]] = None) -> None:
182
+ """Track an integration test event with device identification.
183
+
184
+ Args:
185
+ event_name: The name of the event to track (string or AnalyticsEvent enum)
186
+ event_properties: Optional additional properties to include in the event
187
+ """
188
+ self._track_event(event_name, event_properties)
128
189
 
129
190
 
130
191
  # Global tracker instance
@@ -140,3 +201,30 @@ def get_tracker() -> MixpanelTracker:
140
201
 
141
202
  def track_code_loader_loaded(event_properties: Optional[Dict[str, Any]] = None) -> None:
142
203
  get_tracker().track_code_loader_loaded(event_properties)
204
+
205
+
206
+ def track_integration_test_event(event_name: Union[str, AnalyticsEvent], event_properties: Optional[Dict[str, Any]] = None) -> None:
207
+ get_tracker().track_integration_test_event(event_name, event_properties)
208
+
209
+
210
+ # Module-level set to track which integration test events have been emitted
211
+ _integration_events_emitted: Set[str] = set()
212
+
213
+
214
+ def emit_integration_event_once(event_name: Union[str, AnalyticsEvent], props: Dict[str, Any]) -> None:
215
+ """Emit an integration test event only once per test run."""
216
+ event_name_str = str(event_name)
217
+ if event_name_str in _integration_events_emitted:
218
+ return
219
+
220
+ try:
221
+ track_integration_test_event(event_name, props)
222
+ _integration_events_emitted.add(event_name_str)
223
+ except Exception as e:
224
+ logger.debug(f"Failed to emit integration event once '{event_name}': {e}")
225
+
226
+
227
+ def clear_integration_events() -> None:
228
+ """Clear the integration events set for a new test run."""
229
+ global _integration_events_emitted
230
+ _integration_events_emitted.clear()
@@ -324,7 +324,7 @@ def plot_image_mask(leap_data: LeapImageMask, title: str) -> None:
324
324
 
325
325
  # fill the instance mask with a translucent color
326
326
  overlayed_image[instance_mask] = (
327
- overlayed_image[instance_mask] * (1 - 0.5) + np.array(colors[i][:image.shape[-1]], dtype=np.uint8) * 0.5)
327
+ overlayed_image[instance_mask] * (1 - 0.5) + np.array(colors[i][:image.shape[-1]], dtype=image.dtype) * 0.5)
328
328
 
329
329
  # Display the result using matplotlib
330
330
  fig, ax = plt.subplots(1)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.1
2
2
  Name: code-loader
3
- Version: 1.0.139.dev5
3
+ Version: 1.0.153.dev3
4
4
  Summary:
5
5
  Home-page: https://github.com/tensorleap/code-loader
6
6
  License: MIT
@@ -1,7 +1,7 @@
1
1
  LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
2
2
  code_loader/__init__.py,sha256=outxRQ0M-zMfV0QGVJmAed5qWfRmyD0TV6-goEGAzBw,406
3
3
  code_loader/contract/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
4
- code_loader/contract/datasetclasses.py,sha256=hkHMU1upWzVWkjIBoU3r14XPDleicif4Oia2xfuHgvQ,9395
4
+ code_loader/contract/datasetclasses.py,sha256=aDlpOA9U8boY2BRXMwLHkRRiCSL9CyH8OwyrmHrwX-c,9801
5
5
  code_loader/contract/enums.py,sha256=GEFkvUMXnCNt-GOoz7NJ9ecQZ2PPDettJNOsxsiM0wk,1622
6
6
  code_loader/contract/exceptions.py,sha256=jWqu5i7t-0IG0jGRsKF4DjJdrsdpJjIYpUkN1F4RiyQ,51
7
7
  code_loader/contract/mapping.py,sha256=sWJhpng-IkOzQnWQdMT5w2ZZ3X1Z_OOzSwCLXIS7oxE,1446
@@ -21,17 +21,17 @@ code_loader/experiment_api/utils.py,sha256=XZHtxge12TS4H4-8PjV3sKuhp8Ud6ojAiIzTZ
21
21
  code_loader/experiment_api/workingspace_config_utils.py,sha256=DLzXQCg4dgTV_YgaSbeTVzq-2ja_SQw4zi7LXwKL9cY,990
22
22
  code_loader/inner_leap_binder/__init__.py,sha256=koOlJyMNYzGbEsoIbXathSmQ-L38N_pEXH_HvL7beXU,99
23
23
  code_loader/inner_leap_binder/leapbinder.py,sha256=Q3D9yVM-GNEJfYRFvMV__BoZbcWOgnWKhrZXAv6Tu7o,33232
24
- code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=I6V-Q9qRqhmBJSr_TvrGTcs2RZgi8y9nbLWtL93UH4I,70581
25
- code_loader/leaploader.py,sha256=6D6xZzMI6qSNIb3tuKLB3BbK5H8QS1_r7iQjIXO3OkM,29795
26
- code_loader/leaploaderbase.py,sha256=LIFcC6xo6V_iiGN3BjibXETu_l84EWM_WIOKAvkfTiM,4458
27
- code_loader/mixpanel_tracker.py,sha256=l9z_szKKQ7apEbdNZpGH1TKAiT_TsBHb9AQnePaWTyo,4942
24
+ code_loader/inner_leap_binder/leapbinder_decorators.py,sha256=k7h0OXFgMWNj-0jxelcPlYVZvrddv5GRxIMRk_OD0Ro,81986
25
+ code_loader/leaploader.py,sha256=oxtlf7NhWuiUPeIwAO699JaD-mK_7fGM55okKLyKaJg,30582
26
+ code_loader/leaploaderbase.py,sha256=NXCDIIF7-ziGJccKIE9NszMSYKEE-3bn4Z4Xa3oYYOc,5909
27
+ code_loader/mixpanel_tracker.py,sha256=eKvymkw7X2Ht6iw-a0V9VQm6OnB9kW7hYy35YtwRAvU,8457
28
28
  code_loader/plot_functions/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
29
- code_loader/plot_functions/plot_functions.py,sha256=VyVWxd7R3lALIo2z8oZlYybbN0Ip6G0OiKNTNZ77xHk,14557
29
+ code_loader/plot_functions/plot_functions.py,sha256=OGFLfbL31N2wuwcXIxxQ14f0Kuuvv1BZkAuFi2c0ma4,14560
30
30
  code_loader/plot_functions/visualize.py,sha256=gsBAYYkwMh7jIpJeDMPS8G4CW-pxwx6LznoQIvi4vpo,657
31
31
  code_loader/utils.py,sha256=gXENTYpjdidq2dx0gVbXlErPeHoNs-4TYAZbLRe0y2c,2712
32
32
  code_loader/visualizers/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
33
33
  code_loader/visualizers/default_visualizers.py,sha256=onRnLE_TXfgLN4o52hQIOOhUcFexGlqJ3xSpQDVLuZM,2604
34
- code_loader-1.0.139.dev5.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
35
- code_loader-1.0.139.dev5.dist-info/METADATA,sha256=VuBCYX1zRt_iDqU9pMv0cixcnB8b39BvSRkNXOW6N_8,1095
36
- code_loader-1.0.139.dev5.dist-info/WHEEL,sha256=Nq82e9rUAnEjt98J6MlVmMCZb-t9cYE2Ir1kpBmnWfs,88
37
- code_loader-1.0.139.dev5.dist-info/RECORD,,
34
+ code_loader-1.0.153.dev3.dist-info/LICENSE,sha256=qIwWjdspQeSMTtnFZBC8MuT-95L02FPvzRUdWFxrwJY,1067
35
+ code_loader-1.0.153.dev3.dist-info/METADATA,sha256=5WV-VTDLoQlNwrAhsjWMtS71nwsnjb9v_EDAt4FlVT0,1095
36
+ code_loader-1.0.153.dev3.dist-info/WHEEL,sha256=sP946D7jFCHeNz5Iq4fL4Lu-PrWrFsgfLXbbkciIZwg,88
37
+ code_loader-1.0.153.dev3.dist-info/RECORD,,
@@ -1,4 +1,4 @@
1
1
  Wheel-Version: 1.0
2
- Generator: poetry-core 1.9.1
2
+ Generator: poetry-core 1.9.0
3
3
  Root-Is-Purelib: true
4
4
  Tag: py3-none-any