typesafe-sdk 0.7.4__tar.gz → 0.7.6__tar.gz
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.
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/PKG-INFO +16 -8
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/README.md +7 -3
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/pyproject.toml +18 -6
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/pyproject.toml.orig +24 -6
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/__init__.py +14 -0
- typesafe_sdk-0.7.6/src/typesafe_sdk/_core/assets.py +349 -0
- typesafe_sdk-0.7.6/src/typesafe_sdk/_core/attached.py +49 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/client/aio/client.py +77 -30
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/client/sync/client.py +77 -30
- typesafe_sdk-0.7.6/src/typesafe_sdk/_core/compression.py +38 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/config.py +4 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/constants.py +2 -0
- typesafe_sdk-0.7.6/src/typesafe_sdk/_core/content_types.py +26 -0
- typesafe_sdk-0.7.6/src/typesafe_sdk/_core/endpoints.py +95 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/json.py +2 -2
- typesafe_sdk-0.7.6/src/typesafe_sdk/_core/multipart.py +28 -0
- typesafe_sdk-0.7.6/src/typesafe_sdk/_core/question_types.py +174 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/questions.py +5 -5
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/response_types.py +31 -8
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/schemas/base.py +1 -2
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/transport.py +31 -8
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_schemas/models.py +70 -11
- typesafe_sdk-0.7.4/src/typesafe_sdk/_core/endpoints.py +0 -41
- typesafe_sdk-0.7.4/src/typesafe_sdk/_core/question_types.py +0 -139
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/LICENSE +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/__init__.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/client/__init__.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/client/aio/__init__.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/client/aio/models.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/client/sync/__init__.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/client/sync/models.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/errors.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/json_types.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/logging.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/retry.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_core/schemas/__init__.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_schemas/__init__.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/_version.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/constants.py +0 -0
- {typesafe_sdk-0.7.4 → typesafe_sdk-0.7.6}/src/typesafe_sdk/py.typed +0 -0
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: typesafe-sdk
|
|
3
|
-
Version: 0.7.
|
|
3
|
+
Version: 0.7.6
|
|
4
4
|
Summary: Python SDK for TypeSafe AI API.
|
|
5
5
|
Keywords: typesafe,sdk,api,ai
|
|
6
6
|
Author: TypeSafe AI
|
|
@@ -16,7 +16,6 @@ Classifier: Operating System :: MacOS
|
|
|
16
16
|
Classifier: Operating System :: POSIX :: Linux
|
|
17
17
|
Classifier: Operating System :: Microsoft :: Windows
|
|
18
18
|
Classifier: Programming Language :: Python :: 3 :: Only
|
|
19
|
-
Classifier: Programming Language :: Python :: 3.10
|
|
20
19
|
Classifier: Programming Language :: Python :: 3.11
|
|
21
20
|
Classifier: Programming Language :: Python :: 3.12
|
|
22
21
|
Classifier: Programming Language :: Python :: 3.13
|
|
@@ -24,6 +23,7 @@ Classifier: Programming Language :: Python :: 3.14
|
|
|
24
23
|
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
|
|
25
24
|
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
26
25
|
Classifier: License :: OSI Approved :: MIT License
|
|
26
|
+
Requires-Dist: anyio>=4.0.0
|
|
27
27
|
Requires-Dist: httpx2>=2.0.0
|
|
28
28
|
Requires-Dist: packaging>=24.0
|
|
29
29
|
Requires-Dist: pydantic>=2.12.0
|
|
@@ -32,15 +32,19 @@ Requires-Dist: tenacity>=9.0.0
|
|
|
32
32
|
Requires-Dist: truststore>=0.10.0 ; sys_platform != 'emscripten'
|
|
33
33
|
Requires-Dist: typing-extensions>=4.13.0
|
|
34
34
|
Requires-Dist: httpx2[http2]>=2.0.0 ; extra == 'http2'
|
|
35
|
+
Requires-Dist: pillow>=13.0.0 ; extra == 'pil'
|
|
36
|
+
Requires-Dist: backports-zstd>=1.0.0 ; python_full_version < '3.14' and extra == 'zstd'
|
|
35
37
|
Maintainer: Daniel Gafni
|
|
36
38
|
Maintainer-email: Daniel Gafni <daniel@typesafe.ai>
|
|
37
|
-
Requires-Python: >=3.
|
|
39
|
+
Requires-Python: >=3.11
|
|
38
40
|
Project-URL: Homepage, https://typesafe.ai
|
|
39
|
-
Project-URL: Documentation, https://docs.typesafe.ai/
|
|
40
|
-
Project-URL: Changelog, https://docs.typesafe.ai/
|
|
41
|
+
Project-URL: Documentation, https://docs.typesafe.ai/go/python-sdk
|
|
42
|
+
Project-URL: Changelog, https://docs.typesafe.ai/go/python-changelog
|
|
41
43
|
Project-URL: Repository, https://github.com/typesafe-ai/typesafe-sdk-python
|
|
42
44
|
Project-URL: Issues, https://github.com/typesafe-ai/typesafe-sdk-python/issues
|
|
43
45
|
Provides-Extra: http2
|
|
46
|
+
Provides-Extra: pil
|
|
47
|
+
Provides-Extra: zstd
|
|
44
48
|
Description-Content-Type: text/markdown
|
|
45
49
|
|
|
46
50
|
# TypeSafe AI Python SDK
|
|
@@ -55,7 +59,11 @@ Install the SDK:
|
|
|
55
59
|
uv add typesafe-sdk
|
|
56
60
|
```
|
|
57
61
|
|
|
58
|
-
|
|
62
|
+
Extras (for example, `typesafe-sdk[http2]`) supported:
|
|
63
|
+
|
|
64
|
+
- `http2`: enable [HTTP/2 support](https://docs.typesafe.ai/sdk/python/usage/advanced/#http2)
|
|
65
|
+
- `pil`: send [Pillow images](https://docs.typesafe.ai/sdk/python/api/types/assets/#typesafe_sdk.Image.from_pil)
|
|
66
|
+
- `zstd`: [compress request bodies](https://docs.typesafe.ai/sdk/python/usage/advanced/#ensure-zstd-is-available) on Python 3.13 and earlier
|
|
59
67
|
|
|
60
68
|
Set `TYPESAFE_API_KEY` in your environment, then instantiate and use the client:
|
|
61
69
|
|
|
@@ -64,7 +72,7 @@ from typesafe_sdk import Choice, TypeSafeClient
|
|
|
64
72
|
|
|
65
73
|
with TypeSafeClient() as client:
|
|
66
74
|
response = client.system_one(
|
|
67
|
-
state={"
|
|
75
|
+
state={"ticket": "I was charged twice. Please fix this ASAP."},
|
|
68
76
|
questions={
|
|
69
77
|
"category": Choice(
|
|
70
78
|
instructions="What is this ticket about?",
|
|
@@ -80,4 +88,4 @@ learn what TypeSafe is, what it can do, and how to use it in [TypeSafe docs](htt
|
|
|
80
88
|
|
|
81
89
|
## Documentation
|
|
82
90
|
|
|
83
|
-
Learn more in [SDK docs](https://docs.typesafe.ai/
|
|
91
|
+
Learn more in [SDK docs](https://docs.typesafe.ai/go/python-sdk).
|
|
@@ -10,7 +10,11 @@ Install the SDK:
|
|
|
10
10
|
uv add typesafe-sdk
|
|
11
11
|
```
|
|
12
12
|
|
|
13
|
-
|
|
13
|
+
Extras (for example, `typesafe-sdk[http2]`) supported:
|
|
14
|
+
|
|
15
|
+
- `http2`: enable [HTTP/2 support](https://docs.typesafe.ai/sdk/python/usage/advanced/#http2)
|
|
16
|
+
- `pil`: send [Pillow images](https://docs.typesafe.ai/sdk/python/api/types/assets/#typesafe_sdk.Image.from_pil)
|
|
17
|
+
- `zstd`: [compress request bodies](https://docs.typesafe.ai/sdk/python/usage/advanced/#ensure-zstd-is-available) on Python 3.13 and earlier
|
|
14
18
|
|
|
15
19
|
Set `TYPESAFE_API_KEY` in your environment, then instantiate and use the client:
|
|
16
20
|
|
|
@@ -19,7 +23,7 @@ from typesafe_sdk import Choice, TypeSafeClient
|
|
|
19
23
|
|
|
20
24
|
with TypeSafeClient() as client:
|
|
21
25
|
response = client.system_one(
|
|
22
|
-
state={"
|
|
26
|
+
state={"ticket": "I was charged twice. Please fix this ASAP."},
|
|
23
27
|
questions={
|
|
24
28
|
"category": Choice(
|
|
25
29
|
instructions="What is this ticket about?",
|
|
@@ -35,4 +39,4 @@ learn what TypeSafe is, what it can do, and how to use it in [TypeSafe docs](htt
|
|
|
35
39
|
|
|
36
40
|
## Documentation
|
|
37
41
|
|
|
38
|
-
Learn more in [SDK docs](https://docs.typesafe.ai/
|
|
42
|
+
Learn more in [SDK docs](https://docs.typesafe.ai/go/python-sdk).
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "typesafe-sdk"
|
|
3
|
-
version = "0.7.
|
|
3
|
+
version = "0.7.6"
|
|
4
4
|
description = "Python SDK for TypeSafe AI API."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
7
7
|
license-files = ["LICENSE"]
|
|
8
|
-
requires-python = ">=3.
|
|
8
|
+
requires-python = ">=3.11"
|
|
9
9
|
keywords = [
|
|
10
10
|
"typesafe",
|
|
11
11
|
"sdk",
|
|
@@ -22,7 +22,6 @@ classifiers = [
|
|
|
22
22
|
"Operating System :: POSIX :: Linux",
|
|
23
23
|
"Operating System :: Microsoft :: Windows",
|
|
24
24
|
"Programming Language :: Python :: 3 :: Only",
|
|
25
|
-
"Programming Language :: Python :: 3.10",
|
|
26
25
|
"Programming Language :: Python :: 3.11",
|
|
27
26
|
"Programming Language :: Python :: 3.12",
|
|
28
27
|
"Programming Language :: Python :: 3.13",
|
|
@@ -32,6 +31,7 @@ classifiers = [
|
|
|
32
31
|
"License :: OSI Approved :: MIT License",
|
|
33
32
|
]
|
|
34
33
|
dependencies = [
|
|
34
|
+
"anyio>=4.0.0",
|
|
35
35
|
"httpx2>=2.0.0",
|
|
36
36
|
"packaging>=24.0",
|
|
37
37
|
"pydantic>=2.12.0",
|
|
@@ -51,21 +51,26 @@ email = "daniel@typesafe.ai"
|
|
|
51
51
|
|
|
52
52
|
[project.optional-dependencies]
|
|
53
53
|
http2 = ["httpx2[http2]>=2.0.0"]
|
|
54
|
+
pil = ["pillow>=13.0.0"]
|
|
55
|
+
zstd = ["backports-zstd>=1.0.0 ; python_version < '3.14'"]
|
|
54
56
|
|
|
55
57
|
[project.urls]
|
|
56
58
|
Homepage = "https://typesafe.ai"
|
|
57
|
-
Documentation = "https://docs.typesafe.ai/
|
|
58
|
-
Changelog = "https://docs.typesafe.ai/
|
|
59
|
+
Documentation = "https://docs.typesafe.ai/go/python-sdk"
|
|
60
|
+
Changelog = "https://docs.typesafe.ai/go/python-changelog"
|
|
59
61
|
Repository = "https://github.com/typesafe-ai/typesafe-sdk-python"
|
|
60
62
|
Issues = "https://github.com/typesafe-ai/typesafe-sdk-python/issues"
|
|
61
63
|
|
|
62
64
|
[build-system]
|
|
63
|
-
requires = ["uv_build>=0.12.5,<0.
|
|
65
|
+
requires = ["uv_build>=0.12.5,<0.14"]
|
|
64
66
|
build-backend = "uv_build"
|
|
65
67
|
|
|
66
68
|
[dependency-groups]
|
|
67
69
|
dev = [
|
|
70
|
+
"backports-zstd>=1.0.0 ; python_version < '3.14'",
|
|
71
|
+
"deptry>=0.25.1",
|
|
68
72
|
"gitpython>=3.1.62",
|
|
73
|
+
"pillow>=13.0.0",
|
|
69
74
|
"pyrefly>=1.2.0",
|
|
70
75
|
"pytest>=9.1.1",
|
|
71
76
|
"pytest-asyncio>=1.4.0",
|
|
@@ -94,6 +99,13 @@ markers = ["integration: live API tests requiring TYPESAFE_API_KEY"]
|
|
|
94
99
|
[tool.deptry]
|
|
95
100
|
extend_exclude = [".dagger"]
|
|
96
101
|
|
|
102
|
+
[tool.deptry.per_rule_ignores]
|
|
103
|
+
DEP002 = ["pillow"]
|
|
104
|
+
DEP001 = ["compression"]
|
|
105
|
+
|
|
106
|
+
[tool.deptry.package_module_name_map]
|
|
107
|
+
backports-zstd = "backports"
|
|
108
|
+
|
|
97
109
|
[[tool.uv.index]]
|
|
98
110
|
name = "testpypi"
|
|
99
111
|
url = "https://test.pypi.org/simple/"
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
[project]
|
|
2
2
|
name = "typesafe-sdk"
|
|
3
|
-
version = "0.7.
|
|
3
|
+
version = "0.7.6"
|
|
4
4
|
description = "Python SDK for TypeSafe AI API."
|
|
5
5
|
readme = "README.md"
|
|
6
6
|
license = "MIT"
|
|
@@ -11,7 +11,7 @@ authors = [
|
|
|
11
11
|
maintainers = [
|
|
12
12
|
{ name = "Daniel Gafni", email = "daniel@typesafe.ai" }
|
|
13
13
|
]
|
|
14
|
-
requires-python = ">=3.
|
|
14
|
+
requires-python = ">=3.11"
|
|
15
15
|
keywords = ["typesafe", "sdk", "api", "ai"]
|
|
16
16
|
classifiers = [
|
|
17
17
|
"Typing :: Typed",
|
|
@@ -23,7 +23,6 @@ classifiers = [
|
|
|
23
23
|
"Operating System :: POSIX :: Linux",
|
|
24
24
|
"Operating System :: Microsoft :: Windows",
|
|
25
25
|
"Programming Language :: Python :: 3 :: Only",
|
|
26
|
-
"Programming Language :: Python :: 3.10",
|
|
27
26
|
"Programming Language :: Python :: 3.11",
|
|
28
27
|
"Programming Language :: Python :: 3.12",
|
|
29
28
|
"Programming Language :: Python :: 3.13",
|
|
@@ -33,6 +32,7 @@ classifiers = [
|
|
|
33
32
|
"License :: OSI Approved :: MIT License",
|
|
34
33
|
]
|
|
35
34
|
dependencies = [
|
|
35
|
+
"anyio>=4.0.0",
|
|
36
36
|
"httpx2>=2.0.0",
|
|
37
37
|
"packaging>=24.0",
|
|
38
38
|
"pydantic>=2.12.0",
|
|
@@ -47,21 +47,30 @@ dependencies = [
|
|
|
47
47
|
http2 = [
|
|
48
48
|
"httpx2[http2]>=2.0.0",
|
|
49
49
|
]
|
|
50
|
+
pil = [
|
|
51
|
+
"pillow>=13.0.0",
|
|
52
|
+
]
|
|
53
|
+
zstd = [
|
|
54
|
+
"backports-zstd>=1.0.0 ; python_version < '3.14'",
|
|
55
|
+
]
|
|
50
56
|
|
|
51
57
|
[project.urls]
|
|
52
58
|
Homepage = "https://typesafe.ai"
|
|
53
|
-
Documentation = "https://docs.typesafe.ai/
|
|
54
|
-
Changelog = "https://docs.typesafe.ai/
|
|
59
|
+
Documentation = "https://docs.typesafe.ai/go/python-sdk"
|
|
60
|
+
Changelog = "https://docs.typesafe.ai/go/python-changelog"
|
|
55
61
|
Repository = "https://github.com/typesafe-ai/typesafe-sdk-python"
|
|
56
62
|
Issues = "https://github.com/typesafe-ai/typesafe-sdk-python/issues"
|
|
57
63
|
|
|
58
64
|
[build-system]
|
|
59
|
-
requires = ["uv_build>=0.12.5,<0.
|
|
65
|
+
requires = ["uv_build>=0.12.5,<0.14"]
|
|
60
66
|
build-backend = "uv_build"
|
|
61
67
|
|
|
62
68
|
[dependency-groups]
|
|
63
69
|
dev = [
|
|
70
|
+
"backports-zstd>=1.0.0 ; python_version < '3.14'",
|
|
71
|
+
"deptry>=0.25.1",
|
|
64
72
|
"gitpython>=3.1.62",
|
|
73
|
+
"pillow>=13.0.0",
|
|
65
74
|
"pyrefly>=1.2.0",
|
|
66
75
|
"pytest>=9.1.1",
|
|
67
76
|
"pytest-asyncio>=1.4.0",
|
|
@@ -92,6 +101,15 @@ markers = ["integration: live API tests requiring TYPESAFE_API_KEY"]
|
|
|
92
101
|
[tool.deptry]
|
|
93
102
|
extend_exclude = [".dagger"]
|
|
94
103
|
|
|
104
|
+
[tool.deptry.per_rule_ignores]
|
|
105
|
+
# The `pil` extra installs Pillow for users; the SDK only calls methods on their images.
|
|
106
|
+
DEP002 = ["pillow"]
|
|
107
|
+
# `compression.zstd` is the Python 3.14+ standard library module.
|
|
108
|
+
DEP001 = ["compression"]
|
|
109
|
+
|
|
110
|
+
[tool.deptry.package_module_name_map]
|
|
111
|
+
backports-zstd = "backports"
|
|
112
|
+
|
|
95
113
|
[[tool.uv.index]]
|
|
96
114
|
name = "testpypi"
|
|
97
115
|
url = "https://test.pypi.org/simple/"
|
|
@@ -2,10 +2,12 @@
|
|
|
2
2
|
|
|
3
3
|
from typesafe_sdk import _core as _core
|
|
4
4
|
from typesafe_sdk import constants as constants
|
|
5
|
+
from typesafe_sdk._core.assets import Asset, Image
|
|
5
6
|
from typesafe_sdk._core.client.aio.client import AsyncTypeSafeClient
|
|
6
7
|
from typesafe_sdk._core.client.aio.models import AsyncModels
|
|
7
8
|
from typesafe_sdk._core.client.sync.client import TypeSafeClient
|
|
8
9
|
from typesafe_sdk._core.client.sync.models import Models
|
|
10
|
+
from typesafe_sdk._core.content_types import Content, ContentValue
|
|
9
11
|
from typesafe_sdk._core.errors import (
|
|
10
12
|
TypeSafeAPIConnectionError,
|
|
11
13
|
TypeSafeAPIError,
|
|
@@ -22,6 +24,8 @@ from typesafe_sdk._core.errors import (
|
|
|
22
24
|
)
|
|
23
25
|
from typesafe_sdk._core.json_types import JSONContent, JSONValue
|
|
24
26
|
from typesafe_sdk._core.question_types import (
|
|
27
|
+
Box,
|
|
28
|
+
BoxModel,
|
|
25
29
|
Choice,
|
|
26
30
|
ChoiceModel,
|
|
27
31
|
Noul,
|
|
@@ -35,6 +39,8 @@ from typesafe_sdk._core.question_types import (
|
|
|
35
39
|
)
|
|
36
40
|
from typesafe_sdk._core.response_types import (
|
|
37
41
|
Answer,
|
|
42
|
+
BoxAnswer,
|
|
43
|
+
BoxCoordinates,
|
|
38
44
|
ChoiceAnswer,
|
|
39
45
|
ListModelsResponse,
|
|
40
46
|
ModelMetadata,
|
|
@@ -48,11 +54,19 @@ from typesafe_sdk._version import __version__ as __version__
|
|
|
48
54
|
|
|
49
55
|
__all__ = [
|
|
50
56
|
"Answer",
|
|
57
|
+
"Asset",
|
|
51
58
|
"AsyncModels",
|
|
52
59
|
"AsyncTypeSafeClient",
|
|
60
|
+
"Box",
|
|
61
|
+
"BoxAnswer",
|
|
62
|
+
"BoxCoordinates",
|
|
63
|
+
"BoxModel",
|
|
53
64
|
"Choice",
|
|
54
65
|
"ChoiceAnswer",
|
|
55
66
|
"ChoiceModel",
|
|
67
|
+
"Content",
|
|
68
|
+
"ContentValue",
|
|
69
|
+
"Image",
|
|
56
70
|
"JSONContent",
|
|
57
71
|
"JSONValue",
|
|
58
72
|
"ListModelsResponse",
|
|
@@ -0,0 +1,349 @@
|
|
|
1
|
+
"""Asset objects and their resolution into API assets."""
|
|
2
|
+
|
|
3
|
+
import re
|
|
4
|
+
from base64 import b64decode
|
|
5
|
+
from collections.abc import Iterator, Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from io import BytesIO
|
|
8
|
+
from os import PathLike
|
|
9
|
+
from pathlib import Path
|
|
10
|
+
from typing import TYPE_CHECKING, Any, ClassVar, Literal, Self, TypeAlias
|
|
11
|
+
from uuid import uuid4
|
|
12
|
+
|
|
13
|
+
import anyio
|
|
14
|
+
from pydantic import GetCoreSchemaHandler
|
|
15
|
+
from pydantic_core import CoreSchema, SchemaSerializer, core_schema
|
|
16
|
+
from pydantic_core.core_schema import SerializationInfo
|
|
17
|
+
from typing_extensions import Buffer
|
|
18
|
+
|
|
19
|
+
from typesafe_sdk._core.errors import TypeSafeError
|
|
20
|
+
|
|
21
|
+
if TYPE_CHECKING:
|
|
22
|
+
import PIL.Image
|
|
23
|
+
|
|
24
|
+
# Content types of the image formats recognized by their file signatures, to label upload parts.
|
|
25
|
+
# The API detects formats itself, so unrecognized images are still sent, labeled as generic binary data.
|
|
26
|
+
CONTENT_TYPES = {b"\x89PNG\r\n\x1a\n": "image/png", b"\xff\xd8\xff": "image/jpeg"}
|
|
27
|
+
SIGNATURE_LENGTH = max(map(len, CONTENT_TYPES))
|
|
28
|
+
UNKNOWN_CONTENT_TYPE = "application/octet-stream"
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
@dataclass(frozen=True)
|
|
32
|
+
class References:
|
|
33
|
+
"""Request serialization context: serializes assets as their alias or reference, collecting referenced assets."""
|
|
34
|
+
|
|
35
|
+
aliases: Mapping[int, str]
|
|
36
|
+
"""Aliases of the assets passed in `assets`, by `id(asset)`."""
|
|
37
|
+
found: dict[str, "Asset"] = field(default_factory=dict)
|
|
38
|
+
"""Assets serialized as their reference, by reference."""
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
# Matches the reference of any image, `str(image)`; the reference is the same in text and in JSON.
|
|
42
|
+
REFERENCE_PATTERN = re.compile(rb"<image:[0-9a-f]{32}>")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _serialize_reference(asset: "Image", info: SerializationInfo) -> str:
|
|
46
|
+
references = info.context
|
|
47
|
+
reference = asset._reference # noqa: SLF001 - Internal asset protocol.
|
|
48
|
+
if not isinstance(references, References):
|
|
49
|
+
return reference
|
|
50
|
+
alias = references.aliases.get(id(asset))
|
|
51
|
+
if alias is not None:
|
|
52
|
+
return alias
|
|
53
|
+
references.found[reference] = asset
|
|
54
|
+
return reference
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
REFERENCE_SERIALIZATION = core_schema.plain_serializer_function_ser_schema(_serialize_reference, info_arg=True)
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@dataclass(frozen=True)
|
|
61
|
+
class ResolvedImage:
|
|
62
|
+
"""An image asset with its data read and validated."""
|
|
63
|
+
|
|
64
|
+
type: Literal["image"] = field(default="image", init=False)
|
|
65
|
+
"""Asset type discriminator, always `"image"`."""
|
|
66
|
+
content_type: str
|
|
67
|
+
"""The image's content type, recognized from its file signature."""
|
|
68
|
+
data: memoryview = field(hash=False)
|
|
69
|
+
"""The image file bytes."""
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
@dataclass(frozen=True, eq=False)
|
|
73
|
+
class Image:
|
|
74
|
+
"""An image asset backed by image file bytes, or a path to an image file.
|
|
75
|
+
|
|
76
|
+
!!! tip "Reusing images"
|
|
77
|
+
An `Image` is loaded once, on first use, and reused by every request that sends the same `Image` object.
|
|
78
|
+
|
|
79
|
+
!!! tip "Working with `Buffer` objects"
|
|
80
|
+
`Image` also accepts `Buffer` objects: anything exposing its memory through the [buffer protocol](https://docs.python.org/3/c-api/buffer.html), such as `bytearray`,
|
|
81
|
+
`memoryview`, `mmap`, or NumPy arrays.
|
|
82
|
+
Buffers other than `bytes` are copied into memory once, on first use, so the original can change or be closed afterwards.
|
|
83
|
+
|
|
84
|
+
Examples:
|
|
85
|
+
From a file path:
|
|
86
|
+
|
|
87
|
+
<!-- skip: next -->
|
|
88
|
+
```python
|
|
89
|
+
from pathlib import Path
|
|
90
|
+
|
|
91
|
+
image = Image(Path("photos/product.png"))
|
|
92
|
+
```
|
|
93
|
+
|
|
94
|
+
From bytes in memory:
|
|
95
|
+
|
|
96
|
+
```python
|
|
97
|
+
def from_bytes(data: bytes) -> Image:
|
|
98
|
+
return Image(data)
|
|
99
|
+
```
|
|
100
|
+
|
|
101
|
+
From base64 text, such as an upload:
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
def from_upload(data_base64: str) -> Image:
|
|
105
|
+
return Image.from_base64(data_base64)
|
|
106
|
+
```
|
|
107
|
+
|
|
108
|
+
From a Pillow image (requires the `pil` extra):
|
|
109
|
+
|
|
110
|
+
```python
|
|
111
|
+
import PIL.Image
|
|
112
|
+
|
|
113
|
+
image = Image.from_pil(PIL.Image.new("RGB", (64, 64)), format="jpeg")
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
From a slice of a larger buffer, without copying it into `bytes` first:
|
|
117
|
+
|
|
118
|
+
```python
|
|
119
|
+
def embedded_photo(container: bytes, offset: int, length: int) -> Image:
|
|
120
|
+
return Image(memoryview(container)[offset : offset + length])
|
|
121
|
+
```
|
|
122
|
+
|
|
123
|
+
From a memory-mapped file:
|
|
124
|
+
|
|
125
|
+
```python
|
|
126
|
+
import mmap
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def map_photo(path: Path) -> Image:
|
|
130
|
+
with path.open("rb") as file:
|
|
131
|
+
return Image(mmap.mmap(file.fileno(), 0, access=mmap.ACCESS_READ))
|
|
132
|
+
```
|
|
133
|
+
"""
|
|
134
|
+
|
|
135
|
+
type: Literal["image"] = field(default="image", init=False)
|
|
136
|
+
"""Asset type discriminator, always `"image"`."""
|
|
137
|
+
data: Buffer | PathLike[str]
|
|
138
|
+
"""Image contents, represented as one of:
|
|
139
|
+
|
|
140
|
+
- raw bytes (anything supporting the [`Buffer` protocol](https://docs.python.org/3/library/stdtypes.html#buffer-objects))
|
|
141
|
+
|
|
142
|
+
- [path-like][os.PathLike] object pointing at the image on the filesystem
|
|
143
|
+
"""
|
|
144
|
+
_reference: str = field(default_factory=lambda: f"<image:{uuid4().hex}>", init=False, repr=False)
|
|
145
|
+
_resolution: ResolvedImage | None = field(default=None, init=False, repr=False)
|
|
146
|
+
|
|
147
|
+
# pydantic-core encodes an `Image` as its alias or reference anywhere in a request body, including plain dicts and lists.
|
|
148
|
+
__pydantic_serializer__: ClassVar[SchemaSerializer] = SchemaSerializer(core_schema.any_schema(serialization=REFERENCE_SERIALIZATION))
|
|
149
|
+
|
|
150
|
+
@classmethod
|
|
151
|
+
def from_base64(cls, data: str | Buffer) -> Self:
|
|
152
|
+
"""Create an `Image` instance from a base64-encoded image bytes.
|
|
153
|
+
|
|
154
|
+
Args:
|
|
155
|
+
data: The image file bytes, base64-encoded, as text or an ASCII buffer. Whitespace, such as the
|
|
156
|
+
line breaks of wrapped base64, is ignored.
|
|
157
|
+
|
|
158
|
+
Raises:
|
|
159
|
+
TypeSafeError: The data isn't valid base64 text.
|
|
160
|
+
"""
|
|
161
|
+
text = data if isinstance(data, str) else _buffer(data).tobytes().decode("latin-1")
|
|
162
|
+
text = "".join(text.split()) if text.isascii() else ""
|
|
163
|
+
if not text:
|
|
164
|
+
raise TypeSafeError("Image data must contain non-empty ASCII base64 text.")
|
|
165
|
+
try:
|
|
166
|
+
return cls(b64decode(text, validate=True))
|
|
167
|
+
except ValueError as error:
|
|
168
|
+
raise TypeSafeError("Image data must contain valid base64 text.") from error
|
|
169
|
+
|
|
170
|
+
@classmethod
|
|
171
|
+
def from_pil(cls, image: "PIL.Image.Image", format: str = "jpeg") -> Self: # noqa: A002 - Pillow's own name for it.
|
|
172
|
+
"""Create an `Image` instance from a [Pillow](https://pillow.readthedocs.io/) image.
|
|
173
|
+
|
|
174
|
+
!!! warning "Encoder settings"
|
|
175
|
+
The image is saved with Pillow's default encoder settings, except that JPEG uses quality 95.
|
|
176
|
+
JPEG can't store transparency or palettes, so pass `format="png"` for RGBA or P mode images.
|
|
177
|
+
Encode it yourself if different settings are needed.
|
|
178
|
+
|
|
179
|
+
Args:
|
|
180
|
+
image: The Pillow image to encode.
|
|
181
|
+
format: The image format to save as, by its [Pillow name](https://pillow.readthedocs.io/en/stable/handbook/image-file-formats.html).
|
|
182
|
+
|
|
183
|
+
Raises:
|
|
184
|
+
TypeSafeError: Pillow can't encode the image in this format.
|
|
185
|
+
"""
|
|
186
|
+
buffer = BytesIO()
|
|
187
|
+
try:
|
|
188
|
+
image.save(buffer, format=format, quality=95)
|
|
189
|
+
except (KeyError, OSError, ValueError) as error:
|
|
190
|
+
# Pillow raises `KeyError` for a format it doesn't know.
|
|
191
|
+
raise TypeSafeError(f"Pillow image could not be encoded as {format}: {error}") from error
|
|
192
|
+
return cls(buffer.getvalue())
|
|
193
|
+
|
|
194
|
+
def __str__(self) -> str:
|
|
195
|
+
"""The unique reference to this image, for using it inside text, such as an f-string."""
|
|
196
|
+
return self._reference
|
|
197
|
+
|
|
198
|
+
@classmethod
|
|
199
|
+
def __get_pydantic_core_schema__(cls, source: Any, handler: GetCoreSchemaHandler) -> CoreSchema:
|
|
200
|
+
# Pydantic models, such as question objects, hold `Image` objects as-is; there is no schema for buffer data.
|
|
201
|
+
return core_schema.is_instance_schema(cls, serialization=REFERENCE_SERIALIZATION)
|
|
202
|
+
|
|
203
|
+
@property
|
|
204
|
+
def _is_resolved(self) -> bool:
|
|
205
|
+
"""Whether the image has been read and validated."""
|
|
206
|
+
return self._resolution is not None
|
|
207
|
+
|
|
208
|
+
@property
|
|
209
|
+
def _resolved(self) -> ResolvedImage:
|
|
210
|
+
"""The image in its wire form.
|
|
211
|
+
|
|
212
|
+
Raises:
|
|
213
|
+
RuntimeError: The image is not resolved yet; check `_is_resolved` first.
|
|
214
|
+
"""
|
|
215
|
+
if self._resolution is None:
|
|
216
|
+
raise RuntimeError("Image is not resolved yet; check `_is_resolved` first.")
|
|
217
|
+
return self._resolution
|
|
218
|
+
|
|
219
|
+
def _resolve(self) -> ResolvedImage:
|
|
220
|
+
"""Read and validate the image once, reading a path with blocking file I/O.
|
|
221
|
+
|
|
222
|
+
Raises:
|
|
223
|
+
TypeSafeError: The data can't be read or is empty.
|
|
224
|
+
"""
|
|
225
|
+
if not self._is_resolved:
|
|
226
|
+
data = self.data
|
|
227
|
+
if isinstance(data, PathLike):
|
|
228
|
+
path = data
|
|
229
|
+
try:
|
|
230
|
+
data = Path(path).read_bytes()
|
|
231
|
+
except OSError as error:
|
|
232
|
+
raise _read_error(path, error) from error
|
|
233
|
+
self._set_resolved(data)
|
|
234
|
+
return self._resolved
|
|
235
|
+
|
|
236
|
+
async def _resolve_async(self) -> ResolvedImage:
|
|
237
|
+
"""Read and validate the image once, reading a path with async file I/O.
|
|
238
|
+
|
|
239
|
+
Validation runs on the event loop.
|
|
240
|
+
|
|
241
|
+
Raises:
|
|
242
|
+
TypeSafeError: The data can't be read or is empty.
|
|
243
|
+
"""
|
|
244
|
+
if not self._is_resolved:
|
|
245
|
+
data = self.data
|
|
246
|
+
if isinstance(data, PathLike):
|
|
247
|
+
path = data
|
|
248
|
+
try:
|
|
249
|
+
data = await anyio.Path(path).read_bytes()
|
|
250
|
+
except OSError as error:
|
|
251
|
+
raise _read_error(path, error) from error
|
|
252
|
+
self._set_resolved(data)
|
|
253
|
+
return self._resolved
|
|
254
|
+
|
|
255
|
+
def _set_resolved(self, data: Buffer) -> None:
|
|
256
|
+
# The frozen dataclass caches its resolution in a private field.
|
|
257
|
+
object.__setattr__(self, "_resolution", self._validate(data))
|
|
258
|
+
|
|
259
|
+
def _validate(self, data: Buffer) -> ResolvedImage:
|
|
260
|
+
"""Validate the image contents, with any path already read into `data`."""
|
|
261
|
+
if isinstance(data, str):
|
|
262
|
+
raise TypeSafeError("Image has str data; pass image file bytes or a path, or use Image.from_base64 for base64 text.")
|
|
263
|
+
buffer = _buffer(data)
|
|
264
|
+
if not isinstance(buffer.obj, bytes):
|
|
265
|
+
# The cached view would keep a mutable buffer from being resized or closed, so copy it once.
|
|
266
|
+
with buffer:
|
|
267
|
+
buffer = memoryview(buffer.tobytes())
|
|
268
|
+
if not buffer:
|
|
269
|
+
raise TypeSafeError("Image data is empty.")
|
|
270
|
+
return ResolvedImage(content_type=_content_type(buffer[:SIGNATURE_LENGTH]), data=buffer)
|
|
271
|
+
|
|
272
|
+
|
|
273
|
+
Asset: TypeAlias = Image
|
|
274
|
+
"""An asset referenced from request content; currently only images are supported."""
|
|
275
|
+
|
|
276
|
+
|
|
277
|
+
def resolve_assets(assets: Mapping[str, Asset]) -> dict[str, ResolvedImage]:
|
|
278
|
+
"""Resolve each distinct asset once with blocking file I/O, naming the failing alias in errors."""
|
|
279
|
+
resolved: dict[int, ResolvedImage] = {}
|
|
280
|
+
for name, asset in _assets(assets):
|
|
281
|
+
if id(asset) in resolved:
|
|
282
|
+
continue
|
|
283
|
+
try:
|
|
284
|
+
resolved[id(asset)] = asset._resolve() # noqa: SLF001 - Internal asset protocol.
|
|
285
|
+
except TypeSafeError as error:
|
|
286
|
+
raise _asset_error(name, error) from error
|
|
287
|
+
return {name: resolved[id(asset)] for name, asset in assets.items()}
|
|
288
|
+
|
|
289
|
+
|
|
290
|
+
async def resolve_assets_async(assets: Mapping[str, Asset]) -> dict[str, ResolvedImage]:
|
|
291
|
+
"""Resolve each distinct asset once, concurrently with async file I/O, naming the first failing alias in errors."""
|
|
292
|
+
items = list(_assets(assets))
|
|
293
|
+
results: dict[int, ResolvedImage | Exception] = {}
|
|
294
|
+
|
|
295
|
+
async def resolve(asset: Asset) -> None:
|
|
296
|
+
# Errors are collected rather than raised so the task group doesn't wrap them in an ExceptionGroup,
|
|
297
|
+
# and the first failing alias raises as it would with blocking file I/O.
|
|
298
|
+
try:
|
|
299
|
+
results[id(asset)] = await asset._resolve_async() # noqa: SLF001 - Internal asset protocol.
|
|
300
|
+
except Exception as error: # noqa: BLE001 - Re-raised below.
|
|
301
|
+
results[id(asset)] = error
|
|
302
|
+
|
|
303
|
+
async with anyio.create_task_group() as task_group:
|
|
304
|
+
for asset in {id(asset): asset for _, asset in items}.values():
|
|
305
|
+
task_group.start_soon(resolve, asset)
|
|
306
|
+
resolved = {}
|
|
307
|
+
for name, asset in items:
|
|
308
|
+
result = results[id(asset)]
|
|
309
|
+
if isinstance(result, TypeSafeError):
|
|
310
|
+
raise _asset_error(name, result) from result
|
|
311
|
+
if isinstance(result, Exception):
|
|
312
|
+
raise result
|
|
313
|
+
resolved[name] = result
|
|
314
|
+
return resolved
|
|
315
|
+
|
|
316
|
+
|
|
317
|
+
def _assets(assets: Mapping[str, Asset]) -> Iterator[tuple[str, Asset]]:
|
|
318
|
+
for name, asset in assets.items():
|
|
319
|
+
if not isinstance(name, str) or not name.strip():
|
|
320
|
+
raise TypeSafeError("Asset aliases must be non-empty strings.")
|
|
321
|
+
if not isinstance(asset, Asset):
|
|
322
|
+
raise TypeSafeError(f"Asset {name!r} must be an asset.")
|
|
323
|
+
yield name, asset
|
|
324
|
+
|
|
325
|
+
|
|
326
|
+
def _asset_error(name: str, error: TypeSafeError) -> TypeSafeError:
|
|
327
|
+
return TypeSafeError(f"Asset {name!r}: {error}")
|
|
328
|
+
|
|
329
|
+
|
|
330
|
+
def _read_error(path: PathLike[str], error: OSError) -> TypeSafeError:
|
|
331
|
+
return TypeSafeError(f"Image file {str(path)!r} could not be read: {error.strerror}.")
|
|
332
|
+
|
|
333
|
+
|
|
334
|
+
def _buffer(value: Buffer) -> memoryview:
|
|
335
|
+
try:
|
|
336
|
+
data = memoryview(value)
|
|
337
|
+
except (TypeError, ValueError) as error:
|
|
338
|
+
raise TypeSafeError("Image data must be an accessible buffer of image file bytes.") from error
|
|
339
|
+
# C-extension buffers work through memoryview on Python 3.10/3.11 too,
|
|
340
|
+
# where isinstance(value, typing_extensions.Buffer) cannot recognize all of them.
|
|
341
|
+
# Flatten shaped buffers and copy only when a contiguous view is unavailable.
|
|
342
|
+
return data.cast("B") if data.c_contiguous else memoryview(data.tobytes())
|
|
343
|
+
|
|
344
|
+
|
|
345
|
+
def _content_type(header: bytes | memoryview) -> str:
|
|
346
|
+
for signature, content_type in CONTENT_TYPES.items():
|
|
347
|
+
if header[: len(signature)] == signature:
|
|
348
|
+
return content_type
|
|
349
|
+
return UNKNOWN_CONTENT_TYPE
|