sapiopycommons 2025.7.23a659__py3-none-any.whl → 2025.7.31a664__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 sapiopycommons might be problematic. Click here for more details.

Files changed (34) hide show
  1. sapiopycommons/ai/tool_of_tools.py +809 -0
  2. sapiopycommons/callbacks/callback_util.py +5 -2
  3. sapiopycommons/webhook/webservice_handlers.py +1 -1
  4. {sapiopycommons-2025.7.23a659.dist-info → sapiopycommons-2025.7.31a664.dist-info}/METADATA +1 -1
  5. {sapiopycommons-2025.7.23a659.dist-info → sapiopycommons-2025.7.31a664.dist-info}/RECORD +7 -33
  6. sapiopycommons/ai/api/fielddefinitions/proto/fields_pb2.py +0 -43
  7. sapiopycommons/ai/api/fielddefinitions/proto/fields_pb2.pyi +0 -31
  8. sapiopycommons/ai/api/fielddefinitions/proto/fields_pb2_grpc.py +0 -24
  9. sapiopycommons/ai/api/fielddefinitions/proto/velox_field_def_pb2.py +0 -123
  10. sapiopycommons/ai/api/fielddefinitions/proto/velox_field_def_pb2.pyi +0 -598
  11. sapiopycommons/ai/api/fielddefinitions/proto/velox_field_def_pb2_grpc.py +0 -24
  12. sapiopycommons/ai/api/plan/proto/step_output_pb2.py +0 -45
  13. sapiopycommons/ai/api/plan/proto/step_output_pb2.pyi +0 -42
  14. sapiopycommons/ai/api/plan/proto/step_output_pb2_grpc.py +0 -24
  15. sapiopycommons/ai/api/plan/proto/step_pb2.py +0 -43
  16. sapiopycommons/ai/api/plan/proto/step_pb2.pyi +0 -43
  17. sapiopycommons/ai/api/plan/proto/step_pb2_grpc.py +0 -24
  18. sapiopycommons/ai/api/plan/script/proto/script_pb2.py +0 -55
  19. sapiopycommons/ai/api/plan/script/proto/script_pb2.pyi +0 -115
  20. sapiopycommons/ai/api/plan/script/proto/script_pb2_grpc.py +0 -153
  21. sapiopycommons/ai/api/plan/tool/proto/entry_pb2.py +0 -57
  22. sapiopycommons/ai/api/plan/tool/proto/entry_pb2.pyi +0 -96
  23. sapiopycommons/ai/api/plan/tool/proto/entry_pb2_grpc.py +0 -24
  24. sapiopycommons/ai/api/plan/tool/proto/tool_pb2.py +0 -71
  25. sapiopycommons/ai/api/plan/tool/proto/tool_pb2.pyi +0 -250
  26. sapiopycommons/ai/api/plan/tool/proto/tool_pb2_grpc.py +0 -154
  27. sapiopycommons/ai/api/session/proto/sapio_conn_info_pb2.py +0 -39
  28. sapiopycommons/ai/api/session/proto/sapio_conn_info_pb2.pyi +0 -32
  29. sapiopycommons/ai/api/session/proto/sapio_conn_info_pb2_grpc.py +0 -24
  30. sapiopycommons/ai/protobuf_utils.py +0 -508
  31. sapiopycommons/ai/test_client.py +0 -288
  32. sapiopycommons/ai/tool_service_base.py +0 -916
  33. {sapiopycommons-2025.7.23a659.dist-info → sapiopycommons-2025.7.31a664.dist-info}/WHEEL +0 -0
  34. {sapiopycommons-2025.7.23a659.dist-info → sapiopycommons-2025.7.31a664.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,809 @@
1
+ import base64
2
+ import io
3
+ import math
4
+ import re
5
+ from typing import Final, Mapping, Any
6
+
7
+ import requests
8
+ from pandas import DataFrame
9
+ from requests import Response
10
+ from sapiopylib.rest.DataRecordManagerService import DataRecordManager
11
+ from sapiopylib.rest.DataTypeService import DataTypeManager
12
+ from sapiopylib.rest.ELNService import ElnManager
13
+ from sapiopylib.rest.User import SapioUser
14
+ from sapiopylib.rest.pojo.DataRecord import DataRecord
15
+ from sapiopylib.rest.pojo.Sort import SortDirection
16
+ from sapiopylib.rest.pojo.chartdata.DashboardDefinition import GaugeChartDefinition
17
+ from sapiopylib.rest.pojo.chartdata.DashboardEnums import ChartGroupingType, ChartOperationType
18
+ from sapiopylib.rest.pojo.chartdata.DashboardSeries import GaugeChartSeries
19
+ from sapiopylib.rest.pojo.datatype.DataType import DataTypeDefinition
20
+ from sapiopylib.rest.pojo.datatype.DataTypeLayout import DataTypeLayout, TableLayout
21
+ from sapiopylib.rest.pojo.datatype.FieldDefinition import AbstractVeloxFieldDefinition, FieldType
22
+ from sapiopylib.rest.pojo.eln.ElnEntryPosition import ElnEntryPosition
23
+ from sapiopylib.rest.pojo.eln.ElnExperiment import ElnExperiment
24
+ from sapiopylib.rest.pojo.eln.ExperimentEntry import ExperimentEntry
25
+ from sapiopylib.rest.pojo.eln.ExperimentEntryCriteria import ElnEntryCriteria, ElnFormEntryUpdateCriteria, \
26
+ ElnDashboardEntryUpdateCriteria, ElnTextEntryUpdateCriteria
27
+ from sapiopylib.rest.pojo.eln.SapioELNEnums import ElnEntryType, ElnBaseDataType
28
+ from sapiopylib.rest.pojo.eln.eln_headings import ElnExperimentTabAddCriteria, ElnExperimentTab
29
+ from sapiopylib.rest.pojo.eln.field_set import ElnFieldSetInfo
30
+ from sapiopylib.rest.utils.ProtocolUtils import ELNStepFactory
31
+ from sapiopylib.rest.utils.Protocols import ElnEntryStep, ElnExperimentProtocol
32
+
33
+ from sapiopycommons.callbacks.field_builder import FieldBuilder
34
+ from sapiopycommons.general.aliases import AliasUtil, SapioRecord
35
+ from sapiopycommons.general.exceptions import SapioException
36
+ from sapiopycommons.general.time_util import TimeUtil
37
+ from sapiopycommons.multimodal.multimodal import MultiModalManager
38
+ from sapiopycommons.multimodal.multimodal_data import ImageDataRequestPojo
39
+
40
+ CREDENTIALS_HEADER: Final[str] = "SAPIO_APP_API_KEY"
41
+ API_URL_HEADER: Final[str] = "SAPIO_APP_API_URL"
42
+ EXP_ID_HEADER: Final[str] = "EXPERIMENT_ID"
43
+ TAB_PREFIX_HEADER: Final[str] = "TAB_PREFIX"
44
+
45
+
46
+ # FR-47422: Create utility classes and methods to assist the tool of tools.
47
+ def create_tot_headers(url: str, username: str, password: str, experiment_id: int, tab_prefix: str) \
48
+ -> dict[str, str]:
49
+ """
50
+ Create the headers to be passed to a tool of tools endpoint.
51
+
52
+ :param url: The webservice URL of the system to make the changes in.
53
+ :param username: The username of the user making the changes.
54
+ :param password: The password of the user making the changes.
55
+ :param experiment_id: The ID of the experiment to make the changes in.
56
+ :param tab_prefix: The prefix to use for the tab name that will be created by the tool.
57
+ :return: The headers to be passed to the endpoint.
58
+ """
59
+ # Combine the credentials into the format "username:password"
60
+ credentials: str = f"{username}:{password}"
61
+ # Encode the credentials to bytes, then encode them using base64,
62
+ # and finally convert the result back into a string.
63
+ encoded_credentials: str = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
64
+ # Remove the trailing slash from the URL if it exists.
65
+ if url.endswith("/"):
66
+ url.rstrip("/")
67
+ headers: dict[str, str] = {
68
+ CREDENTIALS_HEADER: f"Basic {encoded_credentials}",
69
+ API_URL_HEADER: url,
70
+ EXP_ID_HEADER: str(experiment_id),
71
+ TAB_PREFIX_HEADER: tab_prefix
72
+ }
73
+ return headers
74
+
75
+
76
+ def create_user_from_tot_headers(headers: Mapping[str, str]) -> SapioUser:
77
+ """
78
+ Create a SapioUser object from the headers passed to a tool of tools endpoint.
79
+
80
+ :param headers: The headers that were passed to the endpoint.
81
+ :return: A SapioUser object created from the headers that can be used to communicate with the Sapio server.
82
+ """
83
+ headers: dict[str, str] = format_tot_headers(headers)
84
+ credentials = (base64.b64decode(headers[CREDENTIALS_HEADER.lower()].removeprefix("Basic "))
85
+ .decode("utf-8").split(":", 1))
86
+ url: str = headers[API_URL_HEADER.lower()]
87
+ if url.endswith("/"):
88
+ url.rstrip("/")
89
+ return SapioUser(url, username=credentials[0], password=credentials[1])
90
+
91
+
92
+ def format_tot_headers(headers: Mapping[str, str]) -> dict[str, str]:
93
+ """
94
+ Format the headers passed to a tool of tools endpoint to guarantee that the keys are lowercase.
95
+
96
+ :param headers: The headers that were passed to the endpoint.
97
+ :return: The headers with all keys converted to lowercase. (Conflicting keys will cause one to overwrite the other,
98
+ but there should not be any conflicting keys in the headers passed to a tool of tools endpoint.)
99
+ """
100
+ return {k.lower(): v for k, v in headers.items()}
101
+
102
+
103
+ class HtmlFormatter:
104
+ """
105
+ A class for formatting text in HTML with tag classes supported by the client.
106
+ """
107
+ TIMESTAMP_TEXT__CSS_CLASS_NAME: Final[str] = "timestamp-text"
108
+ HEADER_1_TEXT__CSS_CLASS_NAME: Final[str] = "header1-text"
109
+ HEADER_2_TEXT__CSS_CLASS_NAME: Final[str] = "header2-text"
110
+ HEADER_3_TEXT__CSS_CLASS_NAME: Final[str] = "header3-text"
111
+ BODY_TEXT__CSS_CLASS_NAME: Final[str] = "body-text"
112
+ CAPTION_TEXT__CSS_CLASS_NAME: Final[str] = "caption-text"
113
+
114
+ @staticmethod
115
+ def timestamp(text: str) -> str:
116
+ """
117
+ Given a text string, return that same text string HTML formatted using the timestamp CSS class.
118
+
119
+ :param text: The text to format.
120
+ :return: The HTML formatted text.
121
+ """
122
+ return f"<span class=\"{HtmlFormatter.TIMESTAMP_TEXT__CSS_CLASS_NAME}\">{text}</span>"
123
+
124
+ @staticmethod
125
+ def header_1(text: str) -> str:
126
+ """
127
+ Given a text string, return that same text string HTML formatted using the header 1 CSS class.
128
+
129
+ :param text: The text to format.
130
+ :return: The HTML formatted text.
131
+ """
132
+ return f"<span class=\"{HtmlFormatter.HEADER_1_TEXT__CSS_CLASS_NAME}\">{text}</span>"
133
+
134
+ @staticmethod
135
+ def header_2(text: str) -> str:
136
+ """
137
+ Given a text string, return that same text string HTML formatted using the header 2 CSS class.
138
+
139
+ :param text: The text to format.
140
+ :return: The HTML formatted text.
141
+ """
142
+ return f"<span class=\"{HtmlFormatter.HEADER_2_TEXT__CSS_CLASS_NAME}\">{text}</span>"
143
+
144
+ @staticmethod
145
+ def header_3(text: str) -> str:
146
+ """
147
+ Given a text string, return that same text string HTML formatted using the header 3 CSS class.
148
+
149
+ :param text: The text to format.
150
+ :return: The HTML formatted text.
151
+ """
152
+ return f"<span class=\"{HtmlFormatter.HEADER_3_TEXT__CSS_CLASS_NAME}\">{text}</span>"
153
+
154
+ @staticmethod
155
+ def body(text: str) -> str:
156
+ """
157
+ Given a text string, return that same text string HTML formatted using the body CSS class.
158
+
159
+ :param text: The text to format.
160
+ :return: The HTML formatted text.
161
+ """
162
+ return f"<span class=\"{HtmlFormatter.BODY_TEXT__CSS_CLASS_NAME}\">{text}</span>"
163
+
164
+ @staticmethod
165
+ def caption(text: str) -> str:
166
+ """
167
+ Given a text string, return that same text string HTML formatted using the caption CSS class.
168
+
169
+ :param text: The text to format.
170
+ :return: The HTML formatted text.
171
+ """
172
+ return f"<span class=\"{HtmlFormatter.CAPTION_TEXT__CSS_CLASS_NAME}\">{text}</span>"
173
+
174
+ @staticmethod
175
+ def replace_newlines(text: str) -> str:
176
+ """
177
+ Given a text string, return that same text string HTML formatted with newlines replaced by HTML line breaks.
178
+
179
+ :param text: The text to format.
180
+ :return: The HTML formatted text.
181
+ """
182
+ return re.sub("\r?\n", "<br>", text)
183
+
184
+
185
+ class AiHelper:
186
+ """
187
+ A class with helper methods for the AI to make use of when creating/updating experiment tabs and entries.
188
+ """
189
+ # Contextual info.
190
+ user: SapioUser
191
+ exp_id: int
192
+
193
+ # Managers.
194
+ dr_man: DataRecordManager
195
+ eln_man: ElnManager
196
+ dt_man: DataTypeManager
197
+
198
+ def __init__(self, user: SapioUser, exp_id: int):
199
+ """
200
+ :param user: The user to send the requests from.
201
+ :param exp_id: The ID of the experiment to create the entries in.
202
+ """
203
+ self.user = user
204
+ self.exp_id = exp_id
205
+
206
+ self.dr_man = DataRecordManager(self.user)
207
+ self.eln_man = ElnManager(self.user)
208
+ self.dt_man = DataTypeManager(self.user)
209
+
210
+ def call_endpoint(self, url: str, payload: Any, tab_prefix: str = "") -> Response:
211
+ """
212
+ Call a tool endpoint. Constructs the tool headers and checks the response for errors for the caller.
213
+
214
+ :param url: The URL of the endpoint to call.
215
+ :param payload: The payload to send to the endpoint.
216
+ :param tab_prefix: The prefix to use for the tab name that will be created by the tool.
217
+ :return: The Response object returned by the endpoint.
218
+ """
219
+ headers = create_tot_headers(self.user.url, self.user.username, self.user.password, self.exp_id, tab_prefix)
220
+ response = requests.post(url, json=payload, headers=headers)
221
+ response.raise_for_status()
222
+ return response
223
+
224
+ @property
225
+ def protocol(self) -> ElnExperimentProtocol:
226
+ """
227
+ :return: An experiment protocol object for this helper's experiment. (Recreating a new protocol object every
228
+ time this is called since the protocol's cache could be invalidated by things that the AI is doing.)
229
+ """
230
+ # The experiment name and record ID aren't necessary to know for our purposes.
231
+ return ElnExperimentProtocol(ElnExperiment(self.exp_id, "", 0), self.user)
232
+
233
+ def create_tab(self, name: str) -> ElnExperimentTab:
234
+ """
235
+ Create a new tab in the experiment.
236
+
237
+ :param name: The name of the tab to create.
238
+ :return: The newly created tab.
239
+ """
240
+ tab_crit = ElnExperimentTabAddCriteria(name, [])
241
+ return self.eln_man.add_tab_for_experiment(self.exp_id, tab_crit)
242
+
243
+ def tab_next_entry_order(self, tab: ElnExperimentTab) -> int:
244
+ """
245
+ :param tab: A tab in this helper's experiment.
246
+ :return: The order that the next entry that gets created in the tab should have.
247
+ """
248
+ max_order: int = 0
249
+ for step in self.protocol.get_sorted_step_list():
250
+ if step.eln_entry.notebook_experiment_tab_id == tab.tab_id and step.eln_entry.order > max_order:
251
+ max_order = step.eln_entry.order
252
+ return max_order + 1
253
+
254
+ def create_experiment_details_from_data_frame(self,
255
+ tab: ElnExperimentTab,
256
+ entry_name: str,
257
+ df: DataFrame,
258
+ sort_field: str | None = None,
259
+ sort_direction: SortDirection = SortDirection.DESCENDING,
260
+ smiles_column: str | None = None) -> ExperimentEntry | None:
261
+ """
262
+ Create an experiment detail entry from a DataFrame.
263
+
264
+ :param tab: The tab that the entry should be added to.
265
+ :param entry_name: The name of the entry.
266
+ :param df: The DataFrame to create the entry from.
267
+ :param sort_field: The field to sort the resulting entry rows by, if any.
268
+ :param sort_direction: The direction to sort the resulting entry rows in, if a sort_field is provided.
269
+ :param smiles_column: The column name in the provided DataFrame that corresponds to the SMILES strings of the
270
+ compounds tracked in the DataFrame, if any. If this is provided, then the entry will be created with
271
+ images of the compounds corresponding to the SMILES strings in each row of the table.
272
+ :return: The newly created experiment detail entry.
273
+ """
274
+ json_list: list[dict[str, Any]] = []
275
+ smiles: list[str] = []
276
+ for _, row in df.iterrows():
277
+ row_dict: dict[str, Any] = row.to_dict()
278
+ if smiles_column is not None:
279
+ smiles.append(row_dict.get(smiles_column))
280
+ json_list.append(row_dict)
281
+ images: list[bytes] | None = None
282
+ if smiles:
283
+ images = self.smiles_to_svg(smiles)
284
+ return self.create_experiment_details_from_json(tab, entry_name, json_list, sort_field, sort_direction, images)
285
+
286
+ def create_experiment_details_from_json(self,
287
+ tab: ElnExperimentTab,
288
+ entry_name: str,
289
+ json_list: list[dict[str, Any]],
290
+ sort_field: str | None = None,
291
+ sort_direction: SortDirection = SortDirection.DESCENDING,
292
+ images: list[bytes] | None = None) -> ExperimentEntry | None:
293
+ """
294
+ Create an experiment detail entry from a list of JSON dictionaries.
295
+
296
+ :param tab: The tab that the entry should be added to.
297
+ :param entry_name: The name of the entry.
298
+ :param json_list: The list of JSON dictionaries to create the entry from. Each dictionary is expected to have the
299
+ same keys.
300
+ :param sort_field: The field to sort the resulting entry rows by, if any.
301
+ :param sort_direction: The direction to sort the resulting entry rows in, if a sort_field is provided.
302
+ :param images: The images to include in the entry, if any. The images will be added to the rows that they
303
+ correspond to based on the order of the images in the images list and the order of the rows in the
304
+ json list.
305
+ :return: The newly created experiment detail entry.
306
+ """
307
+ if not json_list:
308
+ return None
309
+
310
+ # Determine which fields in the JSON can be used to create field definitions.
311
+ fb = FieldBuilder()
312
+ fields: list[AbstractVeloxFieldDefinition] = []
313
+ fields_by_name: dict[str, AbstractVeloxFieldDefinition] = {}
314
+ for key, value in json_list[0].items():
315
+ field_name: str = key.replace(" ", "_")
316
+ if isinstance(value, str):
317
+ field = fb.string_field(field_name, display_name=key)
318
+ fields.append(field)
319
+ fields_by_name[key] = field
320
+ elif isinstance(value, (int, float)):
321
+ field = fb.double_field(field_name, display_name=key, precision=3)
322
+ fields.append(field)
323
+ fields_by_name[key] = field
324
+
325
+ # Sort the JSON list if requested.
326
+ if sort_field and sort_direction != SortDirection.NONE:
327
+ if images:
328
+ old_order: list[str] = [x[sort_field] for x in json_list]
329
+ json_list.sort(key=lambda x: x.get(sort_field), reverse=sort_direction == SortDirection.DESCENDING)
330
+ # We'll need to resort the images as well.
331
+ if images:
332
+ new_order: list[str] = [x[sort_field] for x in json_list]
333
+ new_images: list[bytes] = []
334
+ for val in new_order:
335
+ # noinspection PyUnboundLocalVariable
336
+ new_images.append(images[old_order.index(val)])
337
+ images = new_images
338
+
339
+ # Extract the valid field values from the JSON.
340
+ field_maps: list[dict[str, Any]] = []
341
+ for json_dict in json_list:
342
+ field_map: dict[str, Any] = {}
343
+ for key, field in fields_by_name.items():
344
+ # Watch out for NaN values or other special values in numeric columns.
345
+ val: Any = json_dict.get(key)
346
+ if (field.data_field_type == FieldType.DOUBLE
347
+ and (not isinstance(val, (int, float))) or (isinstance(val, float) and math.isnan(val))):
348
+ val = None
349
+ field_map[field.data_field_name] = val
350
+ field_maps.append(field_map)
351
+
352
+ # Create the experiment detail entry.
353
+ detail_entry = ElnEntryCriteria(ElnEntryType.Table, entry_name,
354
+ ElnBaseDataType.EXPERIMENT_DETAIL.data_type_name,
355
+ self.tab_next_entry_order(tab),
356
+ notebook_experiment_tab_id=tab.tab_id,
357
+ field_definition_list=fields)
358
+ entry = self.eln_man.add_experiment_entry(self.exp_id, detail_entry)
359
+ records: list[DataRecord] = self.dr_man.add_data_records_with_data(entry.data_type_name, field_maps)
360
+
361
+ # If images are provided, update the data type definition of the experiment detail data type to allow
362
+ # record images and add the images to the records.
363
+ if images:
364
+ dt: DataTypeDefinition = self.dt_man.get_data_type_definition(entry.data_type_name)
365
+ dt.is_record_image_assignable = True
366
+ self.eln_man.update_eln_data_type_definition(self.exp_id, entry.entry_id, dt)
367
+
368
+ layout: DataTypeLayout = self.dt_man.get_default_layout(entry.data_type_name)
369
+ layout.table_layout = TableLayout(cell_size=128, record_image_width=128)
370
+ self.eln_man.update_eln_data_type_layout(self.exp_id, entry.entry_id, layout)
371
+
372
+ self.update_record_images(records, images)
373
+
374
+ return entry
375
+
376
+ def create_text_entry(self, tab: ElnExperimentTab, timestamp: str, description: str, auto_format: bool = True) \
377
+ -> ExperimentEntry:
378
+ """
379
+ Create a new text entry in the experiment.
380
+
381
+ :param tab: The tab to create the text entry in.
382
+ :param timestamp: The timestamp to display at the top of the text entry.
383
+ :param description: The description to display in the text entry.
384
+ :param auto_format: Whether to automatically format the text to be added.
385
+ :return: The newly created text entry.
386
+ """
387
+ if auto_format:
388
+ description: str = f"<p>{HtmlFormatter.timestamp(timestamp)}<br>{HtmlFormatter.body(description)}</p>"
389
+ else:
390
+ description: str = f"<p>{timestamp}<br>{description}</p>"
391
+ position = ElnEntryPosition(tab.tab_id, self.tab_next_entry_order(tab))
392
+ text_entry: ElnEntryStep = ELNStepFactory.create_text_entry(self.protocol, description, position)
393
+ return text_entry.eln_entry
394
+
395
+ def set_text_entry(self, text_entry: ExperimentEntry, timestamp: str, description: str,
396
+ auto_format: bool = True) -> None:
397
+ """
398
+ Set the text of a text entry.
399
+
400
+ :param text_entry: The text entry to set the text of.
401
+ :param timestamp: The timestamp to display at the top of the text entry.
402
+ :param description: The description to display in the text entry.
403
+ :param auto_format: Whether to automatically format the text to be added.
404
+ """
405
+ if auto_format:
406
+ timestamp = HtmlFormatter.timestamp(timestamp)
407
+ description = HtmlFormatter.body(description)
408
+ description: str = f"<p>{timestamp}<br>{description}</p>"
409
+ step = ElnEntryStep(self.protocol, text_entry)
410
+ text_record: DataRecord = step.get_records()[0]
411
+ text_record.set_field_value(ElnBaseDataType.get_text_entry_data_field_name(), description)
412
+ self.dr_man.commit_data_records([text_record])
413
+
414
+ def add_to_text_entry(self, text_entry: ExperimentEntry, description: str, auto_format: bool = True) -> None:
415
+ """
416
+ Add to the text of a text entry.
417
+
418
+ :param text_entry: The text entry to add the text to.
419
+ :param description: The text to add to the text entry.
420
+ :param auto_format: Whether to automatically format the text to be added.
421
+ """
422
+ step = ElnEntryStep(self.protocol, text_entry)
423
+ text_record: DataRecord = step.get_records()[0]
424
+ update: str = text_record.get_field_value(ElnBaseDataType.get_text_entry_data_field_name())
425
+ if auto_format:
426
+ description = HtmlFormatter.body(description)
427
+ update += f"<p style=\"padding-top: 10px;\">{description}</p>"
428
+ text_record.set_field_value(ElnBaseDataType.get_text_entry_data_field_name(), update)
429
+ self.dr_man.commit_data_records([text_record])
430
+
431
+ def create_attachment_entry(self, tab: ElnExperimentTab, entry_name: str, file_name: str, file_data: str | bytes) \
432
+ -> ExperimentEntry:
433
+ """
434
+ Add a new attachment entry to the experiment with the provided attachment data.
435
+
436
+ :param tab: The tab where the attachment entry will be added.
437
+ :param entry_name: Name of the attachment entry to create in the experiment.
438
+ :param file_name: The name of the attachment.
439
+ :param file_data: The data of the attachment. This can be a string or bytes.
440
+ :return: The newly created attachment entry.
441
+ """
442
+ tab_id: int = tab.tab_id
443
+
444
+ # Encode the file contents in base64.
445
+ if isinstance(file_data, str):
446
+ file_data: bytes = file_data.encode("utf-8")
447
+ base64_encoded: str = base64.b64encode(file_data).decode("utf-8")
448
+
449
+ # Crete an attachment entry with the provided data.
450
+ attachment_entry = self.eln_man.add_experiment_entry(
451
+ self.exp_id,
452
+ ElnEntryCriteria(ElnEntryType.Attachment, entry_name, "Attachment", order=2,
453
+ notebook_experiment_tab_id=tab_id, attachment_file_name=file_name,
454
+ attachment_data_base64=base64_encoded)
455
+ )
456
+
457
+ # Return the entry object for further use.
458
+ return attachment_entry
459
+
460
+ def create_attachment_entry_from_file(self, tab: ElnExperimentTab, entry_name: str, file_path: str) \
461
+ -> ExperimentEntry:
462
+ """
463
+ Add a new attachment entry to the experiment with the provided file path to a file in the file system.
464
+
465
+ :param tab: The tab where the attachment entry will be added.
466
+ :param entry_name: Name of the attachment entry to create in the experiment.
467
+ :param file_path: The path to a file in the system to attach to the experiment.
468
+ :return: The newly created attachment entry.
469
+ """
470
+ with open(file_path, 'rb') as f:
471
+ file_contents: bytes = f.read()
472
+ return self.create_attachment_entry(tab, entry_name, file_path, file_contents)
473
+
474
+ def smiles_to_svg(self, smiles: list[str]) -> list[bytes]:
475
+ """
476
+ Given a list of SMILES strings, return a list of the corresponding images in SVG format.
477
+
478
+ :param smiles: The SMILES strings to retrieve images for.
479
+ :return: The images in SVG format. The indices of the returned list correspond to the indices of the input
480
+ SMILES.
481
+ """
482
+ if not smiles:
483
+ return []
484
+ reg_man = MultiModalManager(self.user)
485
+ image_list: list[str] = reg_man.load_image_data(ImageDataRequestPojo(smiles, False))
486
+ return [x.encode() for x in image_list]
487
+
488
+ def update_record_images(self, records: list[SapioRecord], images: list[bytes]) -> None:
489
+ """
490
+ Update the images of the given records with the given images.
491
+
492
+ :param records: The records to update the images of.
493
+ :param images: The images to update the records with. Records will be match with the image in the matching
494
+ index of this list.
495
+ """
496
+ for record, image in zip(AliasUtil.to_data_records(records), images):
497
+ with io.BytesIO(image) as bytes_io:
498
+ self.dr_man.set_record_image(record, bytes_io)
499
+
500
+ def create_bar_chart(self, entry_name: str, tab: ElnExperimentTab, source_entry: ExperimentEntry,
501
+ x_axis: str, y_axis: str) -> ExperimentEntry:
502
+ """
503
+ Create a bar chart in the experiment based on the contents of the given source entry.
504
+
505
+ :param entry_name: The name of the bar chart.
506
+ :param tab: The tab to create the bar chart in.
507
+ :param source_entry: The source entry to base the bar chart on.
508
+ :param x_axis: The field to use for the x-axis.
509
+ :param y_axis: The field to use for the y-axis.
510
+ :return: The newly created bar chart entry.
511
+ """
512
+ protocol = self.protocol
513
+ source_step = ElnEntryStep(protocol, source_entry)
514
+ position = ElnEntryPosition(tab.tab_id, self.tab_next_entry_order(tab))
515
+ return ELNStepFactory.create_bar_chart_step(protocol, source_step, entry_name,
516
+ x_axis, y_axis, position=position)[0].eln_entry
517
+
518
+
519
+ class ToolOfToolsHelper:
520
+ """
521
+ A class with helper methods utilized by the Tool of Tools for the creation and updating of experiment tabs that
522
+ track a tool's progress and results.
523
+ """
524
+ # Contextual info.
525
+ user: SapioUser
526
+ tab_prefix: str
527
+ exp_id: int
528
+ helper: AiHelper
529
+
530
+ # Tool info.
531
+ name: str
532
+ description: str
533
+ results_data_type: str | None
534
+
535
+ # Managers.
536
+ dr_man: DataRecordManager
537
+ eln_man: ElnManager
538
+
539
+ # Stuff created by this helper.
540
+ _initialized: bool
541
+ """Whether a tab for this tool has been initialized."""
542
+ tab: ElnExperimentTab
543
+ """The tab that contains the tool's entries."""
544
+ description_entry: ElnEntryStep | None
545
+ """The text entry that displays the description of the tool."""
546
+ description_record: DataRecord | None
547
+ """The record that stores the description of the tool."""
548
+ progress_entry: ElnEntryStep | None
549
+ """A hidden entry for tracking the progress of the tool."""
550
+ progress_record: DataRecord | None
551
+ """The record that stores the progress of the tool."""
552
+ progress_gauge_entry: ElnEntryStep | None
553
+ """A chart entry that displays the progress of the tool using the hidden progress entry."""
554
+ results_entry: ElnEntryStep | None
555
+ """An entry for displaying the results of the tool. If None, the tool does not produce result records."""
556
+
557
+ def __init__(self, headers: Mapping[str, str], name: str, description: str,
558
+ results_data_type: str | None = None):
559
+ """
560
+ :param headers: The headers that were passed to the endpoint.
561
+ :param name: The name of the tool.
562
+ :param description: A description of the tool.
563
+ :param results_data_type: The data type name for the results of the tool. If None, the tool does not produce
564
+ result records.
565
+ """
566
+ headers: dict[str, str] = format_tot_headers(headers)
567
+ self.user = create_user_from_tot_headers(headers)
568
+ self.exp_id = int(headers[EXP_ID_HEADER.lower()])
569
+ self.tab_prefix = headers[TAB_PREFIX_HEADER.lower()]
570
+ self.helper = AiHelper(self.user, self.exp_id)
571
+
572
+ self.name = name
573
+ self.description = description
574
+ self.results_data_type = results_data_type
575
+
576
+ self.dr_man = DataRecordManager(self.user)
577
+ self.eln_man = ElnManager(self.user)
578
+
579
+ self._initialized = False
580
+
581
+ def initialize_tab(self) -> ElnExperimentTab:
582
+ if self._initialized:
583
+ return self.tab
584
+ self._initialized = True
585
+
586
+ # Determine if a previous call to this endpoint already created a tab for these results. If so, grab the entries
587
+ # from that tab.
588
+ tab_name: str = f"{self.tab_prefix.strip()} {self.name.strip()}"
589
+ tabs: list[ElnExperimentTab] = self.eln_man.get_tabs_for_experiment(self.exp_id)
590
+ for tab in tabs:
591
+ if tab.tab_name != tab_name:
592
+ continue
593
+
594
+ for entry in self.helper.protocol.get_sorted_step_list():
595
+ if entry.eln_entry.notebook_experiment_tab_id != tab.tab_id:
596
+ continue
597
+
598
+ dt: str = entry.get_data_type_names()[0] if entry.get_data_type_names() else None
599
+ if (entry.eln_entry.entry_type == ElnEntryType.Form
600
+ and ElnBaseDataType.get_base_type(dt) == ElnBaseDataType.EXPERIMENT_DETAIL
601
+ and not hasattr(self, "progress_entry")):
602
+ self.progress_entry = entry
603
+ self.progress_record = entry.get_records()[0]
604
+ elif (entry.eln_entry.entry_type == ElnEntryType.Dashboard
605
+ and not hasattr(self, "progress_gauge_entry")):
606
+ self.progress_gauge_entry = entry
607
+ elif (entry.eln_entry.entry_type == ElnEntryType.Text
608
+ and not hasattr(self, "description_entry")):
609
+ self.description_entry = entry
610
+ self.description_record = entry.get_records()[0]
611
+ elif (entry.eln_entry.entry_type == ElnEntryType.Table
612
+ and dt == self.results_data_type
613
+ and not hasattr(self, "results_entry")):
614
+ self.results_entry = entry
615
+
616
+ if not hasattr(self, "progress_entry"):
617
+ self.progress_entry = None
618
+ self.progress_record = None
619
+ if not hasattr(self, "progress_gauge_entry"):
620
+ self.progress_gauge_entry = None
621
+ if not hasattr(self, "description_entry"):
622
+ self.description_entry = None
623
+ self.description_record = None
624
+ if not hasattr(self, "results_entry"):
625
+ self.results_entry = None
626
+
627
+ self.tab = tab
628
+ return tab
629
+
630
+ # Otherwise, create the tab for the tool progress and results.
631
+ self.tab = self.helper.create_tab(tab_name)
632
+
633
+ # Create a hidden entry for tracking the progress of the tool.
634
+ field_sets: list[ElnFieldSetInfo] = self.eln_man.get_field_set_info_list()
635
+ progress_field_set: list[ElnFieldSetInfo] = [x for x in field_sets if
636
+ x.field_set_name == "Tool of Tools Progress"]
637
+ if not progress_field_set:
638
+ raise SapioException("Unable to locate the field set for the Tool of Tools progress.")
639
+ progress_entry_crit = ElnEntryCriteria(ElnEntryType.Form, f"{tab_name} Progress",
640
+ ElnBaseDataType.EXPERIMENT_DETAIL.data_type_name, 1,
641
+ notebook_experiment_tab_id=self.tab.tab_id,
642
+ enb_field_set_id=progress_field_set[0].field_set_id)
643
+ progress_entry = ElnEntryStep(self.helper.protocol,
644
+ self.eln_man.add_experiment_entry(self.exp_id, progress_entry_crit))
645
+ self.progress_entry = progress_entry
646
+ self.progress_record = progress_entry.get_records()[0]
647
+
648
+ # Hide the progress entry.
649
+ form_update_crit = ElnFormEntryUpdateCriteria()
650
+ form_update_crit.is_hidden = True
651
+ self.eln_man.update_experiment_entry(self.exp_id, self.progress_entry.get_id(), form_update_crit)
652
+
653
+ # Create the text entry that displays the description of the tool. Include the timestamp of when the
654
+ # tool started and format the description so that the text isn't too small to read.
655
+ # TODO: Get the UTC offset in seconds from the header once that's being sent.
656
+ now: str = TimeUtil.now_in_format("%Y-%m-%d %H:%M:%S UTC", "UTC")
657
+ text_entry = ElnEntryStep(self.helper.protocol, self.helper.create_text_entry(self.tab, now, self.description))
658
+ self.description_entry = text_entry
659
+ self.description_record = text_entry.get_records()[0]
660
+
661
+ # Shrink the text entry by one column.
662
+ text_update_crit = ElnTextEntryUpdateCriteria()
663
+ text_update_crit.column_order = 0
664
+ text_update_crit.column_span = 2
665
+ self.eln_man.update_experiment_entry(self.exp_id, self.description_entry.get_id(), text_update_crit)
666
+
667
+ # Create a gauge entry to display the progress.
668
+ gauge_entry: ElnEntryStep = self._create_gauge_chart(self.helper.protocol, progress_entry,
669
+ f"{self.name} Progress", "Progress", "StatusMsg")
670
+ self.progress_gauge_entry = gauge_entry
671
+
672
+ # Make sure the gauge entry isn't too big and stick it to the right of the text entry.
673
+ dash_update_crit = ElnDashboardEntryUpdateCriteria()
674
+ dash_update_crit.entry_height = 250
675
+ dash_update_crit.column_order = 2
676
+ dash_update_crit.column_span = 2
677
+ self.eln_man.update_experiment_entry(self.exp_id, self.progress_gauge_entry.get_id(), dash_update_crit)
678
+
679
+ # Create a results entry if this tool produces result records.
680
+ if self.results_data_type:
681
+ results_entry = ELNStepFactory.create_table_step(self.helper.protocol, f"{self.name} Results",
682
+ self.results_data_type)
683
+ self.results_entry = results_entry
684
+ else:
685
+ self.results_entry = None
686
+
687
+ return self.tab
688
+
689
+ def add_to_description(self, description: str, auto_format: bool = True) -> None:
690
+ """
691
+ Add to the description entry of the tool.
692
+
693
+ :param description: The text to add to the description.
694
+ :param auto_format: Whether to automatically format the text to be added.
695
+ """
696
+ if not self._initialized:
697
+ raise SapioException("The tab for this tool has not been initialized.")
698
+ field: str = ElnBaseDataType.get_text_entry_data_field_name()
699
+ update: str = self.description_record.get_field_value(field)
700
+ if auto_format:
701
+ description = HtmlFormatter.body(description)
702
+ update += f"<p style=\"padding-top: 10px;\">{description}</p>"
703
+ self.description_record.set_field_value(field, update)
704
+ self.dr_man.commit_data_records([self.description_record])
705
+
706
+ def update_progress(self, progress: float, status_msg: str | None = None) -> None:
707
+ """
708
+ Updates the progress of the tool.
709
+
710
+ :param progress: A value between 0 and 100 representing the progress of the tool.
711
+ :param status_msg: A status message to display to the user alongside the progress gauge.
712
+ """
713
+ if not self._initialized:
714
+ raise SapioException("The tab for this tool has not been initialized.")
715
+ self.progress_record.set_field_value("Progress", progress)
716
+ self.progress_record.set_field_value("StatusMsg", status_msg)
717
+ self.dr_man.commit_data_records([self.progress_record])
718
+
719
+ def add_results(self, results: list[SapioRecord]) -> None:
720
+ """
721
+ Add the results of the tool to the results entry.
722
+
723
+ :param results: The result records to add to the results entry.
724
+ """
725
+ if not self._initialized:
726
+ raise SapioException("The tab for this tool has not been initialized.")
727
+ self.results_entry.add_records(AliasUtil.to_data_records(results))
728
+
729
+ def add_results_bar_chart(self, x_axis: str, y_axis: str) -> ExperimentEntry:
730
+ """
731
+ Create a bar chart entry for the results of the tool.
732
+
733
+ :param x_axis: The data field to use for the x-axis of the chart.
734
+ :param y_axis: The data field to use for the y-axis of the chart.
735
+ :return: The newly created chart entry.
736
+ """
737
+ if not self._initialized:
738
+ raise SapioException("The tab for this tool has not been initialized.")
739
+ if not self.results_entry:
740
+ raise SapioException("This tool does not produce result records.")
741
+ return ELNStepFactory.create_bar_chart_step(self.helper.protocol, self.results_entry,
742
+ f"{self.name} Results Chart", x_axis, y_axis)[0].eln_entry
743
+
744
+ def add_attachment_entry(self, entry_name: str, file_name: str, file_data: str | bytes) -> ExperimentEntry:
745
+ """
746
+ Add a new attachment entry to the experiment with the provided attachment data.
747
+
748
+ :param entry_name: Name of the attachment entry to create in the experiment.
749
+ :param file_name: The name of the attachment.
750
+ :param file_data: The data of the attachment. This can be a string or bytes.
751
+ :return: The newly created attachment entry.
752
+ """
753
+ if not self._initialized:
754
+ raise SapioException("The tab for this tool has not been initialized.")
755
+
756
+ return self.helper.create_attachment_entry(self.tab, entry_name, file_name, file_data)
757
+
758
+ def add_attachment_entry_from_file(self, entry_name: str, file_path: str) -> ExperimentEntry:
759
+ """
760
+ Add a new attachment entry to the experiment with the provided file path to a file in the file system.
761
+
762
+ :param entry_name: Name of the attachment entry to create in the experiment.
763
+ :param file_path: The path to a file in the system to attach to the experiment.
764
+ :return: The newly created attachment entry.
765
+ """
766
+ if not self._initialized:
767
+ raise SapioException("The tab for this tool has not been initialized.")
768
+
769
+ return self.helper.create_attachment_entry_from_file(self.tab, entry_name, file_path)
770
+
771
+ # TODO: Remove this once pylib's gauge chart definition is up to date.
772
+ @staticmethod
773
+ def _create_gauge_chart(protocol: ElnExperimentProtocol, data_source_step: ElnEntryStep, step_name: str,
774
+ field_name: str, status_field: str, group_by_field_name: str = "DataRecordName") \
775
+ -> ElnEntryStep:
776
+ """
777
+ Create a gauge chart step in the experiment protocol.
778
+ """
779
+ if not data_source_step.get_data_type_names():
780
+ raise ValueError("The data source step did not declare a data type name.")
781
+ data_type_name: str = data_source_step.get_data_type_names()[0]
782
+ series = GaugeChartSeries(data_type_name, field_name)
783
+ series.operation_type = ChartOperationType.VALUE
784
+ chart = _GaugeChartDefinition()
785
+ chart.main_data_type_name = data_type_name
786
+ chart.status_field = status_field
787
+ chart.minimum_value = 0.
788
+ chart.maximum_value = 100.
789
+ chart.series_list = [series]
790
+ chart.grouping_type = ChartGroupingType.GROUP_BY_FIELD
791
+ chart.grouping_type_data_type_name = data_type_name
792
+ chart.grouping_type_data_field_name = group_by_field_name
793
+ dashboard, step = ELNStepFactory._create_dashboard_step_from_chart(chart, data_source_step, protocol, step_name,
794
+ None)
795
+ protocol.invalidate()
796
+ return step
797
+
798
+
799
+ # TODO: Using this to set the new status field setting.
800
+ class _GaugeChartDefinition(GaugeChartDefinition):
801
+ status_field: str
802
+
803
+ def to_json(self) -> dict[str, Any]:
804
+ result = super().to_json()
805
+ result["statusValueField"] = {
806
+ "dataTypeName": self.main_data_type_name,
807
+ "dataFieldName": self.status_field
808
+ }
809
+ return result