syncsdk 0.1.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 (52) hide show
  1. sync/__init__.py +63 -0
  2. sync/client.py +144 -0
  3. sync/common/__init__.py +46 -0
  4. sync/common/errors/__init__.py +8 -0
  5. sync/common/errors/bad_request_error.py +9 -0
  6. sync/common/errors/internal_server_error.py +9 -0
  7. sync/common/errors/not_found_error.py +9 -0
  8. sync/common/errors/unauthorized_error.py +9 -0
  9. sync/common/types/__init__.py +39 -0
  10. sync/common/types/audio.py +27 -0
  11. sync/common/types/create_generation_dto.py +44 -0
  12. sync/common/types/estimated_generation_cost.py +33 -0
  13. sync/common/types/generation.py +77 -0
  14. sync/common/types/generation_error.py +35 -0
  15. sync/common/types/generation_error_message.py +5 -0
  16. sync/common/types/generation_id.py +3 -0
  17. sync/common/types/generation_options.py +28 -0
  18. sync/common/types/generation_status.py +7 -0
  19. sync/common/types/input.py +8 -0
  20. sync/common/types/model.py +7 -0
  21. sync/common/types/segment_frames.py +5 -0
  22. sync/common/types/segment_secs.py +5 -0
  23. sync/common/types/sync_mode.py +5 -0
  24. sync/common/types/tts.py +28 -0
  25. sync/common/types/tts_provider_config.py +34 -0
  26. sync/common/types/video.py +35 -0
  27. sync/core/__init__.py +50 -0
  28. sync/core/api_error.py +15 -0
  29. sync/core/client_wrapper.py +55 -0
  30. sync/core/datetime_utils.py +28 -0
  31. sync/core/file.py +67 -0
  32. sync/core/http_client.py +497 -0
  33. sync/core/http_response.py +47 -0
  34. sync/core/jsonable_encoder.py +100 -0
  35. sync/core/pydantic_utilities.py +294 -0
  36. sync/core/query_encoder.py +58 -0
  37. sync/core/remove_none_from_dict.py +11 -0
  38. sync/core/request_options.py +35 -0
  39. sync/core/serialization.py +276 -0
  40. sync/environment.py +7 -0
  41. sync/generate/__init__.py +2 -0
  42. sync/generate/client.py +446 -0
  43. sync/generate/raw_client.py +648 -0
  44. sync/py.typed +0 -0
  45. sync/version.py +3 -0
  46. sync/webhooks/__init__.py +5 -0
  47. sync/webhooks/types/__init__.py +6 -0
  48. sync/webhooks/types/generation_notification.py +73 -0
  49. sync/webhooks/types/webhook_status.py +5 -0
  50. syncsdk-0.1.0.dist-info/METADATA +190 -0
  51. syncsdk-0.1.0.dist-info/RECORD +52 -0
  52. syncsdk-0.1.0.dist-info/WHEEL +4 -0
@@ -0,0 +1,294 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ # nopycln: file
4
+ import datetime as dt
5
+ import typing
6
+ from collections import defaultdict
7
+
8
+ import pydantic
9
+ import typing_extensions
10
+ from .datetime_utils import serialize_datetime
11
+ from .serialization import convert_and_respect_annotation_metadata
12
+
13
+ IS_PYDANTIC_V2 = pydantic.VERSION.startswith("2.")
14
+
15
+ if IS_PYDANTIC_V2:
16
+ # isort will try to reformat the comments on these imports, which breaks mypy
17
+ # isort: off
18
+ from pydantic.v1.datetime_parse import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2
19
+ parse_date as parse_date,
20
+ )
21
+ from pydantic.v1.datetime_parse import ( # pyright: ignore[reportMissingImports] # Pydantic v2
22
+ parse_datetime as parse_datetime,
23
+ )
24
+ from pydantic.v1.json import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2
25
+ ENCODERS_BY_TYPE as encoders_by_type,
26
+ )
27
+ from pydantic.v1.typing import ( # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2
28
+ get_args as get_args,
29
+ )
30
+ from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2
31
+ get_origin as get_origin,
32
+ )
33
+ from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2
34
+ is_literal_type as is_literal_type,
35
+ )
36
+ from pydantic.v1.typing import ( # pyright: ignore[reportMissingImports] # Pydantic v2
37
+ is_union as is_union,
38
+ )
39
+ from pydantic.v1.fields import ModelField as ModelField # type: ignore # pyright: ignore[reportMissingImports] # Pydantic v2
40
+ else:
41
+ from pydantic.datetime_parse import parse_date as parse_date # type: ignore # Pydantic v1
42
+ from pydantic.datetime_parse import parse_datetime as parse_datetime # type: ignore # Pydantic v1
43
+ from pydantic.fields import ModelField as ModelField # type: ignore # Pydantic v1
44
+ from pydantic.json import ENCODERS_BY_TYPE as encoders_by_type # type: ignore # Pydantic v1
45
+ from pydantic.typing import get_args as get_args # type: ignore # Pydantic v1
46
+ from pydantic.typing import get_origin as get_origin # type: ignore # Pydantic v1
47
+ from pydantic.typing import is_literal_type as is_literal_type # type: ignore # Pydantic v1
48
+ from pydantic.typing import is_union as is_union # type: ignore # Pydantic v1
49
+
50
+ # isort: on
51
+
52
+
53
+ T = typing.TypeVar("T")
54
+ Model = typing.TypeVar("Model", bound=pydantic.BaseModel)
55
+
56
+
57
+ def parse_obj_as(type_: typing.Type[T], object_: typing.Any) -> T:
58
+ dealiased_object = convert_and_respect_annotation_metadata(object_=object_, annotation=type_, direction="read")
59
+ if IS_PYDANTIC_V2:
60
+ adapter = pydantic.TypeAdapter(type_) # type: ignore # Pydantic v2
61
+ return adapter.validate_python(dealiased_object)
62
+ else:
63
+ return pydantic.parse_obj_as(type_, dealiased_object)
64
+
65
+
66
+ def to_jsonable_with_fallback(
67
+ obj: typing.Any, fallback_serializer: typing.Callable[[typing.Any], typing.Any]
68
+ ) -> typing.Any:
69
+ if IS_PYDANTIC_V2:
70
+ from pydantic_core import to_jsonable_python
71
+
72
+ return to_jsonable_python(obj, fallback=fallback_serializer)
73
+ else:
74
+ return fallback_serializer(obj)
75
+
76
+
77
+ class UniversalBaseModel(pydantic.BaseModel):
78
+ if IS_PYDANTIC_V2:
79
+ model_config: typing.ClassVar[pydantic.ConfigDict] = pydantic.ConfigDict(
80
+ # Allow fields beginning with `model_` to be used in the model
81
+ protected_namespaces=(),
82
+ ) # type: ignore # Pydantic v2
83
+
84
+ @pydantic.model_serializer(mode="wrap", when_used="json") # type: ignore # Pydantic v2
85
+ def serialize_model(self, handler: pydantic.SerializerFunctionWrapHandler) -> typing.Any: # type: ignore # Pydantic v2
86
+ serialized = handler(self)
87
+ data = {k: serialize_datetime(v) if isinstance(v, dt.datetime) else v for k, v in serialized.items()}
88
+ return data
89
+
90
+ else:
91
+
92
+ class Config:
93
+ smart_union = True
94
+ json_encoders = {dt.datetime: serialize_datetime}
95
+
96
+ @classmethod
97
+ def model_construct(
98
+ cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any
99
+ ) -> "Model":
100
+ dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read")
101
+ return cls.construct(_fields_set, **dealiased_object)
102
+
103
+ @classmethod
104
+ def construct(
105
+ cls: typing.Type["Model"], _fields_set: typing.Optional[typing.Set[str]] = None, **values: typing.Any
106
+ ) -> "Model":
107
+ dealiased_object = convert_and_respect_annotation_metadata(object_=values, annotation=cls, direction="read")
108
+ if IS_PYDANTIC_V2:
109
+ return super().model_construct(_fields_set, **dealiased_object) # type: ignore # Pydantic v2
110
+ else:
111
+ return super().construct(_fields_set, **dealiased_object)
112
+
113
+ def json(self, **kwargs: typing.Any) -> str:
114
+ kwargs_with_defaults: typing.Any = {
115
+ "by_alias": True,
116
+ "exclude_unset": True,
117
+ **kwargs,
118
+ }
119
+ if IS_PYDANTIC_V2:
120
+ return super().model_dump_json(**kwargs_with_defaults) # type: ignore # Pydantic v2
121
+ else:
122
+ return super().json(**kwargs_with_defaults)
123
+
124
+ def dict(self, **kwargs: typing.Any) -> typing.Dict[str, typing.Any]:
125
+ """
126
+ Override the default dict method to `exclude_unset` by default. This function patches
127
+ `exclude_unset` to work include fields within non-None default values.
128
+ """
129
+ # Note: the logic here is multiplexed given the levers exposed in Pydantic V1 vs V2
130
+ # Pydantic V1's .dict can be extremely slow, so we do not want to call it twice.
131
+ #
132
+ # We'd ideally do the same for Pydantic V2, but it shells out to a library to serialize models
133
+ # that we have less control over, and this is less intrusive than custom serializers for now.
134
+ if IS_PYDANTIC_V2:
135
+ kwargs_with_defaults_exclude_unset: typing.Any = {
136
+ **kwargs,
137
+ "by_alias": True,
138
+ "exclude_unset": True,
139
+ "exclude_none": False,
140
+ }
141
+ kwargs_with_defaults_exclude_none: typing.Any = {
142
+ **kwargs,
143
+ "by_alias": True,
144
+ "exclude_none": True,
145
+ "exclude_unset": False,
146
+ }
147
+ dict_dump = deep_union_pydantic_dicts(
148
+ super().model_dump(**kwargs_with_defaults_exclude_unset), # type: ignore # Pydantic v2
149
+ super().model_dump(**kwargs_with_defaults_exclude_none), # type: ignore # Pydantic v2
150
+ )
151
+
152
+ else:
153
+ _fields_set = self.__fields_set__.copy()
154
+
155
+ fields = _get_model_fields(self.__class__)
156
+ for name, field in fields.items():
157
+ if name not in _fields_set:
158
+ default = _get_field_default(field)
159
+
160
+ # If the default values are non-null act like they've been set
161
+ # This effectively allows exclude_unset to work like exclude_none where
162
+ # the latter passes through intentionally set none values.
163
+ if default is not None or ("exclude_unset" in kwargs and not kwargs["exclude_unset"]):
164
+ _fields_set.add(name)
165
+
166
+ if default is not None:
167
+ self.__fields_set__.add(name)
168
+
169
+ kwargs_with_defaults_exclude_unset_include_fields: typing.Any = {
170
+ "by_alias": True,
171
+ "exclude_unset": True,
172
+ "include": _fields_set,
173
+ **kwargs,
174
+ }
175
+
176
+ dict_dump = super().dict(**kwargs_with_defaults_exclude_unset_include_fields)
177
+
178
+ return convert_and_respect_annotation_metadata(object_=dict_dump, annotation=self.__class__, direction="write")
179
+
180
+
181
+ def _union_list_of_pydantic_dicts(
182
+ source: typing.List[typing.Any], destination: typing.List[typing.Any]
183
+ ) -> typing.List[typing.Any]:
184
+ converted_list: typing.List[typing.Any] = []
185
+ for i, item in enumerate(source):
186
+ destination_value = destination[i] # type: ignore
187
+ if isinstance(item, dict):
188
+ converted_list.append(deep_union_pydantic_dicts(item, destination_value))
189
+ elif isinstance(item, list):
190
+ converted_list.append(_union_list_of_pydantic_dicts(item, destination_value))
191
+ else:
192
+ converted_list.append(item)
193
+ return converted_list
194
+
195
+
196
+ def deep_union_pydantic_dicts(
197
+ source: typing.Dict[str, typing.Any], destination: typing.Dict[str, typing.Any]
198
+ ) -> typing.Dict[str, typing.Any]:
199
+ for key, value in source.items():
200
+ node = destination.setdefault(key, {})
201
+ if isinstance(value, dict):
202
+ deep_union_pydantic_dicts(value, node)
203
+ # Note: we do not do this same processing for sets given we do not have sets of models
204
+ # and given the sets are unordered, the processing of the set and matching objects would
205
+ # be non-trivial.
206
+ elif isinstance(value, list):
207
+ destination[key] = _union_list_of_pydantic_dicts(value, node)
208
+ else:
209
+ destination[key] = value
210
+
211
+ return destination
212
+
213
+
214
+ if IS_PYDANTIC_V2:
215
+
216
+ class V2RootModel(UniversalBaseModel, pydantic.RootModel): # type: ignore # Pydantic v2
217
+ pass
218
+
219
+ UniversalRootModel: typing_extensions.TypeAlias = V2RootModel # type: ignore
220
+ else:
221
+ UniversalRootModel: typing_extensions.TypeAlias = UniversalBaseModel # type: ignore
222
+
223
+
224
+ def encode_by_type(o: typing.Any) -> typing.Any:
225
+ encoders_by_class_tuples: typing.Dict[typing.Callable[[typing.Any], typing.Any], typing.Tuple[typing.Any, ...]] = (
226
+ defaultdict(tuple)
227
+ )
228
+ for type_, encoder in encoders_by_type.items():
229
+ encoders_by_class_tuples[encoder] += (type_,)
230
+
231
+ if type(o) in encoders_by_type:
232
+ return encoders_by_type[type(o)](o)
233
+ for encoder, classes_tuple in encoders_by_class_tuples.items():
234
+ if isinstance(o, classes_tuple):
235
+ return encoder(o)
236
+
237
+
238
+ def update_forward_refs(model: typing.Type["Model"], **localns: typing.Any) -> None:
239
+ if IS_PYDANTIC_V2:
240
+ model.model_rebuild(raise_errors=False) # type: ignore # Pydantic v2
241
+ else:
242
+ model.update_forward_refs(**localns)
243
+
244
+
245
+ # Mirrors Pydantic's internal typing
246
+ AnyCallable = typing.Callable[..., typing.Any]
247
+
248
+
249
+ def universal_root_validator(
250
+ pre: bool = False,
251
+ ) -> typing.Callable[[AnyCallable], AnyCallable]:
252
+ def decorator(func: AnyCallable) -> AnyCallable:
253
+ if IS_PYDANTIC_V2:
254
+ return pydantic.model_validator(mode="before" if pre else "after")(func) # type: ignore # Pydantic v2
255
+ else:
256
+ return pydantic.root_validator(pre=pre)(func) # type: ignore # Pydantic v1
257
+
258
+ return decorator
259
+
260
+
261
+ def universal_field_validator(field_name: str, pre: bool = False) -> typing.Callable[[AnyCallable], AnyCallable]:
262
+ def decorator(func: AnyCallable) -> AnyCallable:
263
+ if IS_PYDANTIC_V2:
264
+ return pydantic.field_validator(field_name, mode="before" if pre else "after")(func) # type: ignore # Pydantic v2
265
+ else:
266
+ return pydantic.validator(field_name, pre=pre)(func) # type: ignore # Pydantic v1
267
+
268
+ return decorator
269
+
270
+
271
+ PydanticField = typing.Union[ModelField, pydantic.fields.FieldInfo]
272
+
273
+
274
+ def _get_model_fields(
275
+ model: typing.Type["Model"],
276
+ ) -> typing.Mapping[str, PydanticField]:
277
+ if IS_PYDANTIC_V2:
278
+ return model.model_fields # type: ignore # Pydantic v2
279
+ else:
280
+ return model.__fields__ # type: ignore # Pydantic v1
281
+
282
+
283
+ def _get_field_default(field: PydanticField) -> typing.Any:
284
+ try:
285
+ value = field.get_default() # type: ignore # Pydantic < v1.10.15
286
+ except:
287
+ value = field.default
288
+ if IS_PYDANTIC_V2:
289
+ from pydantic_core import PydanticUndefined
290
+
291
+ if value == PydanticUndefined:
292
+ return None
293
+ return value
294
+ return value
@@ -0,0 +1,58 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from typing import Any, Dict, List, Optional, Tuple
4
+
5
+ import pydantic
6
+
7
+
8
+ # Flattens dicts to be of the form {"key[subkey][subkey2]": value} where value is not a dict
9
+ def traverse_query_dict(dict_flat: Dict[str, Any], key_prefix: Optional[str] = None) -> List[Tuple[str, Any]]:
10
+ result = []
11
+ for k, v in dict_flat.items():
12
+ key = f"{key_prefix}[{k}]" if key_prefix is not None else k
13
+ if isinstance(v, dict):
14
+ result.extend(traverse_query_dict(v, key))
15
+ elif isinstance(v, list):
16
+ for arr_v in v:
17
+ if isinstance(arr_v, dict):
18
+ result.extend(traverse_query_dict(arr_v, key))
19
+ else:
20
+ result.append((key, arr_v))
21
+ else:
22
+ result.append((key, v))
23
+ return result
24
+
25
+
26
+ def single_query_encoder(query_key: str, query_value: Any) -> List[Tuple[str, Any]]:
27
+ if isinstance(query_value, pydantic.BaseModel) or isinstance(query_value, dict):
28
+ if isinstance(query_value, pydantic.BaseModel):
29
+ obj_dict = query_value.dict(by_alias=True)
30
+ else:
31
+ obj_dict = query_value
32
+ return traverse_query_dict(obj_dict, query_key)
33
+ elif isinstance(query_value, list):
34
+ encoded_values: List[Tuple[str, Any]] = []
35
+ for value in query_value:
36
+ if isinstance(value, pydantic.BaseModel) or isinstance(value, dict):
37
+ if isinstance(value, pydantic.BaseModel):
38
+ obj_dict = value.dict(by_alias=True)
39
+ elif isinstance(value, dict):
40
+ obj_dict = value
41
+
42
+ encoded_values.extend(single_query_encoder(query_key, obj_dict))
43
+ else:
44
+ encoded_values.append((query_key, value))
45
+
46
+ return encoded_values
47
+
48
+ return [(query_key, query_value)]
49
+
50
+
51
+ def encode_query(query: Optional[Dict[str, Any]]) -> Optional[List[Tuple[str, Any]]]:
52
+ if query is None:
53
+ return None
54
+
55
+ encoded_query = []
56
+ for k, v in query.items():
57
+ encoded_query.extend(single_query_encoder(k, v))
58
+ return encoded_query
@@ -0,0 +1,11 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ from typing import Any, Dict, Mapping, Optional
4
+
5
+
6
+ def remove_none_from_dict(original: Mapping[str, Optional[Any]]) -> Dict[str, Any]:
7
+ new: Dict[str, Any] = {}
8
+ for key, value in original.items():
9
+ if value is not None:
10
+ new[key] = value
11
+ return new
@@ -0,0 +1,35 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import typing
4
+
5
+ try:
6
+ from typing import NotRequired # type: ignore
7
+ except ImportError:
8
+ from typing_extensions import NotRequired
9
+
10
+
11
+ class RequestOptions(typing.TypedDict, total=False):
12
+ """
13
+ Additional options for request-specific configuration when calling APIs via the SDK.
14
+ This is used primarily as an optional final parameter for service functions.
15
+
16
+ Attributes:
17
+ - timeout_in_seconds: int. The number of seconds to await an API call before timing out.
18
+
19
+ - max_retries: int. The max number of retries to attempt if the API call fails.
20
+
21
+ - additional_headers: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's header dict
22
+
23
+ - additional_query_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's query parameters dict
24
+
25
+ - additional_body_parameters: typing.Dict[str, typing.Any]. A dictionary containing additional parameters to spread into the request's body parameters dict
26
+
27
+ - chunk_size: int. The size, in bytes, to process each chunk of data being streamed back within the response. This equates to leveraging `chunk_size` within `requests` or `httpx`, and is only leveraged for file downloads.
28
+ """
29
+
30
+ timeout_in_seconds: NotRequired[int]
31
+ max_retries: NotRequired[int]
32
+ additional_headers: NotRequired[typing.Dict[str, typing.Any]]
33
+ additional_query_parameters: NotRequired[typing.Dict[str, typing.Any]]
34
+ additional_body_parameters: NotRequired[typing.Dict[str, typing.Any]]
35
+ chunk_size: NotRequired[int]
@@ -0,0 +1,276 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import collections
4
+ import inspect
5
+ import typing
6
+
7
+ import pydantic
8
+ import typing_extensions
9
+
10
+
11
+ class FieldMetadata:
12
+ """
13
+ Metadata class used to annotate fields to provide additional information.
14
+
15
+ Example:
16
+ class MyDict(TypedDict):
17
+ field: typing.Annotated[str, FieldMetadata(alias="field_name")]
18
+
19
+ Will serialize: `{"field": "value"}`
20
+ To: `{"field_name": "value"}`
21
+ """
22
+
23
+ alias: str
24
+
25
+ def __init__(self, *, alias: str) -> None:
26
+ self.alias = alias
27
+
28
+
29
+ def convert_and_respect_annotation_metadata(
30
+ *,
31
+ object_: typing.Any,
32
+ annotation: typing.Any,
33
+ inner_type: typing.Optional[typing.Any] = None,
34
+ direction: typing.Literal["read", "write"],
35
+ ) -> typing.Any:
36
+ """
37
+ Respect the metadata annotations on a field, such as aliasing. This function effectively
38
+ manipulates the dict-form of an object to respect the metadata annotations. This is primarily used for
39
+ TypedDicts, which cannot support aliasing out of the box, and can be extended for additional
40
+ utilities, such as defaults.
41
+
42
+ Parameters
43
+ ----------
44
+ object_ : typing.Any
45
+
46
+ annotation : type
47
+ The type we're looking to apply typing annotations from
48
+
49
+ inner_type : typing.Optional[type]
50
+
51
+ Returns
52
+ -------
53
+ typing.Any
54
+ """
55
+
56
+ if object_ is None:
57
+ return None
58
+ if inner_type is None:
59
+ inner_type = annotation
60
+
61
+ clean_type = _remove_annotations(inner_type)
62
+ # Pydantic models
63
+ if (
64
+ inspect.isclass(clean_type)
65
+ and issubclass(clean_type, pydantic.BaseModel)
66
+ and isinstance(object_, typing.Mapping)
67
+ ):
68
+ return _convert_mapping(object_, clean_type, direction)
69
+ # TypedDicts
70
+ if typing_extensions.is_typeddict(clean_type) and isinstance(object_, typing.Mapping):
71
+ return _convert_mapping(object_, clean_type, direction)
72
+
73
+ if (
74
+ typing_extensions.get_origin(clean_type) == typing.Dict
75
+ or typing_extensions.get_origin(clean_type) == dict
76
+ or clean_type == typing.Dict
77
+ ) and isinstance(object_, typing.Dict):
78
+ key_type = typing_extensions.get_args(clean_type)[0]
79
+ value_type = typing_extensions.get_args(clean_type)[1]
80
+
81
+ return {
82
+ key: convert_and_respect_annotation_metadata(
83
+ object_=value,
84
+ annotation=annotation,
85
+ inner_type=value_type,
86
+ direction=direction,
87
+ )
88
+ for key, value in object_.items()
89
+ }
90
+
91
+ # If you're iterating on a string, do not bother to coerce it to a sequence.
92
+ if not isinstance(object_, str):
93
+ if (
94
+ typing_extensions.get_origin(clean_type) == typing.Set
95
+ or typing_extensions.get_origin(clean_type) == set
96
+ or clean_type == typing.Set
97
+ ) and isinstance(object_, typing.Set):
98
+ inner_type = typing_extensions.get_args(clean_type)[0]
99
+ return {
100
+ convert_and_respect_annotation_metadata(
101
+ object_=item,
102
+ annotation=annotation,
103
+ inner_type=inner_type,
104
+ direction=direction,
105
+ )
106
+ for item in object_
107
+ }
108
+ elif (
109
+ (
110
+ typing_extensions.get_origin(clean_type) == typing.List
111
+ or typing_extensions.get_origin(clean_type) == list
112
+ or clean_type == typing.List
113
+ )
114
+ and isinstance(object_, typing.List)
115
+ ) or (
116
+ (
117
+ typing_extensions.get_origin(clean_type) == typing.Sequence
118
+ or typing_extensions.get_origin(clean_type) == collections.abc.Sequence
119
+ or clean_type == typing.Sequence
120
+ )
121
+ and isinstance(object_, typing.Sequence)
122
+ ):
123
+ inner_type = typing_extensions.get_args(clean_type)[0]
124
+ return [
125
+ convert_and_respect_annotation_metadata(
126
+ object_=item,
127
+ annotation=annotation,
128
+ inner_type=inner_type,
129
+ direction=direction,
130
+ )
131
+ for item in object_
132
+ ]
133
+
134
+ if typing_extensions.get_origin(clean_type) == typing.Union:
135
+ # We should be able to ~relatively~ safely try to convert keys against all
136
+ # member types in the union, the edge case here is if one member aliases a field
137
+ # of the same name to a different name from another member
138
+ # Or if another member aliases a field of the same name that another member does not.
139
+ for member in typing_extensions.get_args(clean_type):
140
+ object_ = convert_and_respect_annotation_metadata(
141
+ object_=object_,
142
+ annotation=annotation,
143
+ inner_type=member,
144
+ direction=direction,
145
+ )
146
+ return object_
147
+
148
+ annotated_type = _get_annotation(annotation)
149
+ if annotated_type is None:
150
+ return object_
151
+
152
+ # If the object is not a TypedDict, a Union, or other container (list, set, sequence, etc.)
153
+ # Then we can safely call it on the recursive conversion.
154
+ return object_
155
+
156
+
157
+ def _convert_mapping(
158
+ object_: typing.Mapping[str, object],
159
+ expected_type: typing.Any,
160
+ direction: typing.Literal["read", "write"],
161
+ ) -> typing.Mapping[str, object]:
162
+ converted_object: typing.Dict[str, object] = {}
163
+ try:
164
+ annotations = typing_extensions.get_type_hints(expected_type, include_extras=True)
165
+ except NameError:
166
+ # The TypedDict contains a circular reference, so
167
+ # we use the __annotations__ attribute directly.
168
+ annotations = getattr(expected_type, "__annotations__", {})
169
+ aliases_to_field_names = _get_alias_to_field_name(annotations)
170
+ for key, value in object_.items():
171
+ if direction == "read" and key in aliases_to_field_names:
172
+ dealiased_key = aliases_to_field_names.get(key)
173
+ if dealiased_key is not None:
174
+ type_ = annotations.get(dealiased_key)
175
+ else:
176
+ type_ = annotations.get(key)
177
+ # Note you can't get the annotation by the field name if you're in read mode, so you must check the aliases map
178
+ #
179
+ # So this is effectively saying if we're in write mode, and we don't have a type, or if we're in read mode and we don't have an alias
180
+ # then we can just pass the value through as is
181
+ if type_ is None:
182
+ converted_object[key] = value
183
+ elif direction == "read" and key not in aliases_to_field_names:
184
+ converted_object[key] = convert_and_respect_annotation_metadata(
185
+ object_=value, annotation=type_, direction=direction
186
+ )
187
+ else:
188
+ converted_object[_alias_key(key, type_, direction, aliases_to_field_names)] = (
189
+ convert_and_respect_annotation_metadata(object_=value, annotation=type_, direction=direction)
190
+ )
191
+ return converted_object
192
+
193
+
194
+ def _get_annotation(type_: typing.Any) -> typing.Optional[typing.Any]:
195
+ maybe_annotated_type = typing_extensions.get_origin(type_)
196
+ if maybe_annotated_type is None:
197
+ return None
198
+
199
+ if maybe_annotated_type == typing_extensions.NotRequired:
200
+ type_ = typing_extensions.get_args(type_)[0]
201
+ maybe_annotated_type = typing_extensions.get_origin(type_)
202
+
203
+ if maybe_annotated_type == typing_extensions.Annotated:
204
+ return type_
205
+
206
+ return None
207
+
208
+
209
+ def _remove_annotations(type_: typing.Any) -> typing.Any:
210
+ maybe_annotated_type = typing_extensions.get_origin(type_)
211
+ if maybe_annotated_type is None:
212
+ return type_
213
+
214
+ if maybe_annotated_type == typing_extensions.NotRequired:
215
+ return _remove_annotations(typing_extensions.get_args(type_)[0])
216
+
217
+ if maybe_annotated_type == typing_extensions.Annotated:
218
+ return _remove_annotations(typing_extensions.get_args(type_)[0])
219
+
220
+ return type_
221
+
222
+
223
+ def get_alias_to_field_mapping(type_: typing.Any) -> typing.Dict[str, str]:
224
+ annotations = typing_extensions.get_type_hints(type_, include_extras=True)
225
+ return _get_alias_to_field_name(annotations)
226
+
227
+
228
+ def get_field_to_alias_mapping(type_: typing.Any) -> typing.Dict[str, str]:
229
+ annotations = typing_extensions.get_type_hints(type_, include_extras=True)
230
+ return _get_field_to_alias_name(annotations)
231
+
232
+
233
+ def _get_alias_to_field_name(
234
+ field_to_hint: typing.Dict[str, typing.Any],
235
+ ) -> typing.Dict[str, str]:
236
+ aliases = {}
237
+ for field, hint in field_to_hint.items():
238
+ maybe_alias = _get_alias_from_type(hint)
239
+ if maybe_alias is not None:
240
+ aliases[maybe_alias] = field
241
+ return aliases
242
+
243
+
244
+ def _get_field_to_alias_name(
245
+ field_to_hint: typing.Dict[str, typing.Any],
246
+ ) -> typing.Dict[str, str]:
247
+ aliases = {}
248
+ for field, hint in field_to_hint.items():
249
+ maybe_alias = _get_alias_from_type(hint)
250
+ if maybe_alias is not None:
251
+ aliases[field] = maybe_alias
252
+ return aliases
253
+
254
+
255
+ def _get_alias_from_type(type_: typing.Any) -> typing.Optional[str]:
256
+ maybe_annotated_type = _get_annotation(type_)
257
+
258
+ if maybe_annotated_type is not None:
259
+ # The actual annotations are 1 onward, the first is the annotated type
260
+ annotations = typing_extensions.get_args(maybe_annotated_type)[1:]
261
+
262
+ for annotation in annotations:
263
+ if isinstance(annotation, FieldMetadata) and annotation.alias is not None:
264
+ return annotation.alias
265
+ return None
266
+
267
+
268
+ def _alias_key(
269
+ key: str,
270
+ type_: typing.Any,
271
+ direction: typing.Literal["read", "write"],
272
+ aliases_to_field_names: typing.Dict[str, str],
273
+ ) -> str:
274
+ if direction == "read":
275
+ return aliases_to_field_names.get(key, key)
276
+ return _get_alias_from_type(type_=type_) or key
sync/environment.py ADDED
@@ -0,0 +1,7 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+
3
+ import enum
4
+
5
+
6
+ class SyncEnvironment(enum.Enum):
7
+ DEFAULT = "https://api.sync.so"
@@ -0,0 +1,2 @@
1
+ # This file was auto-generated by Fern from our API Definition.
2
+