gepetto 0.1.0__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.
@@ -0,0 +1,9 @@
1
+ __pycache__/
2
+ *.pyc
3
+ .venv/
4
+ dist/
5
+ build/
6
+ *.egg-info/
7
+ .pytest_cache/
8
+ .mypy_cache/
9
+ .env
@@ -0,0 +1,8 @@
1
+ # Changelog
2
+
3
+ ## 0.1.0
4
+
5
+ - Every tool of the Gepetto API v2: enhance, declutter, furnish, sunshine, creative_redesign, surfaces, upscale.
6
+ - Waits for the image; retries with the same idempotency key; follows the job if the connection drops.
7
+ - `GepettoError` with `code`, `param`, `status`, `job_id`.
8
+ - Lists, jobs, account, usage. `verify_webhook()`. `mask_from_file()`.
gepetto-0.1.0/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Gepetto
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
gepetto-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,203 @@
1
+ Metadata-Version: 2.5
2
+ Name: gepetto
3
+ Version: 0.1.0
4
+ Summary: The official Python SDK of the Gepetto API v2: real estate photo editing. Enhance, declutter, furnish, blue sky, restyle, walls and floors, upscale.
5
+ Project-URL: Homepage, https://gepettoapp.com
6
+ Project-URL: Documentation, https://docs.gepettoapp.com
7
+ Project-URL: Source, https://github.com/Gepetto-AI/gepetto-python
8
+ Project-URL: Issues, https://github.com/Gepetto-AI/gepetto-python/issues
9
+ Author-email: Gepetto <api@gepettoapp.com>
10
+ License-Expression: MIT
11
+ License-File: LICENSE
12
+ Keywords: api,declutter,gepetto,home staging,photo editing,real estate,sdk,virtual staging
13
+ Classifier: Development Status :: 4 - Beta
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Operating System :: OS Independent
16
+ Classifier: Programming Language :: Python :: 3
17
+ Classifier: Programming Language :: Python :: 3 :: Only
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Multimedia :: Graphics
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Description-Content-Type: text/markdown
27
+
28
+ # Gepetto Python SDK
29
+
30
+ [![PyPI](https://img.shields.io/pypi/v/gepetto)](https://pypi.org/project/gepetto/) [![Tests](https://github.com/Gepetto-AI/gepetto-python/actions/workflows/tests.yml/badge.svg)](https://github.com/Gepetto-AI/gepetto-python/actions/workflows/tests.yml)
31
+
32
+ The official Python SDK of the [Gepetto API v2](https://docs.gepettoapp.com): real estate photo editing. Enhance a photo, declutter a room, furnish it, change the sky, restyle it, repaint walls and floors, upscale. One call, an image URL in return.
33
+
34
+ ```bash
35
+ pip install gepetto
36
+ ```
37
+
38
+ Python 3.10 or later. No dependency: the standard library is enough. Fully typed.
39
+
40
+ ## Quickstart
41
+
42
+ ```python
43
+ from gepetto import Gepetto
44
+
45
+ gepetto = Gepetto() # reads GEPETTO_API_KEY
46
+
47
+ job = gepetto.furnish(
48
+ url="https://assets.gepettoapp.com/raw-images/b85e2aa5-ac29-44a0-93eb-2de0a40f7905.png",
49
+ room_id="living_room",
50
+ style_id="scandinave",
51
+ )
52
+
53
+ print(job.output) # https://assets.gepettoapp.com/api/v2/jobs/.../output.jpg
54
+ ```
55
+
56
+ No key yet? A free test key (200 real renders, no watermark) in two commands:
57
+
58
+ ```bash
59
+ npx @gepetto/cli login # opens a page: check the code, click "Authorize"
60
+ npx @gepetto/cli init # writes GEPETTO_API_KEY to .env
61
+ ```
62
+
63
+ The key can also be given directly: `Gepetto("test_...")`, or `Gepetto(api_key=..., timeout=120)`.
64
+
65
+ ## What you get
66
+
67
+ - **The method waits for the image.** Each tool returns the finished `Job`, whose `output` is the image URL. A failed render raises a `GepettoError`, and is never charged.
68
+ - **Your editor knows the parameters.** Every tool takes keyword arguments with types: completion in VS Code and PyCharm, and mypy or Pyright catch a typo before the API does.
69
+ - **Retries are safe.** Every render is sent with an idempotency key (yours, or one generated). A network error, a `429` or a `5xx` is retried with the same key: a render is never started, nor billed, twice.
70
+ - **Long renders just work.** If the connection drops while the image is being made, the SDK picks up the same job and waits for it.
71
+ - **The names are those of the API, in snake_case.** `room_id` is `roomId` in the [docs](https://docs.gepettoapp.com): same fields, same ids, same error codes.
72
+
73
+ ## Tools
74
+
75
+ The `url` of every tool is a public http(s) URL of a JPEG, PNG, WebP or HEIC image: upload the photo to your own storage first. The output URL is public too; copy the image if you keep it.
76
+
77
+ | Method | What it does |
78
+ | --- | --- |
79
+ | `enhance(url=..., straighten=True)` | Light and colours corrected at the size of the photo, nothing redrawn |
80
+ | `declutter(url=..., keep_fireplace=True)` | The whole room emptied (also `keep_kitchen`, `keep_bathroom`) |
81
+ | `declutter(url=..., mask=...)` | What the mask covers removed |
82
+ | `furnish(url=..., room_id=..., style_id=...)` | The whole room furnished |
83
+ | `furnish(url=..., mask=..., room_id=..., style_id=...)` | The zone of the mask furnished as a room |
84
+ | `furnish(url=..., mask=..., furniture_id=...)` | One piece of furniture in the zone (`style_id` optional) |
85
+ | `sunshine(url=..., sky_id="sunny")` | A blue sky and the matching light (also `light_projection`, `pool_light`, `add_leafs`) |
86
+ | `creative_redesign(url=..., room_id=..., style_id=...)` | The room redesigned in a style (`preserve_floor` to keep the floor) |
87
+ | `surfaces(url=..., surface="walls", wall_type=...)` | Walls repainted (`"custom"` with `custom_wall_color`, `preserve_ceiling`) |
88
+ | `surfaces(url=..., surface="floor", floor_type=...)` | Floor changed (`include_baseboard`) |
89
+ | `surfaces(url=..., surface="finish", finish_id=...)` | A finish applied: clean floor, clean pool, mowed lawn... |
90
+ | `upscale(url=..., resolution="4k")` | Enlarged to about 4 (`"2k"`) or 16 megapixels (`"4k"`, default) |
91
+
92
+ **Masks.** A mask is a black image with the zone painted in white, drawn on the photo. Give its URL, or the image itself in base64: nothing to host.
93
+
94
+ ```python
95
+ from gepetto import mask_from_file
96
+
97
+ job = gepetto.declutter(url=photo_url, mask=mask_from_file("mask.png"))
98
+ ```
99
+
100
+ Every tool also takes:
101
+
102
+ ```python
103
+ gepetto.enhance(
104
+ url=photo_url,
105
+ straighten=True,
106
+ idempotency_key=f"{photo.id}:enhance", # one key per photo and per tool
107
+ timeout=120, # seconds, for this call (default: the client's, 10 minutes)
108
+ )
109
+ ```
110
+
111
+ ## Lists
112
+
113
+ The ids are not guessable: they come from the API.
114
+
115
+ ```python
116
+ gepetto.list_rooms() # room_id, with the modes of each room ("auto": whole room, "zone": with a mask)
117
+ gepetto.list_styles() # style_id
118
+ gepetto.list_furnitures() # furniture_id, grouped by type
119
+ gepetto.list_skies() # sky_id
120
+ gepetto.list_surfaces() # {"walls": [...], "floors": [...], "finishes": [...]}
121
+ ```
122
+
123
+ ## Errors
124
+
125
+ Every error is a `GepettoError`. `code` is stable, for your code; the message says what to do next.
126
+
127
+ ```python
128
+ from gepetto import GepettoError
129
+
130
+ try:
131
+ job = gepetto.furnish(url=photo_url, room_id="bedroom", style_id="modrn")
132
+ except GepettoError as e:
133
+ e.code # "unknown_style"
134
+ e.param # "styleId"
135
+ e.status # 400
136
+ str(e) # No style "modrn". The list is on GET /v2/styles.
137
+ e.job_id # set when a render was started (failed render, timeout)
138
+ ```
139
+
140
+ The codes are listed in the [docs](https://docs.gepettoapp.com) (Errors). The SDK adds `timeout` and `connection_error`.
141
+
142
+ ## Webhooks
143
+
144
+ To not wait for the image in the request, pass `webhook`: the call returns at once with the pending job, and Gepetto sends the finished job to your URL, signed.
145
+
146
+ ```python
147
+ job = gepetto.furnish(url=photo_url, room_id="bedroom", style_id="modern", webhook="https://your-site.com/gepetto")
148
+ # job.status == "pending"
149
+ ```
150
+
151
+ ```python
152
+ from gepetto import verify_webhook
153
+
154
+ # In your webhook route (here Flask). The secret is read from GEPETTO_WEBHOOK_SECRET:
155
+ # it is webhook_secret of gepetto.account(), or `npx @gepetto/cli secret`
156
+ @app.post("/gepetto")
157
+ def gepetto_webhook():
158
+ job = verify_webhook(request.get_data(), request.headers.get("Gepetto-Signature"))
159
+ if job.is_success:
160
+ ... # job.output
161
+ return "", 204
162
+ ```
163
+
164
+ `verify_webhook` raises `invalid_signature` when the request does not come from Gepetto. Give it the raw body, before any JSON decoding.
165
+
166
+ ## Jobs, account
167
+
168
+ ```python
169
+ gepetto.get_job(job_id) # a job, finished or not
170
+ gepetto.wait_for_job(job_id) # waits for a job started with a webhook
171
+ gepetto.list_jobs(status="error", limit=10)
172
+ gepetto.account() # key type, test renders used, webhook secret
173
+ gepetto.usage() # consumption of the current period
174
+ ```
175
+
176
+ ## Options
177
+
178
+ ```python
179
+ Gepetto(
180
+ api_key="...", # default: GEPETTO_API_KEY
181
+ timeout=600, # seconds a call waits for its image, retries included
182
+ max_retries=2, # after a network error, a 429 or a 5xx
183
+ transport=my_send, # your own HTTP layer: (method, url, headers, body, timeout) -> (status, body)
184
+ )
185
+ ```
186
+
187
+ The calls are synchronous. In async code (FastAPI...), run them in a thread: `await asyncio.to_thread(gepetto.furnish, url=...)`.
188
+
189
+ Keep the key on your server: never in a web page or a mobile app.
190
+
191
+ ## About Gepetto
192
+
193
+ Gepetto is the AI photo studio for real estate professionals. From a single photo, it furnishes an empty room, empties a cluttered one, restyles an interior, replaces a grey sky, repaints walls, changes floors, enhances the picture and animates the property on video, in seconds and with no technical skill. Launched in January 2023 in Bordeaux, France, Gepetto is used by more than 1,000 agencies, networks and real estate photographers, on the web, on iPhone and Android, and through this API inside real estate CRMs and platforms.
194
+
195
+ [gepettoapp.com](https://gepettoapp.com) · [API documentation](https://docs.gepettoapp.com) · [TypeScript SDK](https://github.com/Gepetto-AI/gepetto-sdk) · [PHP SDK](https://github.com/Gepetto-AI/gepetto-php) · [CLI](https://github.com/Gepetto-AI/gepetto-cli)
196
+
197
+ ## Changes
198
+
199
+ See [CHANGELOG.md](CHANGELOG.md).
200
+
201
+ ## License
202
+
203
+ MIT
@@ -0,0 +1,176 @@
1
+ # Gepetto Python SDK
2
+
3
+ [![PyPI](https://img.shields.io/pypi/v/gepetto)](https://pypi.org/project/gepetto/) [![Tests](https://github.com/Gepetto-AI/gepetto-python/actions/workflows/tests.yml/badge.svg)](https://github.com/Gepetto-AI/gepetto-python/actions/workflows/tests.yml)
4
+
5
+ The official Python SDK of the [Gepetto API v2](https://docs.gepettoapp.com): real estate photo editing. Enhance a photo, declutter a room, furnish it, change the sky, restyle it, repaint walls and floors, upscale. One call, an image URL in return.
6
+
7
+ ```bash
8
+ pip install gepetto
9
+ ```
10
+
11
+ Python 3.10 or later. No dependency: the standard library is enough. Fully typed.
12
+
13
+ ## Quickstart
14
+
15
+ ```python
16
+ from gepetto import Gepetto
17
+
18
+ gepetto = Gepetto() # reads GEPETTO_API_KEY
19
+
20
+ job = gepetto.furnish(
21
+ url="https://assets.gepettoapp.com/raw-images/b85e2aa5-ac29-44a0-93eb-2de0a40f7905.png",
22
+ room_id="living_room",
23
+ style_id="scandinave",
24
+ )
25
+
26
+ print(job.output) # https://assets.gepettoapp.com/api/v2/jobs/.../output.jpg
27
+ ```
28
+
29
+ No key yet? A free test key (200 real renders, no watermark) in two commands:
30
+
31
+ ```bash
32
+ npx @gepetto/cli login # opens a page: check the code, click "Authorize"
33
+ npx @gepetto/cli init # writes GEPETTO_API_KEY to .env
34
+ ```
35
+
36
+ The key can also be given directly: `Gepetto("test_...")`, or `Gepetto(api_key=..., timeout=120)`.
37
+
38
+ ## What you get
39
+
40
+ - **The method waits for the image.** Each tool returns the finished `Job`, whose `output` is the image URL. A failed render raises a `GepettoError`, and is never charged.
41
+ - **Your editor knows the parameters.** Every tool takes keyword arguments with types: completion in VS Code and PyCharm, and mypy or Pyright catch a typo before the API does.
42
+ - **Retries are safe.** Every render is sent with an idempotency key (yours, or one generated). A network error, a `429` or a `5xx` is retried with the same key: a render is never started, nor billed, twice.
43
+ - **Long renders just work.** If the connection drops while the image is being made, the SDK picks up the same job and waits for it.
44
+ - **The names are those of the API, in snake_case.** `room_id` is `roomId` in the [docs](https://docs.gepettoapp.com): same fields, same ids, same error codes.
45
+
46
+ ## Tools
47
+
48
+ The `url` of every tool is a public http(s) URL of a JPEG, PNG, WebP or HEIC image: upload the photo to your own storage first. The output URL is public too; copy the image if you keep it.
49
+
50
+ | Method | What it does |
51
+ | --- | --- |
52
+ | `enhance(url=..., straighten=True)` | Light and colours corrected at the size of the photo, nothing redrawn |
53
+ | `declutter(url=..., keep_fireplace=True)` | The whole room emptied (also `keep_kitchen`, `keep_bathroom`) |
54
+ | `declutter(url=..., mask=...)` | What the mask covers removed |
55
+ | `furnish(url=..., room_id=..., style_id=...)` | The whole room furnished |
56
+ | `furnish(url=..., mask=..., room_id=..., style_id=...)` | The zone of the mask furnished as a room |
57
+ | `furnish(url=..., mask=..., furniture_id=...)` | One piece of furniture in the zone (`style_id` optional) |
58
+ | `sunshine(url=..., sky_id="sunny")` | A blue sky and the matching light (also `light_projection`, `pool_light`, `add_leafs`) |
59
+ | `creative_redesign(url=..., room_id=..., style_id=...)` | The room redesigned in a style (`preserve_floor` to keep the floor) |
60
+ | `surfaces(url=..., surface="walls", wall_type=...)` | Walls repainted (`"custom"` with `custom_wall_color`, `preserve_ceiling`) |
61
+ | `surfaces(url=..., surface="floor", floor_type=...)` | Floor changed (`include_baseboard`) |
62
+ | `surfaces(url=..., surface="finish", finish_id=...)` | A finish applied: clean floor, clean pool, mowed lawn... |
63
+ | `upscale(url=..., resolution="4k")` | Enlarged to about 4 (`"2k"`) or 16 megapixels (`"4k"`, default) |
64
+
65
+ **Masks.** A mask is a black image with the zone painted in white, drawn on the photo. Give its URL, or the image itself in base64: nothing to host.
66
+
67
+ ```python
68
+ from gepetto import mask_from_file
69
+
70
+ job = gepetto.declutter(url=photo_url, mask=mask_from_file("mask.png"))
71
+ ```
72
+
73
+ Every tool also takes:
74
+
75
+ ```python
76
+ gepetto.enhance(
77
+ url=photo_url,
78
+ straighten=True,
79
+ idempotency_key=f"{photo.id}:enhance", # one key per photo and per tool
80
+ timeout=120, # seconds, for this call (default: the client's, 10 minutes)
81
+ )
82
+ ```
83
+
84
+ ## Lists
85
+
86
+ The ids are not guessable: they come from the API.
87
+
88
+ ```python
89
+ gepetto.list_rooms() # room_id, with the modes of each room ("auto": whole room, "zone": with a mask)
90
+ gepetto.list_styles() # style_id
91
+ gepetto.list_furnitures() # furniture_id, grouped by type
92
+ gepetto.list_skies() # sky_id
93
+ gepetto.list_surfaces() # {"walls": [...], "floors": [...], "finishes": [...]}
94
+ ```
95
+
96
+ ## Errors
97
+
98
+ Every error is a `GepettoError`. `code` is stable, for your code; the message says what to do next.
99
+
100
+ ```python
101
+ from gepetto import GepettoError
102
+
103
+ try:
104
+ job = gepetto.furnish(url=photo_url, room_id="bedroom", style_id="modrn")
105
+ except GepettoError as e:
106
+ e.code # "unknown_style"
107
+ e.param # "styleId"
108
+ e.status # 400
109
+ str(e) # No style "modrn". The list is on GET /v2/styles.
110
+ e.job_id # set when a render was started (failed render, timeout)
111
+ ```
112
+
113
+ The codes are listed in the [docs](https://docs.gepettoapp.com) (Errors). The SDK adds `timeout` and `connection_error`.
114
+
115
+ ## Webhooks
116
+
117
+ To not wait for the image in the request, pass `webhook`: the call returns at once with the pending job, and Gepetto sends the finished job to your URL, signed.
118
+
119
+ ```python
120
+ job = gepetto.furnish(url=photo_url, room_id="bedroom", style_id="modern", webhook="https://your-site.com/gepetto")
121
+ # job.status == "pending"
122
+ ```
123
+
124
+ ```python
125
+ from gepetto import verify_webhook
126
+
127
+ # In your webhook route (here Flask). The secret is read from GEPETTO_WEBHOOK_SECRET:
128
+ # it is webhook_secret of gepetto.account(), or `npx @gepetto/cli secret`
129
+ @app.post("/gepetto")
130
+ def gepetto_webhook():
131
+ job = verify_webhook(request.get_data(), request.headers.get("Gepetto-Signature"))
132
+ if job.is_success:
133
+ ... # job.output
134
+ return "", 204
135
+ ```
136
+
137
+ `verify_webhook` raises `invalid_signature` when the request does not come from Gepetto. Give it the raw body, before any JSON decoding.
138
+
139
+ ## Jobs, account
140
+
141
+ ```python
142
+ gepetto.get_job(job_id) # a job, finished or not
143
+ gepetto.wait_for_job(job_id) # waits for a job started with a webhook
144
+ gepetto.list_jobs(status="error", limit=10)
145
+ gepetto.account() # key type, test renders used, webhook secret
146
+ gepetto.usage() # consumption of the current period
147
+ ```
148
+
149
+ ## Options
150
+
151
+ ```python
152
+ Gepetto(
153
+ api_key="...", # default: GEPETTO_API_KEY
154
+ timeout=600, # seconds a call waits for its image, retries included
155
+ max_retries=2, # after a network error, a 429 or a 5xx
156
+ transport=my_send, # your own HTTP layer: (method, url, headers, body, timeout) -> (status, body)
157
+ )
158
+ ```
159
+
160
+ The calls are synchronous. In async code (FastAPI...), run them in a thread: `await asyncio.to_thread(gepetto.furnish, url=...)`.
161
+
162
+ Keep the key on your server: never in a web page or a mobile app.
163
+
164
+ ## About Gepetto
165
+
166
+ Gepetto is the AI photo studio for real estate professionals. From a single photo, it furnishes an empty room, empties a cluttered one, restyles an interior, replaces a grey sky, repaints walls, changes floors, enhances the picture and animates the property on video, in seconds and with no technical skill. Launched in January 2023 in Bordeaux, France, Gepetto is used by more than 1,000 agencies, networks and real estate photographers, on the web, on iPhone and Android, and through this API inside real estate CRMs and platforms.
167
+
168
+ [gepettoapp.com](https://gepettoapp.com) · [API documentation](https://docs.gepettoapp.com) · [TypeScript SDK](https://github.com/Gepetto-AI/gepetto-sdk) · [PHP SDK](https://github.com/Gepetto-AI/gepetto-php) · [CLI](https://github.com/Gepetto-AI/gepetto-cli)
169
+
170
+ ## Changes
171
+
172
+ See [CHANGELOG.md](CHANGELOG.md).
173
+
174
+ ## License
175
+
176
+ MIT
@@ -0,0 +1,51 @@
1
+ [build-system]
2
+ requires = ["hatchling>=1.25"]
3
+ build-backend = "hatchling.build"
4
+
5
+ [project]
6
+ name = "gepetto"
7
+ dynamic = ["version"]
8
+ description = "The official Python SDK of the Gepetto API v2: real estate photo editing. Enhance, declutter, furnish, blue sky, restyle, walls and floors, upscale."
9
+ readme = "README.md"
10
+ license = "MIT"
11
+ license-files = ["LICENSE"]
12
+ requires-python = ">=3.10"
13
+ authors = [{ name = "Gepetto", email = "api@gepettoapp.com" }]
14
+ keywords = ["gepetto", "real estate", "virtual staging", "home staging", "photo editing", "declutter", "api", "sdk"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Programming Language :: Python :: 3 :: Only",
21
+ "Programming Language :: Python :: 3.10",
22
+ "Programming Language :: Python :: 3.11",
23
+ "Programming Language :: Python :: 3.12",
24
+ "Programming Language :: Python :: 3.13",
25
+ "Programming Language :: Python :: 3.14",
26
+ "Topic :: Multimedia :: Graphics",
27
+ "Typing :: Typed",
28
+ ]
29
+ dependencies = []
30
+
31
+ [project.urls]
32
+ Homepage = "https://gepettoapp.com"
33
+ Documentation = "https://docs.gepettoapp.com"
34
+ Source = "https://github.com/Gepetto-AI/gepetto-python"
35
+ Issues = "https://github.com/Gepetto-AI/gepetto-python/issues"
36
+
37
+ [tool.hatch.version]
38
+ path = "src/gepetto/_version.py"
39
+
40
+ [tool.hatch.build.targets.wheel]
41
+ packages = ["src/gepetto"]
42
+
43
+ [tool.hatch.build.targets.sdist]
44
+ include = ["src/gepetto", "README.md", "LICENSE", "CHANGELOG.md"]
45
+
46
+ [tool.pytest.ini_options]
47
+ testpaths = ["tests"]
48
+
49
+ [tool.mypy]
50
+ strict = true
51
+ files = ["src/gepetto"]
@@ -0,0 +1,32 @@
1
+ """The official Python SDK of the Gepetto API v2: real estate photo editing.
2
+
3
+ .. code-block:: python
4
+
5
+ from gepetto import Gepetto
6
+
7
+ gepetto = Gepetto() # reads GEPETTO_API_KEY
8
+ job = gepetto.furnish(url=photo_url, room_id="living_room", style_id="scandinave")
9
+ print(job.output)
10
+ """
11
+
12
+ from ._client import DEFAULT_BASE_URL, Gepetto, mask_from_file
13
+ from ._errors import GepettoError, TransportError
14
+ from ._job import Job, JobError, JobStatus
15
+ from ._transport import Transport, urllib_transport
16
+ from ._version import __version__
17
+ from ._webhook import verify_webhook
18
+
19
+ __all__ = [
20
+ "DEFAULT_BASE_URL",
21
+ "Gepetto",
22
+ "GepettoError",
23
+ "Job",
24
+ "JobError",
25
+ "JobStatus",
26
+ "Transport",
27
+ "TransportError",
28
+ "__version__",
29
+ "mask_from_file",
30
+ "urllib_transport",
31
+ "verify_webhook",
32
+ ]
@@ -0,0 +1,467 @@
1
+ from __future__ import annotations
2
+
3
+ import base64
4
+ import json
5
+ import os
6
+ import random
7
+ import time
8
+ import uuid
9
+ from pathlib import Path
10
+ from typing import Any, Literal
11
+ from urllib.parse import quote, urlencode
12
+
13
+ from ._errors import GepettoError, TransportError
14
+ from ._job import Job, JobStatus
15
+ from ._transport import Transport, urllib_transport
16
+ from ._version import __version__
17
+
18
+ DEFAULT_BASE_URL = "https://europe-west1-gepettoai.cloudfunctions.net/v2"
19
+ # Seconds. A render is stopped by the API after 450 s: 10 minutes covers it, retries included.
20
+ DEFAULT_TIMEOUT = 600.0
21
+ DEFAULT_MAX_RETRIES = 2
22
+ # Seconds between two checks of a running job
23
+ POLL_INTERVAL = 2.5
24
+
25
+
26
+ class Gepetto:
27
+ """The client of the Gepetto API v2: real estate photo editing.
28
+
29
+ .. code-block:: python
30
+
31
+ from gepetto import Gepetto
32
+
33
+ gepetto = Gepetto() # reads GEPETTO_API_KEY
34
+
35
+ job = gepetto.furnish(
36
+ url="https://example.com/empty-living-room.jpg",
37
+ room_id="living_room",
38
+ style_id="scandinave",
39
+ )
40
+ print(job.output) # the URL of the image
41
+
42
+ Each tool waits for the image and returns the finished Job, or raises a GepettoError.
43
+ With ``webhook=...``, it returns at once with the pending job instead.
44
+
45
+ The parameters are those of the API, in snake_case: ``room_id`` is ``roomId`` in the docs.
46
+ """
47
+
48
+ def __init__(
49
+ self,
50
+ api_key: str | None = None,
51
+ *,
52
+ base_url: str = DEFAULT_BASE_URL,
53
+ timeout: float = DEFAULT_TIMEOUT,
54
+ max_retries: int = DEFAULT_MAX_RETRIES,
55
+ transport: Transport | None = None,
56
+ ) -> None:
57
+ """
58
+ :param api_key: Your API key. By default GEPETTO_API_KEY.
59
+ :param timeout: Seconds a call waits for its image, retries included (each call can set its own).
60
+ :param max_retries: Retries after a network error, a 429 or a 5xx.
61
+ :param transport: Your own HTTP layer (see ``gepetto.Transport``), for tests or another library.
62
+ """
63
+ key = (api_key or os.environ.get("GEPETTO_API_KEY") or "").strip()
64
+ if not key:
65
+ raise GepettoError(
66
+ "missing_api_key",
67
+ "No API key: pass it to Gepetto(...) or set GEPETTO_API_KEY. "
68
+ "Get a free test key with `npx @gepetto/cli login` then `npx @gepetto/cli init`.",
69
+ )
70
+ self._api_key = key
71
+ self.base_url = base_url.rstrip("/")
72
+ self.timeout = timeout
73
+ self.max_retries = max(0, max_retries)
74
+ self._transport: Transport = transport or urllib_transport
75
+
76
+ @property
77
+ def is_test(self) -> bool:
78
+ """A test key (``test_...``): free renders, 200 per account."""
79
+ return self._api_key.startswith("test_")
80
+
81
+ # --- Tools ----------------------------------------------------------------------------------------------------
82
+ # Every tool also takes, optionally:
83
+ # idempotency_key="photo-42:furnish" one key per photo and per tool: a retry never renders, nor bills, twice
84
+ # timeout=120 seconds, for this call
85
+ # The url of the photo is a public http(s) URL: upload the photo to your own storage first.
86
+
87
+ def declutter(
88
+ self,
89
+ *,
90
+ url: str,
91
+ mask: str | None = None,
92
+ keep_kitchen: bool | None = None,
93
+ keep_bathroom: bool | None = None,
94
+ keep_fireplace: bool | None = None,
95
+ webhook: str | None = None,
96
+ idempotency_key: str | None = None,
97
+ timeout: float | None = None,
98
+ ) -> Job:
99
+ """Without a mask, the whole room is emptied; with a mask, only what is painted in white is removed."""
100
+ return self._render(
101
+ "/declutter",
102
+ {
103
+ "url": url,
104
+ "mask": mask,
105
+ "keepKitchen": keep_kitchen,
106
+ "keepBathroom": keep_bathroom,
107
+ "keepFireplace": keep_fireplace,
108
+ "webhook": webhook,
109
+ },
110
+ idempotency_key,
111
+ timeout,
112
+ )
113
+
114
+ def furnish(
115
+ self,
116
+ *,
117
+ url: str,
118
+ room_id: str | None = None,
119
+ style_id: str | None = None,
120
+ mask: str | None = None,
121
+ furniture_id: str | None = None,
122
+ webhook: str | None = None,
123
+ idempotency_key: str | None = None,
124
+ timeout: float | None = None,
125
+ ) -> Job:
126
+ """Without a mask, the whole room is furnished (room_id and style_id). With a mask, the painted zone is
127
+ furnished as a room (room_id and style_id), or with one piece of furniture (furniture_id, style_id optional)."""
128
+ return self._render(
129
+ "/furnish",
130
+ {
131
+ "url": url,
132
+ "roomId": room_id,
133
+ "styleId": style_id,
134
+ "mask": mask,
135
+ "furnitureId": furniture_id,
136
+ "webhook": webhook,
137
+ },
138
+ idempotency_key,
139
+ timeout,
140
+ )
141
+
142
+ def sunshine(
143
+ self,
144
+ *,
145
+ url: str,
146
+ sky_id: str,
147
+ light_projection: bool | None = None,
148
+ pool_light: bool | None = None,
149
+ add_leafs: bool | None = None,
150
+ webhook: str | None = None,
151
+ idempotency_key: str | None = None,
152
+ timeout: float | None = None,
153
+ ) -> Job:
154
+ """A blue sky and the matching light, outside or through the windows."""
155
+ return self._render(
156
+ "/sunshine",
157
+ {
158
+ "url": url,
159
+ "skyId": sky_id,
160
+ "lightProjection": light_projection,
161
+ "poolLight": pool_light,
162
+ "addLeafs": add_leafs,
163
+ "webhook": webhook,
164
+ },
165
+ idempotency_key,
166
+ timeout,
167
+ )
168
+
169
+ def creative_redesign(
170
+ self,
171
+ *,
172
+ url: str,
173
+ room_id: str,
174
+ style_id: str,
175
+ preserve_floor: bool | None = None,
176
+ webhook: str | None = None,
177
+ idempotency_key: str | None = None,
178
+ timeout: float | None = None,
179
+ ) -> Job:
180
+ """The room redesigned in a style: furniture, materials and colours change, the architecture stays."""
181
+ return self._render(
182
+ "/creative-redesign",
183
+ {
184
+ "url": url,
185
+ "roomId": room_id,
186
+ "styleId": style_id,
187
+ "preserveFloor": preserve_floor,
188
+ "webhook": webhook,
189
+ },
190
+ idempotency_key,
191
+ timeout,
192
+ )
193
+
194
+ def surfaces(
195
+ self,
196
+ *,
197
+ url: str,
198
+ surface: Literal["walls", "floor", "finish"],
199
+ wall_type: str | None = None,
200
+ custom_wall_color: str | None = None,
201
+ preserve_ceiling: bool | None = None,
202
+ floor_type: str | None = None,
203
+ include_baseboard: bool | None = None,
204
+ finish_id: str | None = None,
205
+ webhook: str | None = None,
206
+ idempotency_key: str | None = None,
207
+ timeout: float | None = None,
208
+ ) -> Job:
209
+ """One surface per call: "walls" (wall_type, or "custom" with custom_wall_color), "floor" (floor_type)
210
+ or "finish" (finish_id)."""
211
+ return self._render(
212
+ "/surfaces",
213
+ {
214
+ "url": url,
215
+ "surface": surface,
216
+ "wallType": wall_type,
217
+ "customWallColor": custom_wall_color,
218
+ "preserveCeiling": preserve_ceiling,
219
+ "floorType": floor_type,
220
+ "includeBaseboard": include_baseboard,
221
+ "finishId": finish_id,
222
+ "webhook": webhook,
223
+ },
224
+ idempotency_key,
225
+ timeout,
226
+ )
227
+
228
+ def enhance(
229
+ self,
230
+ *,
231
+ url: str,
232
+ straighten: bool | None = None,
233
+ webhook: str | None = None,
234
+ idempotency_key: str | None = None,
235
+ timeout: float | None = None,
236
+ ) -> Job:
237
+ """Light and colours corrected, nothing redrawn, at the size of the photo. straighten: converging verticals."""
238
+ return self._render(
239
+ "/enhance", {"url": url, "straighten": straighten, "webhook": webhook}, idempotency_key, timeout
240
+ )
241
+
242
+ def upscale(
243
+ self,
244
+ *,
245
+ url: str,
246
+ resolution: Literal["2k", "4k"] | None = None,
247
+ webhook: str | None = None,
248
+ idempotency_key: str | None = None,
249
+ timeout: float | None = None,
250
+ ) -> Job:
251
+ """Enlarged to about 4 megapixels ("2k") or 16 megapixels ("4k", the default)."""
252
+ return self._render(
253
+ "/upscale", {"url": url, "resolution": resolution, "webhook": webhook}, idempotency_key, timeout
254
+ )
255
+
256
+ # --- Jobs -----------------------------------------------------------------------------------------------------
257
+
258
+ def get_job(self, job_id: str) -> Job:
259
+ """A job, finished or not."""
260
+ return Job.from_dict(self._get(f"/job/{quote(job_id, safe='')}"))
261
+
262
+ def wait_for_job(self, job_id: str, *, timeout: float | None = None) -> Job:
263
+ """Waits for a job started with a webhook, or after a timeout. Returns it once its image is ready."""
264
+ deadline = time.monotonic() + (timeout if timeout is not None else self.timeout)
265
+ return _finished(self._poll(job_id, deadline))
266
+
267
+ def list_jobs(self, *, status: JobStatus | None = None, limit: int | None = None) -> list[Job]:
268
+ """The latest jobs of the key, newest first."""
269
+ query = urlencode({k: v for k, v in {"status": status, "limit": limit}.items() if v is not None})
270
+ jobs = self._get("/jobs" + (f"?{query}" if query else ""))
271
+ return [Job.from_dict(job) for job in jobs]
272
+
273
+ # --- Lists: the valid ids of the parameters -------------------------------------------------------------------
274
+
275
+ def list_rooms(self) -> list[dict[str, Any]]:
276
+ """room_id, with the modes of each room ("auto": whole room, "zone": with a mask)."""
277
+ return self._get("/rooms") # type: ignore[no-any-return]
278
+
279
+ def list_styles(self) -> list[dict[str, Any]]:
280
+ """style_id."""
281
+ return self._get("/styles") # type: ignore[no-any-return]
282
+
283
+ def list_furnitures(self) -> dict[str, list[dict[str, Any]]]:
284
+ """furniture_id, grouped by type."""
285
+ return self._get("/furnitures") # type: ignore[no-any-return]
286
+
287
+ def list_skies(self) -> list[dict[str, Any]]:
288
+ """sky_id."""
289
+ return self._get("/skies") # type: ignore[no-any-return]
290
+
291
+ def list_surfaces(self) -> dict[str, list[dict[str, Any]]]:
292
+ """wall_type, floor_type and finish_id: {"walls": [...], "floors": [...], "finishes": [...]}."""
293
+ return self._get("/surfaces") # type: ignore[no-any-return]
294
+
295
+ # --- Account --------------------------------------------------------------------------------------------------
296
+
297
+ def account(self) -> dict[str, Any]:
298
+ """The key type, the test renders used, the webhook secret..."""
299
+ return self._get("/account") # type: ignore[no-any-return]
300
+
301
+ def usage(self) -> dict[str, Any]:
302
+ """The consumption of the current billing period."""
303
+ return self._get("/usage") # type: ignore[no-any-return]
304
+
305
+ # --- Internals ------------------------------------------------------------------------------------------------
306
+
307
+ def _render(
308
+ self, path: str, params: dict[str, Any], idempotency_key: str | None, timeout: float | None
309
+ ) -> Job:
310
+ body = {name: value for name, value in params.items() if value is not None}
311
+ deadline = time.monotonic() + (timeout if timeout is not None else self.timeout)
312
+
313
+ # The same key on every attempt: a retry answers the job already created, never a second render (nor a
314
+ # second charge). It also covers a connection dropped while the render runs: the retry gets the running
315
+ # job, which is then followed with GET /job/{id}.
316
+ key = idempotency_key or str(uuid.uuid4())
317
+
318
+ status, data = self._send("POST", path, body, key, deadline, retry_connection=True)
319
+ job = Job.from_dict(_json(status, data))
320
+ if "webhook" in body:
321
+ return job
322
+ if not job.is_finished:
323
+ job = self._poll(job.id, deadline)
324
+ return _finished(job)
325
+
326
+ def _get(self, path: str) -> Any:
327
+ status, data = self._send("GET", path, None, None, time.monotonic() + self.timeout)
328
+ return _json(status, data)
329
+
330
+ def _poll(self, job_id: str, deadline: float) -> Job:
331
+ while True:
332
+ status, data = self._send("GET", f"/job/{quote(job_id, safe='')}", None, None, deadline)
333
+ job = Job.from_dict(_json(status, data))
334
+ if job.is_finished:
335
+ return job
336
+ if time.monotonic() + POLL_INTERVAL >= deadline:
337
+ raise GepettoError(
338
+ "timeout",
339
+ f"Job {job_id} is still {job.status}: stopped waiting (timeout). It goes on: "
340
+ f"follow it with get_job('{job_id}') or wait_for_job('{job_id}').",
341
+ job_id=job_id,
342
+ job=job,
343
+ )
344
+ time.sleep(POLL_INTERVAL)
345
+
346
+ def _send(
347
+ self,
348
+ method: str,
349
+ path: str,
350
+ body: dict[str, Any] | None,
351
+ idempotency_key: str | None,
352
+ deadline: float,
353
+ *,
354
+ retry_connection: bool = False,
355
+ ) -> tuple[int, Any]:
356
+ """Sends a request, with retries after a network error, a 429 or a 5xx (a POST only with an idempotency key)."""
357
+ retryable = method == "GET" or idempotency_key is not None
358
+ headers = {
359
+ "Authorization": f"Bearer {self._api_key}",
360
+ "Accept": "application/json",
361
+ "User-Agent": f"gepetto-python/{__version__}",
362
+ }
363
+ if body is not None:
364
+ headers["Content-Type"] = "application/json"
365
+ if idempotency_key is not None:
366
+ headers["Idempotency-Key"] = idempotency_key
367
+ payload = None if body is None else json.dumps(body).encode()
368
+
369
+ attempt = 0
370
+ while True:
371
+ remaining = deadline - time.monotonic()
372
+ if remaining <= 0:
373
+ raise _timeout_error()
374
+ try:
375
+ status, raw = self._transport(method, self.base_url + path, headers, payload, remaining)
376
+ except TransportError as error:
377
+ if error.timed_out:
378
+ raise _timeout_error() from error
379
+ max_attempts = max(self.max_retries, 2) if retry_connection else self.max_retries
380
+ if retryable and attempt < max_attempts and time.monotonic() < deadline:
381
+ _backoff(attempt)
382
+ attempt += 1
383
+ continue
384
+ hint = (
385
+ f" Retry with the same idempotency_key ({idempotency_key}): a render already started is not run twice."
386
+ if idempotency_key
387
+ else ""
388
+ )
389
+ raise GepettoError("connection_error", f"Could not reach the Gepetto API ({error}).{hint}") from error
390
+
391
+ try:
392
+ data = json.loads(raw) if raw else None
393
+ except ValueError:
394
+ data = _NOT_JSON
395
+
396
+ # 502 is a render that failed: it is answered, not retried
397
+ transient = status == 429 or (status >= 500 and status != 502)
398
+ if transient and retryable and attempt < self.max_retries and time.monotonic() < deadline:
399
+ _backoff(attempt)
400
+ attempt += 1
401
+ continue
402
+ return status, data
403
+
404
+
405
+ # --- Helpers --------------------------------------------------------------------------------------------------------
406
+
407
+
408
+ def mask_from_file(path: str | os.PathLike[str]) -> str:
409
+ """A local image as a base64 data URL, to send as a ``mask`` without hosting it (PNG, JPEG or WebP, 5 MB at most).
410
+ A mask is a black image with the zone painted in white, at the proportions of the photo."""
411
+ try:
412
+ data = Path(path).read_bytes()
413
+ except OSError as error:
414
+ raise GepettoError("invalid_parameter", f"Could not read the mask file {path}.") from error
415
+ if data.startswith(b"\x89PNG"):
416
+ kind = "image/png"
417
+ elif data.startswith(b"\xff\xd8"):
418
+ kind = "image/jpeg"
419
+ elif data[:4] == b"RIFF" and data[8:12] == b"WEBP":
420
+ kind = "image/webp"
421
+ else:
422
+ raise GepettoError("invalid_parameter", f"The mask {path} must be a PNG, JPEG or WebP image.")
423
+ return f"data:{kind};base64," + base64.b64encode(data).decode()
424
+
425
+
426
+ _NOT_JSON = object()
427
+
428
+
429
+ def _json(status: int, data: Any) -> Any:
430
+ """The body of a successful answer; else the error the API sent."""
431
+ if 200 <= status < 300:
432
+ if data is _NOT_JSON or data is None:
433
+ raise GepettoError("invalid_response", "The API answered something that is not JSON.", status=status)
434
+ return data
435
+ error = data if isinstance(data, dict) else {}
436
+ raise GepettoError(
437
+ str(error.get("code") or ("rate_limited" if status == 429 else "invalid_response")),
438
+ str(error.get("message") or f"The API answered HTTP {status}."),
439
+ status=status,
440
+ param=error.get("param"),
441
+ # A render that failed during a synchronous call (502) carries its job id
442
+ job_id=error.get("id"),
443
+ )
444
+
445
+
446
+ def _finished(job: Job) -> Job:
447
+ """The job, if its image is ready; else its error. A failed render is never charged."""
448
+ if job.is_success:
449
+ return job
450
+ raise GepettoError(
451
+ job.error.code if job.error else "render_failed",
452
+ job.error.message if job.error else "The render failed. You were not charged. Try again.",
453
+ job_id=job.id,
454
+ job=job,
455
+ )
456
+
457
+
458
+ def _backoff(attempt: int) -> None:
459
+ """Waits 1 s, 2 s, 4 s... (8 s at most), with a little jitter."""
460
+ time.sleep(min(8, 2**attempt) * (0.8 + random.random() * 0.4))
461
+
462
+
463
+ def _timeout_error() -> GepettoError:
464
+ return GepettoError(
465
+ "timeout",
466
+ "The call took longer than its timeout. A render already started goes on: find it with list_jobs().",
467
+ )
@@ -0,0 +1,56 @@
1
+ from __future__ import annotations
2
+
3
+ from typing import TYPE_CHECKING
4
+
5
+ if TYPE_CHECKING:
6
+ from ._job import Job
7
+
8
+
9
+ class GepettoError(Exception):
10
+ """Every error of the SDK. ``code`` is stable, for your code (``unknown_room``, ``test_limit_reached``...);
11
+ the message says what to do next, for a person.
12
+
13
+ .. code-block:: python
14
+
15
+ try:
16
+ job = gepetto.furnish(url=photo_url, room_id="bedroom", style_id="modrn")
17
+ except GepettoError as e:
18
+ e.code # "unknown_style"
19
+ e.param # "styleId"
20
+ e.status # 400
21
+ str(e) # No style "modrn". The list is on GET /v2/styles.
22
+ """
23
+
24
+ def __init__(
25
+ self,
26
+ code: str,
27
+ message: str,
28
+ *,
29
+ status: int | None = None,
30
+ param: str | None = None,
31
+ job_id: str | None = None,
32
+ job: Job | None = None,
33
+ ) -> None:
34
+ super().__init__(message)
35
+ self.code = code
36
+ """The API's error code, such as ``invalid_parameter``, or ``timeout`` and ``connection_error`` from the SDK."""
37
+ self.message = message
38
+ self.status = status
39
+ """The HTTP status, None when the API was not reached."""
40
+ self.param = param
41
+ """The parameter the error is about, such as ``roomId``."""
42
+ self.job_id = job_id
43
+ """The job concerned, when a render was started: follow it with get_job()."""
44
+ self.job = job
45
+ """The failed or unfinished job, when there is one."""
46
+
47
+ def __repr__(self) -> str:
48
+ return f"GepettoError(code={self.code!r}, status={self.status!r}, message={self.message!r})"
49
+
50
+
51
+ class TransportError(Exception):
52
+ """The API could not be reached, or did not answer in time. Raised by a transport."""
53
+
54
+ def __init__(self, message: str, *, timed_out: bool = False) -> None:
55
+ super().__init__(message)
56
+ self.timed_out = timed_out
@@ -0,0 +1,60 @@
1
+ from __future__ import annotations
2
+
3
+ from dataclasses import dataclass
4
+ from typing import Any, Literal, Mapping
5
+
6
+ JobStatus = Literal["pending", "processing", "success", "error"]
7
+
8
+
9
+ @dataclass(frozen=True)
10
+ class JobError:
11
+ code: str
12
+ message: str
13
+
14
+
15
+ @dataclass(frozen=True)
16
+ class Job:
17
+ """A render. A tool of the client returns it once the image is ready: ``output`` is then its public URL."""
18
+
19
+ id: str
20
+ status: str
21
+ """``pending``, ``processing``, ``success`` or ``error``."""
22
+ tool: str
23
+ """``declutter``, ``furnish``, ``sunshine``, ``creative-redesign``, ``surfaces``, ``enhance`` or ``upscale``."""
24
+ mode: str | None
25
+ """declutter and furnish: ``auto`` or ``zone``; sunshine: the sky id; surfaces: ``walls``, ``floor`` or ``finish``;
26
+ enhance: ``straighten`` or None; upscale: ``2k`` or ``4k``; creative-redesign: None."""
27
+ output: str | None
28
+ """The image, once ``status`` is ``success``. A public URL: copy the image to your storage if you keep it."""
29
+ error: JobError | None
30
+ price_cents: int
31
+ """Price in euro cents (0 with a test key; charged only on success)."""
32
+ test: bool
33
+ created_at: str | None
34
+ finished_at: str | None
35
+
36
+ @classmethod
37
+ def from_dict(cls, data: Mapping[str, Any]) -> Job:
38
+ """A job as the API sends it."""
39
+ error = data.get("error")
40
+ return cls(
41
+ id=str(data.get("id", "")),
42
+ status=str(data.get("status", "")),
43
+ tool=str(data.get("tool", "")),
44
+ mode=data.get("mode"),
45
+ output=data.get("output"),
46
+ error=JobError(str(error.get("code", "")), str(error.get("message", ""))) if isinstance(error, dict) else None,
47
+ price_cents=int(data.get("priceCents") or 0),
48
+ test=bool(data.get("test", False)),
49
+ created_at=data.get("createdAt"),
50
+ finished_at=data.get("finishedAt"),
51
+ )
52
+
53
+ @property
54
+ def is_finished(self) -> bool:
55
+ """Done, one way or the other: ``success`` or ``error``."""
56
+ return self.status in ("success", "error")
57
+
58
+ @property
59
+ def is_success(self) -> bool:
60
+ return self.status == "success" and self.output is not None
@@ -0,0 +1,39 @@
1
+ from __future__ import annotations
2
+
3
+ import socket
4
+ import urllib.error
5
+ import urllib.request
6
+ from typing import Mapping, Protocol
7
+
8
+ from ._errors import TransportError
9
+
10
+
11
+ class Transport(Protocol):
12
+ """Sends one HTTP request. Pass your own to ``Gepetto(transport=...)`` for tests or another HTTP library.
13
+
14
+ Returns the HTTP status and the body. Raises TransportError when the API could not be reached in time.
15
+ """
16
+
17
+ def __call__(
18
+ self, method: str, url: str, headers: Mapping[str, str], body: bytes | None, timeout: float
19
+ ) -> tuple[int, bytes]: ...
20
+
21
+
22
+ def urllib_transport(
23
+ method: str, url: str, headers: Mapping[str, str], body: bytes | None, timeout: float
24
+ ) -> tuple[int, bytes]:
25
+ """The default transport: the standard library, nothing to install."""
26
+ request = urllib.request.Request(url, data=body, headers=dict(headers), method=method)
27
+ try:
28
+ with urllib.request.urlopen(request, timeout=timeout) as response:
29
+ return response.status, response.read()
30
+ except urllib.error.HTTPError as error:
31
+ # An error status is an answer of the API, not a transport failure
32
+ return error.code, error.read()
33
+ except (socket.timeout, TimeoutError) as error:
34
+ raise TransportError("timed out", timed_out=True) from error
35
+ except urllib.error.URLError as error:
36
+ timed_out = isinstance(error.reason, (socket.timeout, TimeoutError))
37
+ raise TransportError(str(error.reason), timed_out=timed_out) from error
38
+ except OSError as error:
39
+ raise TransportError(str(error)) from error
@@ -0,0 +1 @@
1
+ __version__ = "0.1.0"
@@ -0,0 +1,62 @@
1
+ from __future__ import annotations
2
+
3
+ import hashlib
4
+ import hmac
5
+ import json
6
+ import os
7
+ import time
8
+
9
+ from ._errors import GepettoError
10
+ from ._job import Job
11
+
12
+
13
+ def verify_webhook(
14
+ body: bytes | str,
15
+ signature: str | None,
16
+ secret: str | None = None,
17
+ *,
18
+ tolerance: int = 300,
19
+ ) -> Job:
20
+ """Checks the ``Gepetto-Signature`` header of a webhook and returns its job.
21
+
22
+ :param body: The raw body of the request, before any JSON decoding.
23
+ :param signature: The ``Gepetto-Signature`` header.
24
+ :param secret: Your webhook secret (``webhook_secret`` of ``account()``, or ``npx @gepetto/cli secret``);
25
+ by default GEPETTO_WEBHOOK_SECRET. Test and live keys have different secrets.
26
+ :param tolerance: Seconds: an older signature is refused.
27
+ :raises GepettoError: ``invalid_signature`` when the webhook does not come from Gepetto.
28
+ """
29
+ secret = secret or os.environ.get("GEPETTO_WEBHOOK_SECRET")
30
+ if not secret:
31
+ raise GepettoError(
32
+ "invalid_parameter",
33
+ "No webhook secret: pass it to verify_webhook(), or set GEPETTO_WEBHOOK_SECRET. "
34
+ "It is webhook_secret in gepetto.account(), or `npx @gepetto/cli secret`.",
35
+ )
36
+ if not signature:
37
+ raise _invalid("no Gepetto-Signature header")
38
+
39
+ # The header is "t=<unix time>,v1=<hex>"
40
+ parts = dict(part.strip().split("=", 1) for part in signature.split(",") if "=" in part)
41
+ timestamp, given = parts.get("t", ""), parts.get("v1", "")
42
+ if not timestamp.isdigit() or not given:
43
+ raise _invalid("malformed header")
44
+ if abs(time.time() - int(timestamp)) > tolerance:
45
+ raise _invalid("timestamp too old")
46
+
47
+ raw = body.encode() if isinstance(body, str) else body
48
+ expected = hmac.new(secret.encode(), timestamp.encode() + b"." + raw, hashlib.sha256).hexdigest()
49
+ if not hmac.compare_digest(expected, given):
50
+ raise _invalid("signature mismatch (wrong secret, or the body was modified)")
51
+
52
+ try:
53
+ data = json.loads(raw)
54
+ except ValueError:
55
+ raise _invalid("the body is not JSON") from None
56
+ if not isinstance(data, dict):
57
+ raise _invalid("the body is not a job")
58
+ return Job.from_dict(data)
59
+
60
+
61
+ def _invalid(why: str) -> GepettoError:
62
+ return GepettoError("invalid_signature", f"Invalid webhook signature: {why}.")
File without changes