pollen-smart-api 3.145.1__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.
smapi/ChartRestApi.py ADDED
@@ -0,0 +1,558 @@
1
+ # -*- coding: utf-8 -*-
2
+ # ------------------------------------------------------------------------------------------------- #
3
+ # Pollen Metrology PUBLIC PYTHON SDK #
4
+ # ------------------------------------------------------------------------------------------------- #
5
+ # [2014-2025] Pollen Metrology
6
+ # All Rights Reserved.
7
+ #
8
+ # NOTICE: All information contained herein is, and remains the property of Pollen Metrology.
9
+ # The intellectual and technical concepts contained herein are proprietary to Pollen Metrology and
10
+ # may be covered by French, European and/or Foreign Patents, patents in process, and are protected
11
+ # by trade secret or copyright law.
12
+ # Dissemination of this information or reproduction of this material is strictly forbidden unless
13
+ # prior written permission is obtained from Pollen Metrology.
14
+ # ------------------------------------------------------------------------------------------------- #
15
+
16
+ from typing import List, Dict, Union, Optional, Any, Tuple
17
+ from uuid import UUID
18
+
19
+ from typeguard import typechecked
20
+
21
+ from .AbstractRestApi import AbstractRestApi
22
+ from .DataReference import DataReference
23
+
24
+ # ================================================================================================= #
25
+
26
+
27
+ @typechecked
28
+ class ChartPipeline(DataReference):
29
+ """Available chart pipeline information
30
+
31
+ This class represents the configuration and attributes of a chart pipeline. It includes details such as the label,
32
+ description, category, version, input parameters, and more."""
33
+
34
+ __slots__ = (
35
+ "label",
36
+ "description",
37
+ "auto",
38
+ "category",
39
+ "version",
40
+ "inputs",
41
+ "icon",
42
+ "complexTypes",
43
+ "uiSchema",
44
+ "hasDynamicInputSchema",
45
+ )
46
+
47
+ def __init__(
48
+ self,
49
+ identifier: Optional[str] = None,
50
+ attributes: Optional[Dict[str, Any]] = None,
51
+ ) -> None:
52
+ super(ChartPipeline, self).__init__(identifier)
53
+
54
+ if attributes:
55
+ #: Chart label
56
+ self.label: str = attributes.get("label")
57
+ #: Chart description
58
+ self.description: str = attributes.get("description")
59
+ #: Indicates whether charts will be automatically visualized in the graphical interface without user interaction
60
+ self.auto: bool = attributes.get("auto")
61
+ #: Chart category
62
+ self.category: str = attributes.get("category")
63
+ #: Chart version
64
+ self.version: str = attributes.get("version")
65
+ #: JSON Schema defining the input parameters for chart generation
66
+ self.inputs: Dict[str, Any] = attributes.get("inputs")
67
+ #: SVG icon representing the chart type
68
+ self.icon: Optional[str] = attributes.get("icon")
69
+ #: Complex type definitions for advanced chart configuration
70
+ self.complexTypes: Optional[List[Tuple[str, str]]] = attributes.get("complexTypes")
71
+ #: UI schema for form rendering in the user interface
72
+ self.uiSchema: Optional[Dict[str, Any]] = attributes.get("uiSchema")
73
+ #: Indicates whether the chart has dynamic input schema support
74
+ self.hasDynamicInputSchema: bool = attributes.get("hasDynamicInputSchema", False)
75
+
76
+ def equivalent(self, other: "ChartPipeline", uuidMap: Dict[UUID, UUID]) -> bool:
77
+ """Compares this ChartPipeline instance with another for equivalence.
78
+
79
+ Args:
80
+ other (ChartPipeline): The other ChartPipeline instance to compare.
81
+ uuidMap (Dict[UUID, UUID]): A mapping of UUIDs for comparison.
82
+
83
+ Returns:
84
+ bool: True if equivalent, False otherwise.
85
+ """
86
+ return (
87
+ self.label == other.label
88
+ and self.description == other.description
89
+ and self.auto == other.auto
90
+ and self.category == other.category
91
+ and self.version == other.version
92
+ and self.inputs == other.inputs
93
+ and self.icon == other.icon
94
+ and self.complexTypes == other.complexTypes
95
+ and self.uiSchema == other.uiSchema
96
+ and uuidMap[self.identifier] == other.identifier
97
+ )
98
+
99
+ def __repr__(self) -> str:
100
+ return f"ChartPipeline({self.identifier}, {self.label})"
101
+
102
+ @staticmethod
103
+ def data_from_dictionary_internal(dictionary: Dict[str, Any]) -> "ChartPipeline":
104
+ if "id" not in dictionary or "attributes" not in dictionary:
105
+ raise RuntimeError("Unable to create the chart pipeline information!")
106
+
107
+ return ChartPipeline(
108
+ identifier=dictionary.get("id"), attributes=dictionary.get("attributes")
109
+ )
110
+
111
+ @classmethod
112
+ def type(cls) -> str:
113
+ """Returns the string "Charts"."""
114
+ return "Charts"
115
+
116
+
117
+ @typechecked
118
+ class ChartPipelineWithData(ChartPipeline):
119
+ """
120
+ ChartPipelineWithData extends ChartPipeline by adding a `data` field.
121
+
122
+ This class is intended to represent responses coming from the
123
+ dynamic input schema endpoint which return the usual chart pipeline
124
+ information along with an additional `data` payload.
125
+ """
126
+
127
+ __slots__ = ("data",)
128
+
129
+ def __init__(
130
+ self,
131
+ identifier: Optional[str] = None,
132
+ attributes: Optional[Dict[str, Any]] = None,
133
+ ) -> None:
134
+ # Initialize the base ChartPipeline fields
135
+ super(ChartPipelineWithData, self).__init__(identifier, attributes)
136
+
137
+ # Additional data returned by the dynamic input schema endpoint
138
+ self.data: Optional[Dict] = (
139
+ attributes.get("data") if attributes and "data" in attributes else None
140
+ )
141
+
142
+ @staticmethod
143
+ def data_from_dictionary_internal(dictionary: Dict[str, Any]) -> "ChartPipelineWithData":
144
+ """Create a ChartPipelineWithData from a JSON dictionary representing a single resource."""
145
+ return ChartPipelineWithData(
146
+ attributes=dictionary.get("attributes"),
147
+ identifier=dictionary.get("id"),
148
+ )
149
+
150
+ @classmethod
151
+ def type(cls) -> str:
152
+ # Same type name as ChartPipeline (resource is still a Chart)
153
+ return ChartPipeline.type()
154
+
155
+
156
+ @typechecked
157
+ class ChartInformation(DataReference):
158
+ """Charts information
159
+
160
+ This class represents the information related to a chart, including its global status and title.
161
+
162
+ Args:
163
+ id (Optional[str]): The identifier of the chart.
164
+ isGlobal (Optional[bool]): Indicates if the chart is global.
165
+ title (Optional[str]): The title of the chart.
166
+ """
167
+
168
+ __slots__ = ("is_global", "title")
169
+
170
+ def __init__(
171
+ self,
172
+ id: Optional[str] = None,
173
+ isGlobal: Optional[bool] = None,
174
+ title: Optional[str] = None,
175
+ ) -> None:
176
+ super(ChartInformation, self).__init__(id)
177
+
178
+ #: Indicates if the chart is global.
179
+ self.is_global: Optional[bool] = isGlobal
180
+ #: Title of the chart
181
+ self.title: Optional[str] = title
182
+
183
+ def equivalent(self, other: "ChartInformation", uuidMap: Dict[UUID, UUID]) -> bool:
184
+ """Compares this ChartInformation instance with another for equivalence.
185
+
186
+ Args:
187
+ other (ChartInformation): The other ChartInformation instance to compare.
188
+ uuidMap (Dict[UUID, UUID]): A mapping of UUIDs for comparison.
189
+
190
+ Returns:
191
+ bool: True if equivalent, False otherwise.
192
+ """
193
+ return (
194
+ self.is_global == other.is_global
195
+ and self.title == other.title
196
+ and uuidMap[self.identifier] == other.identifier
197
+ )
198
+
199
+ def __repr__(self) -> str:
200
+ return str(self.identifier)
201
+
202
+
203
+ # ================================================================================================= #
204
+
205
+
206
+ @typechecked
207
+ class ChartRelationship(object):
208
+ """Relationships associated with the chart.
209
+
210
+ This class encapsulates the relationships related to a chart, including any associated analysis results
211
+ and the chart pipeline itself. It provides methods to convert the relationships to a detailed string
212
+ representation and to a dictionary format for serialization.
213
+
214
+ Args:
215
+ relationships_data (Dict[str, Any]): A dictionary containing the relationships data for the chart.
216
+ """
217
+
218
+ __slots__ = ("analysis_result", "chart")
219
+
220
+ def __init__(self, relationships_data: Dict[str, Any]) -> None:
221
+ from .AnalysisResultsRestApi import Analysis
222
+
223
+ #: Analysis result associated to the chart (if present).
224
+ self.analysis_result: Optional[DataReference] = None
225
+ if "analysisResult" in relationships_data:
226
+ self.analysis_result = Analysis.reference_from_dictionary(
227
+ relationships_data["analysisResult"]
228
+ )
229
+
230
+ #: Chart pipeline associated to the chart (if present).
231
+ self.chart: Optional[DataReference] = None
232
+ if "chart" in relationships_data:
233
+ chart_data = relationships_data["chart"]
234
+ if "data" in chart_data:
235
+ chart_ref_data = chart_data["data"]
236
+ if "id" in chart_ref_data and "type" in chart_ref_data:
237
+ self.chart = ChartPipeline.reference_from_dictionary(chart_ref_data)
238
+
239
+ def to_detailed_string(self) -> str:
240
+ """Returns a detailed string representation of the ChartRelationship instance."""
241
+ parts = []
242
+ if self.analysis_result:
243
+ parts.append(f"analysis_result = {self.analysis_result}")
244
+ if self.chart:
245
+ parts.append(f"chart = {self.chart}")
246
+ return f"( {', '.join(parts)} )"
247
+
248
+ def to_dictionary(self) -> Dict[str, Any]:
249
+ """Converts the ChartRelationship instance to a dictionary format.
250
+
251
+ Returns:
252
+ Dict[str, Any]: A dictionary representation of the relationships.
253
+ """
254
+ result = {}
255
+ if self.analysis_result:
256
+ result["analysis_result"] = self.analysis_result
257
+ if self.chart:
258
+ result["chart"] = self.chart
259
+ return result
260
+
261
+ def equivalent(self, other: "ChartRelationship", uuidMap: Dict[UUID, UUID]) -> bool:
262
+ """Compares this ChartRelationship instance with another for equivalence.
263
+
264
+ Args:
265
+ other (ChartRelationship): The other ChartRelationship instance to compare.
266
+ uuidMap (Dict[UUID, UUID]): A mapping of UUIDs for comparison.
267
+
268
+ Returns:
269
+ bool: True if equivalent, False otherwise.
270
+ """
271
+ analysis_result_equivalent = True
272
+ if self.analysis_result and other.analysis_result:
273
+ analysis_result_equivalent = (
274
+ uuidMap[self.analysis_result.identifier] == other.analysis_result.identifier
275
+ )
276
+ elif self.analysis_result or other.analysis_result:
277
+ analysis_result_equivalent = False
278
+
279
+ chart_equivalent = True
280
+ if self.chart and other.chart:
281
+ chart_equivalent = uuidMap[self.chart.identifier] == other.chart.identifier
282
+ elif self.chart or other.chart:
283
+ chart_equivalent = False
284
+
285
+ return analysis_result_equivalent and chart_equivalent
286
+
287
+
288
+ @typechecked
289
+ class Chart(DataReference):
290
+ """Chart related information.
291
+
292
+ This class encapsulates the details of a chart, including its data, options, plugins, rendering library,
293
+ title, type, and relationships. It provides methods for creating a chart from a dictionary and for
294
+ comparing chart instances for equivalence.
295
+
296
+ Args:
297
+ attributes (Dict[str, Any]): A dictionary containing chart attributes.
298
+ relationships (Dict[str, Any]): A dictionary containing relationships associated with the chart.
299
+ identifier (Optional[str]): An optional identifier for the chart.
300
+ """
301
+
302
+ __slots__ = (
303
+ "data",
304
+ "options",
305
+ "plugins",
306
+ "renderLibrary",
307
+ "title",
308
+ "ctype",
309
+ "relationships",
310
+ "layout",
311
+ "config",
312
+ )
313
+
314
+ def __init__(
315
+ self,
316
+ attributes: Dict[str, Any],
317
+ relationships: Dict[str, Any],
318
+ identifier: Optional[str] = None,
319
+ ) -> None:
320
+ super(Chart, self).__init__(identifier)
321
+
322
+ render_library: Optional[str] = attributes.get("renderLibrary")
323
+
324
+ #: Values contained in the chart.
325
+ if render_library == "plotly":
326
+ self.data: Union[Dict[str, Any], List[Dict[str, Any]]] = (
327
+ attributes.get("configuration")["data"]
328
+ if "configuration" in attributes
329
+ else attributes.get("data")
330
+ )
331
+ #: Plotly layout configuration
332
+ self.layout: Optional[Dict[str, Any]] = attributes.get("layout")
333
+ #: Plotly configuration options
334
+ self.config: Optional[Dict[str, Any]] = attributes.get("config")
335
+ #: Chart options (not used for Plotly)
336
+ self.options: Optional[Dict[str, Any]] = None
337
+ #: Chart plugins (not used for Plotly)
338
+ self.plugins: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = None
339
+ else:
340
+ self.data: Union[Dict[str, Any], List[Dict[str, Any]]] = attributes.get("data")
341
+ #: Options of the chart (e.g. border color, background color, ...).
342
+ self.options: Optional[Dict[str, Any]] = attributes.get("options")
343
+ #: Additional features provided as plugins by the underlying charts render library (e.g. legend, title, tooltips, ...).
344
+ self.plugins: Optional[Union[Dict[str, Any], List[Dict[str, Any]]]] = attributes.get(
345
+ "plugins"
346
+ )
347
+ #: No layout/config for other libraries
348
+ self.layout: Optional[Dict[str, Any]] = None
349
+ self.config: Optional[Dict[str, Any]] = None
350
+
351
+ #: The underlying library used for render chart (e.g. "chart.js").
352
+ self.renderLibrary: Optional[str] = render_library
353
+ #: Title of the chart.
354
+ self.title: Optional[str] = attributes.get("title")
355
+ #: Type of rendered chart (e.g. bubble, scatter, bar, area, ....).
356
+ self.ctype: Optional[str] = attributes.get("type")
357
+ #: Relationships associated with the chart.
358
+ self.relationships: ChartRelationship = ChartRelationship(relationships)
359
+
360
+ def __repr__(self) -> str:
361
+ return str(self.identifier)
362
+
363
+ @staticmethod
364
+ def data_from_dictionary_internal(dictionary: Dict[str, Any]) -> "Chart":
365
+ if "id" not in dictionary or "attributes" not in dictionary:
366
+ raise RuntimeError("Unable to create the chart information !")
367
+
368
+ return Chart(
369
+ identifier=dictionary.get("id"),
370
+ attributes=dictionary.get("attributes"),
371
+ relationships=dictionary.get("relationships", {}),
372
+ )
373
+
374
+ def equivalent(self, other: "Chart", uuidMap: Dict[UUID, UUID]) -> bool:
375
+ """Compares this Chart instance with another for equivalence.
376
+
377
+ Args:
378
+ other (Chart): The other Chart instance to compare.
379
+ uuidMap (Dict[UUID, UUID]): A mapping of UUIDs for comparison.
380
+
381
+ Returns:
382
+ bool: True if equivalent, False otherwise.
383
+ """
384
+ gdata: bool = (
385
+ self.data,
386
+ self.options,
387
+ self.plugins,
388
+ self.renderLibrary,
389
+ self.title,
390
+ self.ctype,
391
+ self.layout,
392
+ self.config,
393
+ ) == (
394
+ other.data,
395
+ other.options,
396
+ other.plugins,
397
+ other.renderLibrary,
398
+ other.title,
399
+ other.ctype,
400
+ other.layout,
401
+ other.config,
402
+ )
403
+ if not gdata:
404
+ return False
405
+
406
+ return (
407
+ self.relationships.equivalent(other.relationships, uuidMap)
408
+ and other.identifier != self.identifier
409
+ )
410
+
411
+ @classmethod
412
+ def type(cls) -> str:
413
+ """Returns the string "Charts"."""
414
+ return "Charts"
415
+
416
+
417
+ # ================================================================================================= #
418
+
419
+
420
+ @typechecked
421
+ class ChartRestApi(AbstractRestApi):
422
+ """Chart REST API
423
+
424
+ This class provides methods to interact with the Chart REST API, allowing users to retrieve available chart pipelines,
425
+ generate charts based on input parameters, compute a single chart, and get information about specific charts.
426
+ """
427
+
428
+ __slots__ = list()
429
+
430
+ def available(self) -> List[ChartPipeline]:
431
+ """Get available charts.
432
+
433
+ Returns:
434
+ ChartPipeline: List of available chart pipelines with their configuration
435
+ """
436
+ data: Dict[str, Any] = self._get(entrypoint=f"charts")
437
+ return ChartPipeline.data_from_dictionary(data)
438
+
439
+ def generate(self, charts_requests: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
440
+ """Generate charts based on the provided input parameters.
441
+
442
+ This method takes a list of chart generation requests, each containing the UUID of the chart type to generate
443
+ and a dictionary of input parameters. It sends a request to the Chart REST API to generate the specified charts
444
+ and returns the generated charts data.
445
+
446
+ Args:
447
+ charts_requests (List[Dict[str, Any]]): A list of dictionaries where each dictionary contains:
448
+ - id (str): UUID of the chart type to generate.
449
+ - inputs (Dict[str, Any]): A dictionary of input parameters for the chart generation.
450
+
451
+ Returns:
452
+ List[Dict[str, Any]]: A list of dictionaries containing the generated charts data.
453
+
454
+ Raises:
455
+ RuntimeError: If the chart generation request fails or returns an error.
456
+ """
457
+ payload: Dict[str, Any] = dict(
458
+ data=[
459
+ dict(
460
+ id=str(request["id"]),
461
+ type=Chart.type(),
462
+ attributes=dict(inputs=request["inputs"]),
463
+ )
464
+ for request in charts_requests
465
+ ]
466
+ )
467
+
468
+ data: Dict[str, Any] = self._post(entrypoint=f"charts/execute", payload=payload)
469
+ return data.get("data", [])
470
+
471
+ def compute(self, chart: Union[UUID, str], inputs: Dict[str, Any]) -> Chart:
472
+ """Generate a single chart based on the provided chart type and input parameters.
473
+
474
+ This method serves as a compatibility function to generate a chart using the specified chart type identifier
475
+ (either a UUID or a string) and a dictionary of input parameters. It internally calls the `generate` method
476
+ to create the chart and returns the resulting `Chart` object.
477
+
478
+ Args:
479
+ chart (Union[UUID, str]): The UUID or string identifier of the chart type to generate.
480
+ inputs (Dict[str, Any]): A dictionary containing the input parameters required for chart generation.
481
+
482
+ Returns:
483
+ Chart: The generated `Chart` object based on the provided inputs.
484
+
485
+ Raises:
486
+ RuntimeError: If the chart generation fails or if no charts are generated.
487
+ """
488
+ charts_data: List[Dict[str, Any]] = self.generate([{"id": chart, "inputs": inputs}])
489
+ if charts_data:
490
+ return Chart.data_from_dictionary_internal(charts_data[0])
491
+ raise RuntimeError("Unable to generate chart")
492
+
493
+ def get(self, identifiers: Optional[List[Union[UUID, str]]] = None) -> List[Chart]:
494
+ """Get charts information.
495
+
496
+ This method retrieves information about charts based on the provided identifiers. If a list of identifiers is
497
+ provided, it fetches the details for those specific charts. If no identifiers are given, it retrieves all
498
+ available charts.
499
+
500
+ Args:
501
+ identifiers (Optional[List[Union[UUID, str]]]): A list of chart identifiers (UUIDs or strings) to retrieve.
502
+ If None or empty, retrieves all charts.
503
+
504
+ Returns:
505
+ List[Chart]: A list of Chart objects containing the information of the requested charts.
506
+ """
507
+ if identifiers and len(identifiers) > 0:
508
+ identifier_list: str = ",".join(map(str, identifiers))
509
+ data: Dict[str, Any] = self._get(
510
+ entrypoint=f"charts/result?filter[id]={identifier_list}"
511
+ )
512
+ else:
513
+ data: Dict[str, Any] = self._get(entrypoint=f"charts/result")
514
+
515
+ return Chart.data_from_dictionary(data)
516
+
517
+ def get_dynamic_input_schema(
518
+ self,
519
+ identifier: Union[UUID, str],
520
+ **kwargs,
521
+ ) -> ChartPipelineWithData:
522
+ """Get the dynamic input schema for a specific chart by its identifier.
523
+
524
+ This method calls the charts/input endpoint with the chart identifier and input parameters
525
+ to retrieve the dynamic input schema and data for the chart.
526
+
527
+ Args:
528
+ identifier (Union[UUID, str]): The UUID or string identifier of the chart.
529
+ **kwargs: Additional input parameters to pass to the dynamic input schema endpoint.
530
+
531
+ Returns:
532
+ ChartPipelineWithData: A ChartPipelineWithData object containing the chart pipeline
533
+ information along with the dynamic data.
534
+ """
535
+ # Create inputs payload from kwargs
536
+ inputs: Dict = {}
537
+ for key, value in kwargs.items():
538
+ inputs[key] = value
539
+
540
+ # Build the payload with a list containing a single chart request
541
+ payload: Dict = dict(
542
+ data=[
543
+ dict(
544
+ id=str(identifier),
545
+ type=ChartPipeline.type(),
546
+ attributes=dict(inputs=inputs),
547
+ )
548
+ ]
549
+ )
550
+
551
+ # POST to charts/input endpoint
552
+ data: Dict = self._post(entrypoint=f"charts/input", payload=payload)
553
+
554
+ # Extract the first chart from the response data array
555
+ if "data" in data and isinstance(data["data"], list) and len(data["data"]) > 0:
556
+ return ChartPipelineWithData.data_from_dictionary_internal(data["data"][0])
557
+
558
+ raise RuntimeError("Unable to get dynamic input schema for chart")