qubicon 1.0.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.
qubicon/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ from .config import Config
2
+ from .auth import authenticate
3
+ from .api.models import Models
4
+ from .api.quantities import Quantities
5
+ from .api.processes import Processes
6
+
7
+ __all__ = [
8
+ 'Config',
9
+ 'authenticate',
10
+ 'Models',
11
+ 'Quantities',
12
+ 'Processes',
13
+ ]
@@ -0,0 +1,9 @@
1
+ from .models import Models
2
+ from .quantities import Quantities
3
+ from .processes import Processes
4
+
5
+ __all__ = [
6
+ 'Models',
7
+ 'Quantities',
8
+ 'Processes',
9
+ ]
qubicon/api/models.py ADDED
@@ -0,0 +1,237 @@
1
+ from ..utils import make_request
2
+ from ..logger import get_logger
3
+ from ..utils import make_request
4
+ from .quantities import Quantities
5
+ import json
6
+
7
+ class Models:
8
+ def __init__(self, config):
9
+ self.config = config
10
+ self.endpoint = f"{self.config.base_url}/api/computable-models"
11
+ self.logger = get_logger(self.__class__.__name__)
12
+ self.headers = {'Authorization': f'Bearer {self.config.load_token()}', 'Content-Type': 'application/json'}
13
+ self.physical_quantities = Quantities(config) # Delegate handling to the PhysicalQuantities class
14
+
15
+ def list(self, params=None):
16
+ """
17
+ Retrieve a list of models with the same query parameters as the command-line client.
18
+ :param params: Optional dictionary of query parameters.
19
+ :return: List of models (dictionary containing model details).
20
+ """
21
+ headers = {'Authorization': f'Bearer {self.config.load_token()}'}
22
+ # Define the same query parameters used in the command-line client
23
+ default_params = {
24
+ 'search': '',
25
+ 'size': 50,
26
+ 'sort': 'updateDate,desc',
27
+ 'page': 0,
28
+ 'statuses': 'DRAFT,RELEASED'
29
+ }
30
+
31
+ # Merge any additional params provided with the default ones
32
+ if params:
33
+ default_params.update(params)
34
+
35
+ self.logger.info("Fetching list of models with query parameters...")
36
+
37
+ try:
38
+ # Make request to the API endpoint with proper query params
39
+ response = make_request('GET', self.endpoint, headers=headers, params=default_params, timeout=self.config.timeout)
40
+
41
+ # Handle the response and ensure the 'content' field contains models
42
+ if 'content' in response:
43
+ return response['content'] # Return the list of models
44
+ else:
45
+ self.logger.error("Unexpected response format when fetching models.")
46
+ return []
47
+ except Exception as e:
48
+ self.logger.error(f"Error fetching models: {e}")
49
+ return []
50
+
51
+
52
+ def get_model_dict(self):
53
+ """
54
+ Returns a dictionary mapping valid model names to their IDs.
55
+ :return: Dictionary where keys are model names and values are model IDs.
56
+ """
57
+ models = self.list()
58
+
59
+ # Create a dictionary of model names and their IDs
60
+ model_dict = {model['kpiName']: model['id'] for model in models if 'kpiName' in model and 'id' in model}
61
+
62
+ self.logger.info("Generated model dictionary with names and IDs.")
63
+ return model_dict
64
+
65
+ def get(self, model_id):
66
+ """
67
+ Retrieve details of a specific model.
68
+ :param model_id: ID of the model.
69
+ :return: Dictionary containing model details.
70
+ """
71
+ headers = {'Authorization': f'Bearer {self.config.load_token()}'}
72
+ url = f"{self.endpoint}/{model_id}?deleted=false"
73
+ self.logger.info(f"Fetching model with ID {model_id}...")
74
+
75
+ try:
76
+ # Make request to fetch the specific model details
77
+ response = make_request('GET', url, headers=headers, timeout=self.config.timeout)
78
+ return response
79
+ except Exception as e:
80
+ self.logger.error(f"Error fetching model details for ID {model_id}: {e}")
81
+ return None
82
+
83
+ # functions for importing models from JSON files
84
+
85
+ def import_model_from_json(self, file_path):
86
+ """
87
+ Import a model from a JSON file, handling the physical quantities and units mapping.
88
+ """
89
+ with open(file_path, 'r') as f:
90
+ model_data = json.load(f)
91
+
92
+ # Delegate physical quantity handling to the PhysicalQuantities class
93
+ model_data = self.physical_quantities.handle_physical_quantities(model_data)
94
+ self.create_model(model_data)
95
+
96
+ def create_model(self, model_data):
97
+ """
98
+ Create a new model with the updated model data.
99
+ """
100
+ self.logger.info(f"Attempting to create model: {model_data.get('kpiName')}")
101
+
102
+ try:
103
+ # Make the POST request to create the model and get both the response object and JSON data
104
+ response, response_data = make_request('POST', self.endpoint, headers=self.headers, json=model_data)
105
+
106
+ if response:
107
+ status_code = response.status_code
108
+
109
+ if status_code == 201:
110
+ self.logger.info(f"Model '{model_data.get('kpiName')}' created successfully!")
111
+ elif status_code == 200:
112
+ self.logger.info(f"Model '{model_data.get('kpiName')}' updated or already existed.")
113
+ else:
114
+ # If there is an error status code, log the error response content
115
+ error_message = response_data if response_data else response.text
116
+ self.logger.error(f"Error during model creation: {error_message}")
117
+
118
+ else:
119
+ self.logger.error(f"Model creation failed for '{model_data.get('kpiName')}': No response received.")
120
+
121
+ except Exception as e:
122
+ self.logger.error(f"Error during model creation: {e}")
123
+
124
+
125
+ # functions for exporting models to JSON files
126
+
127
+ def fetch_model_details(self, model_id):
128
+ """
129
+ Fetch details of a specific model from the API.
130
+
131
+ Args:
132
+ model_id (int): The ID of the model to fetch.
133
+
134
+ Returns:
135
+ dict: The model details, or None if the request fails.
136
+ """
137
+ url = f"{self.endpoint}/{model_id}?deleted=false"
138
+ self.logger.info(f"Fetching details for model ID: {model_id}")
139
+
140
+ try:
141
+ # Expecting only a single return value from make_request (the response data)
142
+ response_data = make_request('GET', url, headers=self.headers)
143
+ if response_data:
144
+ self.logger.info(f"Successfully fetched model details for ID: {model_id}")
145
+ return response_data
146
+ else:
147
+ self.logger.error(f"Failed to fetch model details.")
148
+ return None
149
+ except Exception as e:
150
+ self.logger.error(f"Error fetching model details: {e}")
151
+ return None
152
+
153
+
154
+ def convert_to_importable_format(self, api_response):
155
+ """
156
+ Converts the fetched model details into an importable JSON structure.
157
+
158
+ Args:
159
+ api_response (dict): The API response containing the model details.
160
+
161
+ Returns:
162
+ dict: The reformatted model ready for export, or None on error.
163
+ """
164
+ if not api_response:
165
+ self.logger.error("No valid model data to convert.")
166
+ return None
167
+
168
+ # Create the structure for the importable model
169
+ importable_model = {
170
+ "engineType": api_response.get("engineType"),
171
+ "kpiName": api_response.get("kpiName"),
172
+ "abbr": api_response.get("abbr"),
173
+ "calculationStyle": api_response.get("calculationStyle"),
174
+ "status": "DRAFT", # Default to DRAFT for export, can be modified later
175
+ "description": api_response.get("description", ""),
176
+ "script": api_response.get("script", "")
177
+ }
178
+
179
+ # Process inputs
180
+ importable_model["inputs"] = [
181
+ {
182
+ "name": input_item.get("name"),
183
+ "order": idx,
184
+ "physicalQuantityUnit": {
185
+ "name": input_item["physicalQuantityUnit"].get("name"),
186
+ "unit": input_item["physicalQuantityUnit"].get("unit"),
187
+ "status": input_item["physicalQuantityUnit"].get("status")
188
+ },
189
+ "description": input_item.get("description", "")
190
+ } for idx, input_item in enumerate(api_response.get("inputs", []))
191
+ ]
192
+
193
+ # Process outputs
194
+ importable_model["outputs"] = [
195
+ {
196
+ "name": output_item.get("name"),
197
+ "order": idx,
198
+ "physicalQuantityUnit": {
199
+ "name": output_item["physicalQuantityUnit"].get("name"),
200
+ "unit": output_item["physicalQuantityUnit"].get("unit"),
201
+ "status": output_item["physicalQuantityUnit"].get("status")
202
+ },
203
+ "description": output_item.get("description", "")
204
+ } for idx, output_item in enumerate(api_response.get("outputs", []))
205
+ ]
206
+
207
+ return importable_model
208
+
209
+ def export_model_to_json(self, model_id, output_file):
210
+ """
211
+ Export a model to a JSON file based on the model's ID.
212
+
213
+ Args:
214
+ model_id (int): The ID of the model to export.
215
+ output_file (str): The output file path for the exported JSON.
216
+ """
217
+ self.logger.info(f"Exporting model with ID {model_id} to {output_file}...")
218
+
219
+ # Fetch model details
220
+ model_details = self.fetch_model_details(model_id)
221
+ if not model_details:
222
+ self.logger.error(f"Failed to fetch model details for ID {model_id}.")
223
+ return
224
+
225
+ # Convert model details to an importable format
226
+ importable_json = self.convert_to_importable_format(model_details)
227
+ if not importable_json:
228
+ self.logger.error(f"Failed to convert model to importable format for ID {model_id}.")
229
+ return
230
+
231
+ # Export the model to a JSON file
232
+ try:
233
+ with open(output_file, 'w') as json_file:
234
+ json.dump(importable_json, json_file, indent=4)
235
+ self.logger.info(f"Model ID {model_id} exported successfully to {output_file}.")
236
+ except IOError as e:
237
+ self.logger.error(f"Failed to write model to JSON file: {e}")
@@ -0,0 +1,145 @@
1
+ from ..utils import make_request
2
+ from ..logger import get_logger
3
+ import pandas as pd
4
+
5
+ class Processes:
6
+ def __init__(self, config):
7
+ """
8
+ Initializes the Processes class with the provided configuration.
9
+
10
+ :param config: A Config object that contains the API base URL and authentication token.
11
+ """
12
+ self.config = config
13
+ self.endpoint = f"{self.config.base_url}/public-api/processes"
14
+ self.logger = get_logger(self.__class__.__name__)
15
+ self.headers = {'Authorization': f'Bearer {self.config.load_token()}'}
16
+
17
+ def list_processes(self):
18
+ """
19
+ Fetches and returns all available processes from the API. This method retrieves a list of processes
20
+ based on parameters like the number of processes to fetch, sorting order, and GMP status.
21
+
22
+ :return: A list of processes in dictionary format, or None if the request fails.
23
+ """
24
+ params = {
25
+ 'size': 90,
26
+ 'sort': 'lastUsageDate,desc',
27
+ 'gmp': False,
28
+ 'archivedOrWillBeArchived': False,
29
+ 'partOfExperiment': False
30
+ }
31
+
32
+ try:
33
+ self.logger.info("Fetching processes from the API...")
34
+ response = make_request('GET', self.endpoint, headers=self.headers, params=params)
35
+ processes = response.get('content', [])
36
+
37
+ if processes:
38
+ self.logger.info(f"Retrieved {len(processes)} processes.")
39
+ return processes
40
+ else:
41
+ self.logger.warning("No processes available or invalid response format.")
42
+ return None
43
+ except Exception as e:
44
+ self.logger.error(f"Error fetching processes: {e}")
45
+ return None
46
+
47
+ def list_process_channels(self, process_id):
48
+ """
49
+ Fetches and returns the channels associated with a specific process.
50
+
51
+ :param process_id: The ID of the process whose channels should be retrieved.
52
+ :return: A list of channels in dictionary format, or None if the request fails.
53
+ """
54
+ url = f"{self.config.base_url}/api/processes/{process_id}/channels"
55
+
56
+ try:
57
+ self.logger.info(f"Fetching channels for process ID: {process_id}")
58
+ response = make_request('GET', url, headers=self.headers)
59
+
60
+ if response:
61
+ self.logger.info(f"Retrieved {len(response)} channels.")
62
+ return response
63
+ else:
64
+ self.logger.warning(f"No channels available for process {process_id}.")
65
+ return None
66
+ except Exception as e:
67
+ self.logger.error(f"Error fetching channels for process {process_id}: {e}")
68
+ return None
69
+
70
+ def extract_process_data(self, process_id, selected_channels, start_date, end_date, granularity, output_file, output_format="json"):
71
+ """
72
+ Extracts process data for the selected channels and saves it in the specified format (JSON or CSV).
73
+
74
+ :param process_id: The ID of the process from which data is to be extracted.
75
+ :param selected_channels: A list of dictionaries, each containing a channel ID.
76
+ :param start_date: The start timestamp (in milliseconds) for data extraction.
77
+ :param end_date: The end timestamp (in milliseconds) for data extraction.
78
+ :param granularity: The granularity of the data to be fetched (e.g., every minute, hour).
79
+ :param output_file: The file path where the extracted data will be saved.
80
+ :param output_format: The format for saving the data, either 'json' or 'csv' (default is 'json').
81
+ """
82
+ url = f"{self.config.base_url}/api/charts/multiplex-data-channels"
83
+ collected_data = []
84
+
85
+ payload = {
86
+ "channels": [
87
+ {
88
+ "id": channel["id"],
89
+ "type": "ONLINE",
90
+ "startDate": start_date,
91
+ "endDate": end_date,
92
+ "granularity": granularity
93
+ } for channel in selected_channels
94
+ ]
95
+ }
96
+
97
+ try:
98
+ self.logger.info(f"Fetching data for process ID: {process_id}")
99
+ response = make_request('POST', url, json=payload, headers=self.headers)
100
+ if response:
101
+ for entry in response['channels']:
102
+ for value in entry['value']:
103
+ collected_data.append({
104
+ "time": value['time'],
105
+ "channel_id": entry['key']['id'],
106
+ "value": value['value']
107
+ })
108
+
109
+ df = pd.DataFrame(collected_data)
110
+ if output_format == "json":
111
+ df.to_json(output_file, orient='records', indent=4)
112
+ self.logger.info(f"Data successfully written to {output_file} in JSON format.")
113
+ elif output_format == "csv":
114
+ df.pivot(index="time", columns="channel_id", values="value").to_csv(output_file)
115
+ self.logger.info(f"Data successfully written to {output_file} in CSV format.")
116
+ else:
117
+ self.logger.error(f"Failed to fetch data for process ID {process_id}.")
118
+ except Exception as e:
119
+ self.logger.error(f"Error extracting data for process {process_id}: {e}")
120
+
121
+ def get_process_details(self, process_id):
122
+ """
123
+ Fetches the start and end dates of a specific process using its ID.
124
+ If the process is still running, the end date is defaulted to 30 minutes after the start date.
125
+
126
+ :param process_id: The ID of the process.
127
+ :return: A tuple containing the start and end dates (in milliseconds) of the process.
128
+ """
129
+ url = f"{self.config.base_url}/public-api/processes/{process_id}"
130
+
131
+ try:
132
+ self.logger.info(f"Fetching details for process ID: {process_id}")
133
+ response = make_request('GET', url, headers=self.headers)
134
+
135
+ if response:
136
+ start_date = response.get('startDate')
137
+ end_date = response.get('endDate') or start_date + (30 * 60 * 1000) # Default to 30 min after start
138
+ self.logger.info(f"Process {process_id} start date: {start_date}, end date: {end_date}")
139
+ return start_date, end_date
140
+ else:
141
+ self.logger.error(f"Failed to fetch details for process {process_id}.")
142
+ return None, None
143
+ except Exception as e:
144
+ self.logger.error(f"Error fetching details for process {process_id}: {e}")
145
+ return None, None
@@ -0,0 +1,160 @@
1
+ from ..utils import make_request
2
+ from ..logger import get_logger
3
+
4
+ class Quantities:
5
+ def __init__(self, config):
6
+ """
7
+ Initializes the Quantities class with the provided configuration.
8
+
9
+ :param config: A Config object that contains the API base URL and authentication token.
10
+ """
11
+ self.config = config
12
+ self.endpoint = f"{self.config.base_url}/api/physical-quantities"
13
+ self.logger = get_logger(self.__class__.__name__)
14
+ self.headers = {'Authorization': f'Bearer {self.config.load_token()}'}
15
+
16
+ def list(self):
17
+ """
18
+ Retrieves and returns a list of all physical quantities available in the system.
19
+
20
+ :return: A list of physical quantities in dictionary format, or None if the request fails.
21
+ """
22
+ self.logger.info("Fetching list of physical quantities...")
23
+ return make_request('GET', self.endpoint, headers=self.headers, timeout=self.config.timeout)
24
+
25
+ def get(self, quantity_id):
26
+ """
27
+ Retrieves the details of a specific physical quantity by its ID.
28
+
29
+ :param quantity_id: The ID of the physical quantity to retrieve.
30
+ :return: A dictionary containing the physical quantity details, or None if the request fails.
31
+ """
32
+ url = f"{self.endpoint}/{quantity_id}"
33
+ self.logger.info(f"Fetching physical quantity with ID {quantity_id}...")
34
+ return make_request('GET', url, headers=self.headers, timeout=self.config.timeout)
35
+
36
+ def normalize_name(self, name):
37
+ """
38
+ Normalizes a physical quantity name by removing special characters and converting it to lowercase.
39
+
40
+ :param name: The name of the physical quantity.
41
+ :return: A normalized version of the name.
42
+ """
43
+ import re
44
+ return re.sub(r'[^a-zA-Z0-9]', '', name).lower()
45
+
46
+ def fuzzy_match(self, name1, name2, threshold=93):
47
+ """
48
+ Performs a fuzzy string matching between two physical quantity names.
49
+
50
+ :param name1: The first name to compare.
51
+ :param name2: The second name to compare.
52
+ :param threshold: The similarity threshold for considering a match (default is 93%).
53
+ :return: True if the similarity exceeds the threshold, False otherwise.
54
+ """
55
+ from rapidfuzz import fuzz
56
+ normalized_name1 = self.normalize_name(name1)
57
+ normalized_name2 = self.normalize_name(name2)
58
+ similarity = fuzz.token_sort_ratio(normalized_name1, normalized_name2)
59
+ return similarity >= threshold
60
+
61
+ def check_existing_physical_quantity(self, pq_name):
62
+ """
63
+ Checks if a physical quantity with a similar name already exists in the system using fuzzy matching.
64
+
65
+ :param pq_name: The name of the physical quantity to check.
66
+ :return: The matching physical quantity if found, or None if no match is found.
67
+ """
68
+ response = make_request('GET', self.endpoint, headers=self.headers)
69
+ if response and isinstance(response, list):
70
+ for pq in response:
71
+ if self.fuzzy_match(pq['name'], pq_name):
72
+ self.logger.info(f"Fuzzy match found: '{pq['name']}' matches '{pq_name}' (ID: {pq['id']}).")
73
+ return pq
74
+ return None
75
+
76
+ def check_existing_unit(self, physical_quantity, unit_name):
77
+ """
78
+ Checks if a specific unit exists within a given physical quantity.
79
+
80
+ :param physical_quantity: The physical quantity dictionary.
81
+ :param unit_name: The name of the unit to check.
82
+ :return: The matching unit if found, or None if no match is found.
83
+ """
84
+ for unit in physical_quantity.get('units', []):
85
+ if self.fuzzy_match(unit['unit'], unit_name):
86
+ self.logger.info(f"Unit match found: '{unit_name}' in physical quantity '{physical_quantity['name']}'.")
87
+ return unit
88
+ return None
89
+
90
+ def create_physical_quantity(self, pq_name, unit_name):
91
+ """
92
+ Creates a new physical quantity along with an initial unit.
93
+
94
+ :param pq_name: The name of the physical quantity to create.
95
+ :param unit_name: The name of the unit to associate with the new physical quantity.
96
+ :return: The created physical quantity in dictionary format, or None if creation fails.
97
+ """
98
+ data = {"name": pq_name, "units": [{"unit": unit_name}]}
99
+ response = make_request('POST', self.endpoint, headers=self.headers, json=data)
100
+ if response and response.status_code in [200, 201]:
101
+ self.logger.info(f"Physical quantity '{pq_name}' created successfully.")
102
+ return response.json()
103
+ else:
104
+ self.logger.error(f"Failed to create physical quantity '{pq_name}'. Response: {response.content}")
105
+ return None
106
+
107
+ def add_unit_to_existing_physical_quantity(self, pq_id, pq_name, unit_name):
108
+ """
109
+ Adds a new unit to an existing physical quantity.
110
+
111
+ :param pq_id: The ID of the existing physical quantity.
112
+ :param pq_name: The name of the existing physical quantity.
113
+ :param unit_name: The name of the unit to add.
114
+ :return: The updated physical quantity in dictionary format, or None if the update fails.
115
+ """
116
+ url = f"{self.endpoint}/{pq_id}"
117
+ existing_pq = self.check_existing_physical_quantity(pq_name)
118
+ if not existing_pq:
119
+ self.logger.error(f"Physical quantity '{pq_name}' not found.")
120
+ return None
121
+
122
+ new_unit = {"unit": unit_name, "physicalQuantityId": pq_id}
123
+ existing_pq['units'].append(new_unit)
124
+ response = make_request('PUT', url, headers=self.headers, json=existing_pq)
125
+ if response and response.status_code == 200:
126
+ self.logger.info(f"Unit '{unit_name}' added to physical quantity '{pq_name}'.")
127
+ return response.json()
128
+ else:
129
+ self.logger.error(f"Failed to add unit to physical quantity '{pq_name}'.")
130
+ return None
131
+
132
+ def handle_physical_quantities(self, model_data):
133
+ """
134
+ Processes and ensures all physical quantities and units in the model data exist in the system.
135
+ If a physical quantity or unit doesn't exist, it is created.
136
+
137
+ :param model_data: A dictionary containing the model's inputs and outputs.
138
+ :return: The updated model data with physicalQuantityId and unit ID populated.
139
+ """
140
+ for var in model_data.get('inputs', []) + model_data.get('outputs', []):
141
+ pq_name = var['physicalQuantityUnit']['name']
142
+ unit_name = var['physicalQuantityUnit']['unit']
143
+
144
+ existing_pq = self.check_existing_physical_quantity(pq_name)
145
+ if existing_pq:
146
+ var['physicalQuantityUnit']['physicalQuantityId'] = existing_pq['id']
147
+ existing_unit = self.check_existing_unit(existing_pq, unit_name)
148
+ if not existing_unit:
149
+ updated_pq = self.add_unit_to_existing_physical_quantity(existing_pq['id'], pq_name, unit_name)
150
+ if updated_pq:
151
+ new_unit = next((u for u in updated_pq['units'] if u['unit'] == unit_name), None)
152
+ if new_unit:
153
+ var['physicalQuantityUnit']['id'] = new_unit['id']
154
+ else:
155
+ new_pq = self.create_physical_quantity(pq_name, unit_name)
156
+ if new_pq:
157
+ var['physicalQuantityUnit']['physicalQuantityId'] = new_pq['id']
158
+ var['physicalQuantityUnit']['id'] = new_pq['units'][0]['id']
159
+
160
+ return model_data
qubicon/auth.py ADDED
@@ -0,0 +1,30 @@
1
+ from .utils import make_request
2
+ from .exceptions import AuthenticationError
3
+ from .logger import get_logger
4
+
5
+ logger = get_logger(__name__)
6
+
7
+ def authenticate(config, username, password):
8
+ """
9
+ Authenticate with the Qubicon API and store the token in the config.
10
+
11
+ :param config: Config object.
12
+ :param username: User's username.
13
+ :param password: User's password.
14
+ :raises AuthenticationError: If authentication fails.
15
+ """
16
+ login_endpoint = '/api/login'
17
+ url = f"{config.base_url}{login_endpoint}"
18
+ data = {'username': username, 'password': password}
19
+ headers = {'Content-Type': 'application/json'}
20
+
21
+ logger.info("Attempting to authenticate with the Qubicon API...")
22
+ response = make_request('POST', url, headers=headers, json=data, timeout=config.timeout)
23
+
24
+ token = response.get('normal', {}).get('token')
25
+ if token:
26
+ config.save_token(token)
27
+ logger.info("Authentication successful.")
28
+ else:
29
+ logger.error("Authentication failed.")
30
+ raise AuthenticationError("Invalid credentials provided.")
qubicon/config.py ADDED
@@ -0,0 +1,36 @@
1
+ import os
2
+
3
+ class Config:
4
+ def __init__(self, base_url, timeout=30):
5
+ """
6
+ Configuration class for Qubicon API interactions.
7
+
8
+ :param base_url: Base URL of the Qubicon API (customer-specific).
9
+ :param timeout: Request timeout in seconds.
10
+ """
11
+ self.base_url = base_url.rstrip('/')
12
+ self.timeout = timeout
13
+ self.token = None
14
+ self.config_dir = os.path.expanduser('~/.qubicon')
15
+ self.token_file = os.path.join(self.config_dir, 'token')
16
+
17
+ def save_token(self, token):
18
+ """Save the authentication token."""
19
+ self.token = token
20
+ if not os.path.exists(self.config_dir):
21
+ os.makedirs(self.config_dir)
22
+ with open(self.token_file, 'w') as f:
23
+ f.write(token)
24
+
25
+ def load_token(self):
26
+ """Load the authentication token."""
27
+ if os.path.exists(self.token_file):
28
+ with open(self.token_file, 'r') as f:
29
+ self.token = f.read().strip()
30
+ return self.token
31
+
32
+ def delete_token(self):
33
+ """Delete the saved authentication token."""
34
+ if os.path.exists(self.token_file):
35
+ os.remove(self.token_file)
36
+ self.token = None
qubicon/exceptions.py ADDED
@@ -0,0 +1,19 @@
1
+ class QubiconError(Exception):
2
+ """Base exception class for the Qubicon library."""
3
+ pass
4
+
5
+ class AuthenticationError(QubiconError):
6
+ """Exception raised for authentication errors."""
7
+ pass
8
+
9
+ class APIRequestError(QubiconError):
10
+ """Exception raised for API request errors."""
11
+ pass
12
+
13
+ class NotFoundError(QubiconError):
14
+ """Exception raised when a requested resource is not found."""
15
+ pass
16
+
17
+ class ValidationError(QubiconError):
18
+ """Exception raised for data validation errors."""
19
+ pass
qubicon/logger.py ADDED
@@ -0,0 +1,23 @@
1
+ import logging
2
+
3
+ def get_logger(name):
4
+ logger = logging.getLogger(name)
5
+ if not logger.handlers:
6
+ logger.setLevel(logging.DEBUG)
7
+ formatter = logging.Formatter(
8
+ '[%(asctime)s] %(levelname)s %(name)s - %(message)s',
9
+ datefmt='%Y-%m-%d %H:%M:%S'
10
+ )
11
+
12
+ # File handler
13
+ fh = logging.FileHandler('qubicon.log')
14
+ fh.setLevel(logging.DEBUG)
15
+ fh.setFormatter(formatter)
16
+ logger.addHandler(fh)
17
+
18
+ # Console handler
19
+ ch = logging.StreamHandler()
20
+ ch.setLevel(logging.INFO)
21
+ ch.setFormatter(formatter)
22
+ logger.addHandler(ch)
23
+ return logger
qubicon/utils.py ADDED
@@ -0,0 +1,48 @@
1
+ import requests
2
+ from .exceptions import AuthenticationError, APIRequestError
3
+ from .logger import get_logger
4
+
5
+ logger = get_logger(__name__)
6
+
7
+ def make_request(method, url, headers=None, json=None, data=None, params=None, timeout=30):
8
+ try:
9
+ if method == 'POST' or method == 'PUT':
10
+ if json:
11
+ response = requests.request(
12
+ method,
13
+ url,
14
+ headers=headers,
15
+ json=json, # Send JSON payload
16
+ params=params,
17
+ timeout=timeout
18
+ )
19
+ else:
20
+ response = requests.request(
21
+ method,
22
+ url,
23
+ headers=headers,
24
+ data=data, # Send form data or other payload
25
+ params=params,
26
+ timeout=timeout
27
+ )
28
+ else:
29
+ response = requests.request(
30
+ method,
31
+ url,
32
+ headers=headers,
33
+ params=params,
34
+ timeout=timeout
35
+ )
36
+
37
+ response.raise_for_status()
38
+ return response.json()
39
+ except requests.exceptions.HTTPError as e:
40
+ if response.status_code == 401:
41
+ logger.error("Authentication error: Unauthorized access.")
42
+ raise AuthenticationError("Unauthorized access.")
43
+ else:
44
+ logger.error(f"HTTP error occurred: {e}")
45
+ raise APIRequestError(f"HTTP error occurred: {e}")
46
+ except requests.exceptions.RequestException as e:
47
+ logger.error(f"Request exception: {e}")
48
+ raise APIRequestError(f"Request exception: {e}")
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2024 QUBICON AG
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,18 @@
1
+ Metadata-Version: 2.1
2
+ Name: qubicon
3
+ Version: 1.0.0
4
+ Summary: Python library for the Qubicon Platform API
5
+ Home-page: https://git.qub-lab.io/qub-client/qubicon-python-library
6
+ Author: Stephan Karas
7
+ Author-email: stephan.karas@qubicon-ag.com
8
+ License: Apache License 2.0
9
+ Classifier: Programming Language :: Python :: 3
10
+ Classifier: Operating System :: OS Independent
11
+ License-File: LICENSE
12
+ Requires-Dist: requests >=2.25.1
13
+ Requires-Dist: rapidfuzz >=2.0.11
14
+ Requires-Dist: pandas >=2.1.1
15
+ Requires-Dist: tabulate >=0.9.0
16
+ Requires-Dist: rich >=13.5.1
17
+ Requires-Dist: re >=2.2.1
18
+
@@ -0,0 +1,15 @@
1
+ qubicon/__init__.py,sha256=M5_Xl5iBE2ckr8goi4XC5dZqiBLYxSfXjiymB05JX7s,276
2
+ qubicon/auth.py,sha256=kihZ9IgZrapzkDhaoH8PFcCFJUZRBUodWhsqMW1vk6Q,1099
3
+ qubicon/config.py,sha256=eYRC1lUW58gVGgOpnujL12N9apZG9tmF90Z3-cFv8VU,1239
4
+ qubicon/exceptions.py,sha256=ZNzJJoYLLknVxA_WlL3NwPUTOQUswxafc0AhrsmRD-s,532
5
+ qubicon/logger.py,sha256=zu38MkUOac-oqidh1yyBGvn0NvnlljeMjODknNU5RSY,673
6
+ qubicon/utils.py,sha256=4xysQkfEFadGCsO7t7ilUG2_fWMBAyyBJQAxtxCb0sk,1730
7
+ qubicon/api/__init__.py,sha256=cW187QcNsxu8sJchJ_Q83vFtXg4yUpddySam46eAE1U,168
8
+ qubicon/api/models.py,sha256=wymOttyaV6CF8zw075wc_s_NNXaoaIjiYxd-hipyZNM,9990
9
+ qubicon/api/processes.py,sha256=deKVXKPVcnsNmZ98b2mT9gK7lofKtR2OrlcpWW8KJmc,6848
10
+ qubicon/api/quantities.py,sha256=OK0u50u5B8GqQP4xgZTR_4UBYlhKMKV4CmH2oGZnzeY,7775
11
+ qubicon-1.0.0.dist-info/LICENSE,sha256=4sNjFI-TB_VRlM6W6W7OhP4Q3FHI2cCl-P2Ov3P53Yk,11541
12
+ qubicon-1.0.0.dist-info/METADATA,sha256=5xfPc-edBBq7hM84q83-tRJsyBP_Bfu6iHS89nzNCso,585
13
+ qubicon-1.0.0.dist-info/WHEEL,sha256=OVMc5UfuAQiSplgO0_WdW7vXVGAt9Hdd6qtN4HotdyA,91
14
+ qubicon-1.0.0.dist-info/top_level.txt,sha256=ov8RJlegYZY6ylhFn6dVjgrKc4O4qKDIpDQdKfRN-Sg,8
15
+ qubicon-1.0.0.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.2.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ qubicon