flatmark 1.0.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.
flatmark/client.py ADDED
@@ -0,0 +1,268 @@
1
+ import ssl
2
+ from typing import Any, Self
3
+
4
+ import httpx
5
+ from attrs import define, evolve, field
6
+
7
+
8
+ @define
9
+ class Client:
10
+ """A class for keeping track of data related to the API
11
+
12
+ The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
13
+
14
+ ``base_url``: The base URL for the API, all requests are made to a relative path to this URL
15
+
16
+ ``cookies``: A dictionary of cookies to be sent with every request
17
+
18
+ ``headers``: A dictionary of headers to be sent with every request
19
+
20
+ ``timeout``: The maximum amount of a time a request can take. API functions will raise
21
+ httpx.TimeoutException if this is exceeded.
22
+
23
+ ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
24
+ but can be set to False for testing purposes.
25
+
26
+ ``follow_redirects``: Whether or not to follow redirects. Default value is False.
27
+
28
+ ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
29
+
30
+
31
+ Attributes:
32
+ raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
33
+ status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
34
+ argument to the constructor.
35
+ """
36
+
37
+ raise_on_unexpected_status: bool = field(default=False, kw_only=True)
38
+ _base_url: str = field(alias="base_url")
39
+ _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
40
+ _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
41
+ _timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")
42
+ _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")
43
+ _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
44
+ _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
45
+ _client: httpx.Client | None = field(default=None, init=False)
46
+ _async_client: httpx.AsyncClient | None = field(default=None, init=False)
47
+
48
+ def with_headers(self, headers: dict[str, str]) -> "Client":
49
+ """Get a new client matching this one with additional headers"""
50
+ if self._client is not None:
51
+ self._client.headers.update(headers)
52
+ if self._async_client is not None:
53
+ self._async_client.headers.update(headers)
54
+ return evolve(self, headers={**self._headers, **headers})
55
+
56
+ def with_cookies(self, cookies: dict[str, str]) -> "Client":
57
+ """Get a new client matching this one with additional cookies"""
58
+ if self._client is not None:
59
+ self._client.cookies.update(cookies)
60
+ if self._async_client is not None:
61
+ self._async_client.cookies.update(cookies)
62
+ return evolve(self, cookies={**self._cookies, **cookies})
63
+
64
+ def with_timeout(self, timeout: httpx.Timeout) -> "Client":
65
+ """Get a new client matching this one with a new timeout configuration"""
66
+ if self._client is not None:
67
+ self._client.timeout = timeout
68
+ if self._async_client is not None:
69
+ self._async_client.timeout = timeout
70
+ return evolve(self, timeout=timeout)
71
+
72
+ def set_httpx_client(self, client: httpx.Client) -> Self:
73
+ """Manually set the underlying httpx.Client
74
+
75
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
76
+ """
77
+ self._client = client
78
+ return self
79
+
80
+ def get_httpx_client(self) -> httpx.Client:
81
+ """Get the underlying httpx.Client, constructing a new one if not previously set"""
82
+ if self._client is None:
83
+ self._client = httpx.Client(
84
+ base_url=self._base_url,
85
+ cookies=self._cookies,
86
+ headers=self._headers,
87
+ timeout=self._timeout,
88
+ verify=self._verify_ssl,
89
+ follow_redirects=self._follow_redirects,
90
+ **self._httpx_args,
91
+ )
92
+ return self._client
93
+
94
+ def __enter__(self) -> Self:
95
+ """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
96
+ self.get_httpx_client().__enter__()
97
+ return self
98
+
99
+ def __exit__(self, *args: Any, **kwargs: Any) -> None:
100
+ """Exit a context manager for internal httpx.Client (see httpx docs)"""
101
+ self.get_httpx_client().__exit__(*args, **kwargs)
102
+
103
+ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> Self:
104
+ """Manually set the underlying httpx.AsyncClient
105
+
106
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
107
+ """
108
+ self._async_client = async_client
109
+ return self
110
+
111
+ def get_async_httpx_client(self) -> httpx.AsyncClient:
112
+ """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
113
+ if self._async_client is None:
114
+ self._async_client = httpx.AsyncClient(
115
+ base_url=self._base_url,
116
+ cookies=self._cookies,
117
+ headers=self._headers,
118
+ timeout=self._timeout,
119
+ verify=self._verify_ssl,
120
+ follow_redirects=self._follow_redirects,
121
+ **self._httpx_args,
122
+ )
123
+ return self._async_client
124
+
125
+ async def __aenter__(self) -> Self:
126
+ """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
127
+ await self.get_async_httpx_client().__aenter__()
128
+ return self
129
+
130
+ async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
131
+ """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
132
+ await self.get_async_httpx_client().__aexit__(*args, **kwargs)
133
+
134
+
135
+ @define
136
+ class AuthenticatedClient:
137
+ """A Client which has been authenticated for use on secured endpoints
138
+
139
+ The following are accepted as keyword arguments and will be used to construct httpx Clients internally:
140
+
141
+ ``base_url``: The base URL for the API, all requests are made to a relative path to this URL
142
+
143
+ ``cookies``: A dictionary of cookies to be sent with every request
144
+
145
+ ``headers``: A dictionary of headers to be sent with every request
146
+
147
+ ``timeout``: The maximum amount of a time a request can take. API functions will raise
148
+ httpx.TimeoutException if this is exceeded.
149
+
150
+ ``verify_ssl``: Whether or not to verify the SSL certificate of the API server. This should be True in production,
151
+ but can be set to False for testing purposes.
152
+
153
+ ``follow_redirects``: Whether or not to follow redirects. Default value is False.
154
+
155
+ ``httpx_args``: A dictionary of additional arguments to be passed to the ``httpx.Client`` and ``httpx.AsyncClient`` constructor.
156
+
157
+
158
+ Attributes:
159
+ raise_on_unexpected_status: Whether or not to raise an errors.UnexpectedStatus if the API returns a
160
+ status code that was not documented in the source OpenAPI document. Can also be provided as a keyword
161
+ argument to the constructor.
162
+ token: The token to use for authentication
163
+ prefix: The prefix to use for the Authorization header
164
+ auth_header_name: The name of the Authorization header
165
+ """
166
+
167
+ raise_on_unexpected_status: bool = field(default=False, kw_only=True)
168
+ _base_url: str = field(alias="base_url")
169
+ _cookies: dict[str, str] = field(factory=dict, kw_only=True, alias="cookies")
170
+ _headers: dict[str, str] = field(factory=dict, kw_only=True, alias="headers")
171
+ _timeout: httpx.Timeout | None = field(default=None, kw_only=True, alias="timeout")
172
+ _verify_ssl: str | bool | ssl.SSLContext = field(default=True, kw_only=True, alias="verify_ssl")
173
+ _follow_redirects: bool = field(default=False, kw_only=True, alias="follow_redirects")
174
+ _httpx_args: dict[str, Any] = field(factory=dict, kw_only=True, alias="httpx_args")
175
+ _client: httpx.Client | None = field(default=None, init=False)
176
+ _async_client: httpx.AsyncClient | None = field(default=None, init=False)
177
+
178
+ token: str
179
+ prefix: str = "Bearer"
180
+ auth_header_name: str = "Authorization"
181
+
182
+ def with_headers(self, headers: dict[str, str]) -> "AuthenticatedClient":
183
+ """Get a new client matching this one with additional headers"""
184
+ if self._client is not None:
185
+ self._client.headers.update(headers)
186
+ if self._async_client is not None:
187
+ self._async_client.headers.update(headers)
188
+ return evolve(self, headers={**self._headers, **headers})
189
+
190
+ def with_cookies(self, cookies: dict[str, str]) -> "AuthenticatedClient":
191
+ """Get a new client matching this one with additional cookies"""
192
+ if self._client is not None:
193
+ self._client.cookies.update(cookies)
194
+ if self._async_client is not None:
195
+ self._async_client.cookies.update(cookies)
196
+ return evolve(self, cookies={**self._cookies, **cookies})
197
+
198
+ def with_timeout(self, timeout: httpx.Timeout) -> "AuthenticatedClient":
199
+ """Get a new client matching this one with a new timeout configuration"""
200
+ if self._client is not None:
201
+ self._client.timeout = timeout
202
+ if self._async_client is not None:
203
+ self._async_client.timeout = timeout
204
+ return evolve(self, timeout=timeout)
205
+
206
+ def set_httpx_client(self, client: httpx.Client) -> Self:
207
+ """Manually set the underlying httpx.Client
208
+
209
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
210
+ """
211
+ self._client = client
212
+ return self
213
+
214
+ def get_httpx_client(self) -> httpx.Client:
215
+ """Get the underlying httpx.Client, constructing a new one if not previously set"""
216
+ if self._client is None:
217
+ self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
218
+ self._client = httpx.Client(
219
+ base_url=self._base_url,
220
+ cookies=self._cookies,
221
+ headers=self._headers,
222
+ timeout=self._timeout,
223
+ verify=self._verify_ssl,
224
+ follow_redirects=self._follow_redirects,
225
+ **self._httpx_args,
226
+ )
227
+ return self._client
228
+
229
+ def __enter__(self) -> Self:
230
+ """Enter a context manager for self.client—you cannot enter twice (see httpx docs)"""
231
+ self.get_httpx_client().__enter__()
232
+ return self
233
+
234
+ def __exit__(self, *args: Any, **kwargs: Any) -> None:
235
+ """Exit a context manager for internal httpx.Client (see httpx docs)"""
236
+ self.get_httpx_client().__exit__(*args, **kwargs)
237
+
238
+ def set_async_httpx_client(self, async_client: httpx.AsyncClient) -> Self:
239
+ """Manually set the underlying httpx.AsyncClient
240
+
241
+ **NOTE**: This will override any other settings on the client, including cookies, headers, and timeout.
242
+ """
243
+ self._async_client = async_client
244
+ return self
245
+
246
+ def get_async_httpx_client(self) -> httpx.AsyncClient:
247
+ """Get the underlying httpx.AsyncClient, constructing a new one if not previously set"""
248
+ if self._async_client is None:
249
+ self._headers[self.auth_header_name] = f"{self.prefix} {self.token}" if self.prefix else self.token
250
+ self._async_client = httpx.AsyncClient(
251
+ base_url=self._base_url,
252
+ cookies=self._cookies,
253
+ headers=self._headers,
254
+ timeout=self._timeout,
255
+ verify=self._verify_ssl,
256
+ follow_redirects=self._follow_redirects,
257
+ **self._httpx_args,
258
+ )
259
+ return self._async_client
260
+
261
+ async def __aenter__(self) -> Self:
262
+ """Enter a context manager for underlying httpx.AsyncClient—you cannot enter twice (see httpx docs)"""
263
+ await self.get_async_httpx_client().__aenter__()
264
+ return self
265
+
266
+ async def __aexit__(self, *args: Any, **kwargs: Any) -> None:
267
+ """Exit a context manager for underlying httpx.AsyncClient (see httpx docs)"""
268
+ await self.get_async_httpx_client().__aexit__(*args, **kwargs)
flatmark/errors.py ADDED
@@ -0,0 +1,16 @@
1
+ """Contains shared errors types that can be raised from API functions"""
2
+
3
+
4
+ class UnexpectedStatus(Exception):
5
+ """Raised by api functions when the response status an undocumented status and Client.raise_on_unexpected_status is True"""
6
+
7
+ def __init__(self, status_code: int, content: bytes):
8
+ self.status_code = status_code
9
+ self.content = content
10
+
11
+ super().__init__(
12
+ f"Unexpected status code: {status_code}\n\nResponse content:\n{content.decode(errors='ignore')}"
13
+ )
14
+
15
+
16
+ __all__ = ["UnexpectedStatus"]
@@ -0,0 +1,33 @@
1
+ """Contains all the data models used in inputs/outputs"""
2
+
3
+ from .body_convert_document import BodyConvertDocument
4
+ from .body_submit_conversion_job import BodySubmitConversionJob
5
+ from .credits_info import CreditsInfo
6
+ from .get_conversion_result_format import GetConversionResultFormat
7
+ from .job_response import JobResponse
8
+ from .job_response_page import JobResponsePage
9
+ from .job_response_result_type_0 import JobResponseResultType0
10
+ from .job_submit_response import JobSubmitResponse
11
+ from .me_response import MeResponse
12
+ from .problem import Problem
13
+ from .problem_errors_type_0_item import ProblemErrorsType0Item
14
+ from .rate_limit_info import RateLimitInfo
15
+ from .sync_convert_response import SyncConvertResponse
16
+ from .sync_convert_response_meta import SyncConvertResponseMeta
17
+
18
+ __all__ = (
19
+ "BodyConvertDocument",
20
+ "BodySubmitConversionJob",
21
+ "CreditsInfo",
22
+ "GetConversionResultFormat",
23
+ "JobResponse",
24
+ "JobResponsePage",
25
+ "JobResponseResultType0",
26
+ "JobSubmitResponse",
27
+ "MeResponse",
28
+ "Problem",
29
+ "ProblemErrorsType0Item",
30
+ "RateLimitInfo",
31
+ "SyncConvertResponse",
32
+ "SyncConvertResponseMeta",
33
+ )
@@ -0,0 +1,75 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from io import BytesIO
5
+ from typing import Any, TypeVar
6
+
7
+ from attrs import define as _attrs_define
8
+ from attrs import field as _attrs_field
9
+
10
+ from .. import types
11
+ from ..types import File
12
+
13
+ T = TypeVar("T", bound="BodyConvertDocument")
14
+
15
+
16
+ @_attrs_define
17
+ class BodyConvertDocument:
18
+ """
19
+ Attributes:
20
+ file (File): The document, sent as multipart form data with its Content-Type.
21
+ """
22
+
23
+ file: File
24
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
25
+
26
+ def to_dict(self) -> dict[str, Any]:
27
+ file = self.file.to_tuple()
28
+
29
+ field_dict: dict[str, Any] = {}
30
+ field_dict.update(self.additional_properties)
31
+ field_dict.update(
32
+ {
33
+ "file": file,
34
+ }
35
+ )
36
+
37
+ return field_dict
38
+
39
+ def to_multipart(self) -> types.RequestFiles:
40
+ files: types.RequestFiles = []
41
+
42
+ files.append(("file", self.file.to_tuple()))
43
+
44
+ for prop_name, prop in self.additional_properties.items():
45
+ files.append((prop_name, (None, str(prop).encode(), "text/plain")))
46
+
47
+ return files
48
+
49
+ @classmethod
50
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
51
+ d = dict(src_dict)
52
+ file = File(payload=BytesIO(d.pop("file")))
53
+
54
+ body_convert_document = cls(
55
+ file=file,
56
+ )
57
+
58
+ body_convert_document.additional_properties = d
59
+ return body_convert_document
60
+
61
+ @property
62
+ def additional_keys(self) -> list[str]:
63
+ return list(self.additional_properties.keys())
64
+
65
+ def __getitem__(self, key: str) -> Any:
66
+ return self.additional_properties[key]
67
+
68
+ def __setitem__(self, key: str, value: Any) -> None:
69
+ self.additional_properties[key] = value
70
+
71
+ def __delitem__(self, key: str) -> None:
72
+ del self.additional_properties[key]
73
+
74
+ def __contains__(self, key: str) -> bool:
75
+ return key in self.additional_properties
@@ -0,0 +1,102 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from io import BytesIO
5
+ from typing import Any, TypeVar, cast
6
+
7
+ from attrs import define as _attrs_define
8
+ from attrs import field as _attrs_field
9
+
10
+ from .. import types
11
+ from ..types import UNSET, File, Unset
12
+
13
+ T = TypeVar("T", bound="BodySubmitConversionJob")
14
+
15
+
16
+ @_attrs_define
17
+ class BodySubmitConversionJob:
18
+ """
19
+ Attributes:
20
+ file (File): The document, sent as multipart form data with its Content-Type.
21
+ webhook_url (None | str | Unset): Optional. A public http or https URL that receives a POST when the job
22
+ finishes.
23
+ """
24
+
25
+ file: File
26
+ webhook_url: None | str | Unset = UNSET
27
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
28
+
29
+ def to_dict(self) -> dict[str, Any]:
30
+ file = self.file.to_tuple()
31
+
32
+ webhook_url: None | str | Unset
33
+ if isinstance(self.webhook_url, Unset):
34
+ webhook_url = UNSET
35
+ else:
36
+ webhook_url = self.webhook_url
37
+
38
+ field_dict: dict[str, Any] = {}
39
+ field_dict.update(self.additional_properties)
40
+ field_dict.update(
41
+ {
42
+ "file": file,
43
+ }
44
+ )
45
+ if webhook_url is not UNSET:
46
+ field_dict["webhook_url"] = webhook_url
47
+
48
+ return field_dict
49
+
50
+ def to_multipart(self) -> types.RequestFiles:
51
+ files: types.RequestFiles = []
52
+
53
+ files.append(("file", self.file.to_tuple()))
54
+
55
+ if not isinstance(self.webhook_url, Unset):
56
+ if isinstance(self.webhook_url, str):
57
+ files.append(("webhook_url", (None, str(self.webhook_url).encode(), "text/plain")))
58
+ else:
59
+ files.append(("webhook_url", (None, str(self.webhook_url).encode(), "text/plain")))
60
+
61
+ for prop_name, prop in self.additional_properties.items():
62
+ files.append((prop_name, (None, str(prop).encode(), "text/plain")))
63
+
64
+ return files
65
+
66
+ @classmethod
67
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
68
+ d = dict(src_dict)
69
+ file = File(payload=BytesIO(d.pop("file")))
70
+
71
+ def _parse_webhook_url(data: object) -> None | str | Unset:
72
+ if data is None:
73
+ return data
74
+ if isinstance(data, Unset):
75
+ return data
76
+ return cast(None | str | Unset, data)
77
+
78
+ webhook_url = _parse_webhook_url(d.pop("webhook_url", UNSET))
79
+
80
+ body_submit_conversion_job = cls(
81
+ file=file,
82
+ webhook_url=webhook_url,
83
+ )
84
+
85
+ body_submit_conversion_job.additional_properties = d
86
+ return body_submit_conversion_job
87
+
88
+ @property
89
+ def additional_keys(self) -> list[str]:
90
+ return list(self.additional_properties.keys())
91
+
92
+ def __getitem__(self, key: str) -> Any:
93
+ return self.additional_properties[key]
94
+
95
+ def __setitem__(self, key: str, value: Any) -> None:
96
+ self.additional_properties[key] = value
97
+
98
+ def __delitem__(self, key: str) -> None:
99
+ del self.additional_properties[key]
100
+
101
+ def __contains__(self, key: str) -> bool:
102
+ return key in self.additional_properties
@@ -0,0 +1,95 @@
1
+ from __future__ import annotations
2
+
3
+ from collections.abc import Mapping
4
+ from typing import Any, TypeVar, cast
5
+
6
+ from attrs import define as _attrs_define
7
+ from attrs import field as _attrs_field
8
+
9
+ from ..types import UNSET, Unset
10
+
11
+ T = TypeVar("T", bound="CreditsInfo")
12
+
13
+
14
+ @_attrs_define
15
+ class CreditsInfo:
16
+ """Your credit balance for the current billing period. `granted` is what
17
+ your plan included, `balance` what is still unspent, and `period_end` the
18
+ date (ISO 8601) your allowance refills. Present only on plans that are
19
+ priced in credits.
20
+
21
+ Attributes:
22
+ balance (int):
23
+ granted (int):
24
+ period_end (None | str | Unset):
25
+ """
26
+
27
+ balance: int
28
+ granted: int
29
+ period_end: None | str | Unset = UNSET
30
+ additional_properties: dict[str, Any] = _attrs_field(init=False, factory=dict)
31
+
32
+ def to_dict(self) -> dict[str, Any]:
33
+ balance = self.balance
34
+
35
+ granted = self.granted
36
+
37
+ period_end: None | str | Unset
38
+ if isinstance(self.period_end, Unset):
39
+ period_end = UNSET
40
+ else:
41
+ period_end = self.period_end
42
+
43
+ field_dict: dict[str, Any] = {}
44
+ field_dict.update(self.additional_properties)
45
+ field_dict.update(
46
+ {
47
+ "balance": balance,
48
+ "granted": granted,
49
+ }
50
+ )
51
+ if period_end is not UNSET:
52
+ field_dict["period_end"] = period_end
53
+
54
+ return field_dict
55
+
56
+ @classmethod
57
+ def from_dict(cls: type[T], src_dict: Mapping[str, Any]) -> T:
58
+ d = dict(src_dict)
59
+ balance = d.pop("balance")
60
+
61
+ granted = d.pop("granted")
62
+
63
+ def _parse_period_end(data: object) -> None | str | Unset:
64
+ if data is None:
65
+ return data
66
+ if isinstance(data, Unset):
67
+ return data
68
+ return cast(None | str | Unset, data)
69
+
70
+ period_end = _parse_period_end(d.pop("period_end", UNSET))
71
+
72
+ credits_info = cls(
73
+ balance=balance,
74
+ granted=granted,
75
+ period_end=period_end,
76
+ )
77
+
78
+ credits_info.additional_properties = d
79
+ return credits_info
80
+
81
+ @property
82
+ def additional_keys(self) -> list[str]:
83
+ return list(self.additional_properties.keys())
84
+
85
+ def __getitem__(self, key: str) -> Any:
86
+ return self.additional_properties[key]
87
+
88
+ def __setitem__(self, key: str, value: Any) -> None:
89
+ self.additional_properties[key] = value
90
+
91
+ def __delitem__(self, key: str) -> None:
92
+ del self.additional_properties[key]
93
+
94
+ def __contains__(self, key: str) -> bool:
95
+ return key in self.additional_properties
@@ -0,0 +1,9 @@
1
+ from enum import StrEnum
2
+
3
+
4
+ class GetConversionResultFormat(StrEnum):
5
+ JSON = "json"
6
+ MARKDOWN = "markdown"
7
+
8
+ def __str__(self) -> str:
9
+ return str(self.value)