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