mycelium-ai 0.5.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 (164) hide show
  1. mycelium/__init__.py +0 -0
  2. mycelium/api/__init__.py +0 -0
  3. mycelium/api/app.py +1147 -0
  4. mycelium/api/client_app.py +170 -0
  5. mycelium/api/generated_sources/__init__.py +0 -0
  6. mycelium/api/generated_sources/server_schemas/__init__.py +97 -0
  7. mycelium/api/generated_sources/server_schemas/api/__init__.py +5 -0
  8. mycelium/api/generated_sources/server_schemas/api/default_api.py +2473 -0
  9. mycelium/api/generated_sources/server_schemas/api_client.py +766 -0
  10. mycelium/api/generated_sources/server_schemas/api_response.py +25 -0
  11. mycelium/api/generated_sources/server_schemas/configuration.py +434 -0
  12. mycelium/api/generated_sources/server_schemas/exceptions.py +166 -0
  13. mycelium/api/generated_sources/server_schemas/models/__init__.py +41 -0
  14. mycelium/api/generated_sources/server_schemas/models/api_section.py +71 -0
  15. mycelium/api/generated_sources/server_schemas/models/chroma_section.py +69 -0
  16. mycelium/api/generated_sources/server_schemas/models/clap_section.py +75 -0
  17. mycelium/api/generated_sources/server_schemas/models/compute_on_server200_response.py +79 -0
  18. mycelium/api/generated_sources/server_schemas/models/compute_on_server_request.py +67 -0
  19. mycelium/api/generated_sources/server_schemas/models/compute_text_search_request.py +69 -0
  20. mycelium/api/generated_sources/server_schemas/models/config_request.py +81 -0
  21. mycelium/api/generated_sources/server_schemas/models/config_response.py +107 -0
  22. mycelium/api/generated_sources/server_schemas/models/create_playlist_request.py +71 -0
  23. mycelium/api/generated_sources/server_schemas/models/get_similar_by_track200_response.py +143 -0
  24. mycelium/api/generated_sources/server_schemas/models/library_stats_response.py +77 -0
  25. mycelium/api/generated_sources/server_schemas/models/logging_section.py +67 -0
  26. mycelium/api/generated_sources/server_schemas/models/media_server_section.py +67 -0
  27. mycelium/api/generated_sources/server_schemas/models/playlist_response.py +73 -0
  28. mycelium/api/generated_sources/server_schemas/models/plex_section.py +71 -0
  29. mycelium/api/generated_sources/server_schemas/models/processing_response.py +90 -0
  30. mycelium/api/generated_sources/server_schemas/models/save_config_response.py +73 -0
  31. mycelium/api/generated_sources/server_schemas/models/scan_library_response.py +75 -0
  32. mycelium/api/generated_sources/server_schemas/models/search_result_response.py +75 -0
  33. mycelium/api/generated_sources/server_schemas/models/server_section.py +67 -0
  34. mycelium/api/generated_sources/server_schemas/models/stop_processing_response.py +71 -0
  35. mycelium/api/generated_sources/server_schemas/models/task_status_response.py +87 -0
  36. mycelium/api/generated_sources/server_schemas/models/track_database_stats.py +75 -0
  37. mycelium/api/generated_sources/server_schemas/models/track_response.py +77 -0
  38. mycelium/api/generated_sources/server_schemas/models/tracks_list_response.py +81 -0
  39. mycelium/api/generated_sources/server_schemas/rest.py +329 -0
  40. mycelium/api/generated_sources/server_schemas/test/__init__.py +0 -0
  41. mycelium/api/generated_sources/server_schemas/test/test_api_section.py +57 -0
  42. mycelium/api/generated_sources/server_schemas/test/test_chroma_section.py +55 -0
  43. mycelium/api/generated_sources/server_schemas/test/test_clap_section.py +60 -0
  44. mycelium/api/generated_sources/server_schemas/test/test_compute_on_server200_response.py +52 -0
  45. mycelium/api/generated_sources/server_schemas/test/test_compute_on_server_request.py +53 -0
  46. mycelium/api/generated_sources/server_schemas/test/test_compute_text_search_request.py +54 -0
  47. mycelium/api/generated_sources/server_schemas/test/test_config_request.py +66 -0
  48. mycelium/api/generated_sources/server_schemas/test/test_config_response.py +97 -0
  49. mycelium/api/generated_sources/server_schemas/test/test_create_playlist_request.py +60 -0
  50. mycelium/api/generated_sources/server_schemas/test/test_default_api.py +150 -0
  51. mycelium/api/generated_sources/server_schemas/test/test_get_similar_by_track200_response.py +61 -0
  52. mycelium/api/generated_sources/server_schemas/test/test_library_stats_response.py +63 -0
  53. mycelium/api/generated_sources/server_schemas/test/test_logging_section.py +53 -0
  54. mycelium/api/generated_sources/server_schemas/test/test_media_server_section.py +53 -0
  55. mycelium/api/generated_sources/server_schemas/test/test_playlist_response.py +58 -0
  56. mycelium/api/generated_sources/server_schemas/test/test_plex_section.py +56 -0
  57. mycelium/api/generated_sources/server_schemas/test/test_processing_response.py +61 -0
  58. mycelium/api/generated_sources/server_schemas/test/test_save_config_response.py +58 -0
  59. mycelium/api/generated_sources/server_schemas/test/test_scan_library_response.py +61 -0
  60. mycelium/api/generated_sources/server_schemas/test/test_search_result_response.py +69 -0
  61. mycelium/api/generated_sources/server_schemas/test/test_server_section.py +53 -0
  62. mycelium/api/generated_sources/server_schemas/test/test_stop_processing_response.py +55 -0
  63. mycelium/api/generated_sources/server_schemas/test/test_task_status_response.py +71 -0
  64. mycelium/api/generated_sources/server_schemas/test/test_track_database_stats.py +60 -0
  65. mycelium/api/generated_sources/server_schemas/test/test_track_response.py +63 -0
  66. mycelium/api/generated_sources/server_schemas/test/test_tracks_list_response.py +75 -0
  67. mycelium/api/generated_sources/worker_schemas/__init__.py +61 -0
  68. mycelium/api/generated_sources/worker_schemas/api/__init__.py +5 -0
  69. mycelium/api/generated_sources/worker_schemas/api/default_api.py +318 -0
  70. mycelium/api/generated_sources/worker_schemas/api_client.py +766 -0
  71. mycelium/api/generated_sources/worker_schemas/api_response.py +25 -0
  72. mycelium/api/generated_sources/worker_schemas/configuration.py +434 -0
  73. mycelium/api/generated_sources/worker_schemas/exceptions.py +166 -0
  74. mycelium/api/generated_sources/worker_schemas/models/__init__.py +23 -0
  75. mycelium/api/generated_sources/worker_schemas/models/save_config_response.py +73 -0
  76. mycelium/api/generated_sources/worker_schemas/models/worker_clap_section.py +75 -0
  77. mycelium/api/generated_sources/worker_schemas/models/worker_client_api_section.py +69 -0
  78. mycelium/api/generated_sources/worker_schemas/models/worker_client_section.py +79 -0
  79. mycelium/api/generated_sources/worker_schemas/models/worker_config_request.py +73 -0
  80. mycelium/api/generated_sources/worker_schemas/models/worker_config_response.py +89 -0
  81. mycelium/api/generated_sources/worker_schemas/models/worker_logging_section.py +67 -0
  82. mycelium/api/generated_sources/worker_schemas/rest.py +329 -0
  83. mycelium/api/generated_sources/worker_schemas/test/__init__.py +0 -0
  84. mycelium/api/generated_sources/worker_schemas/test/test_default_api.py +45 -0
  85. mycelium/api/generated_sources/worker_schemas/test/test_save_config_response.py +58 -0
  86. mycelium/api/generated_sources/worker_schemas/test/test_worker_clap_section.py +60 -0
  87. mycelium/api/generated_sources/worker_schemas/test/test_worker_client_api_section.py +55 -0
  88. mycelium/api/generated_sources/worker_schemas/test/test_worker_client_section.py +65 -0
  89. mycelium/api/generated_sources/worker_schemas/test/test_worker_config_request.py +59 -0
  90. mycelium/api/generated_sources/worker_schemas/test/test_worker_config_response.py +89 -0
  91. mycelium/api/generated_sources/worker_schemas/test/test_worker_logging_section.py +53 -0
  92. mycelium/api/worker_models.py +99 -0
  93. mycelium/application/__init__.py +11 -0
  94. mycelium/application/job_queue.py +323 -0
  95. mycelium/application/library_management_use_cases.py +292 -0
  96. mycelium/application/search_use_cases.py +96 -0
  97. mycelium/application/services.py +340 -0
  98. mycelium/client.py +554 -0
  99. mycelium/client_config.py +251 -0
  100. mycelium/client_frontend_dist/404.html +1 -0
  101. mycelium/client_frontend_dist/_next/static/a4iyRdfsvkjdyMAK9cE9Y/_buildManifest.js +1 -0
  102. mycelium/client_frontend_dist/_next/static/a4iyRdfsvkjdyMAK9cE9Y/_ssgManifest.js +1 -0
  103. mycelium/client_frontend_dist/_next/static/chunks/4bd1b696-cf72ae8a39fa05aa.js +1 -0
  104. mycelium/client_frontend_dist/_next/static/chunks/964-830f77d7ce1c2463.js +1 -0
  105. mycelium/client_frontend_dist/_next/static/chunks/app/_not-found/page-d25eede5a9099bd3.js +1 -0
  106. mycelium/client_frontend_dist/_next/static/chunks/app/layout-9b3d32f96dfe13b6.js +1 -0
  107. mycelium/client_frontend_dist/_next/static/chunks/app/page-cc6bad295789134e.js +1 -0
  108. mycelium/client_frontend_dist/_next/static/chunks/framework-7c95b8e5103c9e90.js +1 -0
  109. mycelium/client_frontend_dist/_next/static/chunks/main-6b37be50736577a2.js +1 -0
  110. mycelium/client_frontend_dist/_next/static/chunks/main-app-4153d115599d3126.js +1 -0
  111. mycelium/client_frontend_dist/_next/static/chunks/pages/_app-0a0020ddd67f79cf.js +1 -0
  112. mycelium/client_frontend_dist/_next/static/chunks/pages/_error-03529f2c21436739.js +1 -0
  113. mycelium/client_frontend_dist/_next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  114. mycelium/client_frontend_dist/_next/static/chunks/webpack-c81e624915b2ea70.js +1 -0
  115. mycelium/client_frontend_dist/_next/static/css/1eb7f0e2c78e0734.css +1 -0
  116. mycelium/client_frontend_dist/favicon.ico +0 -0
  117. mycelium/client_frontend_dist/file.svg +1 -0
  118. mycelium/client_frontend_dist/globe.svg +1 -0
  119. mycelium/client_frontend_dist/index.html +1 -0
  120. mycelium/client_frontend_dist/index.txt +20 -0
  121. mycelium/client_frontend_dist/next.svg +1 -0
  122. mycelium/client_frontend_dist/vercel.svg +1 -0
  123. mycelium/client_frontend_dist/window.svg +1 -0
  124. mycelium/config.py +346 -0
  125. mycelium/domain/__init__.py +13 -0
  126. mycelium/domain/models.py +71 -0
  127. mycelium/domain/repositories.py +98 -0
  128. mycelium/domain/worker.py +77 -0
  129. mycelium/frontend_dist/404.html +1 -0
  130. mycelium/frontend_dist/_next/static/chunks/4bd1b696-cf72ae8a39fa05aa.js +1 -0
  131. mycelium/frontend_dist/_next/static/chunks/964-830f77d7ce1c2463.js +1 -0
  132. mycelium/frontend_dist/_next/static/chunks/app/_not-found/page-d25eede5a9099bd3.js +1 -0
  133. mycelium/frontend_dist/_next/static/chunks/app/layout-9b3d32f96dfe13b6.js +1 -0
  134. mycelium/frontend_dist/_next/static/chunks/app/page-a761463485e0540b.js +1 -0
  135. mycelium/frontend_dist/_next/static/chunks/framework-7c95b8e5103c9e90.js +1 -0
  136. mycelium/frontend_dist/_next/static/chunks/main-6b37be50736577a2.js +1 -0
  137. mycelium/frontend_dist/_next/static/chunks/main-app-4153d115599d3126.js +1 -0
  138. mycelium/frontend_dist/_next/static/chunks/pages/_app-0a0020ddd67f79cf.js +1 -0
  139. mycelium/frontend_dist/_next/static/chunks/pages/_error-03529f2c21436739.js +1 -0
  140. mycelium/frontend_dist/_next/static/chunks/polyfills-42372ed130431b0a.js +1 -0
  141. mycelium/frontend_dist/_next/static/chunks/webpack-c81e624915b2ea70.js +1 -0
  142. mycelium/frontend_dist/_next/static/css/1eb7f0e2c78e0734.css +1 -0
  143. mycelium/frontend_dist/_next/static/glVJ0yJSL0zWN7anTTG3_/_buildManifest.js +1 -0
  144. mycelium/frontend_dist/_next/static/glVJ0yJSL0zWN7anTTG3_/_ssgManifest.js +1 -0
  145. mycelium/frontend_dist/favicon.ico +0 -0
  146. mycelium/frontend_dist/file.svg +1 -0
  147. mycelium/frontend_dist/globe.svg +1 -0
  148. mycelium/frontend_dist/index.html +10 -0
  149. mycelium/frontend_dist/index.txt +20 -0
  150. mycelium/frontend_dist/next.svg +1 -0
  151. mycelium/frontend_dist/vercel.svg +1 -0
  152. mycelium/frontend_dist/window.svg +1 -0
  153. mycelium/infrastructure/__init__.py +17 -0
  154. mycelium/infrastructure/chroma_adapter.py +232 -0
  155. mycelium/infrastructure/clap_adapter.py +280 -0
  156. mycelium/infrastructure/plex_adapter.py +145 -0
  157. mycelium/infrastructure/track_database.py +467 -0
  158. mycelium/main.py +183 -0
  159. mycelium_ai-0.5.0.dist-info/METADATA +312 -0
  160. mycelium_ai-0.5.0.dist-info/RECORD +164 -0
  161. mycelium_ai-0.5.0.dist-info/WHEEL +5 -0
  162. mycelium_ai-0.5.0.dist-info/entry_points.txt +2 -0
  163. mycelium_ai-0.5.0.dist-info/licenses/LICENSE +21 -0
  164. mycelium_ai-0.5.0.dist-info/top_level.txt +1 -0
@@ -0,0 +1,766 @@
1
+ # coding: utf-8
2
+
3
+ """
4
+ Mycelium Worker (Client) API
5
+
6
+ Configuration API for Mycelium client workers
7
+
8
+ The version of the OpenAPI document: 0.1.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 atexit
16
+ import datetime
17
+ from dateutil.parser import parse
18
+ import json
19
+ import mimetypes
20
+ from multiprocessing.pool import ThreadPool
21
+ import os
22
+ import re
23
+ import tempfile
24
+
25
+ from urllib.parse import quote
26
+ from pydantic import SecretStr
27
+
28
+ from mycelium.api.generated_sources.worker_schemas.configuration import Configuration
29
+ from mycelium.api.generated_sources.worker_schemas.api_response import ApiResponse
30
+ import mycelium.api.generated_sources.worker_schemas.models
31
+ from mycelium.api.generated_sources.worker_schemas import rest
32
+ from mycelium.api.generated_sources.worker_schemas.exceptions import ApiValueError, ApiException
33
+
34
+
35
+ class ApiClient:
36
+ """Generic API client for OpenAPI client library builds.
37
+
38
+ OpenAPI generic API client. This client handles the client-
39
+ server communication, and is invariant across implementations. Specifics of
40
+ the methods and models for each application are generated from the OpenAPI
41
+ templates.
42
+
43
+ :param configuration: .Configuration object for this client
44
+ :param header_name: a header to pass when making calls to the API.
45
+ :param header_value: a header value to pass when making calls to
46
+ the API.
47
+ :param cookie: a cookie to include in the header when making calls
48
+ to the API
49
+ :param pool_threads: The number of threads to use for async requests
50
+ to the API. More threads means more concurrent API requests.
51
+ """
52
+
53
+ PRIMITIVE_TYPES = (float, bool, bytes, str, int)
54
+ NATIVE_TYPES_MAPPING = {
55
+ 'int': int,
56
+ 'long': int, # TODO remove as only py3 is supported?
57
+ 'float': float,
58
+ 'str': str,
59
+ 'bool': bool,
60
+ 'date': datetime.date,
61
+ 'datetime': datetime.datetime,
62
+ 'object': object,
63
+ }
64
+ _pool = None
65
+
66
+ def __init__(self, configuration=None, header_name=None, header_value=None,
67
+ cookie=None, pool_threads=1) -> None:
68
+ # use default configuration if none is provided
69
+ if configuration is None:
70
+ configuration = Configuration.get_default()
71
+ self.configuration = configuration
72
+ self.pool_threads = pool_threads
73
+
74
+ self.rest_client = rest.RESTClientObject(configuration)
75
+ self.default_headers = {}
76
+ if header_name is not None:
77
+ self.default_headers[header_name] = header_value
78
+ self.cookie = cookie
79
+ # Set default User-Agent.
80
+ self.user_agent = 'OpenAPI-Generator/0.1.0/python'
81
+ self.client_side_validation = configuration.client_side_validation
82
+
83
+ def __enter__(self):
84
+ return self
85
+
86
+ def __exit__(self, exc_type, exc_value, traceback):
87
+ self.close()
88
+
89
+ def close(self):
90
+ if self._pool:
91
+ self._pool.close()
92
+ self._pool.join()
93
+ self._pool = None
94
+ if hasattr(atexit, 'unregister'):
95
+ atexit.unregister(self.close)
96
+
97
+ @property
98
+ def pool(self):
99
+ """Create thread pool on first request
100
+ avoids instantiating unused threadpool for blocking clients.
101
+ """
102
+ if self._pool is None:
103
+ atexit.register(self.close)
104
+ self._pool = ThreadPool(self.pool_threads)
105
+ return self._pool
106
+
107
+ @property
108
+ def user_agent(self):
109
+ """User agent for this API client"""
110
+ return self.default_headers['User-Agent']
111
+
112
+ @user_agent.setter
113
+ def user_agent(self, value):
114
+ self.default_headers['User-Agent'] = value
115
+
116
+ def set_default_header(self, header_name, header_value):
117
+ self.default_headers[header_name] = header_value
118
+
119
+
120
+ _default = None
121
+
122
+ @classmethod
123
+ def get_default(cls):
124
+ """Return new instance of ApiClient.
125
+
126
+ This method returns newly created, based on default constructor,
127
+ object of ApiClient class or returns a copy of default
128
+ ApiClient.
129
+
130
+ :return: The ApiClient object.
131
+ """
132
+ if cls._default is None:
133
+ cls._default = ApiClient()
134
+ return cls._default
135
+
136
+ @classmethod
137
+ def set_default(cls, default):
138
+ """Set default instance of ApiClient.
139
+
140
+ It stores default ApiClient.
141
+
142
+ :param default: object of ApiClient.
143
+ """
144
+ cls._default = default
145
+
146
+ def __call_api(
147
+ self, resource_path, method, path_params=None,
148
+ query_params=None, header_params=None, body=None, post_params=None,
149
+ files=None, response_types_map=None, auth_settings=None,
150
+ _return_http_data_only=None, collection_formats=None,
151
+ _preload_content=True, _request_timeout=None, _host=None,
152
+ _request_auth=None):
153
+
154
+ config = self.configuration
155
+
156
+ # header parameters
157
+ header_params = header_params or {}
158
+ header_params.update(self.default_headers)
159
+ if self.cookie:
160
+ header_params['Cookie'] = self.cookie
161
+ if header_params:
162
+ header_params = self.sanitize_for_serialization(header_params)
163
+ header_params = dict(self.parameters_to_tuples(header_params,
164
+ collection_formats))
165
+
166
+ # path parameters
167
+ if path_params:
168
+ path_params = self.sanitize_for_serialization(path_params)
169
+ path_params = self.parameters_to_tuples(path_params,
170
+ collection_formats)
171
+ for k, v in path_params:
172
+ # specified safe chars, encode everything
173
+ resource_path = resource_path.replace(
174
+ '{%s}' % k,
175
+ quote(str(v), safe=config.safe_chars_for_path_param)
176
+ )
177
+
178
+ # post parameters
179
+ if post_params or files:
180
+ post_params = post_params if post_params else []
181
+ post_params = self.sanitize_for_serialization(post_params)
182
+ post_params = self.parameters_to_tuples(post_params,
183
+ collection_formats)
184
+ post_params.extend(self.files_parameters(files))
185
+
186
+ # auth setting
187
+ self.update_params_for_auth(
188
+ header_params, query_params, auth_settings,
189
+ resource_path, method, body,
190
+ request_auth=_request_auth)
191
+
192
+ # body
193
+ if body:
194
+ body = self.sanitize_for_serialization(body)
195
+
196
+ # request url
197
+ if _host is None:
198
+ url = self.configuration.host + resource_path
199
+ else:
200
+ # use server/host defined in path or operation instead
201
+ url = _host + resource_path
202
+
203
+ # query parameters
204
+ if query_params:
205
+ query_params = self.sanitize_for_serialization(query_params)
206
+ url_query = self.parameters_to_url_query(query_params,
207
+ collection_formats)
208
+ url += "?" + url_query
209
+
210
+ try:
211
+ # perform request and return response
212
+ response_data = self.request(
213
+ method, url,
214
+ query_params=query_params,
215
+ headers=header_params,
216
+ post_params=post_params, body=body,
217
+ _preload_content=_preload_content,
218
+ _request_timeout=_request_timeout)
219
+ except ApiException as e:
220
+ if e.body:
221
+ e.body = e.body.decode('utf-8')
222
+ raise e
223
+
224
+ self.last_response = response_data
225
+
226
+ return_data = None # assuming deserialization is not needed
227
+ # data needs deserialization or returns HTTP data (deserialized) only
228
+ if _preload_content or _return_http_data_only:
229
+ response_type = response_types_map.get(str(response_data.status), None)
230
+ if not response_type and isinstance(response_data.status, int) and 100 <= response_data.status <= 599:
231
+ # if not found, look for '1XX', '2XX', etc.
232
+ response_type = response_types_map.get(str(response_data.status)[0] + "XX", None)
233
+
234
+ if response_type == "bytearray":
235
+ response_data.data = response_data.data
236
+ else:
237
+ match = None
238
+ content_type = response_data.getheader('content-type')
239
+ if content_type is not None:
240
+ match = re.search(r"charset=([a-zA-Z\-\d]+)[\s;]?", content_type)
241
+ encoding = match.group(1) if match else "utf-8"
242
+ response_data.data = response_data.data.decode(encoding)
243
+
244
+ # deserialize response data
245
+ if response_type == "bytearray":
246
+ return_data = response_data.data
247
+ elif response_type:
248
+ return_data = self.deserialize(response_data, response_type)
249
+ else:
250
+ return_data = None
251
+
252
+ if _return_http_data_only:
253
+ return return_data
254
+ else:
255
+ return ApiResponse(status_code = response_data.status,
256
+ data = return_data,
257
+ headers = response_data.getheaders(),
258
+ raw_data = response_data.data)
259
+
260
+ def sanitize_for_serialization(self, obj):
261
+ """Builds a JSON POST object.
262
+
263
+ If obj is None, return None.
264
+ If obj is SecretStr, return obj.get_secret_value()
265
+ If obj is str, int, long, float, bool, return directly.
266
+ If obj is datetime.datetime, datetime.date
267
+ convert to string in iso8601 format.
268
+ If obj is list, sanitize each element in the list.
269
+ If obj is dict, return the dict.
270
+ If obj is OpenAPI model, return the properties dict.
271
+
272
+ :param obj: The data to serialize.
273
+ :return: The serialized form of data.
274
+ """
275
+ if obj is None:
276
+ return None
277
+ elif isinstance(obj, SecretStr):
278
+ return obj.get_secret_value()
279
+ elif isinstance(obj, self.PRIMITIVE_TYPES):
280
+ return obj
281
+ elif isinstance(obj, list):
282
+ return [self.sanitize_for_serialization(sub_obj)
283
+ for sub_obj in obj]
284
+ elif isinstance(obj, tuple):
285
+ return tuple(self.sanitize_for_serialization(sub_obj)
286
+ for sub_obj in obj)
287
+ elif isinstance(obj, (datetime.datetime, datetime.date)):
288
+ return obj.isoformat()
289
+
290
+ if isinstance(obj, dict):
291
+ obj_dict = obj
292
+ else:
293
+ # Convert model obj to dict except
294
+ # attributes `openapi_types`, `attribute_map`
295
+ # and attributes which value is not None.
296
+ # Convert attribute name to json key in
297
+ # model definition for request.
298
+ if hasattr(obj, 'to_dict') and callable(getattr(obj, 'to_dict')):
299
+ obj_dict = obj.to_dict()
300
+ else:
301
+ obj_dict = obj.__dict__
302
+
303
+ return {key: self.sanitize_for_serialization(val)
304
+ for key, val in obj_dict.items()}
305
+
306
+ def deserialize(self, response, response_type):
307
+ """Deserializes response into an object.
308
+
309
+ :param response: RESTResponse object to be deserialized.
310
+ :param response_type: class literal for
311
+ deserialized object, or string of class name.
312
+
313
+ :return: deserialized object.
314
+ """
315
+ # handle file downloading
316
+ # save response body into a tmp file and return the instance
317
+ if response_type == "file":
318
+ return self.__deserialize_file(response)
319
+
320
+ # fetch data from response object
321
+ try:
322
+ data = json.loads(response.data)
323
+ except ValueError:
324
+ data = response.data
325
+
326
+ return self.__deserialize(data, response_type)
327
+
328
+ def __deserialize(self, data, klass):
329
+ """Deserializes dict, list, str into an object.
330
+
331
+ :param data: dict, list or str.
332
+ :param klass: class literal, or string of class name.
333
+
334
+ :return: object.
335
+ """
336
+ if data is None:
337
+ return None
338
+
339
+ if isinstance(klass, str):
340
+ if klass.startswith('List['):
341
+ sub_kls = re.match(r'List\[(.*)]', klass).group(1)
342
+ return [self.__deserialize(sub_data, sub_kls)
343
+ for sub_data in data]
344
+
345
+ if klass.startswith('Dict['):
346
+ sub_kls = re.match(r'Dict\[([^,]*), (.*)]', klass).group(2)
347
+ return {k: self.__deserialize(v, sub_kls)
348
+ for k, v in data.items()}
349
+
350
+ # convert str to class
351
+ if klass in self.NATIVE_TYPES_MAPPING:
352
+ klass = self.NATIVE_TYPES_MAPPING[klass]
353
+ else:
354
+ klass = getattr(mycelium.api.generated_sources.worker_schemas.models, klass)
355
+
356
+ if klass in self.PRIMITIVE_TYPES:
357
+ return self.__deserialize_primitive(data, klass)
358
+ elif klass == object:
359
+ return self.__deserialize_object(data)
360
+ elif klass == datetime.date:
361
+ return self.__deserialize_date(data)
362
+ elif klass == datetime.datetime:
363
+ return self.__deserialize_datetime(data)
364
+ else:
365
+ return self.__deserialize_model(data, klass)
366
+
367
+ def call_api(self, resource_path, method,
368
+ path_params=None, query_params=None, header_params=None,
369
+ body=None, post_params=None, files=None,
370
+ response_types_map=None, auth_settings=None,
371
+ async_req=None, _return_http_data_only=None,
372
+ collection_formats=None, _preload_content=True,
373
+ _request_timeout=None, _host=None, _request_auth=None):
374
+ """Makes the HTTP request (synchronous) and returns deserialized data.
375
+
376
+ To make an async_req request, set the async_req parameter.
377
+
378
+ :param resource_path: Path to method endpoint.
379
+ :param method: Method to call.
380
+ :param path_params: Path parameters in the url.
381
+ :param query_params: Query parameters in the url.
382
+ :param header_params: Header parameters to be
383
+ placed in the request header.
384
+ :param body: Request body.
385
+ :param post_params dict: Request post form parameters,
386
+ for `application/x-www-form-urlencoded`, `multipart/form-data`.
387
+ :param auth_settings list: Auth Settings names for the request.
388
+ :param response: Response data type.
389
+ :param files dict: key -> filename, value -> filepath,
390
+ for `multipart/form-data`.
391
+ :param async_req bool: execute request asynchronously
392
+ :param _return_http_data_only: response data instead of ApiResponse
393
+ object with status code, headers, etc
394
+ :param _preload_content: if False, the ApiResponse.data will
395
+ be set to none and raw_data will store the
396
+ HTTP response body without reading/decoding.
397
+ Default is True.
398
+ :param collection_formats: dict of collection formats for path, query,
399
+ header, and post parameters.
400
+ :param _request_timeout: timeout setting for this request. If one
401
+ number provided, it will be total request
402
+ timeout. It can also be a pair (tuple) of
403
+ (connection, read) timeouts.
404
+ :param _request_auth: set to override the auth_settings for an a single
405
+ request; this effectively ignores the authentication
406
+ in the spec for a single request.
407
+ :type _request_token: dict, optional
408
+ :return:
409
+ If async_req parameter is True,
410
+ the request will be called asynchronously.
411
+ The method will return the request thread.
412
+ If parameter async_req is False or missing,
413
+ then the method will return the response directly.
414
+ """
415
+ args = (
416
+ resource_path,
417
+ method,
418
+ path_params,
419
+ query_params,
420
+ header_params,
421
+ body,
422
+ post_params,
423
+ files,
424
+ response_types_map,
425
+ auth_settings,
426
+ _return_http_data_only,
427
+ collection_formats,
428
+ _preload_content,
429
+ _request_timeout,
430
+ _host,
431
+ _request_auth,
432
+ )
433
+ if not async_req:
434
+ return self.__call_api(*args)
435
+
436
+ return self.pool.apply_async(self.__call_api, args)
437
+
438
+ def request(self, method, url, query_params=None, headers=None,
439
+ post_params=None, body=None, _preload_content=True,
440
+ _request_timeout=None):
441
+ """Makes the HTTP request using RESTClient."""
442
+ if method == "GET":
443
+ return self.rest_client.get_request(url,
444
+ query_params=query_params,
445
+ _preload_content=_preload_content,
446
+ _request_timeout=_request_timeout,
447
+ headers=headers)
448
+ elif method == "HEAD":
449
+ return self.rest_client.head_request(url,
450
+ query_params=query_params,
451
+ _preload_content=_preload_content,
452
+ _request_timeout=_request_timeout,
453
+ headers=headers)
454
+ elif method == "OPTIONS":
455
+ return self.rest_client.options_request(url,
456
+ query_params=query_params,
457
+ headers=headers,
458
+ _preload_content=_preload_content,
459
+ _request_timeout=_request_timeout)
460
+ elif method == "POST":
461
+ return self.rest_client.post_request(url,
462
+ query_params=query_params,
463
+ headers=headers,
464
+ post_params=post_params,
465
+ _preload_content=_preload_content,
466
+ _request_timeout=_request_timeout,
467
+ body=body)
468
+ elif method == "PUT":
469
+ return self.rest_client.put_request(url,
470
+ query_params=query_params,
471
+ headers=headers,
472
+ post_params=post_params,
473
+ _preload_content=_preload_content,
474
+ _request_timeout=_request_timeout,
475
+ body=body)
476
+ elif method == "PATCH":
477
+ return self.rest_client.patch_request(url,
478
+ query_params=query_params,
479
+ headers=headers,
480
+ post_params=post_params,
481
+ _preload_content=_preload_content,
482
+ _request_timeout=_request_timeout,
483
+ body=body)
484
+ elif method == "DELETE":
485
+ return self.rest_client.delete_request(url,
486
+ query_params=query_params,
487
+ headers=headers,
488
+ _preload_content=_preload_content,
489
+ _request_timeout=_request_timeout,
490
+ body=body)
491
+ else:
492
+ raise ApiValueError(
493
+ "http method must be `GET`, `HEAD`, `OPTIONS`,"
494
+ " `POST`, `PATCH`, `PUT` or `DELETE`."
495
+ )
496
+
497
+ def parameters_to_tuples(self, params, collection_formats):
498
+ """Get parameters as list of tuples, formatting collections.
499
+
500
+ :param params: Parameters as dict or list of two-tuples
501
+ :param dict collection_formats: Parameter collection formats
502
+ :return: Parameters as list of tuples, collections formatted
503
+ """
504
+ new_params = []
505
+ if collection_formats is None:
506
+ collection_formats = {}
507
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
508
+ if k in collection_formats:
509
+ collection_format = collection_formats[k]
510
+ if collection_format == 'multi':
511
+ new_params.extend((k, value) for value in v)
512
+ else:
513
+ if collection_format == 'ssv':
514
+ delimiter = ' '
515
+ elif collection_format == 'tsv':
516
+ delimiter = '\t'
517
+ elif collection_format == 'pipes':
518
+ delimiter = '|'
519
+ else: # csv is the default
520
+ delimiter = ','
521
+ new_params.append(
522
+ (k, delimiter.join(str(value) for value in v)))
523
+ else:
524
+ new_params.append((k, v))
525
+ return new_params
526
+
527
+ def parameters_to_url_query(self, params, collection_formats):
528
+ """Get parameters as list of tuples, formatting collections.
529
+
530
+ :param params: Parameters as dict or list of two-tuples
531
+ :param dict collection_formats: Parameter collection formats
532
+ :return: URL query string (e.g. a=Hello%20World&b=123)
533
+ """
534
+ new_params = []
535
+ if collection_formats is None:
536
+ collection_formats = {}
537
+ for k, v in params.items() if isinstance(params, dict) else params: # noqa: E501
538
+ if isinstance(v, bool):
539
+ v = str(v).lower()
540
+ if isinstance(v, (int, float)):
541
+ v = str(v)
542
+ if isinstance(v, dict):
543
+ v = json.dumps(v)
544
+
545
+ if k in collection_formats:
546
+ collection_format = collection_formats[k]
547
+ if collection_format == 'multi':
548
+ new_params.extend((k, quote(str(value))) for value in v)
549
+ else:
550
+ if collection_format == 'ssv':
551
+ delimiter = ' '
552
+ elif collection_format == 'tsv':
553
+ delimiter = '\t'
554
+ elif collection_format == 'pipes':
555
+ delimiter = '|'
556
+ else: # csv is the default
557
+ delimiter = ','
558
+ new_params.append(
559
+ (k, delimiter.join(quote(str(value)) for value in v)))
560
+ else:
561
+ new_params.append((k, quote(str(v))))
562
+
563
+ return "&".join(["=".join(map(str, item)) for item in new_params])
564
+
565
+ def files_parameters(self, files=None):
566
+ """Builds form parameters.
567
+
568
+ :param files: File parameters.
569
+ :return: Form parameters with files.
570
+ """
571
+ params = []
572
+
573
+ if files:
574
+ for k, v in files.items():
575
+ if not v:
576
+ continue
577
+ file_names = v if type(v) is list else [v]
578
+ for n in file_names:
579
+ with open(n, 'rb') as f:
580
+ filename = os.path.basename(f.name)
581
+ filedata = f.read()
582
+ mimetype = (mimetypes.guess_type(filename)[0] or
583
+ 'application/octet-stream')
584
+ params.append(
585
+ tuple([k, tuple([filename, filedata, mimetype])]))
586
+
587
+ return params
588
+
589
+ def select_header_accept(self, accepts):
590
+ """Returns `Accept` based on an array of accepts provided.
591
+
592
+ :param accepts: List of headers.
593
+ :return: Accept (e.g. application/json).
594
+ """
595
+ if not accepts:
596
+ return
597
+
598
+ for accept in accepts:
599
+ if re.search('json', accept, re.IGNORECASE):
600
+ return accept
601
+
602
+ return accepts[0]
603
+
604
+ def select_header_content_type(self, content_types):
605
+ """Returns `Content-Type` based on an array of content_types provided.
606
+
607
+ :param content_types: List of content-types.
608
+ :return: Content-Type (e.g. application/json).
609
+ """
610
+ if not content_types:
611
+ return None
612
+
613
+ for content_type in content_types:
614
+ if re.search('json', content_type, re.IGNORECASE):
615
+ return content_type
616
+
617
+ return content_types[0]
618
+
619
+ def update_params_for_auth(self, headers, queries, auth_settings,
620
+ resource_path, method, body,
621
+ request_auth=None):
622
+ """Updates header and query params based on authentication setting.
623
+
624
+ :param headers: Header parameters dict to be updated.
625
+ :param queries: Query parameters tuple list to be updated.
626
+ :param auth_settings: Authentication setting identifiers list.
627
+ :resource_path: A string representation of the HTTP request resource path.
628
+ :method: A string representation of the HTTP request method.
629
+ :body: A object representing the body of the HTTP request.
630
+ The object type is the return value of sanitize_for_serialization().
631
+ :param request_auth: if set, the provided settings will
632
+ override the token in the configuration.
633
+ """
634
+ if not auth_settings:
635
+ return
636
+
637
+ if request_auth:
638
+ self._apply_auth_params(headers, queries,
639
+ resource_path, method, body,
640
+ request_auth)
641
+ return
642
+
643
+ for auth in auth_settings:
644
+ auth_setting = self.configuration.auth_settings().get(auth)
645
+ if auth_setting:
646
+ self._apply_auth_params(headers, queries,
647
+ resource_path, method, body,
648
+ auth_setting)
649
+
650
+ def _apply_auth_params(self, headers, queries,
651
+ resource_path, method, body,
652
+ auth_setting):
653
+ """Updates the request parameters based on a single auth_setting
654
+
655
+ :param headers: Header parameters dict to be updated.
656
+ :param queries: Query parameters tuple list to be updated.
657
+ :resource_path: A string representation of the HTTP request resource path.
658
+ :method: A string representation of the HTTP request method.
659
+ :body: A object representing the body of the HTTP request.
660
+ The object type is the return value of sanitize_for_serialization().
661
+ :param auth_setting: auth settings for the endpoint
662
+ """
663
+ if auth_setting['in'] == 'cookie':
664
+ headers['Cookie'] = auth_setting['value']
665
+ elif auth_setting['in'] == 'header':
666
+ if auth_setting['type'] != 'http-signature':
667
+ headers[auth_setting['key']] = auth_setting['value']
668
+ elif auth_setting['in'] == 'query':
669
+ queries.append((auth_setting['key'], auth_setting['value']))
670
+ else:
671
+ raise ApiValueError(
672
+ 'Authentication token must be in `query` or `header`'
673
+ )
674
+
675
+ def __deserialize_file(self, response):
676
+ """Deserializes body to file
677
+
678
+ Saves response body into a file in a temporary folder,
679
+ using the filename from the `Content-Disposition` header if provided.
680
+
681
+ :param response: RESTResponse.
682
+ :return: file path.
683
+ """
684
+ fd, path = tempfile.mkstemp(dir=self.configuration.temp_folder_path)
685
+ os.close(fd)
686
+ os.remove(path)
687
+
688
+ content_disposition = response.getheader("Content-Disposition")
689
+ if content_disposition:
690
+ filename = re.search(r'filename=[\'"]?([^\'"\s]+)[\'"]?',
691
+ content_disposition).group(1)
692
+ path = os.path.join(os.path.dirname(path), filename)
693
+
694
+ with open(path, "wb") as f:
695
+ f.write(response.data)
696
+
697
+ return path
698
+
699
+ def __deserialize_primitive(self, data, klass):
700
+ """Deserializes string to primitive type.
701
+
702
+ :param data: str.
703
+ :param klass: class literal.
704
+
705
+ :return: int, long, float, str, bool.
706
+ """
707
+ try:
708
+ return klass(data)
709
+ except UnicodeEncodeError:
710
+ return str(data)
711
+ except TypeError:
712
+ return data
713
+
714
+ def __deserialize_object(self, value):
715
+ """Return an original value.
716
+
717
+ :return: object.
718
+ """
719
+ return value
720
+
721
+ def __deserialize_date(self, string):
722
+ """Deserializes string to date.
723
+
724
+ :param string: str.
725
+ :return: date.
726
+ """
727
+ try:
728
+ return parse(string).date()
729
+ except ImportError:
730
+ return string
731
+ except ValueError:
732
+ raise rest.ApiException(
733
+ status=0,
734
+ reason="Failed to parse `{0}` as date object".format(string)
735
+ )
736
+
737
+ def __deserialize_datetime(self, string):
738
+ """Deserializes string to datetime.
739
+
740
+ The string should be in iso8601 datetime format.
741
+
742
+ :param string: str.
743
+ :return: datetime.
744
+ """
745
+ try:
746
+ return parse(string)
747
+ except ImportError:
748
+ return string
749
+ except ValueError:
750
+ raise rest.ApiException(
751
+ status=0,
752
+ reason=(
753
+ "Failed to parse `{0}` as datetime object"
754
+ .format(string)
755
+ )
756
+ )
757
+
758
+ def __deserialize_model(self, data, klass):
759
+ """Deserializes list or dict to model.
760
+
761
+ :param data: dict, list.
762
+ :param klass: class literal.
763
+ :return: model object.
764
+ """
765
+
766
+ return klass.from_dict(data)