kalbio 0.2.0__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.
kalbio/exports.py ADDED
@@ -0,0 +1,126 @@
1
+ """
2
+ Service class for handling data exports from Kaleidoscope.
3
+
4
+ This class provides methods to export and download data from the Kaleidoscope API,
5
+ specifically for pulling record search data and saving it as CSV files.
6
+
7
+ Classes:
8
+ ExportsService: Service class for exporting and downloading record search data as CSV.
9
+
10
+ Example:
11
+ ```python
12
+ # Pull data and download as CSV
13
+ file_path = client.exports_service.pull_data(
14
+ filename="my_export.csv",
15
+ entity_slice_id="some-uuid",
16
+ download_path="/path/to/downloads",
17
+ search_text="example"
18
+ )
19
+ ```
20
+ """
21
+
22
+ from typing import Optional
23
+ from kalbio.client import KaleidoscopeClient
24
+
25
+
26
+ class ExportsService:
27
+ """Service class for handling data exports from Kaleidoscope.
28
+
29
+ This class provides methods to export and download data from the Kaleidoscope API,
30
+ specifically for pulling record search data and saving it as CSV files.
31
+
32
+ Example:
33
+ ```python
34
+ # Pull data and download as CSV
35
+ file_path = client.exports_service.pull_data(
36
+ filename="my_export.csv",
37
+ entity_slice_id="some-uuid",
38
+ download_path="/path/to/downloads",
39
+ search_text="example"
40
+ )
41
+ ```
42
+ """
43
+
44
+ def __init__(self, client: "KaleidoscopeClient"):
45
+ self._client = client
46
+
47
+ def pull_data(
48
+ self,
49
+ filename: str,
50
+ entity_slice_id: str,
51
+ download_path: Optional[str] = None,
52
+ record_view_id: Optional[str] = None,
53
+ view_field_ids: Optional[str] = None,
54
+ identifier_ids: Optional[str] = None,
55
+ record_set_id: Optional[str] = None,
56
+ program_id: Optional[str] = None,
57
+ operation_id: Optional[str] = None,
58
+ record_set_filters: Optional[str] = None,
59
+ view_field_filters: Optional[str] = None,
60
+ view_field_sorts: Optional[str] = None,
61
+ entity_field_filters: Optional[str] = None,
62
+ entity_field_sorts: Optional[str] = None,
63
+ search_text: Optional[str] = None,
64
+ ) -> str | None:
65
+ """Pull record search data and download it as a CSV file.
66
+
67
+ This method interacts with the Kaleidoscope API to export records as a CSV file based on the provided parameters.
68
+ It supports filtering, sorting, and searching records, and allows specifying various identifiers and filters
69
+ to customize the export.
70
+
71
+ Args:
72
+ filename (str): The name of the CSV file to be downloaded.
73
+ entity_slice_id (str): The ID of the entity slice to export records from.
74
+ download_path (str, optional): The directory path where the CSV file will be saved. Defaults to None (uses '/tmp').
75
+ record_view_id (str, optional): The ID of the record view to filter records. Defaults to None.
76
+ view_field_ids (str, optional): Comma-separated IDs of view fields to include in the export. Defaults to None.
77
+ identifier_ids (str, optional): Comma-separated IDs of identifiers to filter records. Defaults to None.
78
+ record_set_id (str, optional): The ID of the record set to filter records. Defaults to None.
79
+ program_id (str, optional): The ID of the program to filter records. Defaults to None.
80
+ operation_id (str, optional): The ID of the operation to filter records. Defaults to None.
81
+ record_set_filters (str, optional): Filters to apply to the record set. Defaults to None.
82
+ view_field_filters (str, optional): Filters to apply to view fields. Defaults to None.
83
+ view_field_sorts (str, optional): Sorting options for view fields. Defaults to None.
84
+ entity_field_filters (str, optional): Filters to apply to entity fields. Defaults to None.
85
+ entity_field_sorts (str, optional): Sorting options for entity fields. Defaults to None.
86
+ search_text (str, optional): Text to search within records. Defaults to None.
87
+
88
+ Returns:
89
+ (str | None): The file path of the downloaded CSV file, or None if not successful.
90
+
91
+ API Reference:
92
+ https://kaleidoscope.readme.io/reference/get_records-export-csv
93
+ """
94
+
95
+ params = {
96
+ "filename": filename,
97
+ "entity_slice_id": entity_slice_id,
98
+ }
99
+
100
+ optional_params = {
101
+ "record_view_id": record_view_id,
102
+ "view_field_ids": view_field_ids,
103
+ "identifier_ids": identifier_ids,
104
+ "record_set_id": record_set_id,
105
+ "program_id": program_id,
106
+ "operation_id": operation_id,
107
+ "record_set_filters": record_set_filters,
108
+ "view_field_filters": view_field_filters,
109
+ "view_field_sorts": view_field_sorts,
110
+ "entity_field_filters": entity_field_filters,
111
+ "entity_field_sorts": entity_field_sorts,
112
+ "search_text": search_text,
113
+ }
114
+
115
+ params.update(
116
+ {key: value for key, value in optional_params.items() if value is not None}
117
+ )
118
+
119
+ url = "/records/export/csv"
120
+ file = self._client._get_file(
121
+ url,
122
+ f"{download_path if download_path else "/tmp"}/{filename}",
123
+ params,
124
+ )
125
+
126
+ return file
kalbio/helpers.py ADDED
@@ -0,0 +1,52 @@
1
+ """Module of helper methods for the Kaleidoscope Python Client.
2
+
3
+ This module provides utility functions for data transformation and other helper tasks.
4
+ Currently, it includes functionality to map field IDs to human-readable field names.
5
+
6
+ Functions:
7
+ export_data: Transforms data records by mapping field IDs to field names.
8
+
9
+ Example:
10
+ ```python
11
+ from kalbio.helpers import export_data
12
+
13
+ # Transform raw data with field IDs to data with field names
14
+ processed_data = export_data(client, raw_data)
15
+ ```
16
+ """
17
+
18
+ from kalbio.client import KaleidoscopeClient
19
+ from typing import Any, Dict, List
20
+
21
+
22
+ def export_data(
23
+ client: KaleidoscopeClient, data: List[Dict[str, Any]]
24
+ ) -> List[Dict[str, Any]]:
25
+ """Transform a list of data records by mapping field IDs to their corresponding field names.
26
+
27
+ This function takes raw data records where keys are field IDs and converts them into
28
+ records where keys are human-readable field names. It uses the KaleidoscopeClient to
29
+ retrieve field metadata and perform the mapping. If a field ID is not found in the
30
+ metadata, the original ID is preserved as the key.
31
+
32
+ Args:
33
+ client (KaleidoscopeClient): The client instance containing field metadata used
34
+ to map field IDs to field names.
35
+ data (List[Dict[str, Any]]): A list of records, each represented as a dictionary
36
+ mapping field IDs to their values.
37
+
38
+ Returns:
39
+ (List[Dict[str, Any]]): A list of transformed records, each represented as a dictionary
40
+ mapping field names (as keys) to their values.
41
+ """
42
+ key_fields = client.entity_fields.get_key_fields()
43
+ data_fields = client.entity_fields.get_data_fields()
44
+
45
+ id_to_field = {item.id: item for item in key_fields + data_fields}
46
+ return [
47
+ {
48
+ (id_to_field[id].field_name if id in id_to_field else id): value
49
+ for id, value in record.items()
50
+ }
51
+ for record in data
52
+ ]
kalbio/imports.py ADDED
@@ -0,0 +1,89 @@
1
+ """Service class for handling data imports into Kaleidoscope workspace.
2
+
3
+ This module provides the `ImportsService` class, which facilitates pushing data records
4
+ into the Kaleidoscope system. It supports flexible data import operations, allowing
5
+ organization by experiments, programs, and data sources.
6
+
7
+ Classes:
8
+ ImportsService: Service for handling data imports into the Kaleidoscope workspace, providing methods to push records organized by source, experiment, program, record views, and set names.
9
+
10
+ Example:
11
+ ```python
12
+ key_fields = ["id", "timestamp"]
13
+ records = [
14
+ {"id": "001", "timestamp": "2024-01-01", "value": 42.5, "status": "active"},
15
+ {"id": "002", "timestamp": "2024-01-02", "value": 38.7, "status": "pending"}
16
+ ]
17
+ # Push data to a specific source and experiment
18
+ response = client.imports.push_data(
19
+ key_field_names=key_fields,
20
+ data=records,
21
+ source_id="data_source_123",
22
+ operation_id="exp_456",
23
+ set_name="january_batch"
24
+ )
25
+ ```
26
+ """
27
+
28
+ from typing import Any, Optional
29
+ from kalbio.client import KaleidoscopeClient
30
+
31
+
32
+ class ImportsService:
33
+ """Service class for handling data imports into Kaleidoscope workspace.
34
+
35
+ This service provides functionality to push data records into the workspace,
36
+ with support for organizing data by sources, experiments, programs, and record views.
37
+
38
+ Methods:
39
+ push_data: Imports data records into the workspace with various organizational options.
40
+ """
41
+
42
+ def __init__(self, client: KaleidoscopeClient):
43
+ self._client = client
44
+
45
+ def push_data(
46
+ self,
47
+ key_field_names: list[str],
48
+ data: list[dict[str, Any]],
49
+ source_id: Optional[str] = None,
50
+ operation_id: Optional[str] = None,
51
+ program_id: Optional[str] = None,
52
+ record_view_ids: Optional[list[str]] = [],
53
+ set_name: Optional[str] = None,
54
+ ) -> Any:
55
+ """Import data into the workspace.
56
+
57
+ Sends a list of records, each represented as a dictionary of field names and values,
58
+ to the Kaleidoscope workspace.
59
+
60
+ Args:
61
+ key_field_names (list[str]): List of field names that serve as keys for the records.
62
+ data (list[dict[str, Any]]): List of records to import, each as a dictionary mapping field names to values.
63
+ source_id (str, optional): Identifier for the data source. If provided, data is imported under this source.
64
+ operation_id (str, optional): Identifier for the experiment. If provided, data is imported into this specific experiment.
65
+ program_id (str, optional): Identifier for the program. If provided, data is imported under this program.
66
+ record_view_ids (list[str], optional): List of record view IDs to associate with the imported data.
67
+ set_name (str, optional): Name of the set to which the imported data belongs.
68
+
69
+ Returns:
70
+ Any: Response object from the client's POST request to the import endpoint.
71
+ """
72
+ payload = {
73
+ "key_field_names": key_field_names,
74
+ "data": data,
75
+ "record_view_ids": record_view_ids,
76
+ }
77
+
78
+ if program_id:
79
+ payload["program_id"] = program_id
80
+ if operation_id:
81
+ payload["operation_id"] = operation_id
82
+ if set_name:
83
+ payload["set_name"] = set_name
84
+
85
+ url = "/push/imports"
86
+ if source_id:
87
+ url = url + f"/{source_id}"
88
+
89
+ return self._client._post(url, payload)
kalbio/labels.py ADDED
@@ -0,0 +1,88 @@
1
+ """Module for managing task labels in Kaleidoscope.
2
+
3
+ This module provides classes and services for working with task labels,
4
+ including retrieval and filtering of labels from the Kaleidoscope workspace.
5
+
6
+ Classes:
7
+ Label: Represents a task label with an ID and name.
8
+ LabelsService: Service class for interacting with label-related API endpoints.
9
+ """
10
+
11
+ import logging
12
+
13
+ from functools import lru_cache
14
+ from typing import List
15
+ from kalbio._kaleidoscope_model import _KaleidoscopeBaseModel
16
+ from kalbio.client import KaleidoscopeClient
17
+ from pydantic import TypeAdapter
18
+
19
+ _logger = logging.getLogger(__name__)
20
+
21
+
22
+ class Label(_KaleidoscopeBaseModel):
23
+ """A class representing a label in the Kaleidoscope system.
24
+
25
+ This class extends _KaleidoscopeBaseModel and provides functionality for
26
+ managing label data including serialization and string representations.
27
+
28
+ Attributes:
29
+ label_name (str): The name of the label.
30
+ """
31
+
32
+ label_name: str
33
+
34
+ def __str__(self):
35
+ return f"{self.label_name}"
36
+
37
+
38
+ class LabelsService:
39
+ """Service class for managing and retrieving task labels from Kaleidoscope.
40
+
41
+ This service provides methods to fetch labels from the Kaleidoscope workspace
42
+ and filter them by specific criteria. It uses caching to optimize repeated
43
+ label retrieval requests.
44
+
45
+ Example:
46
+ ```python
47
+ # get all labels
48
+ all_labels = client.labels.get_labels()
49
+
50
+ # get labels by id
51
+ specific_labels = client.labels.get_labels_by_ids(['id1', 'id2'])
52
+ ```
53
+ """
54
+
55
+ def __init__(self, client: KaleidoscopeClient):
56
+ self._client = client
57
+
58
+ @lru_cache
59
+ def get_labels(self) -> List[Label]:
60
+ """Retrieve the task labels defined in the workspace.
61
+
62
+ This method caches its values.
63
+
64
+ Returns:
65
+ List[Label]: The labels in the workspace.
66
+
67
+ Note:
68
+ If an exception occurs during the API request, it logs the error,
69
+ clears the cache, and returns an empty list.
70
+ """
71
+ try:
72
+ resp = self._client._get("/activity_labels")
73
+ return TypeAdapter(List[Label]).validate_python(resp)
74
+ except Exception as e:
75
+ _logger.error(f"Error fetching labels: {e}")
76
+ self.get_labels.cache_clear()
77
+ return []
78
+
79
+ def get_labels_by_ids(self, ids: List[str]) -> List[Label]:
80
+ """Retrieve a list of Label objects whose IDs match the provided list.
81
+
82
+ Args:
83
+ ids (List[str]): A list of label IDs to filter by.
84
+
85
+ Returns:
86
+ List[Label]: A list of Label instances with IDs found in ids.
87
+ """
88
+ return [label for label in self.get_labels() if label.id in ids]
kalbio/programs.py ADDED
@@ -0,0 +1,96 @@
1
+ """Programs module for interacting with Kaleidoscope programs/experiments.
2
+
3
+ The service allows users to retrieve all available programs in a workspace
4
+ and filter programs by specific IDs.
5
+
6
+ Classes:
7
+ Program: Data model for a Kaleidoscope program/experiment.
8
+ ProgramsService: Service for managing program retrieval operations.
9
+
10
+ Example:
11
+ ```python
12
+ # get all programs in the workspace
13
+ programs = client.programs.get_programs()
14
+
15
+ # get several programs by their ids
16
+ filtered = client.programs.get_program_by_ids(['prog1_uuid', 'prog2_uuid'])
17
+ ```
18
+ """
19
+
20
+ import logging
21
+ from functools import lru_cache
22
+ from kalbio._kaleidoscope_model import _KaleidoscopeBaseModel
23
+ from kalbio.client import KaleidoscopeClient
24
+ from pydantic import TypeAdapter
25
+ from typing import List
26
+
27
+ _logger = logging.getLogger(__name__)
28
+
29
+
30
+ class Program(_KaleidoscopeBaseModel):
31
+ """Represents a program in the Kaleidoscope system.
32
+
33
+ A Program is a base model that contains identifying information about
34
+ a program, including its title and ID.
35
+
36
+ Attributes:
37
+ title (str): The title/name of the program.
38
+ """
39
+
40
+ title: str
41
+
42
+ def __str__(self):
43
+ return f"{self.title}"
44
+
45
+
46
+ class ProgramsService:
47
+ """Service class for managing and retrieving programs (experiments) from Kaleidoscope.
48
+
49
+ This service provides methods to interact with the programs API endpoint,
50
+ allowing users to fetch all available programs or filter programs by their IDs.
51
+
52
+ Example:
53
+ ```python
54
+ # get all programs in the workspace
55
+ programs = client.programs.get_programs()
56
+
57
+ # get several programs by their ids
58
+ filtered = client.programs.get_program_by_ids(['prog1_uuid', 'prog2_uuid'])
59
+ ```
60
+ """
61
+
62
+ def __init__(self, client: KaleidoscopeClient):
63
+ self._client = client
64
+
65
+ @lru_cache
66
+ def get_programs(self) -> List[Program]:
67
+ """Retrieve all programs (experiments) available in the workspace.
68
+
69
+ This method caches its values.
70
+
71
+ Returns:
72
+ List[Program]: A list of Program objects representing the experiments in the workspace.
73
+
74
+ Note:
75
+ If an exception occurs during the API request, it logs the error,
76
+ clears the cache, and returns an empty list.
77
+ """
78
+ try:
79
+ resp = self._client._get("/programs")
80
+ return TypeAdapter(List[Program]).validate_python(resp)
81
+ except Exception as e:
82
+ _logger.error(f"Error fetching programs: {e}")
83
+ self.get_programs.cache_clear()
84
+ return []
85
+
86
+ def get_programs_by_ids(self, ids: List[str]) -> List[Program]:
87
+ """Retrieve a list of Program objects whose IDs match the provided list.
88
+
89
+ Args:
90
+ ids (List[str]): A list of program IDs to filter by.
91
+
92
+ Returns:
93
+ List[Program]: A list of Program instances with IDs found in ids.
94
+ """
95
+ programs = self.get_programs()
96
+ return [program for program in programs if program.id in ids]
@@ -0,0 +1,81 @@
1
+ """Service for managing property field definitions in Kaleidoscope.
2
+
3
+ This module provides classes and services for working with property fields, which define
4
+ named properties with descriptions and data types used to structure and validate data
5
+ within the Kaleidoscope framework.
6
+
7
+ Classes:
8
+ PropertyField: Represents a single property field with name, description, and type.
9
+ PropertyFieldsService: Service for retrieving and managing property field definitions.
10
+
11
+ Example:
12
+ ```python
13
+ fields = client.property_fields.get_property_fields()
14
+ for field in fields:
15
+ print(f"{field.property_name}: {field.field_type}")
16
+ ```
17
+ """
18
+
19
+ import logging
20
+ from functools import lru_cache
21
+ from typing import List
22
+ from pydantic import TypeAdapter
23
+ from kalbio._kaleidoscope_model import _KaleidoscopeBaseModel
24
+ from kalbio.client import KaleidoscopeClient
25
+ from kalbio.entity_fields import DataFieldTypeEnum
26
+
27
+ _logger = logging.getLogger(__name__)
28
+
29
+
30
+ class PropertyField(_KaleidoscopeBaseModel):
31
+ """Represents a property field in the Kaleidoscope system.
32
+
33
+ A PropertyField defines a named property with a description and data type,
34
+ used to structure and validate data within the Kaleidoscope framework.
35
+
36
+ Attributes:
37
+ property_name (str): The name of the property field.
38
+ property_description (str): A human-readable description of the property.
39
+ field_type (DataFieldTypeEnum): The data type of the field.
40
+ """
41
+
42
+ property_name: str
43
+ property_description: str
44
+ field_type: DataFieldTypeEnum
45
+
46
+ def __str__(self):
47
+ return f"{self.property_name}"
48
+
49
+
50
+ class PropertyFieldsService:
51
+ """Service class for managing property fields in Kaleidoscope.
52
+
53
+ This service provides methods to retrieve and manage property field definitions
54
+ from the Kaleidoscope API. It uses caching to optimize repeated requests for
55
+ property field data.
56
+
57
+ """
58
+
59
+ def __init__(self, client: KaleidoscopeClient):
60
+ self._client = client
61
+
62
+ @lru_cache
63
+ def get_property_fields(self) -> List[PropertyField]:
64
+ """Retrieve the property fields from the client.
65
+
66
+ This method caches its values.
67
+
68
+ Returns:
69
+ List[PropertyField]: A list of PropertyField objects representing the property fields in the workspace.
70
+
71
+ Note:
72
+ If an exception occurs during the API request, it logs the error,
73
+ clears the cache, and returns an empty list.
74
+ """
75
+ try:
76
+ resp = self._client._get("/property_fields")
77
+ return TypeAdapter(List[PropertyField]).validate_python(resp)
78
+ except Exception as e:
79
+ _logger.error(f"Error fetching property fields: {e}")
80
+ self.get_property_fields.cache_clear()
81
+ return []