mixpeek 0.11.2__py3-none-any.whl → 0.13__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 (189) hide show
  1. mixpeek/__init__.py +9 -1
  2. mixpeek/_hooks/__init__.py +5 -0
  3. mixpeek/_hooks/registration.py +13 -0
  4. mixpeek/_hooks/sdkhooks.py +76 -0
  5. mixpeek/_hooks/types.py +94 -0
  6. mixpeek/_version.py +12 -0
  7. mixpeek/assets.py +1561 -0
  8. mixpeek/basesdk.py +350 -0
  9. mixpeek/collections.py +1029 -0
  10. mixpeek/featureextractors.py +205 -0
  11. mixpeek/features.py +1181 -0
  12. mixpeek/health.py +167 -0
  13. mixpeek/httpclient.py +84 -0
  14. mixpeek/ingest.py +831 -0
  15. mixpeek/interactions.py +221 -0
  16. mixpeek/models/__init__.py +751 -0
  17. mixpeek/models/actionusage.py +16 -0
  18. mixpeek/models/apierror.py +22 -0
  19. mixpeek/models/apikey.py +25 -0
  20. mixpeek/models/apikeyupdate.py +49 -0
  21. mixpeek/models/assetfeatures.py +55 -0
  22. mixpeek/models/assetresponse.py +166 -0
  23. mixpeek/models/assets_model_searchquery.py +21 -0
  24. mixpeek/models/assetupdate.py +28 -0
  25. mixpeek/models/availableindexesresponse.py +23 -0
  26. mixpeek/models/availablemodels.py +12 -0
  27. mixpeek/models/boolindexparams.py +18 -0
  28. mixpeek/models/collectionmodel.py +70 -0
  29. mixpeek/models/collectionresult.py +73 -0
  30. mixpeek/models/create_api_key_organizations_users_user_email_api_keys_postop.py +23 -0
  31. mixpeek/models/create_collection_collections_postop.py +62 -0
  32. mixpeek/models/create_interaction_features_search_interactions_postop.py +59 -0
  33. mixpeek/models/createcollectionrequest.py +59 -0
  34. mixpeek/models/createnamespacerequest.py +62 -0
  35. mixpeek/models/datetimeindexparams.py +18 -0
  36. mixpeek/models/dateusage.py +22 -0
  37. mixpeek/models/db_model_paginationresponse.py +59 -0
  38. mixpeek/models/db_model_taskresponse.py +20 -0
  39. mixpeek/models/delete_api_key_organizations_users_user_email_api_keys_key_name_deleteop.py +23 -0
  40. mixpeek/models/delete_asset_assets_asset_id_deleteop.py +57 -0
  41. mixpeek/models/delete_collection_collections_collection_deleteop.py +59 -0
  42. mixpeek/models/delete_feature_features_feature_id_deleteop.py +57 -0
  43. mixpeek/models/delete_interaction_features_search_interactions_interaction_id_deleteop.py +59 -0
  44. mixpeek/models/delete_namespace_namespaces_namespace_deleteop.py +18 -0
  45. mixpeek/models/delete_user_organizations_users_user_email_deleteop.py +16 -0
  46. mixpeek/models/denseembedding.py +16 -0
  47. mixpeek/models/embeddingrequest.py +59 -0
  48. mixpeek/models/embeddingresponse.py +64 -0
  49. mixpeek/models/errormessage.py +13 -0
  50. mixpeek/models/errorresponse.py +21 -0
  51. mixpeek/models/facedetectsettings.py +52 -0
  52. mixpeek/models/featureextractionembeddingrequest.py +54 -0
  53. mixpeek/models/featureresponse.py +74 -0
  54. mixpeek/models/features_model_paginationresponse.py +59 -0
  55. mixpeek/models/featureupdaterequest.py +21 -0
  56. mixpeek/models/filtercondition.py +74 -0
  57. mixpeek/models/floatindexparams.py +18 -0
  58. mixpeek/models/full_asset_update_assets_asset_id_putop.py +69 -0
  59. mixpeek/models/full_feature_update_features_feature_id_putop.py +69 -0
  60. mixpeek/models/geoindexparams.py +18 -0
  61. mixpeek/models/get_asset_assets_asset_id_getop.py +73 -0
  62. mixpeek/models/get_asset_with_features_assets_asset_id_features_getop.py +73 -0
  63. mixpeek/models/get_collection_collections_collection_getop.py +59 -0
  64. mixpeek/models/get_feature_features_feature_id_getop.py +70 -0
  65. mixpeek/models/get_interaction_features_search_interactions_interaction_id_getop.py +59 -0
  66. mixpeek/models/get_namespace_namespaces_namespace_getop.py +18 -0
  67. mixpeek/models/get_task_tasks_task_id_getop.py +57 -0
  68. mixpeek/models/get_user_organizations_users_user_email_getop.py +16 -0
  69. mixpeek/models/groupbyoptions.py +71 -0
  70. mixpeek/models/groupbyoptionsasset.py +71 -0
  71. mixpeek/models/groupedassetdata.py +18 -0
  72. mixpeek/models/healthcheckresponse.py +13 -0
  73. mixpeek/models/httpvalidationerror.py +21 -0
  74. mixpeek/models/imagedescribesettings.py +82 -0
  75. mixpeek/models/imagedetectsettings.py +53 -0
  76. mixpeek/models/imagereadsettings.py +71 -0
  77. mixpeek/models/imagesettings.py +79 -0
  78. mixpeek/models/ingest_image_url_ingest_images_url_postop.py +59 -0
  79. mixpeek/models/ingest_text_ingest_text_postop.py +59 -0
  80. mixpeek/models/ingest_video_url_ingest_videos_url_postop.py +59 -0
  81. mixpeek/models/inputtype.py +11 -0
  82. mixpeek/models/integerindexparams.py +24 -0
  83. mixpeek/models/interactionresponse.py +87 -0
  84. mixpeek/models/interactiontype.py +11 -0
  85. mixpeek/models/jsonimageoutputsettings.py +55 -0
  86. mixpeek/models/jsontextoutputsettings.py +55 -0
  87. mixpeek/models/jsonvideooutputsettings.py +55 -0
  88. mixpeek/models/keywordindexparams.py +21 -0
  89. mixpeek/models/kill_task_tasks_task_id_deleteop.py +57 -0
  90. mixpeek/models/list_assets_assets_postop.py +77 -0
  91. mixpeek/models/list_collections_collections_getop.py +65 -0
  92. mixpeek/models/list_features_features_postop.py +79 -0
  93. mixpeek/models/list_interactions_features_search_interactions_getop.py +96 -0
  94. mixpeek/models/listassetsrequest.py +75 -0
  95. mixpeek/models/listassetsresponse.py +22 -0
  96. mixpeek/models/listcollectionsresponse.py +22 -0
  97. mixpeek/models/listfeaturesrequest.py +77 -0
  98. mixpeek/models/listfeaturesresponse.py +22 -0
  99. mixpeek/models/logicaloperator_input.py +88 -0
  100. mixpeek/models/logicaloperator_output.py +103 -0
  101. mixpeek/models/logodetectsettings.py +52 -0
  102. mixpeek/models/modality.py +13 -0
  103. mixpeek/models/modeldetails.py +57 -0
  104. mixpeek/models/namespaceresponse.py +54 -0
  105. mixpeek/models/organizationmodel.py +45 -0
  106. mixpeek/models/partial_asset_update_assets_asset_id_patchop.py +69 -0
  107. mixpeek/models/payloadindexconfig.py +94 -0
  108. mixpeek/models/payloadindextype.py +17 -0
  109. mixpeek/models/payloadschematype.py +15 -0
  110. mixpeek/models/percolaterequest.py +57 -0
  111. mixpeek/models/permission.py +10 -0
  112. mixpeek/models/processimageurlinput.py +99 -0
  113. mixpeek/models/processtextinput.py +94 -0
  114. mixpeek/models/processvideourlinput.py +99 -0
  115. mixpeek/models/querysettings.py +56 -0
  116. mixpeek/models/rerankingoptions.py +47 -0
  117. mixpeek/models/search_assets_assets_search_postop.py +59 -0
  118. mixpeek/models/search_features_features_search_postop.py +96 -0
  119. mixpeek/models/search_model_searchquery_input.py +76 -0
  120. mixpeek/models/searchassetsrequest.py +78 -0
  121. mixpeek/models/searchinteraction.py +82 -0
  122. mixpeek/models/searchquery_output.py +79 -0
  123. mixpeek/models/searchrequestfeatures_input.py +151 -0
  124. mixpeek/models/searchrequestfeatures_output.py +151 -0
  125. mixpeek/models/sortoption.py +28 -0
  126. mixpeek/models/sparseembedding.py +21 -0
  127. mixpeek/models/tasks_model_taskresponse.py +24 -0
  128. mixpeek/models/taskstatus.py +16 -0
  129. mixpeek/models/textindexparams.py +31 -0
  130. mixpeek/models/textsettings.py +61 -0
  131. mixpeek/models/tokenizertype.py +11 -0
  132. mixpeek/models/update_api_key_organizations_users_user_email_api_keys_key_name_patchop.py +30 -0
  133. mixpeek/models/update_collection_collections_collection_putop.py +74 -0
  134. mixpeek/models/update_namespace_namespaces_namespace_putop.py +28 -0
  135. mixpeek/models/updateassetrequest.py +60 -0
  136. mixpeek/models/updatenamespacerequest.py +26 -0
  137. mixpeek/models/usage.py +18 -0
  138. mixpeek/models/usermodel_input.py +36 -0
  139. mixpeek/models/usermodel_output.py +36 -0
  140. mixpeek/models/uuidindexparams.py +21 -0
  141. mixpeek/models/validationerror.py +26 -0
  142. mixpeek/models/vectormodel.py +11 -0
  143. mixpeek/models/vectortype.py +9 -0
  144. mixpeek/models/videodescribesettings.py +82 -0
  145. mixpeek/models/videodetectsettings.py +53 -0
  146. mixpeek/models/videoreadsettings.py +71 -0
  147. mixpeek/models/videosettings.py +101 -0
  148. mixpeek/models/videotranscriptionsettings.py +69 -0
  149. mixpeek/namespaces.py +1143 -0
  150. mixpeek/organizations.py +1508 -0
  151. mixpeek/py.typed +1 -0
  152. mixpeek/sdk.py +135 -0
  153. mixpeek/sdkconfiguration.py +45 -0
  154. mixpeek/searchinteractions.py +647 -0
  155. mixpeek/tasks.py +387 -0
  156. mixpeek/types/__init__.py +21 -0
  157. mixpeek/types/basemodel.py +39 -0
  158. mixpeek/utils/__init__.py +97 -0
  159. mixpeek/utils/annotations.py +55 -0
  160. mixpeek/utils/enums.py +34 -0
  161. mixpeek/utils/eventstreaming.py +238 -0
  162. mixpeek/utils/forms.py +202 -0
  163. mixpeek/utils/headers.py +136 -0
  164. mixpeek/utils/logger.py +27 -0
  165. mixpeek/utils/metadata.py +118 -0
  166. mixpeek/utils/queryparams.py +205 -0
  167. mixpeek/utils/requestbodies.py +66 -0
  168. mixpeek/utils/retries.py +217 -0
  169. mixpeek/utils/security.py +174 -0
  170. mixpeek/utils/serializers.py +215 -0
  171. mixpeek/utils/url.py +155 -0
  172. mixpeek/utils/values.py +134 -0
  173. mixpeek-0.13.dist-info/METADATA +439 -0
  174. mixpeek-0.13.dist-info/RECORD +176 -0
  175. {mixpeek-0.11.2.dist-info → mixpeek-0.13.dist-info}/WHEEL +1 -2
  176. py.typed +1 -0
  177. mixpeek/client.py +0 -27
  178. mixpeek/endpoints/__init__.py +0 -0
  179. mixpeek/endpoints/collections.py +0 -86
  180. mixpeek/endpoints/embed.py +0 -66
  181. mixpeek/endpoints/index.py +0 -51
  182. mixpeek/endpoints/register.py +0 -34
  183. mixpeek/endpoints/search.py +0 -44
  184. mixpeek/endpoints/tasks.py +0 -26
  185. mixpeek/endpoints/tools.py +0 -138
  186. mixpeek/exceptions.py +0 -13
  187. mixpeek-0.11.2.dist-info/METADATA +0 -375
  188. mixpeek-0.11.2.dist-info/RECORD +0 -15
  189. mixpeek-0.11.2.dist-info/top_level.txt +0 -1
@@ -0,0 +1,174 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ import base64
4
+ from typing import (
5
+ Any,
6
+ Dict,
7
+ List,
8
+ Tuple,
9
+ )
10
+ from pydantic import BaseModel
11
+ from pydantic.fields import FieldInfo
12
+
13
+ from .metadata import (
14
+ SecurityMetadata,
15
+ find_field_metadata,
16
+ )
17
+
18
+
19
+ def get_security(security: Any) -> Tuple[Dict[str, str], Dict[str, List[str]]]:
20
+ headers: Dict[str, str] = {}
21
+ query_params: Dict[str, List[str]] = {}
22
+
23
+ if security is None:
24
+ return headers, query_params
25
+
26
+ if not isinstance(security, BaseModel):
27
+ raise TypeError("security must be a pydantic model")
28
+
29
+ sec_fields: Dict[str, FieldInfo] = security.__class__.model_fields
30
+ for name in sec_fields:
31
+ sec_field = sec_fields[name]
32
+
33
+ value = getattr(security, name)
34
+ if value is None:
35
+ continue
36
+
37
+ metadata = find_field_metadata(sec_field, SecurityMetadata)
38
+ if metadata is None:
39
+ continue
40
+ if metadata.option:
41
+ _parse_security_option(headers, query_params, value)
42
+ return headers, query_params
43
+ if metadata.scheme:
44
+ # Special case for basic auth or custom auth which could be a flattened model
45
+ if metadata.sub_type in ["basic", "custom"] and not isinstance(
46
+ value, BaseModel
47
+ ):
48
+ _parse_security_scheme(headers, query_params, metadata, name, security)
49
+ else:
50
+ _parse_security_scheme(headers, query_params, metadata, name, value)
51
+
52
+ return headers, query_params
53
+
54
+
55
+ def _parse_security_option(
56
+ headers: Dict[str, str], query_params: Dict[str, List[str]], option: Any
57
+ ):
58
+ if not isinstance(option, BaseModel):
59
+ raise TypeError("security option must be a pydantic model")
60
+
61
+ opt_fields: Dict[str, FieldInfo] = option.__class__.model_fields
62
+ for name in opt_fields:
63
+ opt_field = opt_fields[name]
64
+
65
+ metadata = find_field_metadata(opt_field, SecurityMetadata)
66
+ if metadata is None or not metadata.scheme:
67
+ continue
68
+ _parse_security_scheme(
69
+ headers, query_params, metadata, name, getattr(option, name)
70
+ )
71
+
72
+
73
+ def _parse_security_scheme(
74
+ headers: Dict[str, str],
75
+ query_params: Dict[str, List[str]],
76
+ scheme_metadata: SecurityMetadata,
77
+ field_name: str,
78
+ scheme: Any,
79
+ ):
80
+ scheme_type = scheme_metadata.scheme_type
81
+ sub_type = scheme_metadata.sub_type
82
+
83
+ if isinstance(scheme, BaseModel):
84
+ if scheme_type == "http":
85
+ if sub_type == "basic":
86
+ _parse_basic_auth_scheme(headers, scheme)
87
+ return
88
+ if sub_type == "custom":
89
+ return
90
+
91
+ scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields
92
+ for name in scheme_fields:
93
+ scheme_field = scheme_fields[name]
94
+
95
+ metadata = find_field_metadata(scheme_field, SecurityMetadata)
96
+ if metadata is None or metadata.field_name is None:
97
+ continue
98
+
99
+ value = getattr(scheme, name)
100
+
101
+ _parse_security_scheme_value(
102
+ headers, query_params, scheme_metadata, metadata, name, value
103
+ )
104
+ else:
105
+ _parse_security_scheme_value(
106
+ headers, query_params, scheme_metadata, scheme_metadata, field_name, scheme
107
+ )
108
+
109
+
110
+ def _parse_security_scheme_value(
111
+ headers: Dict[str, str],
112
+ query_params: Dict[str, List[str]],
113
+ scheme_metadata: SecurityMetadata,
114
+ security_metadata: SecurityMetadata,
115
+ field_name: str,
116
+ value: Any,
117
+ ):
118
+ scheme_type = scheme_metadata.scheme_type
119
+ sub_type = scheme_metadata.sub_type
120
+
121
+ header_name = security_metadata.get_field_name(field_name)
122
+
123
+ if scheme_type == "apiKey":
124
+ if sub_type == "header":
125
+ headers[header_name] = value
126
+ elif sub_type == "query":
127
+ query_params[header_name] = [value]
128
+ else:
129
+ raise ValueError("sub type {sub_type} not supported")
130
+ elif scheme_type == "openIdConnect":
131
+ headers[header_name] = _apply_bearer(value)
132
+ elif scheme_type == "oauth2":
133
+ if sub_type != "client_credentials":
134
+ headers[header_name] = _apply_bearer(value)
135
+ elif scheme_type == "http":
136
+ if sub_type == "bearer":
137
+ headers[header_name] = _apply_bearer(value)
138
+ elif sub_type == "custom":
139
+ return
140
+ else:
141
+ raise ValueError("sub type {sub_type} not supported")
142
+ else:
143
+ raise ValueError("scheme type {scheme_type} not supported")
144
+
145
+
146
+ def _apply_bearer(token: str) -> str:
147
+ return token.lower().startswith("bearer ") and token or f"Bearer {token}"
148
+
149
+
150
+ def _parse_basic_auth_scheme(headers: Dict[str, str], scheme: Any):
151
+ username = ""
152
+ password = ""
153
+
154
+ if not isinstance(scheme, BaseModel):
155
+ raise TypeError("basic auth scheme must be a pydantic model")
156
+
157
+ scheme_fields: Dict[str, FieldInfo] = scheme.__class__.model_fields
158
+ for name in scheme_fields:
159
+ scheme_field = scheme_fields[name]
160
+
161
+ metadata = find_field_metadata(scheme_field, SecurityMetadata)
162
+ if metadata is None or metadata.field_name is None:
163
+ continue
164
+
165
+ field_name = metadata.field_name
166
+ value = getattr(scheme, name)
167
+
168
+ if field_name == "username":
169
+ username = value
170
+ if field_name == "password":
171
+ password = value
172
+
173
+ data = f"{username}:{password}".encode()
174
+ headers["Authorization"] = f"Basic {base64.b64encode(data).decode()}"
@@ -0,0 +1,215 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from decimal import Decimal
4
+ import json
5
+ from typing import Any, Dict, List, Union, get_args
6
+ import httpx
7
+ from typing_extensions import get_origin
8
+ from pydantic import ConfigDict, create_model
9
+ from pydantic_core import from_json
10
+ from typing_inspect import is_optional_type
11
+
12
+ from ..types.basemodel import BaseModel, Nullable, OptionalNullable, Unset
13
+
14
+
15
+ def serialize_decimal(as_str: bool):
16
+ def serialize(d):
17
+ if is_optional_type(type(d)) and d is None:
18
+ return None
19
+ if isinstance(d, Unset):
20
+ return d
21
+
22
+ if not isinstance(d, Decimal):
23
+ raise ValueError("Expected Decimal object")
24
+
25
+ return str(d) if as_str else float(d)
26
+
27
+ return serialize
28
+
29
+
30
+ def validate_decimal(d):
31
+ if d is None:
32
+ return None
33
+
34
+ if isinstance(d, (Decimal, Unset)):
35
+ return d
36
+
37
+ if not isinstance(d, (str, int, float)):
38
+ raise ValueError("Expected string, int or float")
39
+
40
+ return Decimal(str(d))
41
+
42
+
43
+ def serialize_float(as_str: bool):
44
+ def serialize(f):
45
+ if is_optional_type(type(f)) and f is None:
46
+ return None
47
+ if isinstance(f, Unset):
48
+ return f
49
+
50
+ if not isinstance(f, float):
51
+ raise ValueError("Expected float")
52
+
53
+ return str(f) if as_str else f
54
+
55
+ return serialize
56
+
57
+
58
+ def validate_float(f):
59
+ if f is None:
60
+ return None
61
+
62
+ if isinstance(f, (float, Unset)):
63
+ return f
64
+
65
+ if not isinstance(f, str):
66
+ raise ValueError("Expected string")
67
+
68
+ return float(f)
69
+
70
+
71
+ def serialize_int(as_str: bool):
72
+ def serialize(i):
73
+ if is_optional_type(type(i)) and i is None:
74
+ return None
75
+ if isinstance(i, Unset):
76
+ return i
77
+
78
+ if not isinstance(i, int):
79
+ raise ValueError("Expected int")
80
+
81
+ return str(i) if as_str else i
82
+
83
+ return serialize
84
+
85
+
86
+ def validate_int(b):
87
+ if b is None:
88
+ return None
89
+
90
+ if isinstance(b, (int, Unset)):
91
+ return b
92
+
93
+ if not isinstance(b, str):
94
+ raise ValueError("Expected string")
95
+
96
+ return int(b)
97
+
98
+
99
+ def validate_open_enum(is_int: bool):
100
+ def validate(e):
101
+ if e is None:
102
+ return None
103
+
104
+ if isinstance(e, Unset):
105
+ return e
106
+
107
+ if is_int:
108
+ if not isinstance(e, int):
109
+ raise ValueError("Expected int")
110
+ else:
111
+ if not isinstance(e, str):
112
+ raise ValueError("Expected string")
113
+
114
+ return e
115
+
116
+ return validate
117
+
118
+
119
+ def validate_const(v):
120
+ def validate(c):
121
+ if is_optional_type(type(c)) and c is None:
122
+ return None
123
+
124
+ if v != c:
125
+ raise ValueError(f"Expected {v}")
126
+
127
+ return c
128
+
129
+ return validate
130
+
131
+
132
+ def unmarshal_json(raw, typ: Any) -> Any:
133
+ return unmarshal(from_json(raw), typ)
134
+
135
+
136
+ def unmarshal(val, typ: Any) -> Any:
137
+ unmarshaller = create_model(
138
+ "Unmarshaller",
139
+ body=(typ, ...),
140
+ __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True),
141
+ )
142
+
143
+ m = unmarshaller(body=val)
144
+
145
+ # pyright: ignore[reportAttributeAccessIssue]
146
+ return m.body # type: ignore
147
+
148
+
149
+ def marshal_json(val, typ):
150
+ if is_nullable(typ) and val is None:
151
+ return "null"
152
+
153
+ marshaller = create_model(
154
+ "Marshaller",
155
+ body=(typ, ...),
156
+ __config__=ConfigDict(populate_by_name=True, arbitrary_types_allowed=True),
157
+ )
158
+
159
+ m = marshaller(body=val)
160
+
161
+ d = m.model_dump(by_alias=True, mode="json", exclude_none=True)
162
+
163
+ if len(d) == 0:
164
+ return ""
165
+
166
+ return json.dumps(d[next(iter(d))], separators=(",", ":"), sort_keys=True)
167
+
168
+
169
+ def is_nullable(field):
170
+ origin = get_origin(field)
171
+ if origin is Nullable or origin is OptionalNullable:
172
+ return True
173
+
174
+ if not origin is Union or type(None) not in get_args(field):
175
+ return False
176
+
177
+ for arg in get_args(field):
178
+ if get_origin(arg) is Nullable or get_origin(arg) is OptionalNullable:
179
+ return True
180
+
181
+ return False
182
+
183
+
184
+ def stream_to_text(stream: httpx.Response) -> str:
185
+ return "".join(stream.iter_text())
186
+
187
+
188
+ async def stream_to_text_async(stream: httpx.Response) -> str:
189
+ return "".join([chunk async for chunk in stream.aiter_text()])
190
+
191
+
192
+ def stream_to_bytes(stream: httpx.Response) -> bytes:
193
+ return stream.content
194
+
195
+
196
+ async def stream_to_bytes_async(stream: httpx.Response) -> bytes:
197
+ return await stream.aread()
198
+
199
+
200
+ def get_pydantic_model(data: Any, typ: Any) -> Any:
201
+ if not _contains_pydantic_model(data):
202
+ return unmarshal(data, typ)
203
+
204
+ return data
205
+
206
+
207
+ def _contains_pydantic_model(data: Any) -> bool:
208
+ if isinstance(data, BaseModel):
209
+ return True
210
+ if isinstance(data, List):
211
+ return any(_contains_pydantic_model(item) for item in data)
212
+ if isinstance(data, Dict):
213
+ return any(_contains_pydantic_model(value) for value in data.values())
214
+
215
+ return False
mixpeek/utils/url.py ADDED
@@ -0,0 +1,155 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from decimal import Decimal
4
+ from typing import (
5
+ Any,
6
+ Dict,
7
+ get_type_hints,
8
+ List,
9
+ Optional,
10
+ Union,
11
+ get_args,
12
+ get_origin,
13
+ )
14
+ from pydantic import BaseModel
15
+ from pydantic.fields import FieldInfo
16
+
17
+ from .metadata import (
18
+ PathParamMetadata,
19
+ find_field_metadata,
20
+ )
21
+ from .values import (
22
+ _get_serialized_params,
23
+ _is_set,
24
+ _populate_from_globals,
25
+ _val_to_string,
26
+ )
27
+
28
+
29
+ def generate_url(
30
+ server_url: str,
31
+ path: str,
32
+ path_params: Any,
33
+ gbls: Optional[Any] = None,
34
+ ) -> str:
35
+ path_param_values: Dict[str, str] = {}
36
+
37
+ globals_already_populated = _populate_path_params(
38
+ path_params, gbls, path_param_values, []
39
+ )
40
+ if _is_set(gbls):
41
+ _populate_path_params(gbls, None, path_param_values, globals_already_populated)
42
+
43
+ for key, value in path_param_values.items():
44
+ path = path.replace("{" + key + "}", value, 1)
45
+
46
+ return remove_suffix(server_url, "/") + path
47
+
48
+
49
+ def _populate_path_params(
50
+ path_params: Any,
51
+ gbls: Any,
52
+ path_param_values: Dict[str, str],
53
+ skip_fields: List[str],
54
+ ) -> List[str]:
55
+ globals_already_populated: List[str] = []
56
+
57
+ if not isinstance(path_params, BaseModel):
58
+ return globals_already_populated
59
+
60
+ path_param_fields: Dict[str, FieldInfo] = path_params.__class__.model_fields
61
+ path_param_field_types = get_type_hints(path_params.__class__)
62
+ for name in path_param_fields:
63
+ if name in skip_fields:
64
+ continue
65
+
66
+ field = path_param_fields[name]
67
+
68
+ param_metadata = find_field_metadata(field, PathParamMetadata)
69
+ if param_metadata is None:
70
+ continue
71
+
72
+ param = getattr(path_params, name) if _is_set(path_params) else None
73
+ param, global_found = _populate_from_globals(
74
+ name, param, PathParamMetadata, gbls
75
+ )
76
+ if global_found:
77
+ globals_already_populated.append(name)
78
+
79
+ if not _is_set(param):
80
+ continue
81
+
82
+ f_name = field.alias if field.alias is not None else name
83
+ serialization = param_metadata.serialization
84
+ if serialization is not None:
85
+ serialized_params = _get_serialized_params(
86
+ param_metadata, f_name, param, path_param_field_types[name]
87
+ )
88
+ for key, value in serialized_params.items():
89
+ path_param_values[key] = value
90
+ else:
91
+ pp_vals: List[str] = []
92
+ if param_metadata.style == "simple":
93
+ if isinstance(param, List):
94
+ for pp_val in param:
95
+ if not _is_set(pp_val):
96
+ continue
97
+ pp_vals.append(_val_to_string(pp_val))
98
+ path_param_values[f_name] = ",".join(pp_vals)
99
+ elif isinstance(param, Dict):
100
+ for pp_key in param:
101
+ if not _is_set(param[pp_key]):
102
+ continue
103
+ if param_metadata.explode:
104
+ pp_vals.append(f"{pp_key}={_val_to_string(param[pp_key])}")
105
+ else:
106
+ pp_vals.append(f"{pp_key},{_val_to_string(param[pp_key])}")
107
+ path_param_values[f_name] = ",".join(pp_vals)
108
+ elif not isinstance(param, (str, int, float, complex, bool, Decimal)):
109
+ param_fields: Dict[str, FieldInfo] = param.__class__.model_fields
110
+ for name in param_fields:
111
+ param_field = param_fields[name]
112
+
113
+ param_value_metadata = find_field_metadata(
114
+ param_field, PathParamMetadata
115
+ )
116
+ if param_value_metadata is None:
117
+ continue
118
+
119
+ param_name = (
120
+ param_field.alias if param_field.alias is not None else name
121
+ )
122
+
123
+ param_field_val = getattr(param, name)
124
+ if not _is_set(param_field_val):
125
+ continue
126
+ if param_metadata.explode:
127
+ pp_vals.append(
128
+ f"{param_name}={_val_to_string(param_field_val)}"
129
+ )
130
+ else:
131
+ pp_vals.append(
132
+ f"{param_name},{_val_to_string(param_field_val)}"
133
+ )
134
+ path_param_values[f_name] = ",".join(pp_vals)
135
+ elif _is_set(param):
136
+ path_param_values[f_name] = _val_to_string(param)
137
+
138
+ return globals_already_populated
139
+
140
+
141
+ def is_optional(field):
142
+ return get_origin(field) is Union and type(None) in get_args(field)
143
+
144
+
145
+ def template_url(url_with_params: str, params: Dict[str, str]) -> str:
146
+ for key, value in params.items():
147
+ url_with_params = url_with_params.replace("{" + key + "}", value)
148
+
149
+ return url_with_params
150
+
151
+
152
+ def remove_suffix(input_string, suffix):
153
+ if suffix and input_string.endswith(suffix):
154
+ return input_string[: -len(suffix)]
155
+ return input_string
@@ -0,0 +1,134 @@
1
+ """Code generated by Speakeasy (https://speakeasy.com). DO NOT EDIT."""
2
+
3
+ from datetime import datetime
4
+ from enum import Enum
5
+ from email.message import Message
6
+ import os
7
+ from typing import Any, Callable, Dict, List, Optional, Tuple, TypeVar, Union
8
+
9
+ from httpx import Response
10
+ from pydantic import BaseModel
11
+ from pydantic.fields import FieldInfo
12
+
13
+ from ..types.basemodel import Unset
14
+
15
+ from .serializers import marshal_json
16
+
17
+ from .metadata import ParamMetadata, find_field_metadata
18
+
19
+
20
+ def match_content_type(content_type: str, pattern: str) -> bool:
21
+ if pattern in (content_type, "*", "*/*"):
22
+ return True
23
+
24
+ msg = Message()
25
+ msg["content-type"] = content_type
26
+ media_type = msg.get_content_type()
27
+
28
+ if media_type == pattern:
29
+ return True
30
+
31
+ parts = media_type.split("/")
32
+ if len(parts) == 2:
33
+ if pattern in (f"{parts[0]}/*", f"*/{parts[1]}"):
34
+ return True
35
+
36
+ return False
37
+
38
+
39
+ def match_status_codes(status_codes: List[str], status_code: int) -> bool:
40
+ if "default" in status_codes:
41
+ return True
42
+
43
+ for code in status_codes:
44
+ if code == str(status_code):
45
+ return True
46
+
47
+ if code.endswith("XX") and code.startswith(str(status_code)[:1]):
48
+ return True
49
+ return False
50
+
51
+
52
+ T = TypeVar("T")
53
+
54
+
55
+ def get_global_from_env(
56
+ value: Optional[T], env_key: str, type_cast: Callable[[str], T]
57
+ ) -> Optional[T]:
58
+ if value is not None:
59
+ return value
60
+ env_value = os.getenv(env_key)
61
+ if env_value is not None:
62
+ try:
63
+ return type_cast(env_value)
64
+ except ValueError:
65
+ pass
66
+ return None
67
+
68
+
69
+ def match_response(
70
+ response: Response, code: Union[str, List[str]], content_type: str
71
+ ) -> bool:
72
+ codes = code if isinstance(code, list) else [code]
73
+ return match_status_codes(codes, response.status_code) and match_content_type(
74
+ response.headers.get("content-type", "application/octet-stream"), content_type
75
+ )
76
+
77
+
78
+ def _populate_from_globals(
79
+ param_name: str, value: Any, param_metadata_type: type, gbls: Any
80
+ ) -> Tuple[Any, bool]:
81
+ if gbls is None:
82
+ return value, False
83
+
84
+ if not isinstance(gbls, BaseModel):
85
+ raise TypeError("globals must be a pydantic model")
86
+
87
+ global_fields: Dict[str, FieldInfo] = gbls.__class__.model_fields
88
+ found = False
89
+ for name in global_fields:
90
+ field = global_fields[name]
91
+ if name is not param_name:
92
+ continue
93
+
94
+ found = True
95
+
96
+ if value is not None:
97
+ return value, True
98
+
99
+ global_value = getattr(gbls, name)
100
+
101
+ param_metadata = find_field_metadata(field, param_metadata_type)
102
+ if param_metadata is None:
103
+ return value, True
104
+
105
+ return global_value, True
106
+
107
+ return value, found
108
+
109
+
110
+ def _val_to_string(val) -> str:
111
+ if isinstance(val, bool):
112
+ return str(val).lower()
113
+ if isinstance(val, datetime):
114
+ return str(val.isoformat().replace("+00:00", "Z"))
115
+ if isinstance(val, Enum):
116
+ return str(val.value)
117
+
118
+ return str(val)
119
+
120
+
121
+ def _get_serialized_params(
122
+ metadata: ParamMetadata, field_name: str, obj: Any, typ: type
123
+ ) -> Dict[str, str]:
124
+ params: Dict[str, str] = {}
125
+
126
+ serialization = metadata.serialization
127
+ if serialization == "json":
128
+ params[field_name] = marshal_json(obj, typ)
129
+
130
+ return params
131
+
132
+
133
+ def _is_set(value: Any) -> bool:
134
+ return value is not None and not isinstance(value, Unset)