devupai 1.0.0a1__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.
@@ -0,0 +1,207 @@
1
+ """Shared parts of the API resources: the endpoint metadata, the resource base classes and the request helpers."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import re
7
+ from collections.abc import Callable, Mapping, Sequence
8
+ from dataclasses import dataclass
9
+ from typing import TYPE_CHECKING, Any, Literal, TypeVar, cast
10
+ from urllib.parse import quote, unquote
11
+
12
+ from devupai._response import APIResponse
13
+ from devupai.resources.shared import MultipartValue, contains_file_input, is_file_input
14
+
15
+ if TYPE_CHECKING:
16
+ from devupai._client import AsyncDevupAI, DevupAI, RequestOptions, RetryPolicy
17
+
18
+ __all__ = [
19
+ "Endpoint",
20
+ "SendKind",
21
+ "endpoint",
22
+ "SyncAPIResource",
23
+ "AsyncAPIResource",
24
+ "is_file_input",
25
+ "contains_file_input",
26
+ "options",
27
+ "json_body",
28
+ "encode_path_segment",
29
+ "encode_model_path",
30
+ "with_data",
31
+ "billed_post_retry",
32
+ ]
33
+
34
+ F = TypeVar("F", bound=Callable[..., Any])
35
+ T = TypeVar("T")
36
+
37
+ _ENDPOINT_ATTRIBUTE = "__devup_endpoint__"
38
+ _INVALID_PERCENT = re.compile(r"%(?![0-9A-Fa-f]{2})")
39
+ # A URL parser removes the dot segments of a path, so a whole segment "." or ".." is sent percent-encoded.
40
+ _DOT_SEGMENTS = {".": "%2E", "..": "%2E%2E"}
41
+
42
+ SendKind = Literal["json", "text", "raw", "stream"]
43
+ """How the body of an answer is read: parsed JSON, text, or left unread (a file or an event stream)."""
44
+
45
+
46
+ @dataclass(frozen=True)
47
+ class Endpoint:
48
+ """The HTTP method and path template of an API method."""
49
+
50
+ method: Literal["GET", "POST"]
51
+ """The HTTP method."""
52
+ path: str
53
+ """The path template, relative to ``base_url`` (``"/models/{model}"``), or to the host root when ``root`` is set."""
54
+ billed: bool
55
+ """Whether a successful call is billed to the account."""
56
+ root: bool = False
57
+ """Whether ``path`` is relative to the host root instead of ``base_url``."""
58
+
59
+
60
+ def endpoint(method: Literal["GET", "POST"], path: str, *, billed: bool, root: bool = False) -> Callable[[F], F]:
61
+ """Marks an API method with its :class:`Endpoint`, kept in its ``__devup_endpoint__`` attribute."""
62
+ metadata = Endpoint(method=method, path=path, billed=billed, root=root)
63
+
64
+ def mark(fn: F) -> F:
65
+ vars(fn)[_ENDPOINT_ATTRIBUTE] = metadata
66
+ return fn
67
+
68
+ return mark
69
+
70
+
71
+ def billed_post_retry() -> RetryPolicy:
72
+ """The retry policy of the billed POST methods."""
73
+ from devupai import _client
74
+
75
+ return _client.BILLED_POST_RETRY
76
+
77
+
78
+ class SyncAPIResource:
79
+ """Base class of the resources of :class:`devupai.DevupAI`."""
80
+
81
+ def __init__(self, client: DevupAI) -> None:
82
+ self._client = client
83
+
84
+ def _send(
85
+ self,
86
+ method: Literal["GET", "POST"],
87
+ path: str | None = None,
88
+ *,
89
+ url: str | None = None,
90
+ query: Mapping[str, str | None] | None = None,
91
+ body: object = None,
92
+ multipart: Sequence[tuple[str, MultipartValue]] | None = None,
93
+ auth: bool = True,
94
+ if_none_match: str | None = None,
95
+ retry: RetryPolicy | None = None,
96
+ kind: SendKind = "json",
97
+ options: RequestOptions | None = None,
98
+ ) -> APIResponse[Any]:
99
+ from devupai import _client
100
+
101
+ return _client.sync_request(
102
+ self._client,
103
+ method,
104
+ path,
105
+ url=url,
106
+ query=query,
107
+ body=body,
108
+ multipart=multipart,
109
+ auth=auth,
110
+ if_none_match=if_none_match,
111
+ retry=_client.DEFAULT_RETRY if retry is None else retry,
112
+ kind=kind,
113
+ options=options,
114
+ )
115
+
116
+
117
+ class AsyncAPIResource:
118
+ """Base class of the resources of :class:`devupai.AsyncDevupAI`."""
119
+
120
+ def __init__(self, client: AsyncDevupAI) -> None:
121
+ self._client = client
122
+
123
+ async def _send(
124
+ self,
125
+ method: Literal["GET", "POST"],
126
+ path: str | None = None,
127
+ *,
128
+ url: str | None = None,
129
+ query: Mapping[str, str | None] | None = None,
130
+ body: object = None,
131
+ multipart: Sequence[tuple[str, MultipartValue]] | None = None,
132
+ auth: bool = True,
133
+ if_none_match: str | None = None,
134
+ retry: RetryPolicy | None = None,
135
+ kind: SendKind = "json",
136
+ options: RequestOptions | None = None,
137
+ ) -> APIResponse[Any]:
138
+ from devupai import _client
139
+
140
+ return await _client.async_request(
141
+ self._client,
142
+ method,
143
+ path,
144
+ url=url,
145
+ query=query,
146
+ body=body,
147
+ multipart=multipart,
148
+ auth=auth,
149
+ if_none_match=if_none_match,
150
+ retry=_client.DEFAULT_RETRY if retry is None else retry,
151
+ kind=kind,
152
+ options=options,
153
+ )
154
+
155
+
156
+ def options(
157
+ *, timeout: float | None, max_retries: int | None, extra_headers: Mapping[str, str] | None
158
+ ) -> RequestOptions:
159
+ """The request options of one call, without the values that are not set."""
160
+ result: RequestOptions = {}
161
+ if timeout is not None:
162
+ result["timeout"] = timeout
163
+ if max_retries is not None:
164
+ result["max_retries"] = max_retries
165
+ if extra_headers is not None:
166
+ result["extra_headers"] = extra_headers
167
+ return result
168
+
169
+
170
+ def json_body(params: Mapping[str, object], extra_body: Mapping[str, object] | None) -> dict[str, object]:
171
+ """The JSON body of a call: ``params``, then ``extra_body`` merged last."""
172
+ body: dict[str, object] = dict(params)
173
+ if extra_body is not None:
174
+ body.update(extra_body)
175
+ return body
176
+
177
+
178
+ def encode_path_segment(value: str) -> str:
179
+ """Encodes ``value`` as one URL path segment, the same way as JavaScript's ``encodeURIComponent``.
180
+
181
+ A whole segment ``.`` or ``..`` is sent as ``%2E`` or ``%2E%2E``, so a URL parser does not remove it from the path.
182
+ """
183
+ encoded = quote(value, safe="!*'()")
184
+ return _DOT_SEGMENTS.get(encoded, encoded)
185
+
186
+
187
+ def encode_model_path(value: str) -> str:
188
+ """Encodes a model path as one URL path segment.
189
+
190
+ Leading slashes are removed, and a path that is already encoded is decoded first, so it is encoded exactly once
191
+ (``/`` becomes ``%2F``). A path that is not valid percent-encoded text is encoded as it is. As for
192
+ :func:`encode_path_segment`, a whole segment ``.`` or ``..`` (also given as ``%2e%2e``) is sent as ``%2E`` or
193
+ ``%2E%2E``.
194
+ """
195
+ clean = value.lstrip("/")
196
+ if _INVALID_PERCENT.search(clean):
197
+ return encode_path_segment(clean)
198
+ try:
199
+ decoded = unquote(clean, errors="strict")
200
+ except UnicodeDecodeError:
201
+ return encode_path_segment(clean)
202
+ return encode_path_segment(decoded)
203
+
204
+
205
+ def with_data(response: APIResponse[object], data: T) -> APIResponse[T]:
206
+ """A copy of ``response`` that carries ``data``."""
207
+ return cast("APIResponse[T]", dataclasses.replace(response, data=data))