workbench 0.8.161__py3-none-any.whl → 0.8.192__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 (96) hide show
  1. workbench/algorithms/dataframe/proximity.py +143 -102
  2. workbench/algorithms/graph/light/proximity_graph.py +2 -1
  3. workbench/api/compound.py +1 -1
  4. workbench/api/endpoint.py +12 -0
  5. workbench/api/feature_set.py +4 -4
  6. workbench/api/meta.py +5 -2
  7. workbench/api/model.py +16 -12
  8. workbench/api/monitor.py +1 -16
  9. workbench/core/artifacts/artifact.py +11 -3
  10. workbench/core/artifacts/data_capture_core.py +355 -0
  11. workbench/core/artifacts/endpoint_core.py +168 -78
  12. workbench/core/artifacts/feature_set_core.py +72 -13
  13. workbench/core/artifacts/model_core.py +50 -15
  14. workbench/core/artifacts/monitor_core.py +33 -248
  15. workbench/core/cloud_platform/aws/aws_account_clamp.py +50 -1
  16. workbench/core/cloud_platform/aws/aws_meta.py +12 -5
  17. workbench/core/cloud_platform/aws/aws_session.py +4 -4
  18. workbench/core/transforms/data_to_features/light/molecular_descriptors.py +4 -4
  19. workbench/core/transforms/features_to_model/features_to_model.py +9 -4
  20. workbench/core/transforms/model_to_endpoint/model_to_endpoint.py +36 -6
  21. workbench/core/transforms/pandas_transforms/pandas_to_features.py +27 -0
  22. workbench/core/views/training_view.py +49 -53
  23. workbench/core/views/view.py +51 -1
  24. workbench/core/views/view_utils.py +4 -4
  25. workbench/model_scripts/custom_models/chem_info/mol_descriptors.py +483 -0
  26. workbench/model_scripts/custom_models/chem_info/mol_standardize.py +450 -0
  27. workbench/model_scripts/custom_models/chem_info/molecular_descriptors.py +7 -9
  28. workbench/model_scripts/custom_models/proximity/feature_space_proximity.template +3 -5
  29. workbench/model_scripts/custom_models/proximity/proximity.py +143 -102
  30. workbench/model_scripts/custom_models/uq_models/bayesian_ridge.template +7 -8
  31. workbench/model_scripts/custom_models/uq_models/ensemble_xgb.template +10 -17
  32. workbench/model_scripts/custom_models/uq_models/gaussian_process.template +5 -11
  33. workbench/model_scripts/custom_models/uq_models/meta_uq.template +156 -58
  34. workbench/model_scripts/custom_models/uq_models/ngboost.template +20 -14
  35. workbench/model_scripts/custom_models/uq_models/proximity.py +143 -102
  36. workbench/model_scripts/custom_models/uq_models/requirements.txt +1 -3
  37. workbench/model_scripts/ensemble_xgb/ensemble_xgb.template +5 -13
  38. workbench/model_scripts/pytorch_model/pytorch.template +19 -20
  39. workbench/model_scripts/scikit_learn/scikit_learn.template +4 -9
  40. workbench/model_scripts/script_generation.py +7 -2
  41. workbench/model_scripts/uq_models/mapie.template +492 -0
  42. workbench/model_scripts/uq_models/requirements.txt +1 -0
  43. workbench/model_scripts/xgb_model/xgb_model.template +31 -40
  44. workbench/repl/workbench_shell.py +11 -6
  45. workbench/scripts/lambda_launcher.py +63 -0
  46. workbench/scripts/ml_pipeline_batch.py +137 -0
  47. workbench/scripts/ml_pipeline_sqs.py +186 -0
  48. workbench/scripts/monitor_cloud_watch.py +20 -100
  49. workbench/utils/aws_utils.py +4 -3
  50. workbench/utils/chem_utils/__init__.py +0 -0
  51. workbench/utils/chem_utils/fingerprints.py +134 -0
  52. workbench/utils/chem_utils/misc.py +194 -0
  53. workbench/utils/chem_utils/mol_descriptors.py +483 -0
  54. workbench/utils/chem_utils/mol_standardize.py +450 -0
  55. workbench/utils/chem_utils/mol_tagging.py +348 -0
  56. workbench/utils/chem_utils/projections.py +209 -0
  57. workbench/utils/chem_utils/salts.py +256 -0
  58. workbench/utils/chem_utils/sdf.py +292 -0
  59. workbench/utils/chem_utils/toxicity.py +250 -0
  60. workbench/utils/chem_utils/vis.py +253 -0
  61. workbench/utils/cloudwatch_handler.py +1 -1
  62. workbench/utils/cloudwatch_utils.py +137 -0
  63. workbench/utils/config_manager.py +3 -7
  64. workbench/utils/endpoint_utils.py +5 -7
  65. workbench/utils/license_manager.py +2 -6
  66. workbench/utils/model_utils.py +76 -30
  67. workbench/utils/monitor_utils.py +44 -62
  68. workbench/utils/pandas_utils.py +3 -3
  69. workbench/utils/shap_utils.py +10 -2
  70. workbench/utils/workbench_logging.py +0 -3
  71. workbench/utils/workbench_sqs.py +1 -1
  72. workbench/utils/xgboost_model_utils.py +283 -145
  73. workbench/web_interface/components/plugins/dashboard_status.py +3 -1
  74. workbench/web_interface/components/plugins/generated_compounds.py +1 -1
  75. workbench/web_interface/components/plugins/scatter_plot.py +3 -3
  76. {workbench-0.8.161.dist-info → workbench-0.8.192.dist-info}/METADATA +4 -4
  77. {workbench-0.8.161.dist-info → workbench-0.8.192.dist-info}/RECORD +81 -76
  78. {workbench-0.8.161.dist-info → workbench-0.8.192.dist-info}/entry_points.txt +3 -0
  79. workbench/model_scripts/custom_models/chem_info/local_utils.py +0 -769
  80. workbench/model_scripts/custom_models/chem_info/tautomerize.py +0 -83
  81. workbench/model_scripts/custom_models/proximity/generated_model_script.py +0 -138
  82. workbench/model_scripts/custom_models/uq_models/generated_model_script.py +0 -393
  83. workbench/model_scripts/custom_models/uq_models/mapie_xgb.template +0 -203
  84. workbench/model_scripts/ensemble_xgb/generated_model_script.py +0 -279
  85. workbench/model_scripts/pytorch_model/generated_model_script.py +0 -565
  86. workbench/model_scripts/quant_regression/quant_regression.template +0 -279
  87. workbench/model_scripts/quant_regression/requirements.txt +0 -1
  88. workbench/model_scripts/scikit_learn/generated_model_script.py +0 -307
  89. workbench/model_scripts/xgb_model/generated_model_script.py +0 -477
  90. workbench/utils/chem_utils.py +0 -1556
  91. workbench/utils/execution_environment.py +0 -211
  92. workbench/utils/fast_inference.py +0 -167
  93. workbench/utils/resource_utils.py +0 -39
  94. {workbench-0.8.161.dist-info → workbench-0.8.192.dist-info}/WHEEL +0 -0
  95. {workbench-0.8.161.dist-info → workbench-0.8.192.dist-info}/licenses/LICENSE +0 -0
  96. {workbench-0.8.161.dist-info → workbench-0.8.192.dist-info}/top_level.txt +0 -0
@@ -236,6 +236,12 @@ class Artifact(ABC):
236
236
  This functionality will work for FeatureSets, Models, and Endpoints
237
237
  but not for DataSources. The DataSource class overrides this method.
238
238
  """
239
+
240
+ # Check for ReadOnly Role
241
+ if self.aws_account_clamp.read_only:
242
+ self.log.info("Cannot add metadata with a ReadOnly Permissions...")
243
+ return
244
+
239
245
  # Sanity check
240
246
  aws_arn = self.arn()
241
247
  if aws_arn is None:
@@ -444,10 +450,12 @@ class Artifact(ABC):
444
450
 
445
451
  if __name__ == "__main__":
446
452
  """Exercise the Artifact Class"""
447
- from workbench.api.data_source import DataSource
448
- from workbench.api.feature_set import FeatureSet
453
+ from workbench.api import DataSource, FeatureSet, Endpoint
454
+
455
+ # Grab an Endpoint (which is a subclass of Artifact)
456
+ end = Endpoint("wine-classification")
449
457
 
450
- # Create a DataSource (which is a subclass of Artifact)
458
+ # Grab a DataSource (which is a subclass of Artifact)
451
459
  data_source = DataSource("test_data")
452
460
 
453
461
  # Just some random tests
@@ -0,0 +1,355 @@
1
+ """DataCaptureCore class for managing SageMaker endpoint data capture"""
2
+
3
+ import logging
4
+ import re
5
+ import time
6
+ from datetime import datetime
7
+ from typing import Tuple
8
+ import pandas as pd
9
+ from sagemaker import Predictor
10
+ from sagemaker.model_monitor import DataCaptureConfig
11
+ import awswrangler as wr
12
+
13
+ # Workbench Imports
14
+ from workbench.core.artifacts.endpoint_core import EndpointCore
15
+ from workbench.core.cloud_platform.aws.aws_account_clamp import AWSAccountClamp
16
+ from workbench.utils.monitor_utils import process_data_capture
17
+
18
+ # Setup logging
19
+ log = logging.getLogger("workbench")
20
+
21
+
22
+ class DataCaptureCore:
23
+ """Manages data capture configuration and retrieval for SageMaker endpoints"""
24
+
25
+ def __init__(self, endpoint_name: str):
26
+ """DataCaptureCore Class
27
+
28
+ Args:
29
+ endpoint_name (str): Name of the endpoint to manage data capture for
30
+ """
31
+ self.log = logging.getLogger("workbench")
32
+ self.endpoint_name = endpoint_name
33
+ self.endpoint = EndpointCore(self.endpoint_name)
34
+
35
+ # Initialize Class Attributes
36
+ self.sagemaker_session = self.endpoint.sm_session
37
+ self.sagemaker_client = self.endpoint.sm_client
38
+ self.data_capture_path = self.endpoint.endpoint_data_capture_path
39
+ self.workbench_role_arn = AWSAccountClamp().aws_session.get_workbench_execution_role_arn()
40
+
41
+ def summary(self) -> dict:
42
+ """Return the summary of data capture configuration
43
+
44
+ Returns:
45
+ dict: Summary of data capture status
46
+ """
47
+ if self.endpoint.is_serverless():
48
+ return {"endpoint_type": "serverless", "data_capture": "not supported"}
49
+ else:
50
+ return {
51
+ "endpoint_type": "realtime",
52
+ "data_capture_enabled": self.is_enabled(),
53
+ "capture_percentage": self.capture_percentage(),
54
+ "capture_modes": self.capture_modes() if self.is_enabled() else [],
55
+ "data_capture_path": self.data_capture_path if self.is_enabled() else None,
56
+ }
57
+
58
+ def enable(self, capture_percentage=100, capture_options=None, force_redeploy=False):
59
+ """
60
+ Enable data capture for the SageMaker endpoint.
61
+
62
+ Args:
63
+ capture_percentage (int): Percentage of data to capture. Defaults to 100.
64
+ capture_options (list): List of what to capture - ["REQUEST"], ["RESPONSE"], or ["REQUEST", "RESPONSE"].
65
+ Defaults to ["REQUEST", "RESPONSE"] to capture both.
66
+ force_redeploy (bool): If True, force redeployment even if data capture is already enabled.
67
+ """
68
+ # Early returns for cases where we can't/don't need to add data capture
69
+ if self.endpoint.is_serverless():
70
+ self.log.warning("Data capture is not supported for serverless endpoints.")
71
+ return
72
+
73
+ # Default to capturing both if not specified
74
+ if capture_options is None:
75
+ capture_options = ["REQUEST", "RESPONSE"]
76
+
77
+ # Validate capture_options
78
+ valid_options = {"REQUEST", "RESPONSE"}
79
+ if not all(opt in valid_options for opt in capture_options):
80
+ self.log.error("Invalid capture_options. Must be a list containing 'REQUEST' and/or 'RESPONSE'")
81
+ return
82
+
83
+ if self.is_enabled() and not force_redeploy:
84
+ self.log.important(f"Data capture already configured for {self.endpoint_name}.")
85
+ return
86
+
87
+ # Get the current endpoint configuration name for later deletion
88
+ current_endpoint_config_name = self.endpoint.endpoint_config_name()
89
+
90
+ # Log the data capture operation
91
+ self.log.important(f"Enabling Data Capture for {self.endpoint_name} --> {self.data_capture_path}")
92
+ self.log.important(f"Capturing: {', '.join(capture_options)} at {capture_percentage}% sampling")
93
+ self.log.important("This will redeploy the endpoint...")
94
+
95
+ # Create and apply the data capture configuration
96
+ data_capture_config = DataCaptureConfig(
97
+ enable_capture=True,
98
+ sampling_percentage=capture_percentage,
99
+ destination_s3_uri=self.data_capture_path,
100
+ capture_options=capture_options,
101
+ )
102
+
103
+ # Update endpoint with the new capture configuration
104
+ Predictor(self.endpoint_name, sagemaker_session=self.sagemaker_session).update_data_capture_config(
105
+ data_capture_config=data_capture_config
106
+ )
107
+
108
+ # Clean up old endpoint configuration
109
+ try:
110
+ self.sagemaker_client.delete_endpoint_config(EndpointConfigName=current_endpoint_config_name)
111
+ self.log.info(f"Deleted old endpoint configuration: {current_endpoint_config_name}")
112
+ except Exception as e:
113
+ self.log.warning(f"Could not delete old endpoint configuration {current_endpoint_config_name}: {e}")
114
+
115
+ def disable(self):
116
+ """
117
+ Disable data capture for the SageMaker endpoint.
118
+ """
119
+ # Early return if data capture isn't configured
120
+ if not self.is_enabled():
121
+ self.log.important(f"Data capture is not currently enabled for {self.endpoint_name}.")
122
+ return
123
+
124
+ # Get the current endpoint configuration name for later deletion
125
+ current_endpoint_config_name = self.endpoint.endpoint_config_name()
126
+
127
+ # Log the operation
128
+ self.log.important(f"Disabling Data Capture for {self.endpoint_name}")
129
+ self.log.important("This normally redeploys the endpoint...")
130
+
131
+ # Create a configuration with capture disabled
132
+ data_capture_config = DataCaptureConfig(enable_capture=False, destination_s3_uri=self.data_capture_path)
133
+
134
+ # Update endpoint with the new configuration
135
+ Predictor(self.endpoint_name, sagemaker_session=self.sagemaker_session).update_data_capture_config(
136
+ data_capture_config=data_capture_config
137
+ )
138
+
139
+ # Clean up old endpoint configuration
140
+ self.sagemaker_client.delete_endpoint_config(EndpointConfigName=current_endpoint_config_name)
141
+
142
+ def is_enabled(self) -> bool:
143
+ """
144
+ Check if data capture is enabled on the endpoint.
145
+
146
+ Returns:
147
+ bool: True if data capture is enabled, False otherwise.
148
+ """
149
+ try:
150
+ endpoint_config_name = self.endpoint.endpoint_config_name()
151
+ endpoint_config = self.sagemaker_client.describe_endpoint_config(EndpointConfigName=endpoint_config_name)
152
+ data_capture_config = endpoint_config.get("DataCaptureConfig", {})
153
+
154
+ # Check if data capture is enabled
155
+ is_enabled = data_capture_config.get("EnableCapture", False)
156
+ return is_enabled
157
+ except Exception as e:
158
+ self.log.error(f"Error checking data capture configuration: {e}")
159
+ return False
160
+
161
+ def capture_percentage(self) -> int:
162
+ """
163
+ Get the data capture percentage from the endpoint configuration.
164
+
165
+ Returns:
166
+ int: Data capture percentage if enabled, None otherwise.
167
+ """
168
+ try:
169
+ endpoint_config_name = self.endpoint.endpoint_config_name()
170
+ endpoint_config = self.sagemaker_client.describe_endpoint_config(EndpointConfigName=endpoint_config_name)
171
+ data_capture_config = endpoint_config.get("DataCaptureConfig", {})
172
+
173
+ # Check if data capture is enabled and return the percentage
174
+ if data_capture_config.get("EnableCapture", False):
175
+ return data_capture_config.get("InitialSamplingPercentage", 0)
176
+ else:
177
+ return None
178
+ except Exception as e:
179
+ self.log.error(f"Error checking data capture percentage: {e}")
180
+ return None
181
+
182
+ def get_config(self) -> dict:
183
+ """
184
+ Returns the complete data capture configuration from the endpoint config.
185
+
186
+ Returns:
187
+ dict: Complete DataCaptureConfig from AWS, or None if not configured
188
+ """
189
+ config_name = self.endpoint.endpoint_config_name()
190
+ response = self.sagemaker_client.describe_endpoint_config(EndpointConfigName=config_name)
191
+ data_capture_config = response.get("DataCaptureConfig")
192
+ if not data_capture_config:
193
+ self.log.error(f"No data capture configuration found for endpoint config {config_name}")
194
+ return None
195
+ return data_capture_config
196
+
197
+ def capture_modes(self) -> list:
198
+ """Get the current capture modes (REQUEST/RESPONSE)"""
199
+ if not self.is_enabled():
200
+ return []
201
+
202
+ config = self.get_config()
203
+ if not config:
204
+ return []
205
+
206
+ capture_options = config.get("CaptureOptions", [])
207
+ modes = [opt.get("CaptureMode") for opt in capture_options]
208
+ return ["REQUEST" if m == "Input" else "RESPONSE" for m in modes if m]
209
+
210
+ def get_captured_data(self, from_date: str = None, add_timestamp: bool = True) -> Tuple[pd.DataFrame, pd.DataFrame]:
211
+ """
212
+ Read and process captured data from S3.
213
+
214
+ Args:
215
+ from_date (str, optional): Only process files from this date onwards (YYYY-MM-DD format).
216
+ Defaults to None to process all files.
217
+ add_timestamp (bool, optional): Whether to add a timestamp column to the DataFrame.
218
+
219
+ Returns:
220
+ Tuple[pd.DataFrame, pd.DataFrame]: Processed input and output DataFrames.
221
+ """
222
+ files = wr.s3.list_objects(self.data_capture_path)
223
+ if not files:
224
+ self.log.warning(f"No data capture files found in {self.data_capture_path}.")
225
+ return pd.DataFrame(), pd.DataFrame()
226
+
227
+ # Filter by date if specified
228
+ if from_date:
229
+ from_date_obj = datetime.strptime(from_date, "%Y-%m-%d").date()
230
+ files = [f for f in files if self._file_date_filter(f, from_date_obj)]
231
+ self.log.info(f"Processing {len(files)} files from {from_date} onwards.")
232
+ else:
233
+ self.log.info(f"Processing all {len(files)} files...")
234
+
235
+ # Check if any files remain after filtering
236
+ if not files:
237
+ self.log.info("No files to process after date filtering.")
238
+ return pd.DataFrame(), pd.DataFrame()
239
+
240
+ # Sort files by name (assumed to include timestamp)
241
+ files.sort()
242
+
243
+ # Get all timestamps in one batch if needed
244
+ timestamps = {}
245
+ if add_timestamp:
246
+ # Batch describe operation - much more efficient than per-file calls
247
+ timestamps = wr.s3.describe_objects(path=files)
248
+
249
+ # Process files using concurrent.futures
250
+ start_time = time.time()
251
+
252
+ def process_single_file(file_path):
253
+ """Process a single file and return input/output DataFrames."""
254
+ try:
255
+ log.debug(f"Processing file: {file_path}...")
256
+ df = wr.s3.read_json(path=file_path, lines=True)
257
+ if not df.empty:
258
+ input_df, output_df = process_data_capture(df)
259
+ if add_timestamp and file_path in timestamps:
260
+ output_df["timestamp"] = timestamps[file_path]["LastModified"]
261
+ return input_df, output_df
262
+ return pd.DataFrame(), pd.DataFrame()
263
+ except Exception as e:
264
+ self.log.warning(f"Error processing {file_path}: {e}")
265
+ return pd.DataFrame(), pd.DataFrame()
266
+
267
+ # Use ThreadPoolExecutor for I/O-bound operations
268
+ from concurrent.futures import ThreadPoolExecutor
269
+
270
+ max_workers = min(32, len(files)) # Cap at 32 threads or number of files
271
+
272
+ all_input_dfs, all_output_dfs = [], []
273
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
274
+ futures = [executor.submit(process_single_file, file_path) for file_path in files]
275
+ for future in futures:
276
+ input_df, output_df = future.result()
277
+ if not input_df.empty:
278
+ all_input_dfs.append(input_df)
279
+ if not output_df.empty:
280
+ all_output_dfs.append(output_df)
281
+
282
+ if not all_input_dfs:
283
+ self.log.warning("No valid data was processed.")
284
+ return pd.DataFrame(), pd.DataFrame()
285
+
286
+ input_df = pd.concat(all_input_dfs, ignore_index=True)
287
+ output_df = pd.concat(all_output_dfs, ignore_index=True)
288
+
289
+ elapsed_time = time.time() - start_time
290
+ self.log.info(f"Processed {len(files)} files in {elapsed_time:.2f} seconds.")
291
+ return input_df, output_df
292
+
293
+ def _file_date_filter(self, file_path, from_date_obj):
294
+ """Extract date from S3 path and compare with from_date."""
295
+ try:
296
+ # Match YYYY/MM/DD pattern in the path
297
+ date_match = re.search(r"/(\d{4})/(\d{2})/(\d{2})/", file_path)
298
+ if date_match:
299
+ year, month, day = date_match.groups()
300
+ file_date = datetime(int(year), int(month), int(day)).date()
301
+ return file_date >= from_date_obj
302
+ return False # No date pattern found
303
+ except ValueError:
304
+ return False
305
+
306
+ def __repr__(self) -> str:
307
+ """String representation of this DataCaptureCore object
308
+
309
+ Returns:
310
+ str: String representation of this DataCaptureCore object
311
+ """
312
+ summary_dict = self.summary()
313
+ summary_items = [f" {repr(key)}: {repr(value)}" for key, value in summary_dict.items()]
314
+ summary_str = f"{self.__class__.__name__}: {self.endpoint_name}\n" + ",\n".join(summary_items)
315
+ return summary_str
316
+
317
+
318
+ # Test function for the class
319
+ if __name__ == "__main__":
320
+ """Exercise the MonitorCore class"""
321
+ from pprint import pprint
322
+
323
+ # Set options for actually seeing the dataframe
324
+ pd.set_option("display.max_columns", None)
325
+ pd.set_option("display.width", None)
326
+
327
+ # Create the Class and test it out
328
+ endpoint_name = "abalone-regression-rt"
329
+ my_endpoint = EndpointCore(endpoint_name)
330
+ if not my_endpoint.exists():
331
+ print(f"Endpoint {endpoint_name} does not exist.")
332
+ exit(1)
333
+ dc = my_endpoint.data_capture()
334
+
335
+ # Check the summary of the data capture class
336
+ pprint(dc.summary())
337
+
338
+ # Enable data capture on the endpoint
339
+ # dc.enable(force_redeploy=True)
340
+ my_endpoint.enable_data_capture()
341
+
342
+ # Test the data capture by running some predictions
343
+ # pred_df = my_endpoint.auto_inference()
344
+ # print(pred_df.head())
345
+
346
+ # Check that data capture is working
347
+ input_df, output_df = dc.get_captured_data(from_date="2025-09-01")
348
+ if input_df.empty and output_df.empty:
349
+ print("No data capture files found, for a new endpoint it may take a few minutes to start capturing data")
350
+ else:
351
+ print("Found data capture files")
352
+ print("Input")
353
+ print(input_df.head())
354
+ print("Output")
355
+ print(output_df.head())