workbench 0.8.162__py3-none-any.whl → 0.8.202__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 workbench might be problematic. Click here for more details.

Files changed (113) hide show
  1. workbench/algorithms/dataframe/__init__.py +1 -2
  2. workbench/algorithms/dataframe/fingerprint_proximity.py +2 -2
  3. workbench/algorithms/dataframe/proximity.py +261 -235
  4. workbench/algorithms/graph/light/proximity_graph.py +10 -8
  5. workbench/api/__init__.py +2 -1
  6. workbench/api/compound.py +1 -1
  7. workbench/api/endpoint.py +11 -0
  8. workbench/api/feature_set.py +11 -8
  9. workbench/api/meta.py +5 -2
  10. workbench/api/model.py +16 -15
  11. workbench/api/monitor.py +1 -16
  12. workbench/core/artifacts/__init__.py +11 -2
  13. workbench/core/artifacts/artifact.py +11 -3
  14. workbench/core/artifacts/data_capture_core.py +355 -0
  15. workbench/core/artifacts/endpoint_core.py +256 -118
  16. workbench/core/artifacts/feature_set_core.py +265 -16
  17. workbench/core/artifacts/model_core.py +107 -60
  18. workbench/core/artifacts/monitor_core.py +33 -248
  19. workbench/core/cloud_platform/aws/aws_account_clamp.py +50 -1
  20. workbench/core/cloud_platform/aws/aws_meta.py +12 -5
  21. workbench/core/cloud_platform/aws/aws_parameter_store.py +18 -2
  22. workbench/core/cloud_platform/aws/aws_session.py +4 -4
  23. workbench/core/transforms/data_to_features/light/molecular_descriptors.py +4 -4
  24. workbench/core/transforms/features_to_model/features_to_model.py +42 -32
  25. workbench/core/transforms/model_to_endpoint/model_to_endpoint.py +36 -6
  26. workbench/core/transforms/pandas_transforms/pandas_to_features.py +27 -0
  27. workbench/core/views/training_view.py +113 -42
  28. workbench/core/views/view.py +53 -3
  29. workbench/core/views/view_utils.py +4 -4
  30. workbench/model_scripts/chemprop/chemprop.template +852 -0
  31. workbench/model_scripts/chemprop/generated_model_script.py +852 -0
  32. workbench/model_scripts/chemprop/requirements.txt +11 -0
  33. workbench/model_scripts/custom_models/chem_info/fingerprints.py +134 -0
  34. workbench/model_scripts/custom_models/chem_info/mol_descriptors.py +483 -0
  35. workbench/model_scripts/custom_models/chem_info/mol_standardize.py +450 -0
  36. workbench/model_scripts/custom_models/chem_info/molecular_descriptors.py +7 -9
  37. workbench/model_scripts/custom_models/chem_info/morgan_fingerprints.py +1 -1
  38. workbench/model_scripts/custom_models/proximity/feature_space_proximity.template +3 -5
  39. workbench/model_scripts/custom_models/proximity/proximity.py +261 -235
  40. workbench/model_scripts/custom_models/uq_models/bayesian_ridge.template +7 -8
  41. workbench/model_scripts/custom_models/uq_models/ensemble_xgb.template +20 -21
  42. workbench/model_scripts/custom_models/uq_models/gaussian_process.template +5 -11
  43. workbench/model_scripts/custom_models/uq_models/meta_uq.template +166 -62
  44. workbench/model_scripts/custom_models/uq_models/ngboost.template +30 -18
  45. workbench/model_scripts/custom_models/uq_models/proximity.py +261 -235
  46. workbench/model_scripts/custom_models/uq_models/requirements.txt +1 -3
  47. workbench/model_scripts/ensemble_xgb/ensemble_xgb.template +15 -17
  48. workbench/model_scripts/pytorch_model/generated_model_script.py +373 -190
  49. workbench/model_scripts/pytorch_model/pytorch.template +370 -187
  50. workbench/model_scripts/scikit_learn/generated_model_script.py +7 -12
  51. workbench/model_scripts/scikit_learn/scikit_learn.template +4 -9
  52. workbench/model_scripts/script_generation.py +17 -9
  53. workbench/model_scripts/uq_models/generated_model_script.py +605 -0
  54. workbench/model_scripts/uq_models/mapie.template +605 -0
  55. workbench/model_scripts/uq_models/requirements.txt +1 -0
  56. workbench/model_scripts/xgb_model/generated_model_script.py +37 -46
  57. workbench/model_scripts/xgb_model/xgb_model.template +44 -46
  58. workbench/repl/workbench_shell.py +28 -14
  59. workbench/scripts/endpoint_test.py +162 -0
  60. workbench/scripts/lambda_test.py +73 -0
  61. workbench/scripts/ml_pipeline_batch.py +137 -0
  62. workbench/scripts/ml_pipeline_sqs.py +186 -0
  63. workbench/scripts/monitor_cloud_watch.py +20 -100
  64. workbench/utils/aws_utils.py +4 -3
  65. workbench/utils/chem_utils/__init__.py +0 -0
  66. workbench/utils/chem_utils/fingerprints.py +134 -0
  67. workbench/utils/chem_utils/misc.py +194 -0
  68. workbench/utils/chem_utils/mol_descriptors.py +483 -0
  69. workbench/utils/chem_utils/mol_standardize.py +450 -0
  70. workbench/utils/chem_utils/mol_tagging.py +348 -0
  71. workbench/utils/chem_utils/projections.py +209 -0
  72. workbench/utils/chem_utils/salts.py +256 -0
  73. workbench/utils/chem_utils/sdf.py +292 -0
  74. workbench/utils/chem_utils/toxicity.py +250 -0
  75. workbench/utils/chem_utils/vis.py +253 -0
  76. workbench/utils/chemprop_utils.py +760 -0
  77. workbench/utils/cloudwatch_handler.py +1 -1
  78. workbench/utils/cloudwatch_utils.py +137 -0
  79. workbench/utils/config_manager.py +3 -7
  80. workbench/utils/endpoint_utils.py +5 -7
  81. workbench/utils/license_manager.py +2 -6
  82. workbench/utils/model_utils.py +95 -34
  83. workbench/utils/monitor_utils.py +44 -62
  84. workbench/utils/pandas_utils.py +3 -3
  85. workbench/utils/pytorch_utils.py +526 -0
  86. workbench/utils/shap_utils.py +10 -2
  87. workbench/utils/workbench_logging.py +0 -3
  88. workbench/utils/workbench_sqs.py +1 -1
  89. workbench/utils/xgboost_model_utils.py +371 -156
  90. workbench/web_interface/components/model_plot.py +7 -1
  91. workbench/web_interface/components/plugin_unit_test.py +5 -2
  92. workbench/web_interface/components/plugins/dashboard_status.py +3 -1
  93. workbench/web_interface/components/plugins/generated_compounds.py +1 -1
  94. workbench/web_interface/components/plugins/model_details.py +9 -7
  95. workbench/web_interface/components/plugins/scatter_plot.py +3 -3
  96. {workbench-0.8.162.dist-info → workbench-0.8.202.dist-info}/METADATA +27 -6
  97. {workbench-0.8.162.dist-info → workbench-0.8.202.dist-info}/RECORD +101 -85
  98. {workbench-0.8.162.dist-info → workbench-0.8.202.dist-info}/entry_points.txt +4 -0
  99. {workbench-0.8.162.dist-info → workbench-0.8.202.dist-info}/licenses/LICENSE +1 -1
  100. workbench/model_scripts/custom_models/chem_info/local_utils.py +0 -769
  101. workbench/model_scripts/custom_models/chem_info/tautomerize.py +0 -83
  102. workbench/model_scripts/custom_models/proximity/generated_model_script.py +0 -138
  103. workbench/model_scripts/custom_models/uq_models/generated_model_script.py +0 -393
  104. workbench/model_scripts/custom_models/uq_models/mapie_xgb.template +0 -203
  105. workbench/model_scripts/ensemble_xgb/generated_model_script.py +0 -279
  106. workbench/model_scripts/quant_regression/quant_regression.template +0 -279
  107. workbench/model_scripts/quant_regression/requirements.txt +0 -1
  108. workbench/utils/chem_utils.py +0 -1556
  109. workbench/utils/execution_environment.py +0 -211
  110. workbench/utils/fast_inference.py +0 -167
  111. workbench/utils/resource_utils.py +0 -39
  112. {workbench-0.8.162.dist-info → workbench-0.8.202.dist-info}/WHEEL +0 -0
  113. {workbench-0.8.162.dist-info → workbench-0.8.202.dist-info}/top_level.txt +0 -0
@@ -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())