workbench 0.8.172__py3-none-any.whl → 0.8.174__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 (36) hide show
  1. workbench/algorithms/graph/light/proximity_graph.py +2 -1
  2. workbench/api/compound.py +1 -1
  3. workbench/api/monitor.py +1 -16
  4. workbench/core/artifacts/data_capture_core.py +348 -0
  5. workbench/core/artifacts/endpoint_core.py +9 -3
  6. workbench/core/artifacts/monitor_core.py +33 -249
  7. workbench/core/transforms/data_to_features/light/molecular_descriptors.py +4 -4
  8. workbench/model_scripts/custom_models/chem_info/mol_descriptors.py +471 -0
  9. workbench/model_scripts/custom_models/chem_info/mol_standardize.py +428 -0
  10. workbench/model_scripts/custom_models/chem_info/molecular_descriptors.py +7 -9
  11. workbench/model_scripts/custom_models/uq_models/generated_model_script.py +95 -204
  12. workbench/model_scripts/xgb_model/generated_model_script.py +5 -5
  13. workbench/repl/workbench_shell.py +3 -3
  14. workbench/utils/chem_utils/__init__.py +0 -0
  15. workbench/utils/chem_utils/fingerprints.py +134 -0
  16. workbench/utils/chem_utils/misc.py +194 -0
  17. workbench/utils/chem_utils/mol_descriptors.py +471 -0
  18. workbench/utils/chem_utils/mol_standardize.py +428 -0
  19. workbench/utils/chem_utils/mol_tagging.py +348 -0
  20. workbench/utils/chem_utils/projections.py +209 -0
  21. workbench/utils/chem_utils/salts.py +256 -0
  22. workbench/utils/chem_utils/sdf.py +292 -0
  23. workbench/utils/chem_utils/toxicity.py +250 -0
  24. workbench/utils/chem_utils/vis.py +253 -0
  25. workbench/utils/monitor_utils.py +44 -62
  26. workbench/utils/pandas_utils.py +3 -3
  27. workbench/web_interface/components/plugins/generated_compounds.py +1 -1
  28. {workbench-0.8.172.dist-info → workbench-0.8.174.dist-info}/METADATA +1 -1
  29. {workbench-0.8.172.dist-info → workbench-0.8.174.dist-info}/RECORD +33 -22
  30. workbench/model_scripts/custom_models/chem_info/local_utils.py +0 -769
  31. workbench/model_scripts/custom_models/chem_info/tautomerize.py +0 -83
  32. workbench/utils/chem_utils.py +0 -1556
  33. {workbench-0.8.172.dist-info → workbench-0.8.174.dist-info}/WHEEL +0 -0
  34. {workbench-0.8.172.dist-info → workbench-0.8.174.dist-info}/entry_points.txt +0 -0
  35. {workbench-0.8.172.dist-info → workbench-0.8.174.dist-info}/licenses/LICENSE +0 -0
  36. {workbench-0.8.172.dist-info → workbench-0.8.174.dist-info}/top_level.txt +0 -0
@@ -135,7 +135,8 @@ if __name__ == "__main__":
135
135
  from workbench.algorithms.dataframe.fingerprint_proximity import FingerprintProximity
136
136
  from workbench.web_interface.components.plugins.graph_plot import GraphPlot
137
137
  from workbench.api import DFStore
138
- from workbench.utils.chem_utils import compute_morgan_fingerprints, project_fingerprints
138
+ from workbench.utils.chem_utils.fingerprints import compute_morgan_fingerprints
139
+ from workbench.utils.chem_utils.projections import project_fingerprints
139
140
  from workbench.utils.graph_utils import connected_sample, graph_layout
140
141
 
141
142
  def show_graph(graph, id_column):
workbench/api/compound.py CHANGED
@@ -3,7 +3,7 @@ import logging
3
3
  from typing import List
4
4
 
5
5
  # Workbench Imports
6
- from workbench.utils.chem_utils import svg_from_smiles
6
+ from workbench.utils.chem_utils.vis import svg_from_smiles
7
7
 
8
8
 
9
9
  @dataclass
workbench/api/monitor.py CHANGED
@@ -15,7 +15,7 @@ class Monitor(MonitorCore):
15
15
 
16
16
  Common Usage:
17
17
  ```
18
- mon = Endpoint(name).get_monitor() # Pull from endpoint OR
18
+ mon = Endpoint(name).monitor() # Pull from endpoint OR
19
19
  mon = Monitor(name) # Create using Endpoint Name
20
20
  mon.summary()
21
21
  mon.details()
@@ -29,7 +29,6 @@ class Monitor(MonitorCore):
29
29
  baseline_df = mon.get_baseline()
30
30
  constraints_df = mon.get_constraints()
31
31
  stats_df = mon.get_statistics()
32
- input_df, output_df = mon.get_captured_data()
33
32
  ```
34
33
  """
35
34
 
@@ -81,15 +80,6 @@ class Monitor(MonitorCore):
81
80
  """
82
81
  super().create_monitoring_schedule(schedule)
83
82
 
84
- def get_captured_data(self) -> (pd.DataFrame, pd.DataFrame):
85
- """
86
- Get the latest data capture input and output from S3.
87
-
88
- Returns:
89
- DataFrame (input), DataFrame(output): Flattened and processed DataFrames for input and output data.
90
- """
91
- return super().get_captured_data()
92
-
93
83
  def get_baseline(self) -> Union[pd.DataFrame, None]:
94
84
  """Code to get the baseline CSV from the S3 baseline directory
95
85
 
@@ -155,8 +145,3 @@ if __name__ == "__main__":
155
145
 
156
146
  print("\nStatistics...")
157
147
  print(mm.get_statistics())
158
-
159
- # Get the latest data capture
160
- input_df, output_df = mm.get_captured_data()
161
- print(input_df.head())
162
- print(output_df.head())
@@ -0,0 +1,348 @@
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
+ files.sort()
235
+
236
+ # Get all timestamps in one batch if needed
237
+ timestamps = {}
238
+ if add_timestamp:
239
+ # Batch describe operation - much more efficient than per-file calls
240
+ timestamps = wr.s3.describe_objects(path=files)
241
+
242
+ # Process files using concurrent.futures
243
+ start_time = time.time()
244
+
245
+ def process_single_file(file_path):
246
+ """Process a single file and return input/output DataFrames."""
247
+ try:
248
+ log.debug(f"Processing file: {file_path}...")
249
+ df = wr.s3.read_json(path=file_path, lines=True)
250
+ if not df.empty:
251
+ input_df, output_df = process_data_capture(df)
252
+ if add_timestamp and file_path in timestamps:
253
+ output_df["timestamp"] = timestamps[file_path]["LastModified"]
254
+ return input_df, output_df
255
+ return pd.DataFrame(), pd.DataFrame()
256
+ except Exception as e:
257
+ self.log.warning(f"Error processing {file_path}: {e}")
258
+ return pd.DataFrame(), pd.DataFrame()
259
+
260
+ # Use ThreadPoolExecutor for I/O-bound operations
261
+ from concurrent.futures import ThreadPoolExecutor
262
+
263
+ max_workers = min(32, len(files)) # Cap at 32 threads or number of files
264
+
265
+ all_input_dfs, all_output_dfs = [], []
266
+ with ThreadPoolExecutor(max_workers=max_workers) as executor:
267
+ futures = [executor.submit(process_single_file, file_path) for file_path in files]
268
+ for future in futures:
269
+ input_df, output_df = future.result()
270
+ if not input_df.empty:
271
+ all_input_dfs.append(input_df)
272
+ if not output_df.empty:
273
+ all_output_dfs.append(output_df)
274
+
275
+ if not all_input_dfs:
276
+ self.log.warning("No valid data was processed.")
277
+ return pd.DataFrame(), pd.DataFrame()
278
+
279
+ input_df = pd.concat(all_input_dfs, ignore_index=True)
280
+ output_df = pd.concat(all_output_dfs, ignore_index=True)
281
+
282
+ elapsed_time = time.time() - start_time
283
+ self.log.info(f"Processed {len(files)} files in {elapsed_time:.2f} seconds.")
284
+ return input_df, output_df
285
+
286
+ def _file_date_filter(self, file_path, from_date_obj):
287
+ """Extract date from S3 path and compare with from_date."""
288
+ try:
289
+ # Match YYYY/MM/DD pattern in the path
290
+ date_match = re.search(r"/(\d{4})/(\d{2})/(\d{2})/", file_path)
291
+ if date_match:
292
+ year, month, day = date_match.groups()
293
+ file_date = datetime(int(year), int(month), int(day)).date()
294
+ return file_date >= from_date_obj
295
+ return False # No date pattern found
296
+ except ValueError:
297
+ return False
298
+
299
+ def __repr__(self) -> str:
300
+ """String representation of this DataCaptureCore object
301
+
302
+ Returns:
303
+ str: String representation of this DataCaptureCore object
304
+ """
305
+ summary_dict = self.summary()
306
+ summary_items = [f" {repr(key)}: {repr(value)}" for key, value in summary_dict.items()]
307
+ summary_str = f"{self.__class__.__name__}: {self.endpoint_name}\n" + ",\n".join(summary_items)
308
+ return summary_str
309
+
310
+
311
+ # Test function for the class
312
+ if __name__ == "__main__":
313
+ """Exercise the MonitorCore class"""
314
+ from pprint import pprint
315
+
316
+ # Set options for actually seeing the dataframe
317
+ pd.set_option("display.max_columns", None)
318
+ pd.set_option("display.width", None)
319
+
320
+ # Create the Class and test it out
321
+ endpoint_name = "abalone-regression-rt"
322
+ my_endpoint = EndpointCore(endpoint_name)
323
+ if not my_endpoint.exists():
324
+ print(f"Endpoint {endpoint_name} does not exist.")
325
+ exit(1)
326
+ dc = my_endpoint.data_capture()
327
+
328
+ # Check the summary of the data capture class
329
+ pprint(dc.summary())
330
+
331
+ # Enable data capture on the endpoint
332
+ # dc.enable(force_redeploy=True)
333
+ my_endpoint.enable_data_capture()
334
+
335
+ # Test the data capture by running some predictions
336
+ # pred_df = my_endpoint.auto_inference()
337
+ # print(pred_df.head())
338
+
339
+ # Check that data capture is working
340
+ input_df, output_df = dc.get_captured_data()
341
+ if input_df.empty and output_df.empty:
342
+ print("No data capture files found, for a new endpoint it may take a few minutes to start capturing data")
343
+ else:
344
+ print("Found data capture files")
345
+ print("Input")
346
+ print(input_df.head())
347
+ print("Output")
348
+ print(output_df.head())
@@ -164,11 +164,17 @@ class EndpointCore(Artifact):
164
164
  """
165
165
  return "Serverless" in self.endpoint_meta["InstanceType"]
166
166
 
167
- def add_data_capture(self):
167
+ def data_capture(self):
168
+ """Get the MonitorCore class for this endpoint"""
169
+ from workbench.core.artifacts.data_capture_core import DataCaptureCore
170
+
171
+ return DataCaptureCore(self.endpoint_name)
172
+
173
+ def enable_data_capture(self):
168
174
  """Add data capture to the endpoint"""
169
- self.get_monitor().add_data_capture()
175
+ self.data_capture().enable()
170
176
 
171
- def get_monitor(self):
177
+ def monitor(self):
172
178
  """Get the MonitorCore class for this endpoint"""
173
179
  from workbench.core.artifacts.monitor_core import MonitorCore
174
180