chunkify-analytics-sdk 0.9.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 (179) hide show
  1. chunkify_analytics/__init__.py +102 -0
  2. chunkify_analytics/_base_client.py +2153 -0
  3. chunkify_analytics/_client.py +1262 -0
  4. chunkify_analytics/_compat.py +226 -0
  5. chunkify_analytics/_constants.py +14 -0
  6. chunkify_analytics/_exceptions.py +108 -0
  7. chunkify_analytics/_files.py +173 -0
  8. chunkify_analytics/_models.py +964 -0
  9. chunkify_analytics/_qs.py +149 -0
  10. chunkify_analytics/_resource.py +43 -0
  11. chunkify_analytics/_response.py +835 -0
  12. chunkify_analytics/_streaming.py +338 -0
  13. chunkify_analytics/_types.py +274 -0
  14. chunkify_analytics/_utils/__init__.py +64 -0
  15. chunkify_analytics/_utils/_compat.py +45 -0
  16. chunkify_analytics/_utils/_datetime_parse.py +136 -0
  17. chunkify_analytics/_utils/_json.py +35 -0
  18. chunkify_analytics/_utils/_logs.py +25 -0
  19. chunkify_analytics/_utils/_path.py +127 -0
  20. chunkify_analytics/_utils/_proxy.py +65 -0
  21. chunkify_analytics/_utils/_reflection.py +42 -0
  22. chunkify_analytics/_utils/_resources_proxy.py +24 -0
  23. chunkify_analytics/_utils/_streams.py +12 -0
  24. chunkify_analytics/_utils/_sync.py +58 -0
  25. chunkify_analytics/_utils/_transform.py +457 -0
  26. chunkify_analytics/_utils/_typing.py +156 -0
  27. chunkify_analytics/_utils/_utils.py +433 -0
  28. chunkify_analytics/_version.py +4 -0
  29. chunkify_analytics/lib/.keep +4 -0
  30. chunkify_analytics/pagination.py +221 -0
  31. chunkify_analytics/py.typed +0 -0
  32. chunkify_analytics/resources/__init__.py +243 -0
  33. chunkify_analytics/resources/admin/__init__.py +33 -0
  34. chunkify_analytics/resources/admin/admin.py +253 -0
  35. chunkify_analytics/resources/admin/keys.py +283 -0
  36. chunkify_analytics/resources/dimensions.py +436 -0
  37. chunkify_analytics/resources/engagement.py +479 -0
  38. chunkify_analytics/resources/errors.py +400 -0
  39. chunkify_analytics/resources/events.py +562 -0
  40. chunkify_analytics/resources/exports.py +584 -0
  41. chunkify_analytics/resources/health.py +159 -0
  42. chunkify_analytics/resources/playback_rates.py +391 -0
  43. chunkify_analytics/resources/project/__init__.py +33 -0
  44. chunkify_analytics/resources/project/keys.py +379 -0
  45. chunkify_analytics/resources/project/project.py +322 -0
  46. chunkify_analytics/resources/quality.py +471 -0
  47. chunkify_analytics/resources/renditions.py +391 -0
  48. chunkify_analytics/resources/retention.py +377 -0
  49. chunkify_analytics/resources/subtitles.py +389 -0
  50. chunkify_analytics/resources/summary.py +469 -0
  51. chunkify_analytics/resources/timeseries.py +399 -0
  52. chunkify_analytics/resources/videos.py +424 -0
  53. chunkify_analytics/resources/views.py +579 -0
  54. chunkify_analytics/types/__init__.py +145 -0
  55. chunkify_analytics/types/admin/__init__.py +3 -0
  56. chunkify_analytics/types/admin_create_project_params.py +25 -0
  57. chunkify_analytics/types/analytics_event.py +32 -0
  58. chunkify_analytics/types/analytics_event_param.py +30 -0
  59. chunkify_analytics/types/created_project.py +37 -0
  60. chunkify_analytics/types/created_project_key.py +34 -0
  61. chunkify_analytics/types/deleted_project.py +18 -0
  62. chunkify_analytics/types/dimension_list_values_params.py +124 -0
  63. chunkify_analytics/types/dimension_values.py +42 -0
  64. chunkify_analytics/types/engagement.py +60 -0
  65. chunkify_analytics/types/engagement_breakdown_page.py +44 -0
  66. chunkify_analytics/types/engagement_response.py +11 -0
  67. chunkify_analytics/types/engagement_retrieve_params.py +158 -0
  68. chunkify_analytics/types/engagement_timeseries.py +28 -0
  69. chunkify_analytics/types/engagement_timeseries_bucket.py +63 -0
  70. chunkify_analytics/types/error_group.py +17 -0
  71. chunkify_analytics/types/error_list_params.py +124 -0
  72. chunkify_analytics/types/error_page.py +14 -0
  73. chunkify_analytics/types/event_ingest_params.py +19 -0
  74. chunkify_analytics/types/event_ingest_response.py +11 -0
  75. chunkify_analytics/types/event_list_params.py +146 -0
  76. chunkify_analytics/types/event_page.py +18 -0
  77. chunkify_analytics/types/export.py +18 -0
  78. chunkify_analytics/types/export_columns.py +12 -0
  79. chunkify_analytics/types/export_create_params.py +40 -0
  80. chunkify_analytics/types/export_download_response.py +7 -0
  81. chunkify_analytics/types/export_list_columns_params.py +69 -0
  82. chunkify_analytics/types/export_query_param.py +141 -0
  83. chunkify_analytics/types/health.py +11 -0
  84. chunkify_analytics/types/metrics.py +13 -0
  85. chunkify_analytics/types/metrics_breakdown_page.py +40 -0
  86. chunkify_analytics/types/metrics_response.py +11 -0
  87. chunkify_analytics/types/native_created.py +13 -0
  88. chunkify_analytics/types/native_duplicate.py +13 -0
  89. chunkify_analytics/types/playback_error.py +180 -0
  90. chunkify_analytics/types/playback_error_param.py +182 -0
  91. chunkify_analytics/types/playback_rate_changed.py +150 -0
  92. chunkify_analytics/types/playback_rate_changed_param.py +152 -0
  93. chunkify_analytics/types/playback_rate_metric.py +21 -0
  94. chunkify_analytics/types/playback_rate_report.py +31 -0
  95. chunkify_analytics/types/playback_rate_retrieve_params.py +117 -0
  96. chunkify_analytics/types/playback_state_changed.py +150 -0
  97. chunkify_analytics/types/playback_state_changed_param.py +156 -0
  98. chunkify_analytics/types/project/__init__.py +6 -0
  99. chunkify_analytics/types/project/key_create_params.py +21 -0
  100. chunkify_analytics/types/project/project.py +35 -0
  101. chunkify_analytics/types/project_key.py +21 -0
  102. chunkify_analytics/types/project_keys.py +14 -0
  103. chunkify_analytics/types/project_update_params.py +25 -0
  104. chunkify_analytics/types/quality.py +117 -0
  105. chunkify_analytics/types/quality_breakdown_page.py +44 -0
  106. chunkify_analytics/types/quality_response.py +11 -0
  107. chunkify_analytics/types/quality_retrieve_params.py +158 -0
  108. chunkify_analytics/types/quality_timeseries.py +28 -0
  109. chunkify_analytics/types/quality_timeseries_bucket.py +120 -0
  110. chunkify_analytics/types/rendition_changed.py +156 -0
  111. chunkify_analytics/types/rendition_changed_param.py +158 -0
  112. chunkify_analytics/types/rendition_metric.py +40 -0
  113. chunkify_analytics/types/rendition_report.py +43 -0
  114. chunkify_analytics/types/rendition_retrieve_params.py +117 -0
  115. chunkify_analytics/types/retention_bucket.py +22 -0
  116. chunkify_analytics/types/retention_report.py +33 -0
  117. chunkify_analytics/types/retention_retrieve_params.py +110 -0
  118. chunkify_analytics/types/rotated_project_key.py +29 -0
  119. chunkify_analytics/types/seek_completed.py +166 -0
  120. chunkify_analytics/types/seek_completed_param.py +168 -0
  121. chunkify_analytics/types/shared/__init__.py +24 -0
  122. chunkify_analytics/types/shared/browser_context.py +62 -0
  123. chunkify_analytics/types/shared/custom_dimensions.py +8 -0
  124. chunkify_analytics/types/shared/event_context.py +161 -0
  125. chunkify_analytics/types/shared/event_envelope.py +152 -0
  126. chunkify_analytics/types/shared/metric_count_ratio.py +18 -0
  127. chunkify_analytics/types/shared/otlp_any_value.py +56 -0
  128. chunkify_analytics/types/shared/otlp_attribute.py +24 -0
  129. chunkify_analytics/types/shared/otlp_attribute_value.py +136 -0
  130. chunkify_analytics/types/shared/otlp_context_attribute.py +22 -0
  131. chunkify_analytics/types/shared/otlp_log_record.py +48 -0
  132. chunkify_analytics/types/shared/otlp_resource.py +20 -0
  133. chunkify_analytics/types/shared/otlp_scope.py +24 -0
  134. chunkify_analytics/types/shared/playback_rate_playing_time.py +12 -0
  135. chunkify_analytics/types/shared/playback_score.py +28 -0
  136. chunkify_analytics/types/shared/played_range.py +13 -0
  137. chunkify_analytics/types/shared/progress_reached.py +39 -0
  138. chunkify_analytics/types/shared/rendition_playing_time.py +21 -0
  139. chunkify_analytics/types/shared/startup_outcomes.py +39 -0
  140. chunkify_analytics/types/shared/stored_otlp_context.py +50 -0
  141. chunkify_analytics/types/shared/subtitle_playing_time.py +14 -0
  142. chunkify_analytics/types/shared/view_metrics.py +100 -0
  143. chunkify_analytics/types/shared/watch_time_distribution.py +41 -0
  144. chunkify_analytics/types/shared_params/__init__.py +8 -0
  145. chunkify_analytics/types/shared_params/browser_context.py +62 -0
  146. chunkify_analytics/types/shared_params/custom_dimensions.py +10 -0
  147. chunkify_analytics/types/shared_params/playback_rate_playing_time.py +14 -0
  148. chunkify_analytics/types/shared_params/played_range.py +15 -0
  149. chunkify_analytics/types/shared_params/rendition_playing_time.py +22 -0
  150. chunkify_analytics/types/shared_params/subtitle_playing_time.py +15 -0
  151. chunkify_analytics/types/stored_event.py +44 -0
  152. chunkify_analytics/types/subtitle_changed.py +150 -0
  153. chunkify_analytics/types/subtitle_changed_param.py +152 -0
  154. chunkify_analytics/types/subtitle_metric.py +26 -0
  155. chunkify_analytics/types/subtitle_report.py +31 -0
  156. chunkify_analytics/types/subtitle_retrieve_params.py +117 -0
  157. chunkify_analytics/types/summary_retrieve_params.py +158 -0
  158. chunkify_analytics/types/time_bucket.py +22 -0
  159. chunkify_analytics/types/timeseries.py +28 -0
  160. chunkify_analytics/types/timeseries_response.py +12 -0
  161. chunkify_analytics/types/timesery_retrieve_params.py +115 -0
  162. chunkify_analytics/types/video_list_params.py +140 -0
  163. chunkify_analytics/types/video_metrics.py +23 -0
  164. chunkify_analytics/types/video_page.py +14 -0
  165. chunkify_analytics/types/view.py +43 -0
  166. chunkify_analytics/types/view_detail.py +21 -0
  167. chunkify_analytics/types/view_ended.py +180 -0
  168. chunkify_analytics/types/view_ended_param.py +182 -0
  169. chunkify_analytics/types/view_list_params.py +152 -0
  170. chunkify_analytics/types/view_page.py +14 -0
  171. chunkify_analytics/types/view_retrieve_params.py +23 -0
  172. chunkify_analytics/types/view_snapshot.py +180 -0
  173. chunkify_analytics/types/view_snapshot_param.py +182 -0
  174. chunkify_analytics/types/view_started.py +192 -0
  175. chunkify_analytics/types/view_started_param.py +194 -0
  176. chunkify_analytics_sdk-0.9.0.dist-info/METADATA +487 -0
  177. chunkify_analytics_sdk-0.9.0.dist-info/RECORD +179 -0
  178. chunkify_analytics_sdk-0.9.0.dist-info/WHEEL +4 -0
  179. chunkify_analytics_sdk-0.9.0.dist-info/licenses/LICENSE +201 -0
@@ -0,0 +1,226 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING, Any, Union, Generic, TypeVar, Callable, cast, overload
4
+ from datetime import date, datetime
5
+ from typing_extensions import Self, Literal, TypedDict
6
+
7
+ import pydantic
8
+ from pydantic.fields import FieldInfo
9
+
10
+ from ._types import IncEx, StrBytesIntFloat
11
+
12
+ _T = TypeVar("_T")
13
+ _ModelT = TypeVar("_ModelT", bound=pydantic.BaseModel)
14
+
15
+ # --------------- Pydantic v2, v3 compatibility ---------------
16
+
17
+ # Pyright incorrectly reports some of our functions as overriding a method when they don't
18
+ # pyright: reportIncompatibleMethodOverride=false
19
+
20
+ PYDANTIC_V1 = pydantic.VERSION.startswith("1.")
21
+
22
+ if TYPE_CHECKING:
23
+
24
+ def parse_date(value: date | StrBytesIntFloat) -> date: # noqa: ARG001
25
+ ...
26
+
27
+ def parse_datetime(value: Union[datetime, StrBytesIntFloat]) -> datetime: # noqa: ARG001
28
+ ...
29
+
30
+ def get_args(t: type[Any]) -> tuple[Any, ...]: # noqa: ARG001
31
+ ...
32
+
33
+ def is_union(tp: type[Any] | None) -> bool: # noqa: ARG001
34
+ ...
35
+
36
+ def get_origin(t: type[Any]) -> type[Any] | None: # noqa: ARG001
37
+ ...
38
+
39
+ def is_literal_type(type_: type[Any]) -> bool: # noqa: ARG001
40
+ ...
41
+
42
+ def is_typeddict(type_: type[Any]) -> bool: # noqa: ARG001
43
+ ...
44
+
45
+ else:
46
+ # v1 re-exports
47
+ if PYDANTIC_V1:
48
+ from pydantic.typing import (
49
+ get_args as get_args,
50
+ is_union as is_union,
51
+ get_origin as get_origin,
52
+ is_typeddict as is_typeddict,
53
+ is_literal_type as is_literal_type,
54
+ )
55
+ from pydantic.datetime_parse import parse_date as parse_date, parse_datetime as parse_datetime
56
+ else:
57
+ from ._utils import (
58
+ get_args as get_args,
59
+ is_union as is_union,
60
+ get_origin as get_origin,
61
+ parse_date as parse_date,
62
+ is_typeddict as is_typeddict,
63
+ parse_datetime as parse_datetime,
64
+ is_literal_type as is_literal_type,
65
+ )
66
+
67
+
68
+ # refactored config
69
+ if TYPE_CHECKING:
70
+ from pydantic import ConfigDict as ConfigDict
71
+ else:
72
+ if PYDANTIC_V1:
73
+ # TODO: provide an error message here?
74
+ ConfigDict = None
75
+ else:
76
+ from pydantic import ConfigDict as ConfigDict
77
+
78
+
79
+ # renamed methods / properties
80
+ def parse_obj(model: type[_ModelT], value: object) -> _ModelT:
81
+ if PYDANTIC_V1:
82
+ return cast(_ModelT, model.parse_obj(value)) # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
83
+ else:
84
+ return model.model_validate(value)
85
+
86
+
87
+ def field_is_required(field: FieldInfo) -> bool:
88
+ if PYDANTIC_V1:
89
+ return field.required # type: ignore
90
+ return field.is_required()
91
+
92
+
93
+ def field_get_default(field: FieldInfo) -> Any:
94
+ value = field.get_default()
95
+ if PYDANTIC_V1:
96
+ return value
97
+ from pydantic_core import PydanticUndefined
98
+
99
+ if value == PydanticUndefined:
100
+ return None
101
+ return value
102
+
103
+
104
+ def field_outer_type(field: FieldInfo) -> Any:
105
+ if PYDANTIC_V1:
106
+ return field.outer_type_ # type: ignore
107
+ return field.annotation
108
+
109
+
110
+ def get_model_config(model: type[pydantic.BaseModel]) -> Any:
111
+ if PYDANTIC_V1:
112
+ return model.__config__ # type: ignore
113
+ return model.model_config
114
+
115
+
116
+ def get_model_fields(model: type[pydantic.BaseModel]) -> dict[str, FieldInfo]:
117
+ if PYDANTIC_V1:
118
+ return model.__fields__ # type: ignore
119
+ return model.model_fields
120
+
121
+
122
+ def model_copy(model: _ModelT, *, deep: bool = False) -> _ModelT:
123
+ if PYDANTIC_V1:
124
+ return model.copy(deep=deep) # type: ignore
125
+ return model.model_copy(deep=deep)
126
+
127
+
128
+ def model_json(model: pydantic.BaseModel, *, indent: int | None = None) -> str:
129
+ if PYDANTIC_V1:
130
+ return model.json(indent=indent) # type: ignore
131
+ return model.model_dump_json(indent=indent)
132
+
133
+
134
+ class _ModelDumpKwargs(TypedDict, total=False):
135
+ by_alias: bool
136
+
137
+
138
+ def model_dump(
139
+ model: pydantic.BaseModel,
140
+ *,
141
+ exclude: IncEx | None = None,
142
+ exclude_unset: bool = False,
143
+ exclude_defaults: bool = False,
144
+ warnings: bool = True,
145
+ mode: Literal["json", "python"] = "python",
146
+ by_alias: bool | None = None,
147
+ ) -> dict[str, Any]:
148
+ if (not PYDANTIC_V1) or hasattr(model, "model_dump"):
149
+ kwargs: _ModelDumpKwargs = {}
150
+ if by_alias is not None:
151
+ kwargs["by_alias"] = by_alias
152
+ return model.model_dump(
153
+ mode=mode,
154
+ exclude=exclude,
155
+ exclude_unset=exclude_unset,
156
+ exclude_defaults=exclude_defaults,
157
+ # warnings are not supported in Pydantic v1
158
+ warnings=True if PYDANTIC_V1 else warnings,
159
+ **kwargs,
160
+ )
161
+ return cast(
162
+ "dict[str, Any]",
163
+ model.dict( # pyright: ignore[reportDeprecated, reportUnnecessaryCast]
164
+ exclude=exclude, exclude_unset=exclude_unset, exclude_defaults=exclude_defaults, by_alias=bool(by_alias)
165
+ ),
166
+ )
167
+
168
+
169
+ def model_parse(model: type[_ModelT], data: Any) -> _ModelT:
170
+ if PYDANTIC_V1:
171
+ return model.parse_obj(data) # pyright: ignore[reportDeprecated]
172
+ return model.model_validate(data)
173
+
174
+
175
+ # generic models
176
+ if TYPE_CHECKING:
177
+
178
+ class GenericModel(pydantic.BaseModel): ...
179
+
180
+ else:
181
+ if PYDANTIC_V1:
182
+ import pydantic.generics
183
+
184
+ class GenericModel(pydantic.generics.GenericModel, pydantic.BaseModel): ...
185
+ else:
186
+ # there no longer needs to be a distinction in v2 but
187
+ # we still have to create our own subclass to avoid
188
+ # inconsistent MRO ordering errors
189
+ class GenericModel(pydantic.BaseModel): ...
190
+
191
+
192
+ # cached properties
193
+ if TYPE_CHECKING:
194
+ cached_property = property
195
+
196
+ # we define a separate type (copied from typeshed)
197
+ # that represents that `cached_property` is `set`able
198
+ # at runtime, which differs from `@property`.
199
+ #
200
+ # this is a separate type as editors likely special case
201
+ # `@property` and we don't want to cause issues just to have
202
+ # more helpful internal types.
203
+
204
+ class typed_cached_property(Generic[_T]):
205
+ func: Callable[[Any], _T]
206
+ attrname: str | None
207
+
208
+ def __init__(self, func: Callable[[Any], _T]) -> None: ...
209
+
210
+ @overload
211
+ def __get__(self, instance: None, owner: type[Any] | None = None) -> Self: ...
212
+
213
+ @overload
214
+ def __get__(self, instance: object, owner: type[Any] | None = None) -> _T: ...
215
+
216
+ def __get__(self, instance: object, owner: type[Any] | None = None) -> _T | Self:
217
+ raise NotImplementedError()
218
+
219
+ def __set_name__(self, owner: type[Any], name: str) -> None: ...
220
+
221
+ # __set__ is not defined at runtime, but @cached_property is designed to be settable
222
+ def __set__(self, instance: object, value: _T) -> None: ...
223
+ else:
224
+ from functools import cached_property as cached_property
225
+
226
+ typed_cached_property = cached_property
@@ -0,0 +1,14 @@
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ import httpx
4
+
5
+ RAW_RESPONSE_HEADER = "X-Stainless-Raw-Response"
6
+ OVERRIDE_CAST_TO_HEADER = "____stainless_override_cast_to"
7
+
8
+ # default timeout is 1 minute
9
+ DEFAULT_TIMEOUT = httpx.Timeout(timeout=60, connect=5.0)
10
+ DEFAULT_MAX_RETRIES = 2
11
+ DEFAULT_CONNECTION_LIMITS = httpx.Limits(max_connections=100, max_keepalive_connections=20)
12
+
13
+ INITIAL_RETRY_DELAY = 0.5
14
+ MAX_RETRY_DELAY = 8.0
@@ -0,0 +1,108 @@
1
+ # File generated from our OpenAPI spec by Stainless. See CONTRIBUTING.md for details.
2
+
3
+ from __future__ import annotations
4
+
5
+ from typing_extensions import Literal
6
+
7
+ import httpx
8
+
9
+ __all__ = [
10
+ "BadRequestError",
11
+ "AuthenticationError",
12
+ "PermissionDeniedError",
13
+ "NotFoundError",
14
+ "ConflictError",
15
+ "UnprocessableEntityError",
16
+ "RateLimitError",
17
+ "InternalServerError",
18
+ ]
19
+
20
+
21
+ class ChunkifyAnalyticsError(Exception):
22
+ pass
23
+
24
+
25
+ class APIError(ChunkifyAnalyticsError):
26
+ message: str
27
+ request: httpx.Request
28
+
29
+ body: object | None
30
+ """The API response body.
31
+
32
+ If the API responded with a valid JSON structure then this property will be the
33
+ decoded result.
34
+
35
+ If it isn't a valid JSON structure then this will be the raw response.
36
+
37
+ If there was no response associated with this error then it will be `None`.
38
+ """
39
+
40
+ def __init__(self, message: str, request: httpx.Request, *, body: object | None) -> None: # noqa: ARG002
41
+ super().__init__(message)
42
+ self.request = request
43
+ self.message = message
44
+ self.body = body
45
+
46
+
47
+ class APIResponseValidationError(APIError):
48
+ response: httpx.Response
49
+ status_code: int
50
+
51
+ def __init__(self, response: httpx.Response, body: object | None, *, message: str | None = None) -> None:
52
+ super().__init__(message or "Data returned by API invalid for expected schema.", response.request, body=body)
53
+ self.response = response
54
+ self.status_code = response.status_code
55
+
56
+
57
+ class APIStatusError(APIError):
58
+ """Raised when an API response has a status code of 4xx or 5xx."""
59
+
60
+ response: httpx.Response
61
+ status_code: int
62
+
63
+ def __init__(self, message: str, *, response: httpx.Response, body: object | None) -> None:
64
+ super().__init__(message, response.request, body=body)
65
+ self.response = response
66
+ self.status_code = response.status_code
67
+
68
+
69
+ class APIConnectionError(APIError):
70
+ def __init__(self, *, message: str = "Connection error.", request: httpx.Request) -> None:
71
+ super().__init__(message, request, body=None)
72
+
73
+
74
+ class APITimeoutError(APIConnectionError):
75
+ def __init__(self, request: httpx.Request) -> None:
76
+ super().__init__(message="Request timed out.", request=request)
77
+
78
+
79
+ class BadRequestError(APIStatusError):
80
+ status_code: Literal[400] = 400 # pyright: ignore[reportIncompatibleVariableOverride]
81
+
82
+
83
+ class AuthenticationError(APIStatusError):
84
+ status_code: Literal[401] = 401 # pyright: ignore[reportIncompatibleVariableOverride]
85
+
86
+
87
+ class PermissionDeniedError(APIStatusError):
88
+ status_code: Literal[403] = 403 # pyright: ignore[reportIncompatibleVariableOverride]
89
+
90
+
91
+ class NotFoundError(APIStatusError):
92
+ status_code: Literal[404] = 404 # pyright: ignore[reportIncompatibleVariableOverride]
93
+
94
+
95
+ class ConflictError(APIStatusError):
96
+ status_code: Literal[409] = 409 # pyright: ignore[reportIncompatibleVariableOverride]
97
+
98
+
99
+ class UnprocessableEntityError(APIStatusError):
100
+ status_code: Literal[422] = 422 # pyright: ignore[reportIncompatibleVariableOverride]
101
+
102
+
103
+ class RateLimitError(APIStatusError):
104
+ status_code: Literal[429] = 429 # pyright: ignore[reportIncompatibleVariableOverride]
105
+
106
+
107
+ class InternalServerError(APIStatusError):
108
+ pass
@@ -0,0 +1,173 @@
1
+ from __future__ import annotations
2
+
3
+ import io
4
+ import os
5
+ import pathlib
6
+ from typing import Sequence, cast, overload
7
+ from typing_extensions import TypeVar, TypeGuard
8
+
9
+ import anyio
10
+
11
+ from ._types import (
12
+ FileTypes,
13
+ FileContent,
14
+ RequestFiles,
15
+ HttpxFileTypes,
16
+ Base64FileInput,
17
+ HttpxFileContent,
18
+ HttpxRequestFiles,
19
+ )
20
+ from ._utils import is_list, is_mapping, is_tuple_t, is_mapping_t, is_sequence_t
21
+
22
+ _T = TypeVar("_T")
23
+
24
+
25
+ def is_base64_file_input(obj: object) -> TypeGuard[Base64FileInput]:
26
+ return isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike)
27
+
28
+
29
+ def is_file_content(obj: object) -> TypeGuard[FileContent]:
30
+ return (
31
+ isinstance(obj, bytes) or isinstance(obj, tuple) or isinstance(obj, io.IOBase) or isinstance(obj, os.PathLike)
32
+ )
33
+
34
+
35
+ def assert_is_file_content(obj: object, *, key: str | None = None) -> None:
36
+ if not is_file_content(obj):
37
+ prefix = f"Expected entry at `{key}`" if key is not None else f"Expected file input `{obj!r}`"
38
+ raise RuntimeError(
39
+ f"{prefix} to be bytes, an io.IOBase instance, PathLike or a tuple but received {type(obj)} instead."
40
+ ) from None
41
+
42
+
43
+ @overload
44
+ def to_httpx_files(files: None) -> None: ...
45
+
46
+
47
+ @overload
48
+ def to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ...
49
+
50
+
51
+ def to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None:
52
+ if files is None:
53
+ return None
54
+
55
+ if is_mapping_t(files):
56
+ files = {key: _transform_file(file) for key, file in files.items()}
57
+ elif is_sequence_t(files):
58
+ files = [(key, _transform_file(file)) for key, file in files]
59
+ else:
60
+ raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence")
61
+
62
+ return files
63
+
64
+
65
+ def _transform_file(file: FileTypes) -> HttpxFileTypes:
66
+ if is_file_content(file):
67
+ if isinstance(file, os.PathLike):
68
+ path = pathlib.Path(file)
69
+ return (path.name, path.read_bytes())
70
+
71
+ return file
72
+
73
+ if is_tuple_t(file):
74
+ return (file[0], read_file_content(file[1]), *file[2:])
75
+
76
+ raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
77
+
78
+
79
+ def read_file_content(file: FileContent) -> HttpxFileContent:
80
+ if isinstance(file, os.PathLike):
81
+ return pathlib.Path(file).read_bytes()
82
+ return file
83
+
84
+
85
+ @overload
86
+ async def async_to_httpx_files(files: None) -> None: ...
87
+
88
+
89
+ @overload
90
+ async def async_to_httpx_files(files: RequestFiles) -> HttpxRequestFiles: ...
91
+
92
+
93
+ async def async_to_httpx_files(files: RequestFiles | None) -> HttpxRequestFiles | None:
94
+ if files is None:
95
+ return None
96
+
97
+ if is_mapping_t(files):
98
+ files = {key: await _async_transform_file(file) for key, file in files.items()}
99
+ elif is_sequence_t(files):
100
+ files = [(key, await _async_transform_file(file)) for key, file in files]
101
+ else:
102
+ raise TypeError(f"Unexpected file type input {type(files)}, expected mapping or sequence")
103
+
104
+ return files
105
+
106
+
107
+ async def _async_transform_file(file: FileTypes) -> HttpxFileTypes:
108
+ if is_file_content(file):
109
+ if isinstance(file, os.PathLike):
110
+ path = anyio.Path(file)
111
+ return (path.name, await path.read_bytes())
112
+
113
+ return file
114
+
115
+ if is_tuple_t(file):
116
+ return (file[0], await async_read_file_content(file[1]), *file[2:])
117
+
118
+ raise TypeError(f"Expected file types input to be a FileContent type or to be a tuple")
119
+
120
+
121
+ async def async_read_file_content(file: FileContent) -> HttpxFileContent:
122
+ if isinstance(file, os.PathLike):
123
+ return await anyio.Path(file).read_bytes()
124
+
125
+ return file
126
+
127
+
128
+ def deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]]) -> _T:
129
+ """Copy only the containers along the given paths.
130
+
131
+ Used to guard against mutation by extract_files without copying the entire structure.
132
+ Only dicts and lists that lie on a path are copied; everything else
133
+ is returned by reference.
134
+
135
+ For example, given paths=[["foo", "files", "file"]] and the structure:
136
+ {
137
+ "foo": {
138
+ "bar": {"baz": {}},
139
+ "files": {"file": <content>}
140
+ }
141
+ }
142
+ The root dict, "foo", and "files" are copied (they lie on the path).
143
+ "bar" and "baz" are returned by reference (off the path).
144
+ """
145
+ return _deepcopy_with_paths(item, paths, 0)
146
+
147
+
148
+ def _deepcopy_with_paths(item: _T, paths: Sequence[Sequence[str]], index: int) -> _T:
149
+ if not paths:
150
+ return item
151
+ if is_mapping(item):
152
+ key_to_paths: dict[str, list[Sequence[str]]] = {}
153
+ for path in paths:
154
+ if index < len(path):
155
+ key_to_paths.setdefault(path[index], []).append(path)
156
+
157
+ # if no path continues through this mapping, it won't be mutated and copying it is redundant
158
+ if not key_to_paths:
159
+ return item
160
+
161
+ result = dict(item)
162
+ for key, subpaths in key_to_paths.items():
163
+ if key in result:
164
+ result[key] = _deepcopy_with_paths(result[key], subpaths, index + 1)
165
+ return cast(_T, result)
166
+ if is_list(item):
167
+ array_paths = [path for path in paths if index < len(path) and path[index] == "<array>"]
168
+
169
+ # if no path expects a list here, nothing will be mutated inside it - return by reference
170
+ if not array_paths:
171
+ return cast(_T, item)
172
+ return cast(_T, [_deepcopy_with_paths(entry, array_paths, index + 1) for entry in item])
173
+ return item