sapiopycommons 2025.7.17a612__py3-none-any.whl → 2025.7.18a614__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 (59) hide show
  1. sapiopycommons/ai/__init__.py +0 -0
  2. sapiopycommons/ai/api/fielddefinitions/proto/fields_pb2.py +43 -0
  3. sapiopycommons/ai/api/fielddefinitions/proto/fields_pb2.pyi +31 -0
  4. sapiopycommons/ai/api/fielddefinitions/proto/fields_pb2_grpc.py +24 -0
  5. sapiopycommons/ai/api/fielddefinitions/proto/velox_field_def_pb2.py +123 -0
  6. sapiopycommons/ai/api/fielddefinitions/proto/velox_field_def_pb2.pyi +598 -0
  7. sapiopycommons/ai/api/fielddefinitions/proto/velox_field_def_pb2_grpc.py +24 -0
  8. sapiopycommons/ai/api/plan/proto/step_output_pb2.py +45 -0
  9. sapiopycommons/ai/api/plan/proto/step_output_pb2.pyi +42 -0
  10. sapiopycommons/ai/api/plan/proto/step_output_pb2_grpc.py +24 -0
  11. sapiopycommons/ai/api/plan/proto/step_pb2.py +43 -0
  12. sapiopycommons/ai/api/plan/proto/step_pb2.pyi +43 -0
  13. sapiopycommons/ai/api/plan/proto/step_pb2_grpc.py +24 -0
  14. sapiopycommons/ai/api/plan/script/proto/script_pb2.py +55 -0
  15. sapiopycommons/ai/api/plan/script/proto/script_pb2.pyi +115 -0
  16. sapiopycommons/ai/api/plan/script/proto/script_pb2_grpc.py +153 -0
  17. sapiopycommons/ai/api/plan/tool/proto/entry_pb2.py +57 -0
  18. sapiopycommons/ai/api/plan/tool/proto/entry_pb2.pyi +96 -0
  19. sapiopycommons/ai/api/plan/tool/proto/entry_pb2_grpc.py +24 -0
  20. sapiopycommons/ai/api/plan/tool/proto/tool_pb2.py +69 -0
  21. sapiopycommons/ai/api/plan/tool/proto/tool_pb2.pyi +232 -0
  22. sapiopycommons/ai/api/plan/tool/proto/tool_pb2_grpc.py +154 -0
  23. sapiopycommons/ai/api/session/proto/sapio_conn_info_pb2.py +39 -0
  24. sapiopycommons/ai/api/session/proto/sapio_conn_info_pb2.pyi +32 -0
  25. sapiopycommons/ai/api/session/proto/sapio_conn_info_pb2_grpc.py +24 -0
  26. sapiopycommons/ai/protobuf_utils.py +508 -0
  27. sapiopycommons/ai/test_client.py +251 -0
  28. sapiopycommons/ai/tool_service_base.py +826 -0
  29. sapiopycommons/callbacks/callback_util.py +332 -665
  30. sapiopycommons/callbacks/field_builder.py +0 -2
  31. sapiopycommons/chem/IndigoMolecules.py +1 -29
  32. sapiopycommons/chem/Molecules.py +3 -3
  33. sapiopycommons/customreport/auto_pagers.py +1 -26
  34. sapiopycommons/customreport/term_builder.py +1 -1
  35. sapiopycommons/datatype/pseudo_data_types.py +326 -349
  36. sapiopycommons/eln/experiment_handler.py +767 -408
  37. sapiopycommons/eln/experiment_report_util.py +6 -11
  38. sapiopycommons/eln/plate_designer.py +2 -7
  39. sapiopycommons/files/file_util.py +5 -7
  40. sapiopycommons/general/accession_service.py +2 -2
  41. sapiopycommons/general/aliases.py +1 -3
  42. sapiopycommons/general/audit_log.py +0 -7
  43. sapiopycommons/general/custom_report_util.py +0 -12
  44. sapiopycommons/processtracking/custom_workflow_handler.py +1 -11
  45. sapiopycommons/processtracking/endpoints.py +0 -27
  46. sapiopycommons/recordmodel/record_handler.py +391 -785
  47. sapiopycommons/rules/eln_rule_handler.py +1 -8
  48. sapiopycommons/rules/on_save_rule_handler.py +1 -8
  49. sapiopycommons/webhook/webhook_handlers.py +4 -9
  50. sapiopycommons/webhook/webservice_handlers.py +2 -2
  51. {sapiopycommons-2025.7.17a612.dist-info → sapiopycommons-2025.7.18a614.dist-info}/METADATA +2 -2
  52. sapiopycommons-2025.7.18a614.dist-info/RECORD +92 -0
  53. sapiopycommons/eln/experiment_cache.py +0 -188
  54. sapiopycommons/eln/experiment_step_factory.py +0 -476
  55. sapiopycommons/eln/step_creation.py +0 -236
  56. sapiopycommons/general/data_structure_util.py +0 -115
  57. sapiopycommons-2025.7.17a612.dist-info/RECORD +0 -68
  58. {sapiopycommons-2025.7.17a612.dist-info → sapiopycommons-2025.7.18a614.dist-info}/WHEEL +0 -0
  59. {sapiopycommons-2025.7.17a612.dist-info → sapiopycommons-2025.7.18a614.dist-info}/licenses/LICENSE +0 -0
@@ -0,0 +1,826 @@
1
+ from __future__ import annotations
2
+
3
+ import json
4
+ import logging
5
+ import traceback
6
+ from abc import abstractmethod, ABC
7
+ from logging import Logger
8
+ from typing import Any, Iterable, Sequence, Mapping
9
+
10
+ from grpc import ServicerContext
11
+ from sapiopylib.rest.User import SapioUser, ensure_logger_initialized
12
+ from sapiopylib.rest.pojo.datatype.FieldDefinition import AbstractVeloxFieldDefinition
13
+
14
+ from sapiopycommons.ai.api.fielddefinitions.proto.fields_pb2 import FieldValueMapPbo, FieldValuePbo
15
+ from sapiopycommons.ai.api.fielddefinitions.proto.velox_field_def_pb2 import VeloxFieldDefPbo, FieldTypePbo, \
16
+ SelectionPropertiesPbo, IntegerPropertiesPbo, DoublePropertiesPbo, BooleanPropertiesPbo, StringPropertiesPbo
17
+ from sapiopycommons.ai.api.plan.tool.proto.entry_pb2 import StepOutputBatchPbo, StepItemContainerPbo, DataTypePbo, \
18
+ StepBinaryContainerPbo, StepCsvContainerPbo, StepCsvHeaderRowPbo, StepCsvRowPbo, StepImageContainerPbo, \
19
+ StepJsonContainerPbo, StepTextContainerPbo, StepInputBatchPbo
20
+ from sapiopycommons.ai.api.plan.tool.proto.tool_pb2 import ToolDetailsRequestPbo, ToolDetailsResponsePbo, \
21
+ ToolDetailsPbo, ProcessStepRequestPbo, ProcessStepResponsePbo, ToolOutputDetailsPbo, ToolIoConfigBasePbo, \
22
+ ToolInputDetailsPbo, ExampleContainerPbo
23
+ from sapiopycommons.ai.api.plan.tool.proto.tool_pb2_grpc import ToolServiceServicer
24
+ from sapiopycommons.ai.api.session.proto.sapio_conn_info_pb2 import SapioUserSecretTypePbo, SapioConnectionInfoPbo
25
+ from sapiopycommons.ai.protobuf_utils import ProtobufUtils
26
+ from sapiopycommons.general.aliases import FieldMap, FieldValue
27
+
28
+
29
+ class SapioToolResult(ABC):
30
+ """
31
+ A class representing a result from a Sapio tool. Instantiate one of the subclasses to create a result object.
32
+ """
33
+
34
+ @abstractmethod
35
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
36
+ """
37
+ Convert this SapioToolResult object to a StepOutputBatchPbo or list of FieldValueMapPbo proto objects.
38
+ """
39
+ pass
40
+
41
+
42
+ class BinaryResult(SapioToolResult):
43
+ """
44
+ A class representing binary results from a Sapio tool.
45
+ """
46
+ binary_data: list[bytes]
47
+
48
+ def __init__(self, binary_data: list[bytes]):
49
+ """
50
+ :param binary_data: The binary data as a list of bytes.
51
+ """
52
+ self.binary_data = binary_data
53
+
54
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
55
+ return StepOutputBatchPbo(
56
+ item_container=StepItemContainerPbo(
57
+ dataType=DataTypePbo.BINARY,
58
+ binary_container=StepBinaryContainerPbo(items=self.binary_data)
59
+ )
60
+ )
61
+
62
+
63
+ class CsvResult(SapioToolResult):
64
+ """
65
+ A class representing CSV results from a Sapio tool.
66
+ """
67
+ csv_data: list[dict[str, Any]]
68
+
69
+ def __init__(self, csv_data: list[dict[str, Any]]):
70
+ """
71
+ :param csv_data: The list of CSV data results, provided as a list of dictionaries of column name to value.
72
+ """
73
+ self.csv_data = csv_data
74
+
75
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
76
+ return StepOutputBatchPbo(
77
+ item_container=StepItemContainerPbo(
78
+ dataType=DataTypePbo.CSV,
79
+ csv_container=StepCsvContainerPbo(
80
+ header=StepCsvHeaderRowPbo(cells=self.csv_data[0].keys()),
81
+ items=[StepCsvRowPbo(cells=[str(x) for x in row.values()]) for row in self.csv_data]
82
+ )
83
+ ) if self.csv_data else None
84
+ )
85
+
86
+
87
+ class FieldMapResult(SapioToolResult):
88
+ """
89
+ A class representing field map results from a Sapio tool.
90
+ """
91
+ field_maps: list[FieldMap]
92
+
93
+ def __init__(self, field_maps: list[FieldMap]):
94
+ """
95
+ :param field_maps: A list of field maps, where each map is a dictionary of field names to values. Each entry
96
+ will create a new data record in the system, so long as the tool definition specifies an output data type
97
+ name.
98
+ """
99
+ self.field_maps = field_maps
100
+
101
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
102
+ new_records: list[FieldValueMapPbo] = []
103
+ for field_map in self.field_maps:
104
+ fields: dict[str, FieldValuePbo] = {}
105
+ for field, value in field_map.items():
106
+ field_value = FieldValuePbo()
107
+ if isinstance(value, str):
108
+ field_value.string_value = value
109
+ elif isinstance(value, int):
110
+ field_value.int_value = value
111
+ elif isinstance(value, float):
112
+ field_value.double_value = value
113
+ elif isinstance(value, bool):
114
+ field_value.bool_value = value
115
+ fields[field] = field_value
116
+ new_records.append(FieldValueMapPbo(fields=fields))
117
+ return new_records
118
+
119
+
120
+ class ImageResult(SapioToolResult):
121
+ """
122
+ A class representing image results from a Sapio tool.
123
+ """
124
+ image_format: str
125
+ image_data: list[bytes]
126
+
127
+ def __init__(self, image_format: str, image_data: list[bytes]):
128
+ """
129
+ :param image_format: The format of the image (e.g., PNG, JPEG).
130
+ :param image_data: The image data as a list of bytes. Each entry in the list represents a separate image.
131
+ """
132
+ self.image_format = image_format
133
+ self.image_data = image_data
134
+
135
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
136
+ return StepOutputBatchPbo(
137
+ item_container=StepItemContainerPbo(
138
+ dataType=DataTypePbo.IMAGE,
139
+ image_container=StepImageContainerPbo(
140
+ image_format=self.image_format,
141
+ items=self.image_data)
142
+ )
143
+ )
144
+
145
+
146
+ class JsonResult(SapioToolResult):
147
+ """
148
+ A class representing JSON results from a Sapio tool.
149
+ """
150
+ json_data: list[Any]
151
+
152
+ def __init__(self, json_data: list[Any]):
153
+ """
154
+ :param json_data: The list of JSON data results. Each entry in the list represents a separate JSON object.
155
+ These entries must be able to be serialized to JSON using json.dumps().
156
+ """
157
+ self.json_data = json_data
158
+
159
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
160
+ return StepOutputBatchPbo(
161
+ item_container=StepItemContainerPbo(
162
+ dataType=DataTypePbo.JSON,
163
+ json_container=StepJsonContainerPbo(items=[json.dumps(x) for x in self.json_data])
164
+ )
165
+ )
166
+
167
+
168
+ class TextResult(SapioToolResult):
169
+ """
170
+ A class representing text results from a Sapio tool.
171
+ """
172
+ text_data: list[str]
173
+
174
+ def __init__(self, text_data: list[str]):
175
+ """
176
+ :param text_data: The text data as a list of strings.
177
+ """
178
+ self.text_data = text_data
179
+
180
+ def to_proto(self) -> StepOutputBatchPbo | list[FieldValueMapPbo]:
181
+ return StepOutputBatchPbo(
182
+ item_container=StepItemContainerPbo(
183
+ dataType=DataTypePbo.TEXT,
184
+ text_container=StepTextContainerPbo(items=self.text_data)
185
+ )
186
+ )
187
+
188
+
189
+ class ToolServiceBase(ToolServiceServicer, ABC):
190
+ """
191
+ A base class for implementing a tool service. Subclasses should implement the register_tools method to register
192
+ their tools with the service.
193
+ """
194
+ def GetToolDetails(self, request: ToolDetailsRequestPbo, context: ServicerContext) -> ToolDetailsResponsePbo:
195
+ try:
196
+ # Get the tool details from the registered tools.
197
+ details: list[ToolDetailsPbo] = self.get_details()
198
+ return ToolDetailsResponsePbo(tool_framework_version=self.tool_version(), tool_details=details)
199
+ except Exception:
200
+ # TODO: This response doesn't even allow logs. What should we do if an exception occurs in this case?
201
+ return ToolDetailsResponsePbo()
202
+
203
+ def ProcessData(self, request: ProcessStepRequestPbo, context: ServicerContext) -> ProcessStepResponsePbo:
204
+ try:
205
+ # Convert the SapioConnectionInfo proto object to a SapioUser object.
206
+ user = self.create_user(request.sapio_user)
207
+ # Get the tool results from the registered tool matching the request and convert them to proto objects.
208
+ output_data: list[StepOutputBatchPbo] = []
209
+ new_records: list[FieldValueMapPbo] = []
210
+ # TODO: Make use of the success value after the response object has a field for it.
211
+ success, results, logs = self.run(user, request, context)
212
+ for result in results:
213
+ data: StepOutputBatchPbo | list[FieldValueMapPbo] = result.to_proto()
214
+ if isinstance(data, StepOutputBatchPbo):
215
+ output_data.append(data)
216
+ else:
217
+ new_records.extend(data)
218
+ # Return a ProcessStepResponse proto object containing the output data and new records to the caller.
219
+ return ProcessStepResponsePbo(output=output_data, log=logs, new_records=new_records)
220
+ except Exception:
221
+ # TODO: Return a False success result after the response object has a field for it.
222
+ return ProcessStepResponsePbo(log=[traceback.format_exc()])
223
+
224
+ @staticmethod
225
+ def create_user(info: SapioConnectionInfoPbo, timeout_seconds: int = 60) -> SapioUser:
226
+ """
227
+ Create a SapioUser object from the given SapioConnectionInfo proto object.
228
+
229
+ :param info: The SapioConnectionInfo proto object.
230
+ :param timeout_seconds: The request timeout for calls made from this user object.
231
+ """
232
+ # TODO: Have a customizable request timeout? Would need to be added to the request object.
233
+ # TODO: How should the RMI hosts and port be used in the connection info?
234
+ user = SapioUser(info.webservice_url, True, timeout_seconds, guid=info.app_guid)
235
+ if info.secret_type == SapioUserSecretTypePbo.SESSION_TOKEN:
236
+ user.api_token = info.secret
237
+ elif info.secret_type == SapioUserSecretTypePbo.PASSWORD:
238
+ # TODO: Will the secret be base64 encoded if it's a password? That's how basic auth is normally handled.
239
+ user.password = info.secret
240
+ else:
241
+ raise Exception(f"Unexpected secret type: {info.secret_type}")
242
+ return user
243
+
244
+ @staticmethod
245
+ def tool_version() -> int:
246
+ """
247
+ :return: The version of this tool.
248
+ """
249
+ return 1
250
+
251
+ def _get_tools(self) -> list[ToolBase]:
252
+ """
253
+ return: Get instances of the tools registered with this service.
254
+ """
255
+ # This is complaining about the name and description not being filled from ToolBase,
256
+ # but none of the provided tools should have any init parameters.
257
+ # noinspection PyArgumentList
258
+ tools: list[ToolBase] = [x() for x in self.register_tools()]
259
+ if not tools:
260
+ raise Exception("No tools registered with this service.")
261
+ return tools
262
+
263
+ def _get_tool(self, name: str) -> ToolBase:
264
+ """
265
+ Get a specific tool instance by its name.
266
+
267
+ :param name: The name of the tool to retrieve.
268
+ :return: The tool object corresponding to the given name.
269
+ """
270
+ tools: dict[str, ToolBase] = {x.name: x for x in self._get_tools()}
271
+ if name not in tools:
272
+ raise Exception(f"Tool \"{name}\" not found in registered tools.")
273
+ return tools[name]
274
+
275
+ @abstractmethod
276
+ def register_tools(self) -> list[type[ToolBase]]:
277
+ """
278
+ Register the tool types with this service. Provided tools should be subclasses of ToolBase and should not have
279
+ any init parameters.
280
+
281
+ :return: A list of tools to register to this service.
282
+ """
283
+ pass
284
+
285
+ def get_details(self) -> list[ToolDetailsPbo]:
286
+ """
287
+ Get the details of the tool.
288
+
289
+ :return: A ToolDetailsResponse object containing the tool details.
290
+ """
291
+ tool_details: list[ToolDetailsPbo] = []
292
+ for tool in self._get_tools():
293
+ tool_details.append(tool.to_pbo())
294
+ return tool_details
295
+
296
+ def run(self, user: SapioUser, request: ProcessStepRequestPbo, context: ServicerContext) \
297
+ -> tuple[bool, list[SapioToolResult], list[str]]:
298
+ """
299
+ Execute a tool from this service.
300
+
301
+ :param user: A user object that can be used to initialize manager classes using DataMgmtServer to query the
302
+ system.
303
+ :param request: The request object containing the input data.
304
+ :param context: The gRPC context.
305
+ :return: Whether or not the tool succeeded, the results of the tool, and any logs generated by the tool.
306
+ """
307
+ tool = self._get_tool(request.tool_name)
308
+ try:
309
+ tool.setup(user, request, context)
310
+ results: list[SapioToolResult] = tool.run(user)
311
+ return True, results, tool.logs
312
+ except Exception as e:
313
+ tool.log_exception("Exception occurred during tool execution.", e)
314
+ return False, [], tool.logs
315
+
316
+
317
+ class ToolBase(ABC):
318
+ """
319
+ A base class for implementing a tool.
320
+ """
321
+ name: str
322
+ description: str
323
+ data_type_name: str | None
324
+ inputs: list[ToolInputDetailsPbo]
325
+ outputs: list[ToolOutputDetailsPbo]
326
+ configs: list[VeloxFieldDefPbo]
327
+
328
+ logs: list[str]
329
+ logger: Logger
330
+ verbose_logging: bool
331
+
332
+ user: SapioUser
333
+ request: ProcessStepRequestPbo
334
+ context: ServicerContext
335
+
336
+ def __init__(self, name: str, description: str, data_type_name: str | None = None):
337
+ """
338
+ :param name: The name of the tool.
339
+ :param description: A description of the tool.
340
+ :param data_type_name: The name of the output data type of this tool, if applicable. When this tool returns
341
+ FieldMapResult objects in its run method, this name will be used to set the data type of the output data.
342
+ """
343
+ self.name = name
344
+ self.description = description
345
+ self.data_type_name = data_type_name
346
+ self.inputs = []
347
+ self.outputs = []
348
+ self.configs = []
349
+ self.logs = []
350
+ self.logger = logging.getLogger(f"ToolBase.{self.name}")
351
+ ensure_logger_initialized(self.logger)
352
+
353
+ def setup(self, user: SapioUser, request: ProcessStepRequestPbo, context: ServicerContext) -> None:
354
+ """
355
+ Setup the tool with the user, request, and context. This method can be overridden by subclasses to perform
356
+ additional setup.
357
+
358
+ :param user: A user object that can be used to initialize manager classes using DataMgmtServer to query the
359
+ system.
360
+ :param request: The request object containing the input data.
361
+ :param context: The gRPC context.
362
+ """
363
+ self.user = user
364
+ self.request = request
365
+ self.context = context
366
+ # TODO: Determine verbose logging from the request.
367
+ self.verbose_logging = False
368
+
369
+ def add_input(self, content_type: DataTypePbo, display_name: str, description: str,
370
+ structure_example: str | bytes | None = None, validation: str | None = None,
371
+ input_count: tuple[int, int] | None = None, is_paged: bool = False,
372
+ page_size: tuple[int, int] | None = None, max_request_bytes: int | None = None) -> None:
373
+ """
374
+ Add an input configuration to the tool. This determines how many inputs this tool will accept in the plan
375
+ manager, as well as what those inputs are. The IO number of the input will be set to the current number of
376
+ inputs. That is, the first time this is called, the IO number will be 0, the second time it is called, the IO
377
+ number will be 1, and so on.
378
+
379
+ :param content_type: The content type of the input.
380
+ :param display_name: The display name of the input.
381
+ :param description: The description of the input.
382
+ :param structure_example: An optional example of the structure of the input, such as how the structure of a
383
+ JSON output may look. This does not need to be an entirely valid example, and should often be truncated for
384
+ brevity.
385
+ :param validation: An optional validation string for the input.
386
+ :param input_count: A tuple of the minimum and maximum number of inputs allowed for this tool.
387
+ :param is_paged: If true, this input will be paged. If false, this input will not be paged.
388
+ :param page_size: A tuple of the minimum and maximum page size for this tool. The input must be paged in order
389
+ for this to have an effect.
390
+ :param max_request_bytes: The maximum request size in bytes for this tool.
391
+ """
392
+ structure: ExampleContainerPbo | None = None
393
+ if isinstance(structure_example, str):
394
+ structure = ExampleContainerPbo(text_example=structure_example)
395
+ elif isinstance(structure_example, bytes):
396
+ structure = ExampleContainerPbo(binary_example=structure_example)
397
+ self.inputs.append(ToolInputDetailsPbo(
398
+ base_config=ToolIoConfigBasePbo(
399
+ io_number=len(self.inputs),
400
+ content_type=ProtobufUtils.content_type_str(content_type),
401
+ display_name=display_name,
402
+ description=description,
403
+ structure_example=structure
404
+ ),
405
+ validation=validation,
406
+ min_input_count=input_count[0] if input_count else None,
407
+ max_input_count=input_count[1] if input_count else None,
408
+ paged=is_paged,
409
+ min_page_size=page_size[0] if page_size else None,
410
+ max_page_size=page_size[1] if page_size else None,
411
+ max_request_bytes=max_request_bytes,
412
+ ))
413
+
414
+ def add_output(self, content_type: DataTypePbo, display_name: str, description: str,
415
+ testing_example: str | bytes | None = None, structure_example: str | bytes | None = None) -> None:
416
+ """
417
+ Add an output configuration to the tool. This determines how many inputs this tool will accept in the plan
418
+ manager, as well as what those inputs are. The IO number of the output will be set to the current number of
419
+ outputs. That is, the first time this is called, the IO number will be 0, the second time it is called, the IO
420
+ number will be 1, and so on.
421
+
422
+ :param content_type: The content type of the output.
423
+ :param display_name: The display name of the output.
424
+ :param description: The description of the output.
425
+ :param testing_example: An example of the input to be used when testing this tool in the system. This must be
426
+ an entirely valid example of what an output of this tool could look like so that it can be properly used
427
+ to run tests with. The provided example may be a string, such as for representing JSON or CSV outputs,
428
+ or bytes, such as for representing binary outputs like images or files.
429
+ :param structure_example: An optional example of the structure of the input, such as how the structure of a
430
+ JSON output may look. This does not need to be an entirely valid example, and should often be truncated for
431
+ brevity.
432
+ """
433
+ structure: ExampleContainerPbo | None = None
434
+ if isinstance(structure_example, str):
435
+ structure = ExampleContainerPbo(text_example=structure_example)
436
+ elif isinstance(structure_example, bytes):
437
+ structure = ExampleContainerPbo(binary_example=structure_example)
438
+
439
+ testing: ExampleContainerPbo | None = None
440
+ if isinstance(testing_example, str):
441
+ testing = ExampleContainerPbo(text_example=testing_example)
442
+ elif isinstance(testing_example, bytes):
443
+ testing = ExampleContainerPbo(binary_example=testing_example)
444
+
445
+ self.outputs.append(ToolOutputDetailsPbo(
446
+ base_config=ToolIoConfigBasePbo(
447
+ io_number=len(self.outputs),
448
+ content_type=ProtobufUtils.content_type_str(content_type),
449
+ display_name=display_name,
450
+ description=description,
451
+ structure_example=structure,
452
+ testing_example=testing
453
+ )))
454
+
455
+ def add_config_field(self, field: VeloxFieldDefPbo) -> None:
456
+ """
457
+ Add a configuration field to the tool. This field will be used to configure the tool in the plan manager.
458
+
459
+ :param field: The configuration field details.
460
+ """
461
+ self.configs.append(field)
462
+
463
+ def add_config_field_def(self, field: AbstractVeloxFieldDefinition) -> None:
464
+ """
465
+ Add a configuration field to the tool. This field will be used to configure the tool in the plan manager.
466
+
467
+ :param field: The configuration field details.
468
+ """
469
+ self.configs.append(ProtobufUtils.field_def_to_pbo(field))
470
+
471
+ def add_boolean_config_field(self, field_name: str, display_name: str, description: str, default_value: bool,
472
+ optional: bool = False) -> None:
473
+ """
474
+ Add a boolean configuration field to the tool. This field will be used to configure the tool in the plan
475
+ manager.
476
+
477
+ :param field_name: The name of the field.
478
+ :param display_name: The display name of the field.
479
+ :param description: The description of the field.
480
+ :param default_value: The default value of the field.
481
+ :param optional: If true, this field is optional. If false, this field is required.
482
+ """
483
+ self.configs.append(VeloxFieldDefPbo(
484
+ data_field_type=FieldTypePbo.BOOLEAN,
485
+ data_field_name=field_name,
486
+ display_name=display_name,
487
+ description=description,
488
+ required=not optional,
489
+ editable=True,
490
+ boolean_properties=BooleanPropertiesPbo(
491
+ default_value=default_value
492
+ )
493
+ ))
494
+
495
+ def add_double_config_field(self, field_name: str, display_name: str, description: str, default_value: float,
496
+ min_value: float = -10.**120, max_value: float = 10.**120, precision: int = 2,
497
+ optional: bool = False) -> None:
498
+ """
499
+ Add a double configuration field to the tool. This field will be used to configure the tool in the plan
500
+ manager.
501
+
502
+ :param field_name: The name of the field.
503
+ :param display_name: The display name of the field.
504
+ :param description: The description of the field.
505
+ :param default_value: The default value of the field.
506
+ :param min_value: The minimum value of the field.
507
+ :param max_value: The maximum value of the field.
508
+ :param precision: The precision of the field.
509
+ :param optional: If true, this field is optional. If false, this field is required.
510
+ """
511
+ self.configs.append(VeloxFieldDefPbo(
512
+ data_field_type=FieldTypePbo.DOUBLE,
513
+ data_field_name=field_name,
514
+ display_name=display_name,
515
+ description=description,
516
+ required=not optional,
517
+ editable=True,
518
+ double_properties=DoublePropertiesPbo(
519
+ default_value=default_value,
520
+ min_value=min_value,
521
+ max_value=max_value,
522
+ precision=precision
523
+ )
524
+ ))
525
+
526
+ def add_integer_config_field(self, field_name: str, display_name: str, description: str,
527
+ default_value: int, min_value: int = -2**31, max_value: int = 2**31-1,
528
+ optional: bool = False) -> None:
529
+ """
530
+ Add an integer configuration field to the tool. This field will be used to configure the tool in the plan
531
+ manager.
532
+
533
+ :param field_name: The name of the field.
534
+ :param display_name: The display name of the field.
535
+ :param description: The description of the field.
536
+ :param default_value: The default value of the field.
537
+ :param min_value: The minimum value of the field.
538
+ :param max_value: The maximum value of the field.
539
+ :param optional: If true, this field is optional. If false, this field is required.
540
+ """
541
+ self.configs.append(VeloxFieldDefPbo(
542
+ data_field_type=FieldTypePbo.INTEGER,
543
+ data_field_name=field_name,
544
+ display_name=display_name,
545
+ description=description,
546
+ required=not optional,
547
+ editable=True,
548
+ integer_properties=IntegerPropertiesPbo(
549
+ default_value=default_value,
550
+ min_value=min_value,
551
+ max_value=max_value
552
+ )
553
+ ))
554
+
555
+ def add_string_config_field(self, field_name: str, display_name: str, description: str,
556
+ default_value: str, max_length: int = 1000, optional: bool = False) -> None:
557
+ """
558
+ Add a string configuration field to the tool. This field will be used to configure the tool in the plan
559
+ manager.
560
+
561
+ :param field_name: The name of the field.
562
+ :param display_name: The display name of the field.
563
+ :param description: The description of the field.
564
+ :param default_value: The default value of the field.
565
+ :param max_length: The maximum length of the field.
566
+ :param optional: If true, this field is optional. If false, this field is required.
567
+ """
568
+ self.configs.append(VeloxFieldDefPbo(
569
+ data_field_type=FieldTypePbo.STRING,
570
+ data_field_name=field_name,
571
+ display_name=display_name,
572
+ description=description,
573
+ required=not optional,
574
+ editable=True,
575
+ string_properties=StringPropertiesPbo(
576
+ default_value=default_value,
577
+ max_length=max_length
578
+ )
579
+ ))
580
+
581
+ def add_list_config_field(self, field_name: str, display_name: str, description: str, default_value: str,
582
+ allowed_values: list[str], direct_edit: bool = False, optional: bool = False) -> None:
583
+ """
584
+ Add a list configuration field to the tool. This field will be used to configure the tool in the plan
585
+ manager.
586
+
587
+ :param field_name: The name of the field.
588
+ :param display_name: The display name of the field.
589
+ :param description: The description of the field.
590
+ :param default_value: The default value of the field.
591
+ :param allowed_values: The list of allowed values for the field.
592
+ :param direct_edit: If true, the user can enter a value that is not in the list of allowed values. If false,
593
+ the user can only select from the list of allowed values.
594
+ :param optional: If true, this field is optional. If false, this field is required.
595
+ """
596
+ self.configs.append(VeloxFieldDefPbo(
597
+ data_field_type=FieldTypePbo.SELECTION,
598
+ data_field_name=field_name,
599
+ display_name=display_name,
600
+ description=description,
601
+ required=not optional,
602
+ editable=True,
603
+ selection_properties=SelectionPropertiesPbo(
604
+ default_value=default_value,
605
+ static_list_values=allowed_values,
606
+ direct_edit=direct_edit,
607
+ )
608
+ ))
609
+
610
+ def add_multi_list_config_field(self, field_name: str, display_name: str, description: str,
611
+ default_value: list[str], allowed_values: list[str], direct_edit: bool = False,
612
+ optional: bool = False) -> None:
613
+ """
614
+ Add a multi-select list configuration field to the tool. This field will be used to configure the tool in the
615
+ plan manager.
616
+
617
+ :param field_name: The name of the field.
618
+ :param display_name: The display name of the field.
619
+ :param description: The description of the field.
620
+ :param default_value: The default value of the field.
621
+ :param allowed_values: The list of allowed values for the field.
622
+ :param direct_edit: If true, the user can enter a value that is not in the list of allowed values. If false,
623
+ the user can only select from the list of allowed values.
624
+ :param optional: If true, this field is optional. If false, this field is required.
625
+ """
626
+ self.configs.append(VeloxFieldDefPbo(
627
+ data_field_type=FieldTypePbo.SELECTION,
628
+ data_field_name=field_name,
629
+ display_name=display_name,
630
+ description=description,
631
+ required=not optional,
632
+ editable=True,
633
+ selection_properties=SelectionPropertiesPbo(
634
+ default_value=",".join(default_value),
635
+ static_list_values=allowed_values,
636
+ multi_select=True,
637
+ direct_edit=direct_edit,
638
+ )
639
+ ))
640
+
641
+ def to_pbo(self) -> ToolDetailsPbo:
642
+ """
643
+ :return: The ToolDetailsPbo proto object representing this tool.
644
+ """
645
+ return ToolDetailsPbo(
646
+ name=self.name,
647
+ description=self.description,
648
+ input_configs=self.inputs,
649
+ output_configs=self.outputs,
650
+ output_data_type_name=self.data_type_name,
651
+ config_fields=self.configs
652
+ )
653
+
654
+ @abstractmethod
655
+ def run(self, user: SapioUser) -> list[SapioToolResult]:
656
+ """
657
+ Execute this tool.
658
+
659
+ The request inputs can be accessed using the self.get_input_*() methods.
660
+ The request settings can be accessed using the self.get_config_fields() method.
661
+ The request itself can be accessed using self.request.
662
+
663
+ :param user: A user object that can be used to initialize manager classes using DataMgmtServer to query the
664
+ system.
665
+ :return: A SapioToolResults object containing the response data. Each result in the list corresponds to a
666
+ separate output from the tool. Field map results do not appear as tool output in the plan manager, instead
667
+ appearing as records related to the plan step during the run.
668
+ """
669
+ pass
670
+
671
+ def log_info(self, message: str) -> None:
672
+ """
673
+ Log an info message for this tool. If verbose logging is enabled, this message will be included in the logs
674
+ returned to the caller. Empty/None inputs will not be logged.
675
+
676
+ :param message: The message to log.
677
+ """
678
+ if not message:
679
+ return
680
+ if self.verbose_logging:
681
+ self.logs.append(f"INFO: {self.name}: {message}")
682
+ self.logger.info(message)
683
+
684
+ def log_warning(self, message: str) -> None:
685
+ """
686
+ Log a warning message for this tool. This message will be included in the logs returned to the caller.
687
+ Empty/None inputs will not be logged.
688
+
689
+ :param message: The message to log.
690
+ """
691
+ if not message:
692
+ return
693
+ self.logs.append(f"WARNING: {self.name}: {message}")
694
+ self.logger.warning(message)
695
+
696
+ def log_error(self, message: str) -> None:
697
+ """
698
+ Log an error message for this tool. This message will be included in the logs returned to the caller.
699
+ Empty/None inputs will not be logged.
700
+
701
+ :param message: The message to log.
702
+ """
703
+ if not message:
704
+ return
705
+ self.logs.append(f"ERROR: {self.name}: {message}")
706
+ self.logger.error(message)
707
+
708
+ def log_exception(self, message: str, e: Exception) -> None:
709
+ """
710
+ Log an exception for this tool. This message will be included in the logs returned to the caller.
711
+ Empty/None inputs will not be logged.
712
+
713
+ :param message: The message to log.
714
+ :param e: The exception to log.
715
+ """
716
+ if not message and not e:
717
+ return
718
+ self.logs.append(f"EXCEPTION: {self.name}: {message} - {e}")
719
+ self.logger.error(f"{message}\n{traceback.format_exc()}")
720
+
721
+ def get_input_binary(self, index: int = 0) -> list[bytes]:
722
+ """
723
+ Get the binary data from the request object.
724
+
725
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
726
+ :return: The binary data from the request object.
727
+ """
728
+ return list(self.request.input[index].item_container.binary_container.items)
729
+
730
+ def get_input_csv(self, index: int = 0) -> tuple[list[str], list[dict[str, str]]]:
731
+ """
732
+ Parse the CSV data from the request object.
733
+
734
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
735
+ :return: A tuple containing the header row and the data rows. The header row is a list of strings representing
736
+ the column names, and the data rows are a list of dictionaries where each dictionary represents a row in the
737
+ CSV with the column names as keys and the corresponding values as strings.
738
+ """
739
+ input_data: Sequence[StepInputBatchPbo] = self.request.input
740
+ ret_val: list[dict[str, str]] = []
741
+ headers: Iterable[str] = input_data[index].item_container.csv_container.header.cells
742
+ for row in input_data[index].item_container.csv_container.items:
743
+ row_dict: dict[str, str] = {}
744
+ for header, value in zip(headers, row.cells):
745
+ row_dict[header] = value
746
+ ret_val.append(row_dict)
747
+ return list(headers), ret_val
748
+
749
+ def get_input_images(self, index: int = 0) -> tuple[str, list[bytes]]:
750
+ """
751
+ Parse the image data from the request object.
752
+
753
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
754
+ :return: A tuple containing the image format and the image data. The image format is a string representing the
755
+ format of the image (e.g., PNG, JPEG), and the image data is a list of bytes representing the image data.
756
+ Each entry in the list represents a separate image.
757
+ """
758
+ image_data: StepImageContainerPbo = self.request.input[index].item_container.image_container
759
+ return image_data.image_format, list(image_data.items)
760
+
761
+ def get_input_json(self, index: int = 0) -> list[list[Any]] | list[dict[str, Any]]:
762
+ """
763
+ Parse the JSON data from the request object.
764
+
765
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
766
+ :return: A list of parsed JSON objects. Each entry in the list represents a separate JSON entry from the input.
767
+ Depending on this tool, this may be a list of dictionaries or a list of lists.
768
+ """
769
+ return [json.loads(x) for x in self.request.input[index].item_container.json_container.items]
770
+
771
+ def get_input_text(self, index: int = 0) -> list[str]:
772
+ """
773
+ Parse the text data from the request object.
774
+
775
+ :param index: The index of the input to parse. Defaults to 0. Used for tools that accept multiple inputs.
776
+ :return: A list of text data as strings.
777
+ """
778
+ return list(self.request.input[index].item_container.text_container.items)
779
+
780
+ def get_config_defs(self) -> dict[str, VeloxFieldDefPbo]:
781
+ """
782
+ Get the config field definitions for this tool.
783
+
784
+ :return: A dictionary of field definitions, where the keys are the field names and the values are the
785
+ VeloxFieldDefPbo objects representing the field definitions.
786
+ """
787
+ field_defs: dict[str, VeloxFieldDefPbo] = {}
788
+ for field_def in self.to_pbo().config_fields:
789
+ field_defs[field_def.data_field_name] = field_def
790
+ return field_defs
791
+
792
+ def get_config_fields(self) -> dict[str, FieldValue]:
793
+ """
794
+ Get the configuration field values from the request object. If a field is not present in the request,
795
+ the default value from the config definition will be returned.
796
+
797
+ :return: A dictionary of configuration field names and their values.
798
+ """
799
+ config_fields: dict[str, Any] = {}
800
+ raw_configs: Mapping[str, FieldValuePbo] = self.request.config_field_values
801
+ for field_name, field_def in self.get_config_defs().items():
802
+ # Use the default value if the field is not present in the request.
803
+ if field_name not in raw_configs:
804
+ config_fields[field_name] = ProtobufUtils.field_def_pbo_to_default_value(field_def)
805
+ else:
806
+ config_fields[field_name] = ProtobufUtils.field_pbo_to_value(field_def, raw_configs[field_name])
807
+ return config_fields
808
+
809
+ @staticmethod
810
+ def read_from_json(json_data: list[dict[str, Any]], key: str) -> list[Any]:
811
+ """
812
+ From a list of dictionaries, return a list of values for the given key from each dictionary. Skips null values.
813
+
814
+ :param json_data: The JSON data to read from.
815
+ :param key: The key to read the values from.
816
+ :return: A list of values corresponding to the given key in the JSON data.
817
+ """
818
+ ret_val: list[Any] = []
819
+ for entry in json_data:
820
+ if key in entry:
821
+ value = entry[key]
822
+ if isinstance(value, list):
823
+ ret_val.extend(value)
824
+ elif value is not None:
825
+ ret_val.append(value)
826
+ return ret_val