admin-api-lib 3.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.
Files changed (106) hide show
  1. admin_api_lib/__init__.py +0 -0
  2. admin_api_lib/api_endpoints/document_deleter.py +24 -0
  3. admin_api_lib/api_endpoints/document_reference_retriever.py +25 -0
  4. admin_api_lib/api_endpoints/documents_status_retriever.py +20 -0
  5. admin_api_lib/api_endpoints/file_uploader.py +31 -0
  6. admin_api_lib/api_endpoints/source_uploader.py +40 -0
  7. admin_api_lib/api_endpoints/uploader_base.py +30 -0
  8. admin_api_lib/apis/__init__.py +0 -0
  9. admin_api_lib/apis/admin_api.py +197 -0
  10. admin_api_lib/apis/admin_api_base.py +120 -0
  11. admin_api_lib/chunker/__init__.py +0 -0
  12. admin_api_lib/chunker/chunker.py +25 -0
  13. admin_api_lib/dependency_container.py +236 -0
  14. admin_api_lib/extractor_api_client/__init__.py +0 -0
  15. admin_api_lib/extractor_api_client/openapi_client/__init__.py +38 -0
  16. admin_api_lib/extractor_api_client/openapi_client/api/__init__.py +4 -0
  17. admin_api_lib/extractor_api_client/openapi_client/api/extractor_api.py +516 -0
  18. admin_api_lib/extractor_api_client/openapi_client/api_client.py +695 -0
  19. admin_api_lib/extractor_api_client/openapi_client/api_response.py +20 -0
  20. admin_api_lib/extractor_api_client/openapi_client/configuration.py +460 -0
  21. admin_api_lib/extractor_api_client/openapi_client/exceptions.py +197 -0
  22. admin_api_lib/extractor_api_client/openapi_client/models/__init__.py +21 -0
  23. admin_api_lib/extractor_api_client/openapi_client/models/content_type.py +34 -0
  24. admin_api_lib/extractor_api_client/openapi_client/models/extraction_parameters.py +103 -0
  25. admin_api_lib/extractor_api_client/openapi_client/models/extraction_request.py +82 -0
  26. admin_api_lib/extractor_api_client/openapi_client/models/information_piece.py +104 -0
  27. admin_api_lib/extractor_api_client/openapi_client/models/key_value_pair.py +92 -0
  28. admin_api_lib/extractor_api_client/openapi_client/rest.py +209 -0
  29. admin_api_lib/extractor_api_client/openapi_client/test/__init__.py +0 -0
  30. admin_api_lib/extractor_api_client/openapi_client/test/test_content_type.py +35 -0
  31. admin_api_lib/extractor_api_client/openapi_client/test/test_extraction_parameters.py +59 -0
  32. admin_api_lib/extractor_api_client/openapi_client/test/test_extraction_request.py +56 -0
  33. admin_api_lib/extractor_api_client/openapi_client/test/test_extractor_api.py +39 -0
  34. admin_api_lib/extractor_api_client/openapi_client/test/test_information_piece.py +62 -0
  35. admin_api_lib/extractor_api_client/openapi_client/test/test_key_value_pair.py +54 -0
  36. admin_api_lib/file_services/file_service.py +77 -0
  37. admin_api_lib/impl/__init__.py +0 -0
  38. admin_api_lib/impl/admin_api.py +167 -0
  39. admin_api_lib/impl/api_endpoints/default_document_deleter.py +84 -0
  40. admin_api_lib/impl/api_endpoints/default_document_reference_retriever.py +72 -0
  41. admin_api_lib/impl/api_endpoints/default_documents_status_retriever.py +41 -0
  42. admin_api_lib/impl/api_endpoints/default_file_uploader.py +234 -0
  43. admin_api_lib/impl/api_endpoints/default_source_uploader.py +202 -0
  44. admin_api_lib/impl/chunker/__init__.py +0 -0
  45. admin_api_lib/impl/chunker/chunker_type.py +11 -0
  46. admin_api_lib/impl/chunker/semantic_text_chunker.py +252 -0
  47. admin_api_lib/impl/chunker/text_chunker.py +33 -0
  48. admin_api_lib/impl/file_services/__init__.py +0 -0
  49. admin_api_lib/impl/file_services/s3_service.py +130 -0
  50. admin_api_lib/impl/information_enhancer/__init__.py +0 -0
  51. admin_api_lib/impl/information_enhancer/general_enhancer.py +52 -0
  52. admin_api_lib/impl/information_enhancer/page_summary_enhancer.py +62 -0
  53. admin_api_lib/impl/information_enhancer/summary_enhancer.py +74 -0
  54. admin_api_lib/impl/key_db/__init__.py +0 -0
  55. admin_api_lib/impl/key_db/file_status_key_value_store.py +111 -0
  56. admin_api_lib/impl/mapper/informationpiece2document.py +108 -0
  57. admin_api_lib/impl/settings/__init__.py +0 -0
  58. admin_api_lib/impl/settings/chunker_class_type_settings.py +18 -0
  59. admin_api_lib/impl/settings/chunker_settings.py +29 -0
  60. admin_api_lib/impl/settings/document_extractor_settings.py +21 -0
  61. admin_api_lib/impl/settings/key_value_settings.py +26 -0
  62. admin_api_lib/impl/settings/rag_api_settings.py +21 -0
  63. admin_api_lib/impl/settings/s3_settings.py +31 -0
  64. admin_api_lib/impl/settings/source_uploader_settings.py +23 -0
  65. admin_api_lib/impl/settings/summarizer_settings.py +86 -0
  66. admin_api_lib/impl/summarizer/__init__.py +0 -0
  67. admin_api_lib/impl/summarizer/langchain_summarizer.py +117 -0
  68. admin_api_lib/information_enhancer/__init__.py +0 -0
  69. admin_api_lib/information_enhancer/information_enhancer.py +34 -0
  70. admin_api_lib/main.py +54 -0
  71. admin_api_lib/models/__init__.py +0 -0
  72. admin_api_lib/models/document_status.py +86 -0
  73. admin_api_lib/models/extra_models.py +9 -0
  74. admin_api_lib/models/http_validation_error.py +105 -0
  75. admin_api_lib/models/key_value_pair.py +85 -0
  76. admin_api_lib/models/status.py +44 -0
  77. admin_api_lib/models/validation_error.py +104 -0
  78. admin_api_lib/models/validation_error_loc_inner.py +114 -0
  79. admin_api_lib/prompt_templates/__init__.py +0 -0
  80. admin_api_lib/prompt_templates/summarize_prompt.py +14 -0
  81. admin_api_lib/rag_backend_client/__init__.py +0 -0
  82. admin_api_lib/rag_backend_client/openapi_client/__init__.py +60 -0
  83. admin_api_lib/rag_backend_client/openapi_client/api/__init__.py +4 -0
  84. admin_api_lib/rag_backend_client/openapi_client/api/rag_api.py +968 -0
  85. admin_api_lib/rag_backend_client/openapi_client/api_client.py +698 -0
  86. admin_api_lib/rag_backend_client/openapi_client/api_response.py +22 -0
  87. admin_api_lib/rag_backend_client/openapi_client/configuration.py +460 -0
  88. admin_api_lib/rag_backend_client/openapi_client/exceptions.py +197 -0
  89. admin_api_lib/rag_backend_client/openapi_client/models/__init__.py +41 -0
  90. admin_api_lib/rag_backend_client/openapi_client/models/chat_history.py +99 -0
  91. admin_api_lib/rag_backend_client/openapi_client/models/chat_history_message.py +83 -0
  92. admin_api_lib/rag_backend_client/openapi_client/models/chat_request.py +93 -0
  93. admin_api_lib/rag_backend_client/openapi_client/models/chat_response.py +103 -0
  94. admin_api_lib/rag_backend_client/openapi_client/models/chat_role.py +35 -0
  95. admin_api_lib/rag_backend_client/openapi_client/models/content_type.py +37 -0
  96. admin_api_lib/rag_backend_client/openapi_client/models/delete_request.py +99 -0
  97. admin_api_lib/rag_backend_client/openapi_client/models/information_piece.py +110 -0
  98. admin_api_lib/rag_backend_client/openapi_client/models/key_value_pair.py +83 -0
  99. admin_api_lib/rag_backend_client/openapi_client/rest.py +209 -0
  100. admin_api_lib/summarizer/__init__.py +0 -0
  101. admin_api_lib/summarizer/summarizer.py +33 -0
  102. admin_api_lib/utils/__init__.py +0 -0
  103. admin_api_lib/utils/utils.py +32 -0
  104. admin_api_lib-3.2.0.dist-info/METADATA +24 -0
  105. admin_api_lib-3.2.0.dist-info/RECORD +106 -0
  106. admin_api_lib-3.2.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,698 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ STACKIT RAG
5
+
6
+ The perfect rag solution.
7
+
8
+ The version of the OpenAPI document: 1.0.0
9
+ Generated by OpenAPI Generator (https://openapi-generator.tech)
10
+
11
+ Do not edit the class manually.
12
+ """ # noqa: E501
13
+
14
+
15
+ import datetime
16
+ import decimal
17
+ import json
18
+ import mimetypes
19
+ import os
20
+ import re
21
+ import tempfile
22
+ from enum import Enum
23
+ from typing import Dict, List, Optional, Tuple, Union
24
+ from urllib.parse import quote
25
+
26
+ from dateutil.parser import parse
27
+ from pydantic import SecretStr
28
+
29
+ import admin_api_lib.rag_backend_client.openapi_client.models
30
+ from admin_api_lib.rag_backend_client.openapi_client import rest
31
+ from admin_api_lib.rag_backend_client.openapi_client.api_response import ApiResponse
32
+ from admin_api_lib.rag_backend_client.openapi_client.api_response import (
33
+ T as ApiResponseT,
34
+ )
35
+ from admin_api_lib.rag_backend_client.openapi_client.configuration import Configuration
36
+ from admin_api_lib.rag_backend_client.openapi_client.exceptions import (
37
+ ApiException,
38
+ ApiValueError,
39
+ BadRequestException,
40
+ ForbiddenException,
41
+ NotFoundException,
42
+ ServiceException,
43
+ UnauthorizedException,
44
+ )
45
+
46
+ RequestSerialized = Tuple[str, str, Dict[str, str], Optional[str], List[str]]
47
+
48
+
49
+ class ApiClient:
50
+ """Generic API client for OpenAPI client library builds.
51
+
52
+ OpenAPI generic API client. This client handles the client-
53
+ server communication, and is invariant across implementations. Specifics of
54
+ the methods and models for each application are generated from the OpenAPI
55
+ templates.
56
+
57
+ :param configuration: .Configuration object for this client
58
+ :param header_name: a header to pass when making calls to the API.
59
+ :param header_value: a header value to pass when making calls to
60
+ the API.
61
+ :param cookie: a cookie to include in the header when making calls
62
+ to the API
63
+ """
64
+
65
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
66
+ NATIVE_TYPES_MAPPING = {
67
+ "int": int,
68
+ "long": int, # TODO remove as only py3 is supported?
69
+ "float": float,
70
+ "str": str,
71
+ "bool": bool,
72
+ "date": datetime.date,
73
+ "datetime": datetime.datetime,
74
+ "decimal": decimal.Decimal,
75
+ "object": object,
76
+ }
77
+ _pool = None
78
+
79
+ def __init__(self, configuration=None, header_name=None, header_value=None, cookie=None) -> None:
80
+ # use default configuration if none is provided
81
+ if configuration is None:
82
+ configuration = Configuration.get_default()
83
+ self.configuration = configuration
84
+
85
+ self.rest_client = rest.RESTClientObject(configuration)
86
+ self.default_headers = {}
87
+ if header_name is not None:
88
+ self.default_headers[header_name] = header_value
89
+ self.cookie = cookie
90
+ # Set default User-Agent.
91
+ self.user_agent = "OpenAPI-Generator/1.0.0/python"
92
+ self.client_side_validation = configuration.client_side_validation
93
+
94
+ def __enter__(self):
95
+ return self
96
+
97
+ def __exit__(self, exc_type, exc_value, traceback):
98
+ pass
99
+
100
+ @property
101
+ def user_agent(self):
102
+ """User agent for this API client"""
103
+ return self.default_headers["User-Agent"]
104
+
105
+ @user_agent.setter
106
+ def user_agent(self, value):
107
+ self.default_headers["User-Agent"] = value
108
+
109
+ def set_default_header(self, header_name, header_value):
110
+ self.default_headers[header_name] = header_value
111
+
112
+ _default = None
113
+
114
+ @classmethod
115
+ def get_default(cls):
116
+ """Return new instance of ApiClient.
117
+
118
+ This method returns newly created, based on default constructor,
119
+ object of ApiClient class or returns a copy of default
120
+ ApiClient.
121
+
122
+ :return: The ApiClient object.
123
+ """
124
+ if cls._default is None:
125
+ cls._default = ApiClient()
126
+ return cls._default
127
+
128
+ @classmethod
129
+ def set_default(cls, default):
130
+ """Set default instance of ApiClient.
131
+
132
+ It stores default ApiClient.
133
+
134
+ :param default: object of ApiClient.
135
+ """
136
+ cls._default = default
137
+
138
+ def param_serialize(
139
+ self,
140
+ method,
141
+ resource_path,
142
+ path_params=None,
143
+ query_params=None,
144
+ header_params=None,
145
+ body=None,
146
+ post_params=None,
147
+ files=None,
148
+ auth_settings=None,
149
+ collection_formats=None,
150
+ _host=None,
151
+ _request_auth=None,
152
+ ) -> RequestSerialized:
153
+ """Builds the HTTP request params needed by the request.
154
+ :param method: Method to call.
155
+ :param resource_path: Path to method endpoint.
156
+ :param path_params: Path parameters in the url.
157
+ :param query_params: Query parameters in the url.
158
+ :param header_params: Header parameters to be
159
+ placed in the request header.
160
+ :param body: Request body.
161
+ :param post_params dict: Request post form parameters,
162
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
163
+ :param auth_settings list: Auth Settings names for the request.
164
+ :param files dict: key -> filename, value -> filepath,
165
+ for `multipart/form-data`.
166
+ :param collection_formats: dict of collection formats for path, query,
167
+ header, and post parameters.
168
+ :param _request_auth: set to override the auth_settings for an a single
169
+ request; this effectively ignores the authentication
170
+ in the spec for a single request.
171
+ :return: tuple of form (path, http_method, query_params, header_params,
172
+ body, post_params, files)
173
+ """
174
+
175
+ config = self.configuration
176
+
177
+ # header parameters
178
+ header_params = header_params or {}
179
+ header_params.update(self.default_headers)
180
+ if self.cookie:
181
+ header_params["Cookie"] = self.cookie
182
+ if header_params:
183
+ header_params = self.sanitize_for_serialization(header_params)
184
+ header_params = dict(self.parameters_to_tuples(header_params, collection_formats))
185
+
186
+ # path parameters
187
+ if path_params:
188
+ path_params = self.sanitize_for_serialization(path_params)
189
+ path_params = self.parameters_to_tuples(path_params, collection_formats)
190
+ for k, v in path_params:
191
+ # specified safe chars, encode everything
192
+ resource_path = resource_path.replace("{%s}" % k, quote(str(v), safe=config.safe_chars_for_path_param))
193
+
194
+ # post parameters
195
+ if post_params or files:
196
+ post_params = post_params if post_params else []
197
+ post_params = self.sanitize_for_serialization(post_params)
198
+ post_params = self.parameters_to_tuples(post_params, collection_formats)
199
+ if files:
200
+ post_params.extend(self.files_parameters(files))
201
+
202
+ # auth setting
203
+ self.update_params_for_auth(
204
+ header_params, query_params, auth_settings, resource_path, method, body, request_auth=_request_auth
205
+ )
206
+
207
+ # body
208
+ if body:
209
+ body = self.sanitize_for_serialization(body)
210
+
211
+ # request url
212
+ if _host is None or self.configuration.ignore_operation_servers:
213
+ url = self.configuration.host + resource_path
214
+ else:
215
+ # use server/host defined in path or operation instead
216
+ url = _host + resource_path
217
+
218
+ # query parameters
219
+ if query_params:
220
+ query_params = self.sanitize_for_serialization(query_params)
221
+ url_query = self.parameters_to_url_query(query_params, collection_formats)
222
+ url += "?" + url_query
223
+
224
+ return method, url, header_params, body, post_params
225
+
226
+ def call_api(
227
+ self, method, url, header_params=None, body=None, post_params=None, _request_timeout=None
228
+ ) -> rest.RESTResponse:
229
+ """Makes the HTTP request (synchronous)
230
+ :param method: Method to call.
231
+ :param url: Path to method endpoint.
232
+ :param header_params: Header parameters to be
233
+ placed in the request header.
234
+ :param body: Request body.
235
+ :param post_params dict: Request post form parameters,
236
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
237
+ :param _request_timeout: timeout setting for this request.
238
+ :return: RESTResponse
239
+ """
240
+
241
+ try:
242
+ # perform request and return response
243
+ response_data = self.rest_client.request(
244
+ method,
245
+ url,
246
+ headers=header_params,
247
+ body=body,
248
+ post_params=post_params,
249
+ _request_timeout=_request_timeout,
250
+ )
251
+
252
+ except ApiException as e:
253
+ raise e
254
+
255
+ return response_data
256
+
257
+ def response_deserialize(
258
+ self, response_data: rest.RESTResponse, response_types_map: Optional[Dict[str, ApiResponseT]] = None
259
+ ) -> ApiResponse[ApiResponseT]:
260
+ """Deserializes response into an object.
261
+ :param response_data: RESTResponse object to be deserialized.
262
+ :param response_types_map: dict of response types.
263
+ :return: ApiResponse
264
+ """
265
+
266
+ msg = "RESTResponse.read() must be called before passing it to response_deserialize()"
267
+ assert response_data.data is not None, msg
268
+
269
+ response_type = response_types_map.get(str(response_data.status), None)
270
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
271
+ # if not found, look for '1XX', '2XX', etc.
272
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
273
+
274
+ # deserialize response data
275
+ response_text = None
276
+ return_data = None
277
+ try:
278
+ if response_type == "bytearray":
279
+ return_data = response_data.data
280
+ elif response_type == "file":
281
+ return_data = self.__deserialize_file(response_data)
282
+ elif response_type is not None:
283
+ match = None
284
+ content_type = response_data.getheader("content-type")
285
+ if content_type is not None:
286
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
287
+ encoding = match.group(1) if match else "utf-8"
288
+ response_text = response_data.data.decode(encoding)
289
+ return_data = self.deserialize(response_text, response_type, content_type)
290
+ finally:
291
+ if not 200 <= response_data.status <= 299:
292
+ raise ApiException.from_response(
293
+ http_resp=response_data,
294
+ body=response_text,
295
+ data=return_data,
296
+ )
297
+
298
+ return ApiResponse(
299
+ status_code=response_data.status,
300
+ data=return_data,
301
+ headers=response_data.getheaders(),
302
+ raw_data=response_data.data,
303
+ )
304
+
305
+ def sanitize_for_serialization(self, obj):
306
+ """Builds a JSON POST object.
307
+
308
+ If obj is None, return None.
309
+ If obj is SecretStr, return obj.get_secret_value()
310
+ If obj is str, int, long, float, bool, return directly.
311
+ If obj is datetime.datetime, datetime.date
312
+ convert to string in iso8601 format.
313
+ If obj is decimal.Decimal return string representation.
314
+ If obj is list, sanitize each element in the list.
315
+ If obj is dict, return the dict.
316
+ If obj is OpenAPI model, return the properties dict.
317
+
318
+ :param obj: The data to serialize.
319
+ :return: The serialized form of data.
320
+ """
321
+ if obj is None:
322
+ return None
323
+ elif isinstance(obj, Enum):
324
+ return obj.value
325
+ elif isinstance(obj, SecretStr):
326
+ return obj.get_secret_value()
327
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
328
+ return obj
329
+ elif isinstance(obj, list):
330
+ return [self.sanitize_for_serialization(sub_obj) for sub_obj in obj]
331
+ elif isinstance(obj, tuple):
332
+ return tuple(self.sanitize_for_serialization(sub_obj) for sub_obj in obj)
333
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
334
+ return obj.isoformat()
335
+ elif isinstance(obj, decimal.Decimal):
336
+ return str(obj)
337
+
338
+ elif isinstance(obj, dict):
339
+ obj_dict = obj
340
+ else:
341
+ # Convert model obj to dict except
342
+ # attributes `openapi_types`, `attribute_map`
343
+ # and attributes which value is not None.
344
+ # Convert attribute name to json key in
345
+ # model definition for request.
346
+ if hasattr(obj, "to_dict") and callable(getattr(obj, "to_dict")):
347
+ obj_dict = obj.to_dict()
348
+ else:
349
+ obj_dict = obj.__dict__
350
+
351
+ return {key: self.sanitize_for_serialization(val) for key, val in obj_dict.items()}
352
+
353
+ def deserialize(self, response_text: str, response_type: str, content_type: Optional[str]):
354
+ """Deserializes response into an object.
355
+
356
+ :param response: RESTResponse object to be deserialized.
357
+ :param response_type: class literal for
358
+ deserialized object, or string of class name.
359
+ :param content_type: content type of response.
360
+
361
+ :return: deserialized object.
362
+ """
363
+
364
+ # fetch data from response object
365
+ if content_type is None:
366
+ try:
367
+ data = json.loads(response_text)
368
+ except ValueError:
369
+ data = response_text
370
+ elif re.match(r"^application/(json|[\w!#$&.+-^_]+\+json)\s*(;|$)", content_type, re.IGNORECASE):
371
+ if response_text == "":
372
+ data = ""
373
+ else:
374
+ data = json.loads(response_text)
375
+ elif re.match(r"^text\/[a-z.+-]+\s*(;|$)", content_type, re.IGNORECASE):
376
+ data = response_text
377
+ else:
378
+ raise ApiException(status=0, reason="Unsupported content type: {0}".format(content_type))
379
+
380
+ return self.__deserialize(data, response_type)
381
+
382
+ def __deserialize(self, data, klass):
383
+ """Deserializes dict, list, str into an object.
384
+
385
+ :param data: dict, list or str.
386
+ :param klass: class literal, or string of class name.
387
+
388
+ :return: object.
389
+ """
390
+ if data is None:
391
+ return None
392
+
393
+ if isinstance(klass, str):
394
+ if klass.startswith("List["):
395
+ m = re.match(r"List\[(.*)]", klass)
396
+ assert m is not None, "Malformed List type definition"
397
+ sub_kls = m.group(1)
398
+ return [self.__deserialize(sub_data, sub_kls) for sub_data in data]
399
+
400
+ if klass.startswith("Dict["):
401
+ m = re.match(r"Dict\[([^,]*), (.*)]", klass)
402
+ assert m is not None, "Malformed Dict type definition"
403
+ sub_kls = m.group(2)
404
+ return {k: self.__deserialize(v, sub_kls) for k, v in data.items()}
405
+
406
+ # convert str to class
407
+ if klass in self.NATIVE_TYPES_MAPPING:
408
+ klass = self.NATIVE_TYPES_MAPPING[klass]
409
+ else:
410
+ klass = getattr(admin_api_lib.rag_backend_client.openapi_client.models, klass)
411
+
412
+ if klass in self.PRIMITIVE_TYPES:
413
+ return self.__deserialize_primitive(data, klass)
414
+ elif klass == object:
415
+ return self.__deserialize_object(data)
416
+ elif klass == datetime.date:
417
+ return self.__deserialize_date(data)
418
+ elif klass == datetime.datetime:
419
+ return self.__deserialize_datetime(data)
420
+ elif klass == decimal.Decimal:
421
+ return decimal.Decimal(data)
422
+ elif issubclass(klass, Enum):
423
+ return self.__deserialize_enum(data, klass)
424
+ else:
425
+ return self.__deserialize_model(data, klass)
426
+
427
+ def parameters_to_tuples(self, params, collection_formats):
428
+ """Get parameters as list of tuples, formatting collections.
429
+
430
+ :param params: Parameters as dict or list of two-tuples
431
+ :param dict collection_formats: Parameter collection formats
432
+ :return: Parameters as list of tuples, collections formatted
433
+ """
434
+ new_params: List[Tuple[str, str]] = []
435
+ if collection_formats is None:
436
+ collection_formats = {}
437
+ for k, v in params.items() if isinstance(params, dict) else params:
438
+ if k in collection_formats:
439
+ collection_format = collection_formats[k]
440
+ if collection_format == "multi":
441
+ new_params.extend((k, value) for value in v)
442
+ else:
443
+ if collection_format == "ssv":
444
+ delimiter = " "
445
+ elif collection_format == "tsv":
446
+ delimiter = "\t"
447
+ elif collection_format == "pipes":
448
+ delimiter = "|"
449
+ else: # csv is the default
450
+ delimiter = ","
451
+ new_params.append((k, delimiter.join(str(value) for value in v)))
452
+ else:
453
+ new_params.append((k, v))
454
+ return new_params
455
+
456
+ def parameters_to_url_query(self, params, collection_formats):
457
+ """Get parameters as list of tuples, formatting collections.
458
+
459
+ :param params: Parameters as dict or list of two-tuples
460
+ :param dict collection_formats: Parameter collection formats
461
+ :return: URL query string (e.g. a=Hello%20World&b=123)
462
+ """
463
+ new_params: List[Tuple[str, str]] = []
464
+ if collection_formats is None:
465
+ collection_formats = {}
466
+ for k, v in params.items() if isinstance(params, dict) else params:
467
+ if isinstance(v, bool):
468
+ v = str(v).lower()
469
+ if isinstance(v, (int, float)):
470
+ v = str(v)
471
+ if isinstance(v, dict):
472
+ v = json.dumps(v)
473
+
474
+ if k in collection_formats:
475
+ collection_format = collection_formats[k]
476
+ if collection_format == "multi":
477
+ new_params.extend((k, str(value)) for value in v)
478
+ else:
479
+ if collection_format == "ssv":
480
+ delimiter = " "
481
+ elif collection_format == "tsv":
482
+ delimiter = "\t"
483
+ elif collection_format == "pipes":
484
+ delimiter = "|"
485
+ else: # csv is the default
486
+ delimiter = ","
487
+ new_params.append((k, delimiter.join(quote(str(value)) for value in v)))
488
+ else:
489
+ new_params.append((k, quote(str(v))))
490
+
491
+ return "&".join(["=".join(map(str, item)) for item in new_params])
492
+
493
+ def files_parameters(
494
+ self,
495
+ files: Dict[str, Union[str, bytes, List[str], List[bytes], Tuple[str, bytes]]],
496
+ ):
497
+ """Builds form parameters.
498
+
499
+ :param files: File parameters.
500
+ :return: Form parameters with files.
501
+ """
502
+ params = []
503
+ for k, v in files.items():
504
+ if isinstance(v, str):
505
+ with open(v, "rb") as f:
506
+ filename = os.path.basename(f.name)
507
+ filedata = f.read()
508
+ elif isinstance(v, bytes):
509
+ filename = k
510
+ filedata = v
511
+ elif isinstance(v, tuple):
512
+ filename, filedata = v
513
+ elif isinstance(v, list):
514
+ for file_param in v:
515
+ params.extend(self.files_parameters({k: file_param}))
516
+ continue
517
+ else:
518
+ raise ValueError("Unsupported file value")
519
+ mimetype = mimetypes.guess_type(filename)[0] or "application/octet-stream"
520
+ params.append(tuple([k, tuple([filename, filedata, mimetype])]))
521
+ return params
522
+
523
+ def select_header_accept(self, accepts: List[str]) -> Optional[str]:
524
+ """Returns `Accept` based on an array of accepts provided.
525
+
526
+ :param accepts: List of headers.
527
+ :return: Accept (e.g. application/json).
528
+ """
529
+ if not accepts:
530
+ return None
531
+
532
+ for accept in accepts:
533
+ if re.search("json", accept, re.IGNORECASE):
534
+ return accept
535
+
536
+ return accepts[0]
537
+
538
+ def select_header_content_type(self, content_types):
539
+ """Returns `Content-Type` based on an array of content_types provided.
540
+
541
+ :param content_types: List of content-types.
542
+ :return: Content-Type (e.g. application/json).
543
+ """
544
+ if not content_types:
545
+ return None
546
+
547
+ for content_type in content_types:
548
+ if re.search("json", content_type, re.IGNORECASE):
549
+ return content_type
550
+
551
+ return content_types[0]
552
+
553
+ def update_params_for_auth(
554
+ self, headers, queries, auth_settings, resource_path, method, body, request_auth=None
555
+ ) -> None:
556
+ """Updates header and query params based on authentication setting.
557
+
558
+ :param headers: Header parameters dict to be updated.
559
+ :param queries: Query parameters tuple list to be updated.
560
+ :param auth_settings: Authentication setting identifiers list.
561
+ :resource_path: A string representation of the HTTP request resource path.
562
+ :method: A string representation of the HTTP request method.
563
+ :body: A object representing the body of the HTTP request.
564
+ The object type is the return value of sanitize_for_serialization().
565
+ :param request_auth: if set, the provided settings will
566
+ override the token in the configuration.
567
+ """
568
+ if not auth_settings:
569
+ return
570
+
571
+ if request_auth:
572
+ self._apply_auth_params(headers, queries, resource_path, method, body, request_auth)
573
+ else:
574
+ for auth in auth_settings:
575
+ auth_setting = self.configuration.auth_settings().get(auth)
576
+ if auth_setting:
577
+ self._apply_auth_params(headers, queries, resource_path, method, body, auth_setting)
578
+
579
+ def _apply_auth_params(self, headers, queries, resource_path, method, body, auth_setting) -> None:
580
+ """Updates the request parameters based on a single auth_setting
581
+
582
+ :param headers: Header parameters dict to be updated.
583
+ :param queries: Query parameters tuple list to be updated.
584
+ :resource_path: A string representation of the HTTP request resource path.
585
+ :method: A string representation of the HTTP request method.
586
+ :body: A object representing the body of the HTTP request.
587
+ The object type is the return value of sanitize_for_serialization().
588
+ :param auth_setting: auth settings for the endpoint
589
+ """
590
+ if auth_setting["in"] == "cookie":
591
+ headers["Cookie"] = auth_setting["value"]
592
+ elif auth_setting["in"] == "header":
593
+ if auth_setting["type"] != "http-signature":
594
+ headers[auth_setting["key"]] = auth_setting["value"]
595
+ elif auth_setting["in"] == "query":
596
+ queries.append((auth_setting["key"], auth_setting["value"]))
597
+ else:
598
+ raise ApiValueError("Authentication token must be in `query` or `header`")
599
+
600
+ def __deserialize_file(self, response):
601
+ """Deserializes body to file
602
+
603
+ Saves response body into a file in a temporary folder,
604
+ using the filename from the `Content-Disposition` header if provided.
605
+
606
+ handle file downloading
607
+ save response body into a tmp file and return the instance
608
+
609
+ :param response: RESTResponse.
610
+ :return: file path.
611
+ """
612
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
613
+ os.close(fd)
614
+ os.remove(path)
615
+
616
+ content_disposition = response.getheader("Content-Disposition")
617
+ if content_disposition:
618
+ m = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?', content_disposition)
619
+ assert m is not None, "Unexpected 'content-disposition' header value"
620
+ filename = m.group(1)
621
+ path = os.path.join(os.path.dirname(path), filename)
622
+
623
+ with open(path, "wb") as f:
624
+ f.write(response.data)
625
+
626
+ return path
627
+
628
+ def __deserialize_primitive(self, data, klass):
629
+ """Deserializes string to primitive type.
630
+
631
+ :param data: str.
632
+ :param klass: class literal.
633
+
634
+ :return: int, long, float, str, bool.
635
+ """
636
+ try:
637
+ return klass(data)
638
+ except UnicodeEncodeError:
639
+ return str(data)
640
+ except TypeError:
641
+ return data
642
+
643
+ def __deserialize_object(self, value):
644
+ """Return an original value.
645
+
646
+ :return: object.
647
+ """
648
+ return value
649
+
650
+ def __deserialize_date(self, string):
651
+ """Deserializes string to date.
652
+
653
+ :param string: str.
654
+ :return: date.
655
+ """
656
+ try:
657
+ return parse(string).date()
658
+ except ImportError:
659
+ return string
660
+ except ValueError:
661
+ raise rest.ApiException(status=0, reason="Failed to parse `{0}` as date object".format(string))
662
+
663
+ def __deserialize_datetime(self, string):
664
+ """Deserializes string to datetime.
665
+
666
+ The string should be in iso8601 datetime format.
667
+
668
+ :param string: str.
669
+ :return: datetime.
670
+ """
671
+ try:
672
+ return parse(string)
673
+ except ImportError:
674
+ return string
675
+ except ValueError:
676
+ raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as datetime object".format(string)))
677
+
678
+ def __deserialize_enum(self, data, klass):
679
+ """Deserializes primitive type to enum.
680
+
681
+ :param data: primitive type.
682
+ :param klass: class literal.
683
+ :return: enum value.
684
+ """
685
+ try:
686
+ return klass(data)
687
+ except ValueError:
688
+ raise rest.ApiException(status=0, reason=("Failed to parse `{0}` as `{1}`".format(data, klass)))
689
+
690
+ def __deserialize_model(self, data, klass):
691
+ """Deserializes list or dict to model.
692
+
693
+ :param data: dict, list.
694
+ :param klass: class literal.
695
+ :return: model object.
696
+ """
697
+
698
+ return klass.from_dict(data)