propermesh 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,36 @@
1
+ # Thisll just be a directory where I throw scrap code in that i might want to reference at some
2
+ # point but isnt worth committing
3
+ scrap
4
+
5
+ personal_notes/*
6
+
7
+ __pycache__
8
+
9
+ # This can be a good place to store test mesh files that you dont want to commit to the repo
10
+ testdata/private/*
11
+ testdata/parts/auto-orient-tests/output/*
12
+
13
+ .env*
14
+
15
+ # The provider lock file is committed so every machine and CI use the same provider versions
16
+ *terraform.tfstate*
17
+ .terraform
18
+
19
+ # runner-* is my convention for scripts that would only be used on my local machine that set up an
20
+ # environment before calling out to another script that would normally be executed by a CICD runner
21
+ # or something
22
+ etc/**/runner-*
23
+
24
+ .propermesh*
25
+
26
+ tmp/*
27
+
28
+ # Committed, non-secret local test config
29
+ !.env.test
30
+
31
+ # Saved terraform plans contain secrets
32
+ infrastructure/tfplan
33
+
34
+ # Claude Code: per-machine settings and its own worktrees
35
+ .claude/settings.local.json
36
+ .claude/worktrees/
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Propermesh
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.
@@ -0,0 +1,133 @@
1
+ Metadata-Version: 2.5
2
+ Name: propermesh
3
+ Version: 0.1.0
4
+ Summary: Python client for the Propermesh 3D printing analysis API
5
+ Project-URL: Homepage, https://propermesh.com
6
+ Project-URL: Documentation, https://propermesh.com/docs
7
+ License-Expression: MIT
8
+ License-File: LICENSE
9
+ Keywords: 3d-printing,api,mesh,overhang,stl,thickness
10
+ Classifier: Programming Language :: Python :: 3
11
+ Classifier: Topic :: Multimedia :: Graphics :: 3D Modeling
12
+ Requires-Python: >=3.9
13
+ Requires-Dist: requests>=2
14
+ Description-Content-Type: text/markdown
15
+
16
+ # Propermesh Python SDK
17
+
18
+ A client for the [Propermesh](https://propermesh.com) API: check 3D models for thin walls, overhangs
19
+ and broken geometry before you print them, and slice them to G-code. Get free API keys at
20
+ [propermesh.com/account](https://propermesh.com/account).
21
+
22
+ ```sh
23
+ pip install propermesh
24
+ ```
25
+
26
+ ```python
27
+ import os
28
+ from propermesh import ProperMeshClient, SliceSettings, Units
29
+
30
+ client = ProperMeshClient(os.environ["PROPERMESH_ACCESS_KEY"], os.environ["PROPERMESH_SECRET_KEY"])
31
+
32
+ part_id = client.upload_part_file("bracket.stl", Units.mm)
33
+
34
+ # Flag anything thinner than 2 mm
35
+ job = client.start_thickness_analysis_job(part_id, threshold=2).json()
36
+ result = client.wait_for_thickness_analysis_job_to_complete(job["id"]).json()
37
+ print(result["status"], result["is_thin"], result["thin_surface_area"])
38
+ ```
39
+
40
+ ### Waiting for a job
41
+
42
+ Every job type has a `run_<job>` helper that starts the job, waits for it and returns the finished job.
43
+ If the job fails or is cancelled it raises `ProperMeshJobFailedError` (`.job_type`, `.job_id`, `.status`,
44
+ `.failure_reason`), so you don't check `status` yourself:
45
+
46
+ ```python
47
+ from propermesh import ProperMeshJobFailedError
48
+
49
+ try:
50
+ job = client.run_thickness_analysis(part_id, threshold=2)
51
+ print(job["is_thin"])
52
+ except ProperMeshJobFailedError as e:
53
+ print(e.status, e.failure_reason)
54
+ ```
55
+
56
+ The helpers are `run_geometry_analysis`, `run_thickness_analysis`, `run_overhang_analysis`,
57
+ `run_orientation`, `run_repair`, `run_transform`, `run_slice` and `run_quote`, with the arguments of
58
+ their `start_*_job` methods. `ProperMeshAPIError` still covers 4xx and 5xx responses.
59
+
60
+ A plan runs a few jobs at once (one on Free). Start more and the `start_*_job` calls wait for a free
61
+ slot instead of raising: they retry the "too many jobs running" 429 for up to 10 minutes. Change that
62
+ with `ProperMeshClient(..., wait_for_job_slot=120)` (seconds), or turn it off with
63
+ `wait_for_job_slot=None` and the 429 raises `ProperMeshAPIError` (`.retry_after` says how long to wait).
64
+ A limit on parts or jobs per month always raises right away.
65
+
66
+ Slice with a built-in PrusaSlicer printer (Prusa, Creality, Elegoo), optionally overriding a few
67
+ settings for this slice:
68
+
69
+ ```python
70
+ presets = client.list_presets("prusaslicer") # printers (with brand), processes, filaments
71
+ profile = client.create_profile_from_preset("prusa-mk4s-0.4")
72
+ settings: SliceSettings = {"infill_percentage": 20, "wall_count": 3} # also layer_height_mm, supports
73
+ job = client.start_slice_job(part_id, profile["id"], settings=settings).json()
74
+ result = client.wait_for_slice_job_to_complete(job["id"]).json()
75
+ print(result["print_time_seconds"], result["filament_weight_g"]) # PrusaSlicer's estimate
76
+ gcode = client.download_gcode(job["id"])
77
+ ```
78
+
79
+ Or slice with your own printer profile: a PrusaSlicer config export (`.ini`) or a PrusaSlicer
80
+ `.3mf` project:
81
+
82
+ ```python
83
+ profile_id = client.upload_printer_profile("my_printer.ini", "My printer")
84
+ job = client.start_slice_job(part_id, profile_id).json()
85
+ ```
86
+
87
+ Bambu Studio and OrcaSlicer profiles are coming soon. A quote formula takes the same overrides as
88
+ `slice_settings`, so slice-based quotes can use them too.
89
+
90
+ ## Quotes with options
91
+
92
+ Each quote item can pick its own printer profile and slice settings. A formula lists the other profiles
93
+ items may use in `profile_rates`, each with its own rates, so a mixed order is one quote with one base
94
+ fee and one minimum:
95
+
96
+ ```python
97
+ formula = client.create_quote_formula({
98
+ "name": "Mixed order", "currency": "USD", "base_fee": "5", "minimum_price": "15",
99
+ "printer_profile_id": pla_profile_id,
100
+ "terms": [{"field": "filament_weight_g", "rate": "0.05"}],
101
+ "profile_rates": [{"printer_profile_id": petg_profile_id,
102
+ "rates": [{"field": "filament_weight_g", "rate": "0.08"}]}],
103
+ }).json()
104
+ quote = client.create_quote(formula["id"], [
105
+ {"part_id": part_id, "quantity": 2, "label": "PLA"},
106
+ {"part_id": part_id, "quantity": 2, "label": "PETG strong",
107
+ "printer_profile_id": petg_profile_id, "slice_settings": {"infill_percentage": 40}},
108
+ ]).json()
109
+ quote = client.wait_for_quote_to_complete(quote["id"]).json()
110
+ print(quote["total"]) # one base fee for the whole order
111
+ ```
112
+
113
+ To compare variants of one part, make them items of one quote with a `label`. Each line's `unit_price`
114
+ and `line_total` are exact; `total` isn't any one variant's price. For one variant's order price, make a
115
+ one-item quote, which reuses its slice:
116
+
117
+ ```python
118
+ quote = client.create_quote(formula["id"], [
119
+ {"part_id": part_id, "quantity": 1, "label": "15%", "slice_settings": {"infill_percentage": 15}},
120
+ {"part_id": part_id, "quantity": 1, "label": "40%", "slice_settings": {"infill_percentage": 40}},
121
+ ]).json()
122
+ quote = client.wait_for_quote_to_complete(quote["id"]).json()
123
+ for item in quote["items"]:
124
+ print(item["label"], item["unit_price"])
125
+ ```
126
+
127
+ Slices past your running-job limit wait for a slot (`items[].slice_waiting`) instead of failing.
128
+ `preview_quote` never slices: `items_needing_slice` lists the items without a slice yet, and
129
+ `create_quote` with the same items slices them.
130
+
131
+ Every analysis follows the same pattern: `start_*` returns the job, and `wait_for_*` polls until it's
132
+ finished. Errors raise `ProperMeshAPIError` with `status_code`, `detail` and, for usage limits,
133
+ `retry_after`. The full API is documented at [propermesh.com/docs](https://propermesh.com/docs).
@@ -0,0 +1,118 @@
1
+ # Propermesh Python SDK
2
+
3
+ A client for the [Propermesh](https://propermesh.com) API: check 3D models for thin walls, overhangs
4
+ and broken geometry before you print them, and slice them to G-code. Get free API keys at
5
+ [propermesh.com/account](https://propermesh.com/account).
6
+
7
+ ```sh
8
+ pip install propermesh
9
+ ```
10
+
11
+ ```python
12
+ import os
13
+ from propermesh import ProperMeshClient, SliceSettings, Units
14
+
15
+ client = ProperMeshClient(os.environ["PROPERMESH_ACCESS_KEY"], os.environ["PROPERMESH_SECRET_KEY"])
16
+
17
+ part_id = client.upload_part_file("bracket.stl", Units.mm)
18
+
19
+ # Flag anything thinner than 2 mm
20
+ job = client.start_thickness_analysis_job(part_id, threshold=2).json()
21
+ result = client.wait_for_thickness_analysis_job_to_complete(job["id"]).json()
22
+ print(result["status"], result["is_thin"], result["thin_surface_area"])
23
+ ```
24
+
25
+ ### Waiting for a job
26
+
27
+ Every job type has a `run_<job>` helper that starts the job, waits for it and returns the finished job.
28
+ If the job fails or is cancelled it raises `ProperMeshJobFailedError` (`.job_type`, `.job_id`, `.status`,
29
+ `.failure_reason`), so you don't check `status` yourself:
30
+
31
+ ```python
32
+ from propermesh import ProperMeshJobFailedError
33
+
34
+ try:
35
+ job = client.run_thickness_analysis(part_id, threshold=2)
36
+ print(job["is_thin"])
37
+ except ProperMeshJobFailedError as e:
38
+ print(e.status, e.failure_reason)
39
+ ```
40
+
41
+ The helpers are `run_geometry_analysis`, `run_thickness_analysis`, `run_overhang_analysis`,
42
+ `run_orientation`, `run_repair`, `run_transform`, `run_slice` and `run_quote`, with the arguments of
43
+ their `start_*_job` methods. `ProperMeshAPIError` still covers 4xx and 5xx responses.
44
+
45
+ A plan runs a few jobs at once (one on Free). Start more and the `start_*_job` calls wait for a free
46
+ slot instead of raising: they retry the "too many jobs running" 429 for up to 10 minutes. Change that
47
+ with `ProperMeshClient(..., wait_for_job_slot=120)` (seconds), or turn it off with
48
+ `wait_for_job_slot=None` and the 429 raises `ProperMeshAPIError` (`.retry_after` says how long to wait).
49
+ A limit on parts or jobs per month always raises right away.
50
+
51
+ Slice with a built-in PrusaSlicer printer (Prusa, Creality, Elegoo), optionally overriding a few
52
+ settings for this slice:
53
+
54
+ ```python
55
+ presets = client.list_presets("prusaslicer") # printers (with brand), processes, filaments
56
+ profile = client.create_profile_from_preset("prusa-mk4s-0.4")
57
+ settings: SliceSettings = {"infill_percentage": 20, "wall_count": 3} # also layer_height_mm, supports
58
+ job = client.start_slice_job(part_id, profile["id"], settings=settings).json()
59
+ result = client.wait_for_slice_job_to_complete(job["id"]).json()
60
+ print(result["print_time_seconds"], result["filament_weight_g"]) # PrusaSlicer's estimate
61
+ gcode = client.download_gcode(job["id"])
62
+ ```
63
+
64
+ Or slice with your own printer profile: a PrusaSlicer config export (`.ini`) or a PrusaSlicer
65
+ `.3mf` project:
66
+
67
+ ```python
68
+ profile_id = client.upload_printer_profile("my_printer.ini", "My printer")
69
+ job = client.start_slice_job(part_id, profile_id).json()
70
+ ```
71
+
72
+ Bambu Studio and OrcaSlicer profiles are coming soon. A quote formula takes the same overrides as
73
+ `slice_settings`, so slice-based quotes can use them too.
74
+
75
+ ## Quotes with options
76
+
77
+ Each quote item can pick its own printer profile and slice settings. A formula lists the other profiles
78
+ items may use in `profile_rates`, each with its own rates, so a mixed order is one quote with one base
79
+ fee and one minimum:
80
+
81
+ ```python
82
+ formula = client.create_quote_formula({
83
+ "name": "Mixed order", "currency": "USD", "base_fee": "5", "minimum_price": "15",
84
+ "printer_profile_id": pla_profile_id,
85
+ "terms": [{"field": "filament_weight_g", "rate": "0.05"}],
86
+ "profile_rates": [{"printer_profile_id": petg_profile_id,
87
+ "rates": [{"field": "filament_weight_g", "rate": "0.08"}]}],
88
+ }).json()
89
+ quote = client.create_quote(formula["id"], [
90
+ {"part_id": part_id, "quantity": 2, "label": "PLA"},
91
+ {"part_id": part_id, "quantity": 2, "label": "PETG strong",
92
+ "printer_profile_id": petg_profile_id, "slice_settings": {"infill_percentage": 40}},
93
+ ]).json()
94
+ quote = client.wait_for_quote_to_complete(quote["id"]).json()
95
+ print(quote["total"]) # one base fee for the whole order
96
+ ```
97
+
98
+ To compare variants of one part, make them items of one quote with a `label`. Each line's `unit_price`
99
+ and `line_total` are exact; `total` isn't any one variant's price. For one variant's order price, make a
100
+ one-item quote, which reuses its slice:
101
+
102
+ ```python
103
+ quote = client.create_quote(formula["id"], [
104
+ {"part_id": part_id, "quantity": 1, "label": "15%", "slice_settings": {"infill_percentage": 15}},
105
+ {"part_id": part_id, "quantity": 1, "label": "40%", "slice_settings": {"infill_percentage": 40}},
106
+ ]).json()
107
+ quote = client.wait_for_quote_to_complete(quote["id"]).json()
108
+ for item in quote["items"]:
109
+ print(item["label"], item["unit_price"])
110
+ ```
111
+
112
+ Slices past your running-job limit wait for a slot (`items[].slice_waiting`) instead of failing.
113
+ `preview_quote` never slices: `items_needing_slice` lists the items without a slice yet, and
114
+ `create_quote` with the same items slices them.
115
+
116
+ Every analysis follows the same pattern: `start_*` returns the job, and `wait_for_*` polls until it's
117
+ finished. Errors raise `ProperMeshAPIError` with `status_code`, `detail` and, for usage limits,
118
+ `retry_after`. The full API is documented at [propermesh.com/docs](https://propermesh.com/docs).
@@ -0,0 +1,28 @@
1
+ [project]
2
+ name = "propermesh"
3
+ version = "0.1.0"
4
+ description = "Python client for the Propermesh 3D printing analysis API"
5
+ readme = "README.md"
6
+ license = "MIT"
7
+ license-files = ["LICENSE"]
8
+ requires-python = ">=3.9"
9
+ dependencies = ["requests>=2"]
10
+ keywords = ["3d-printing", "stl", "mesh", "api", "thickness", "overhang"]
11
+ classifiers = [
12
+ "Programming Language :: Python :: 3",
13
+ "Topic :: Multimedia :: Graphics :: 3D Modeling",
14
+ ]
15
+
16
+ [project.urls]
17
+ Homepage = "https://propermesh.com"
18
+ Documentation = "https://propermesh.com/docs"
19
+
20
+ [build-system]
21
+ requires = ["hatchling"]
22
+ build-backend = "hatchling.build"
23
+
24
+ [tool.hatch.build.targets.wheel]
25
+ packages = ["src/propermesh"]
26
+
27
+ [tool.hatch.build.targets.sdist]
28
+ include = ["LICENSE", "src/propermesh", "README.md"]
@@ -0,0 +1,6 @@
1
+ """Python client for the Propermesh 3D printing analysis API (https://propermesh.com)"""
2
+ from propermesh.client import ProperMeshAPIError, ProperMeshClient, ProperMeshJobFailedError, QuoteFormula, QuoteItem, SliceSettings
3
+ from propermesh.units import Units
4
+ from propermesh.webhooks import verify_webhook
5
+
6
+ __all__ = ['ProperMeshClient', 'ProperMeshAPIError', 'ProperMeshJobFailedError', 'QuoteFormula', 'QuoteItem', 'SliceSettings', 'Units', 'verify_webhook']
@@ -0,0 +1,966 @@
1
+ import requests
2
+ import os
3
+ from importlib import metadata
4
+ from typing import Any, Optional, TypedDict, Union
5
+ import random
6
+ import time
7
+ import uuid
8
+
9
+ from propermesh.units import Units
10
+
11
+ API_VERSION = 'v0.1'
12
+
13
+ FIRST_POLL_INTERVAL_SECONDS = 0.5
14
+ POLL_BACKOFF_FACTOR = 1.5
15
+ MAX_POLL_INTERVAL_SECONDS = 5.0
16
+ # Sets a fixed poll interval for clients that don't pass poll_interval_seconds. The integration tests use
17
+ # it (.env.test) so they don't sit out the backoff after a job finishes
18
+ POLL_INTERVAL_ENV_VAR = 'PROPERMESH_POLL_INTERVAL_SECONDS'
19
+
20
+
21
+ # A 429 with a Retry-After longer than this is a period limit (parts or jobs per month), not a busy
22
+ # slot, and isn't waited on
23
+ MAX_SLOT_RETRY_AFTER_SECONDS = 60
24
+ DEFAULT_WAIT_FOR_JOB_SLOT_SECONDS = 600.0
25
+ SLOT_RETRY_JITTER_SECONDS = 1.0
26
+
27
+ # Sent as the User-Agent's product, so the API can tell the SDK's requests from other API-key clients
28
+ # (src/auth/request_source.py)
29
+ USER_AGENT_PRODUCT = 'propermesh-python'
30
+
31
+
32
+ def package_version(name: str) -> str:
33
+ """The installed version of a package, or 0.0.0 when it isn't installed as one (e.g. run from a checkout)"""
34
+ try:
35
+ return metadata.version(name)
36
+ except metadata.PackageNotFoundError:
37
+ return '0.0.0'
38
+
39
+
40
+ def user_agent(prefix: Optional[str], sdk_version: str) -> str:
41
+ """The SDK's User-Agent, after `prefix` (the product of a client built on the SDK, like the MCP server)"""
42
+ if prefix is not None and not (prefix.isascii() and prefix.isprintable()):
43
+ raise ValueError('user_agent_prefix must be printable ASCII, on one line')
44
+ sdk = f'{USER_AGENT_PRODUCT}/{sdk_version}'
45
+ return f'{prefix} {sdk}' if prefix else sdk
46
+
47
+
48
+ def should_retry(status_code: int, retry_after: Optional[int], waited: float,
49
+ cap: Optional[float]) -> Optional[float]:
50
+ """Seconds to sleep before retrying a job start, or None to raise the error.
51
+
52
+ Retries only a 429 whose Retry-After is short (a running-jobs slot, not a period limit), and only
53
+ while the sleep fits in `cap` total seconds of waiting. A cap of None or 0 never retries
54
+ """
55
+ if not cap or status_code != 429 or retry_after is None:
56
+ return None
57
+ if retry_after > MAX_SLOT_RETRY_AFTER_SECONDS:
58
+ return None
59
+ if waited + retry_after > cap:
60
+ return None
61
+ return float(retry_after)
62
+
63
+
64
+ def next_poll_interval(previous: float) -> float:
65
+ """The wait after `previous` seconds: grows by 1.5x, capped at 5 s"""
66
+ return min(previous * POLL_BACKOFF_FACTOR, MAX_POLL_INTERVAL_SECONDS)
67
+
68
+
69
+ def poll_interval_after(previous: Optional[float], fixed: Optional[float]) -> float:
70
+ """The next wait while polling, where None is the first: always `fixed` when it's set, otherwise
71
+ 0.5 s growing to 5 s"""
72
+ if fixed:
73
+ return fixed
74
+ return FIRST_POLL_INTERVAL_SECONDS if previous is None else next_poll_interval(previous)
75
+
76
+
77
+ def fixed_poll_interval_from_env(value: Optional[str]) -> Optional[float]:
78
+ """The fixed poll interval POLL_INTERVAL_ENV_VAR sets, or None (back off) when it's unset or not a
79
+ positive number"""
80
+ try:
81
+ seconds = float(value) if value else 0.0
82
+ except ValueError:
83
+ return None
84
+ return seconds if seconds > 0 else None
85
+
86
+
87
+ class ProperMeshAPIError(Exception):
88
+ """Raised for any 4xx/5xx response from the API.
89
+
90
+ The client is either the requests module (deployed environments) or FastAPI's TestClient (local),
91
+ which raise different exception types (requests.HTTPError vs httpx.HTTPStatusError). Raising this
92
+ instead means callers handle errors the same way in both modes.
93
+ """
94
+
95
+ def __init__(self, status_code: int, detail: str, retry_after: Optional[int] = None,
96
+ request_id: Optional[str] = None):
97
+ super().__init__(f'{status_code}: {detail}')
98
+ self.status_code = status_code
99
+ self.detail = detail
100
+ # Seconds to wait before retrying, when the API says (429 responses for usage limits). None
101
+ # means retrying won't help, e.g. the storage limit
102
+ self.retry_after = retry_after
103
+ # The X-Request-ID the API answered with: the id to trace this failure by in the logs
104
+ self.request_id = request_id
105
+
106
+
107
+ class ProperMeshJobFailedError(Exception):
108
+ """Raised by the run_<job> helpers when the job finished without completing.
109
+
110
+ No HTTP request failed, so this isn't a ProperMeshAPIError. status is 'failed' or 'cancelled', and
111
+ failure_reason is the job's own explanation, or None when it gave none."""
112
+
113
+ def __init__(self, job_type: str, job_id: str, status: str, failure_reason: Optional[str]):
114
+ super().__init__(f'{job_type} job {job_id} {status}: {failure_reason}')
115
+ self.job_type = job_type
116
+ self.job_id = job_id
117
+ self.status = status
118
+ self.failure_reason = failure_reason
119
+
120
+
121
+ class _JobBase(TypedDict):
122
+ id: str
123
+ status: str
124
+ part_id: str
125
+
126
+
127
+ def raise_unless_complete(job_type: str, job: Any, status_field: str = 'status') -> None:
128
+ """Raises ProperMeshJobFailedError for a finished job whose status isn't complete"""
129
+ status = job[status_field]
130
+ if status != 'complete':
131
+ raise ProperMeshJobFailedError(job_type, str(job['id']), status, job.get('failure_reason'))
132
+
133
+
134
+ def _sent_request_id(response: Any) -> Optional[str]:
135
+ """The ID this client sent, for errors that came from CloudFront and not the API"""
136
+ try:
137
+ return response.request.headers.get('X-Request-ID')
138
+ except Exception:
139
+ return None
140
+
141
+
142
+ def _raise_for_error(response: Any) -> None:
143
+ if response.status_code < 400:
144
+ return
145
+
146
+ # FastAPI puts the error message in a JSON "detail" field. Fall back to the raw body for anything
147
+ # else (e.g. a gateway error page)
148
+ try:
149
+ detail = str(response.json()['detail'])
150
+ except Exception:
151
+ detail = response.text
152
+
153
+ retry_after_header = response.headers.get('Retry-After')
154
+ retry_after = int(retry_after_header) if retry_after_header and retry_after_header.isdigit() else None
155
+
156
+ raise ProperMeshAPIError(response.status_code, detail, retry_after, response.headers.get('X-Request-ID') or _sent_request_id(response))
157
+
158
+
159
+ class QuoteFormulaTerm(TypedDict):
160
+ field: str
161
+ rate: Union[str, float, int]
162
+
163
+
164
+ class QuoteDiscount(TypedDict):
165
+ min_quantity: int
166
+ discount_percent: Union[str, float, int]
167
+
168
+
169
+ class QuoteBuildVolume(TypedDict):
170
+ x_mm: Union[str, float, int]
171
+ y_mm: Union[str, float, int]
172
+ z_mm: Union[str, float, int]
173
+
174
+
175
+ class _QuoteFormulaRequired(TypedDict):
176
+ name: str
177
+ currency: str
178
+ terms: list[QuoteFormulaTerm]
179
+
180
+
181
+ class PrinterProfileInfo(TypedDict):
182
+ id: str
183
+ label: str
184
+ slicer: str
185
+ slicer_version: Optional[str]
186
+ prusaslicer_version: Optional[str]
187
+
188
+
189
+ class PresetPrinterInfo(TypedDict):
190
+ id: str
191
+ brand: str
192
+ name: str
193
+ slicer: str
194
+ slicer_version: str
195
+ processes: list[str]
196
+ filaments: list[str]
197
+ default_process: str
198
+ default_filament: str
199
+ recommended: bool
200
+
201
+
202
+ class PresetProcessInfo(TypedDict):
203
+ id: str
204
+ name: str
205
+
206
+
207
+ class PresetFilamentInfo(TypedDict):
208
+ id: str
209
+ name: str
210
+ material: Optional[str]
211
+
212
+
213
+ class PresetList(TypedDict):
214
+ printers: list[PresetPrinterInfo]
215
+ processes: list[PresetProcessInfo]
216
+ filaments: list[PresetFilamentInfo]
217
+
218
+
219
+ class SliceSettings(TypedDict, total=False):
220
+ """Overrides of a printer profile's settings. An unset one keeps the profile's value"""
221
+ infill_percentage: float
222
+ layer_height_mm: float
223
+ wall_count: int
224
+ supports: bool
225
+
226
+
227
+ class _QuoteItemRequired(TypedDict):
228
+ part_id: str
229
+ quantity: int
230
+
231
+
232
+ class QuoteItem(_QuoteItemRequired, total=False):
233
+ """slice_settings override the formula's, field by field. label is echoed back. printer_profile_id is the
234
+ formula's own profile or one in its profile_rates; it defaults to the formula's"""
235
+ printer_profile_id: str
236
+ slice_settings: SliceSettings
237
+ label: str
238
+
239
+
240
+ class _SliceStartBody(TypedDict, total=False):
241
+ profile_id: str
242
+ settings: SliceSettings
243
+
244
+
245
+ class _ProfileRatesRequired(TypedDict):
246
+ printer_profile_id: str
247
+
248
+
249
+ class QuoteProfileRates(_ProfileRatesRequired, total=False):
250
+ """What differs for items on another printer profile: rates replace the formula's for those fields"""
251
+ rates: list[QuoteFormulaTerm]
252
+ per_part_fee: Union[str, float, int]
253
+ build_volume: QuoteBuildVolume
254
+
255
+
256
+ class QuoteFormula(_QuoteFormulaRequired, total=False):
257
+ """A quote formula. Only name, currency and terms are required; the rest default as in the API docs"""
258
+ per_part_fee: Union[str, float, int]
259
+ base_fee: Union[str, float, int]
260
+ markup_percent: Union[str, float, int]
261
+ minimum_price: Union[str, float, int]
262
+ quantity_discounts: list[QuoteDiscount]
263
+ build_volume: Optional[QuoteBuildVolume]
264
+ printer_profile_id: Optional[str]
265
+ slice_settings: Optional[SliceSettings]
266
+ profile_rates: list[QuoteProfileRates]
267
+ quote_valid_days: int
268
+
269
+
270
+
271
+ class LayerInfo(TypedDict):
272
+ """Describes the per-face file a job's layer endpoint serves"""
273
+ face_count: int
274
+ dtype: str
275
+ units: str
276
+
277
+
278
+ class GeometryAnalysisJob(_JobBase, total=False):
279
+ failure_reason: Optional[str]
280
+ volume: Optional[float]
281
+ surface_area: Optional[float]
282
+ bounding_box_x: Optional[float]
283
+ bounding_box_y: Optional[float]
284
+ bounding_box_z: Optional[float]
285
+ oriented_bounding_box_status: Optional[str]
286
+ oriented_bounding_box_x: Optional[float]
287
+ oriented_bounding_box_y: Optional[float]
288
+ oriented_bounding_box_z: Optional[float]
289
+ oriented_bounding_box_failure_reason: Optional[str]
290
+ is_watertight: Optional[bool]
291
+ is_manifold: Optional[bool]
292
+ is_winding_consistent: Optional[bool]
293
+ num_boundary_edges: Optional[int]
294
+ num_non_manifold_edges: Optional[int]
295
+ num_non_manifold_vertices: Optional[int]
296
+ num_degenerate_faces: Optional[int]
297
+ num_duplicate_faces: Optional[int]
298
+ num_shells: Optional[int]
299
+ num_flipped_triangles: Optional[int]
300
+ num_intersecting_faces: Optional[int]
301
+ layer: Optional[LayerInfo]
302
+
303
+
304
+ class ThicknessAnalysisJob(_JobBase, total=False):
305
+ failure_reason: Optional[str]
306
+ threshold: float
307
+ units: str
308
+ is_thin: Optional[bool]
309
+ thin_surface_area: Optional[float]
310
+ total_surface_area: Optional[float]
311
+ layer: Optional[LayerInfo]
312
+
313
+
314
+ class OverhangAnalysisJob(_JobBase, total=False):
315
+ failure_reason: Optional[str]
316
+ critical_angle: Optional[float]
317
+ rotation: Optional[list[list[float]]]
318
+ overhang_surface_area: Optional[float]
319
+ num_overhang_faces: Optional[int]
320
+ num_overhang_clusters: Optional[int]
321
+ layer: Optional[LayerInfo]
322
+
323
+
324
+ class OptimalOrientationJob(_JobBase, total=False):
325
+ failure_reason: Optional[str]
326
+ transform: Optional[list[list[float]]]
327
+ oriented_part_id: Optional[str]
328
+
329
+
330
+ class RepairJob(_JobBase, total=False):
331
+ failure_reason: Optional[str]
332
+ repaired_part_id: Optional[str]
333
+ repaired_is_watertight: Optional[bool]
334
+ repaired_is_manifold: Optional[bool]
335
+ repaired_is_winding_consistent: Optional[bool]
336
+ repaired_num_shells: Optional[int]
337
+ repaired_method: Optional[str]
338
+
339
+
340
+ class TransformJob(_JobBase, total=False):
341
+ failure_reason: Optional[str]
342
+ rotation: list[list[float]]
343
+ scale: list[float]
344
+ units: Optional[str]
345
+ transform: Optional[list[list[float]]]
346
+ transformed_part_id: Optional[str]
347
+
348
+
349
+ class SliceJob(_JobBase, total=False):
350
+ failure_reason: Optional[str]
351
+ printer_profile_id: Optional[str]
352
+ settings: Optional[SliceSettings]
353
+ print_time_seconds: Optional[int]
354
+ filament_length_mm: Optional[float]
355
+ filament_weight_g: Optional[float]
356
+
357
+
358
+ class _QuoteJobRequired(TypedDict):
359
+ id: str
360
+ status: str
361
+
362
+
363
+ class QuoteJob(_QuoteJobRequired, total=False):
364
+ """A quote. price is the priced items and totals (money as strings), null until the quote is complete"""
365
+ failure_reason: Optional[str]
366
+ formula_id: Optional[str]
367
+ currency: str
368
+ items: list[QuoteItem]
369
+ price: Optional[object]
370
+ total: Optional[str]
371
+ warnings: list[str]
372
+ expires_at: str
373
+ expired: bool
374
+ created_at: str
375
+ completed_at: Optional[str]
376
+
377
+
378
+ def _as_lists(value: Any) -> Any:
379
+ """Anything with .tolist() (a numpy array) as lists, the rest as it is"""
380
+ return value.tolist() if hasattr(value, 'tolist') else value
381
+
382
+
383
+ class _OverhangRequired(TypedDict):
384
+ critical_angle: float
385
+
386
+
387
+ class OverhangRequestBody(_OverhangRequired, total=False):
388
+ rotation: Any # Steps or a matrix, as lists
389
+
390
+
391
+ def overhang_request_body(critical_angle: float, rotation: Any = None) -> OverhangRequestBody:
392
+ """The JSON body of POST /overhang/{part_id}/start. rotation is sent only when given"""
393
+ body: OverhangRequestBody = {'critical_angle': critical_angle}
394
+ if rotation is not None:
395
+ body['rotation'] = _as_lists(rotation)
396
+ return body
397
+
398
+
399
+ def transform_request_body(rotation: Any = None, scale: Any = None,
400
+ convert_to: Optional[Union[Units, str]] = None) -> dict[str, Any]:
401
+ """The JSON body of POST /transform/{part_id}/start. Only what's given is sent. Anything with
402
+ .tolist() (a numpy array) becomes lists, and convert_to a string"""
403
+ body: dict[str, Any] = {}
404
+ if rotation is not None:
405
+ body['rotation'] = _as_lists(rotation)
406
+ if scale is not None:
407
+ body['scale'] = _as_lists(scale)
408
+ if convert_to is not None:
409
+ body['convert_to'] = Units(convert_to).value
410
+ return body
411
+
412
+
413
+ class ProperMeshClient:
414
+ def __init__(self, access_key: str, secret_access_key: str, client: Any = requests,
415
+ domain: str = 'https://propermesh.com',
416
+ wait_for_job_slot: Optional[float] = DEFAULT_WAIT_FOR_JOB_SLOT_SECONDS,
417
+ poll_interval_seconds: Optional[float] = None, user_agent_prefix: Optional[str] = None):
418
+ """wait_for_job_slot is the most seconds a job start waits for a free running-jobs slot, retrying
419
+ the 429 that says so. None or 0 turns it off, and the 429 raises ProperMeshAPIError. A 429 for a
420
+ period limit (parts or jobs per month) always raises.
421
+
422
+ poll_interval_seconds fixes how often the wait_for_* methods poll. None reads
423
+ PROPERMESH_POLL_INTERVAL_SECONDS, and without it polling backs off from 0.5 s to 5 s
424
+
425
+ user_agent_prefix goes before the SDK's own product in the User-Agent, for a tool built on the SDK
426
+ (e.g. 'my-tool/1.0')"""
427
+ self.user_agent = user_agent(user_agent_prefix, package_version('propermesh'))
428
+ self.wait_for_job_slot = wait_for_job_slot
429
+ self.poll_interval_seconds = (poll_interval_seconds if poll_interval_seconds is not None
430
+ else fixed_poll_interval_from_env(os.environ.get(POLL_INTERVAL_ENV_VAR)))
431
+ self.access_key = access_key
432
+ self.secret_access_key = secret_access_key
433
+ # TODO: does the fastapi test client have the same API as a regular python HTTP client?
434
+ self.client = client
435
+ self.domain = domain
436
+
437
+ # Poll a job until it reaches a terminal status. Raises instead of hanging forever if the job never
438
+ # finishes (e.g. no worker is running or the worker crashed). The timeout leaves room for the
439
+ # worker Lambda to cold-start and for a job that waits up to 8 minutes on its part's translation
440
+ def _wait_for_job_to_finish(self, job_type: str, job_id: str, timeout_seconds: float = 900,
441
+ poll_interval_seconds: Optional[float] = None, status_field: str = 'status') -> requests.Response:
442
+ # A caller's poll_interval_seconds is used as is, then the client's
443
+ fixed = poll_interval_seconds if poll_interval_seconds is not None else self.poll_interval_seconds
444
+ interval = poll_interval_after(None, fixed)
445
+ deadline = time.monotonic() + timeout_seconds
446
+ while time.monotonic() < deadline:
447
+ response = self.client.get(
448
+ f'{self.domain}/api/{API_VERSION}/{job_type}/{job_id}',
449
+ headers=self._auth_headers(),
450
+ )
451
+
452
+ if response.status_code == 200:
453
+ if response.json()[status_field] in ('complete', 'failed', 'cancelled'):
454
+ return response
455
+
456
+ time.sleep(interval)
457
+ interval = poll_interval_after(interval, fixed)
458
+
459
+ raise TimeoutError(f'{job_type} job {job_id} did not finish within {timeout_seconds} seconds')
460
+
461
+
462
+ # TODO: return the whole part
463
+ # NOTE: Im just currently returning the id of the newly created part but i should return an
464
+ # actual part I just need to figure out the typing
465
+ def upload_part_file(self, filepath: str, units: Optional[Union[Units, str]] = None) -> str:
466
+ """Uploads the file straight to storage through an upload URL, so it works for files of any
467
+ size the API accepts (sending the file in the request to POST /parts doesn't for large ones)"""
468
+ filename = os.path.basename(filepath)
469
+ size_bytes = os.path.getsize(filepath)
470
+
471
+ response = self.client.post(
472
+ f'{self.domain}/api/{API_VERSION}/parts/upload-url',
473
+ json={'filename': filename, 'size_bytes': size_bytes,
474
+ 'units': Units(units).value if units is not None else None},
475
+ headers=self._auth_headers(),
476
+ )
477
+ _raise_for_error(response)
478
+ upload = response.json()
479
+
480
+ # The upload URL points at storage, not the API, so it goes through requests even when
481
+ # self.client is an in-process test client. It's presigned: sending the API keys there would
482
+ # only leak them
483
+ with open(filepath, 'rb') as f:
484
+ upload_response = requests.put(upload['upload_url'], data=f,
485
+ headers={'Content-Length': str(size_bytes)}, timeout=600)
486
+ _raise_for_error(upload_response)
487
+
488
+ response = self.client.post(
489
+ f'{self.domain}/api/{API_VERSION}/parts',
490
+ data={'upload_token': upload['upload_token']},
491
+ headers=self._auth_headers(),
492
+ )
493
+ _raise_for_error(response)
494
+
495
+ part_id = response.json().get('id')
496
+ return part_id
497
+
498
+ def _auth_headers(self) -> dict[str, str]:
499
+ return {'x-access-key': self.access_key, 'x-secret-access-key': self.secret_access_key,
500
+ 'X-Request-ID': uuid.uuid4().hex, 'User-Agent': self.user_agent}
501
+
502
+ def _download_file(self, path: str) -> bytes:
503
+ """Downloads a file from a route that redirects to a presigned storage URL.
504
+
505
+ The redirect is followed by hand: HTTP clients resend custom headers (the API keys) when they
506
+ follow one, and the in-process test client can only reach the API, not storage
507
+ """
508
+ # requests and httpx (FastAPI's TestClient) name this option differently
509
+ no_redirects = ({'follow_redirects': False} if hasattr(self.client, 'follow_redirects')
510
+ else {'allow_redirects': False})
511
+
512
+ response = self.client.get(f'{self.domain}/api/{API_VERSION}/{path}',
513
+ headers=self._auth_headers(), **no_redirects)
514
+ _raise_for_error(response)
515
+
516
+ if response.status_code in (301, 302, 303, 307, 308):
517
+ response = requests.get(response.headers['location'], timeout=600)
518
+ _raise_for_error(response)
519
+
520
+ return response.content
521
+
522
+ def _start_job(self, path: str, body: Any) -> requests.Response:
523
+ """POSTs a job start, waiting for a free job slot when the running-jobs limit says to retry"""
524
+ waited = 0.0
525
+ while True:
526
+ response = self.client.post(f'{self.domain}/api/{API_VERSION}/{path}', json=body,
527
+ headers=self._auth_headers())
528
+ try:
529
+ _raise_for_error(response)
530
+ except ProperMeshAPIError as e:
531
+ sleep_seconds = should_retry(e.status_code, e.retry_after, waited, self.wait_for_job_slot)
532
+ if sleep_seconds is None:
533
+ raise
534
+ sleep_seconds += random.uniform(0, SLOT_RETRY_JITTER_SECONDS)
535
+ time.sleep(sleep_seconds)
536
+ waited += sleep_seconds
537
+ continue
538
+ return response
539
+
540
+ def _run_job(self, job_type: str, start_response: Any, status_field: str = 'status') -> Any:
541
+ """Waits for the job a start response (201, or 200 for the existing job) names, and returns it.
542
+ Raises ProperMeshJobFailedError unless it completes"""
543
+ job_id = start_response.json()['id']
544
+ job = self._wait_for_job_to_finish(job_type, job_id, status_field=status_field).json()
545
+ raise_unless_complete(job_type, job, status_field)
546
+ return job
547
+
548
+ def get_supported_file_types(self) -> requests.Response:
549
+ response = self.client.get(
550
+ f'{self.domain}/api/{API_VERSION}/parts/supported-file-types',
551
+ headers=self._auth_headers(),
552
+ )
553
+
554
+ _raise_for_error(response)
555
+
556
+ return response
557
+
558
+ def start_geometry_analysis_job(self, part_id: str, include_oriented_bounding_box: bool = False) -> requests.Response:
559
+ return self._start_job(f'geometry/{part_id}/start', {'include_oriented_bounding_box': include_oriented_bounding_box})
560
+
561
+ def wait_for_geometry_analysis_job_to_complete(self, job_id: str) -> requests.Response:
562
+ return self._wait_for_job_to_finish('geometry', job_id)
563
+
564
+ def wait_for_oriented_bounding_box(self, job_id: str) -> requests.Response:
565
+ """Waits for the geometry analysis' oriented bounding box, which is made separately"""
566
+ return self._wait_for_job_to_finish('geometry', job_id, status_field='oriented_bounding_box_status')
567
+
568
+ def wait_for_part_geometry_analysis_to_complete(self, part_id: str) -> requests.Response:
569
+ """Waits for the geometry analysis that creating the part started"""
570
+ job_id = self.get_geometry_analysis_for_part(part_id).json()['id']
571
+ return self.wait_for_geometry_analysis_job_to_complete(job_id)
572
+
573
+ def start_thickness_analysis_job(self, part_id: str, threshold: float) -> requests.Response:
574
+ return self._start_job(f'thickness/{part_id}/start', { 'threshold': threshold })
575
+
576
+ def start_overhang_analysis_job(self, part_id: str, critical_angle: float, rotation: Any = None) -> requests.Response:
577
+ """rotation analyzes the part in that orientation: a list of {"axis", "degrees"} steps or a 3x3/4x4
578
+ matrix (lists or numpy arrays), the same as start_transform_job's"""
579
+ return self._start_job(f'overhang/{part_id}/start', overhang_request_body(critical_angle, rotation))
580
+
581
+ def start_optimal_orientation_job(self, part_id: str) -> requests.Response:
582
+ return self._start_job(f'orient/{part_id}/start', { })
583
+
584
+
585
+ def wait_for_overhang_analysis_job_to_complete(self, job_id: str) -> requests.Response:
586
+ return self._wait_for_job_to_finish('overhang', job_id)
587
+
588
+ def wait_for_optimal_orientation_job_to_complete(self, job_id: str) -> requests.Response:
589
+ return self._wait_for_job_to_finish('orient', job_id)
590
+
591
+ def wait_for_thickness_analysis_job_to_complete(self, job_id: str) -> requests.Response:
592
+ return self._wait_for_job_to_finish('thickness', job_id)
593
+
594
+ # The job of a type a part has at most one of (GET /parts/<part_id>/<job_type>). 404 if none was started
595
+ def _get_part_job(self, job_type: str, part_id: str) -> requests.Response:
596
+ response = self.client.get(
597
+ f'{self.domain}/api/{API_VERSION}/parts/{part_id}/{job_type}',
598
+ headers=self._auth_headers(),
599
+ )
600
+
601
+ _raise_for_error(response)
602
+
603
+ return response
604
+
605
+ def get_geometry_analysis_for_part(self, part_id: str) -> requests.Response:
606
+ return self._get_part_job('geometry', part_id)
607
+
608
+ def get_optimal_orientation_job_for_part(self, part_id: str) -> requests.Response:
609
+ return self._get_part_job('orient', part_id)
610
+
611
+ def get_repair_job_for_part(self, part_id: str) -> requests.Response:
612
+ return self._get_part_job('repair', part_id)
613
+
614
+ # One page of a part's jobs of one type (GET /parts/<part_id>/<job_type>). The JSON is
615
+ # {"data": [...jobs, oldest first], "next_cursor": ...}. Pass next_cursor as cursor for the next page
616
+ def _get_part_jobs(self, job_type: str, part_id: str, limit: Optional[int], cursor: Optional[str]) -> requests.Response:
617
+ params = {name: value for name, value in (('limit', limit), ('cursor', cursor)) if value is not None}
618
+ response = self.client.get(
619
+ f'{self.domain}/api/{API_VERSION}/parts/{part_id}/{job_type}',
620
+ params=params,
621
+ headers=self._auth_headers(),
622
+ )
623
+
624
+ _raise_for_error(response)
625
+
626
+ return response
627
+
628
+
629
+ def get_thickness_analyses_for_part(self, part_id: str, limit: Optional[int] = None,
630
+ cursor: Optional[str] = None) -> requests.Response:
631
+ return self._get_part_jobs('thickness', part_id, limit, cursor)
632
+
633
+ def get_overhang_analyses_for_part(self, part_id: str, limit: Optional[int] = None,
634
+ cursor: Optional[str] = None) -> requests.Response:
635
+ return self._get_part_jobs('overhang', part_id, limit, cursor)
636
+
637
+ def get_slice_jobs_for_part(self, part_id: str, limit: Optional[int] = None,
638
+ cursor: Optional[str] = None) -> requests.Response:
639
+ return self._get_part_jobs('slice', part_id, limit, cursor)
640
+
641
+ def get_part(self, part_id: str) -> requests.Response:
642
+ response = self.client.get(f'{self.domain}/api/{API_VERSION}/parts/{part_id}', headers=self._auth_headers())
643
+
644
+ _raise_for_error(response)
645
+
646
+ return response
647
+
648
+ def wait_for_part_thumbnail(self, part_id: str, timeout_seconds: float = 600) -> bytes:
649
+ """Polls until the thumbnail is made (409 until then). Raises ProperMeshAPIError (404) if there
650
+ won't be one"""
651
+ deadline = time.monotonic() + timeout_seconds
652
+ interval = poll_interval_after(None, self.poll_interval_seconds)
653
+ while True:
654
+ try:
655
+ return self.get_part_thumbnail(part_id)
656
+ except ProperMeshAPIError as e:
657
+ if e.status_code != 409 or time.monotonic() > deadline:
658
+ raise
659
+ time.sleep(interval)
660
+ interval = poll_interval_after(interval, self.poll_interval_seconds)
661
+
662
+ def get_part_thumbnail(self, part_id: str) -> bytes:
663
+ response: requests.Response = self.client.get(
664
+ f'{self.domain}/api/{API_VERSION}/parts/{part_id}/thumbnail',
665
+ headers=self._auth_headers(),
666
+ )
667
+
668
+ _raise_for_error(response)
669
+
670
+ return response.content
671
+
672
+
673
+ def get_part_display_mesh(self, part_id: str) -> bytes:
674
+ """The binary STL that the part's analysis layers draw on: face i is face i of every layer"""
675
+ return self._download_file(f'parts/{part_id}/display-mesh')
676
+
677
+ def download_part_file(self, part_id: str) -> bytes:
678
+ return self._download_file(f'parts/{part_id}/file')
679
+
680
+ def get_thickness_list(self, job_id: str) -> bytes:
681
+ return self._download_file(f'thickness/{job_id}/list')
682
+
683
+ def get_thickness_layer(self, job_id: str) -> bytes:
684
+ """The decoded layer: little-endian float32 thickness per face (NaN is unknown)"""
685
+ return self._download_file(f'thickness/{job_id}/layer')
686
+
687
+ def get_overhang_layer(self, job_id: str) -> bytes:
688
+ """The decoded layer: little-endian float32 angle in degrees per face (Infinity on the build plate)"""
689
+ return self._download_file(f'overhang/{job_id}/layer')
690
+
691
+ def download_geometry_layer(self, job_id: str) -> bytes:
692
+ """The decoded defects layer: a little-endian uint16 of bit flags per face (the job's layer.bits)"""
693
+ return self._download_file(f'geometry/{job_id}/layer')
694
+
695
+ def get_thickness_visualization_ply_file(self, job_id: str) -> bytes:
696
+ return self._download_file(f'thickness/{job_id}/visual/ply')
697
+
698
+ def get_overhang_visualization_ply_file(self, job_id: str) -> bytes:
699
+ return self._download_file(f'overhang/{job_id}/visual/ply')
700
+
701
+ def get_oriented_stl(self, job_id: str) -> bytes:
702
+ return self._download_file(f'orient/{job_id}/stl')
703
+
704
+ def update_part_units(self, part_id: str, units: Union[Units, str]) -> requests.Response:
705
+ response = self.client.put(
706
+ f'{self.domain}/api/{API_VERSION}/parts/{part_id}/units',
707
+ json={ 'units': Units(units).value },
708
+ headers=self._auth_headers(),
709
+ )
710
+
711
+ _raise_for_error(response)
712
+
713
+ return response
714
+
715
+
716
+ def delete_part(self, part_id: str) -> requests.Response:
717
+ response = self.client.delete(
718
+ f'{self.domain}/api/{API_VERSION}/parts/{part_id}',
719
+ headers=self._auth_headers(),
720
+ )
721
+
722
+ _raise_for_error(response)
723
+
724
+ return response
725
+
726
+
727
+ def delete_geometry_analysis_job(self, job_id: str) -> requests.Response:
728
+ response = self.client.delete(
729
+ f'{self.domain}/api/{API_VERSION}/geometry/{job_id}',
730
+ headers=self._auth_headers(),
731
+ )
732
+
733
+ _raise_for_error(response)
734
+
735
+ return response
736
+
737
+ def delete_thickness_analysis_job(self, job_id: str) -> requests.Response:
738
+ response = self.client.delete(
739
+ f'{self.domain}/api/{API_VERSION}/thickness/{job_id}',
740
+ headers=self._auth_headers(),
741
+ )
742
+
743
+ _raise_for_error(response)
744
+
745
+ return response
746
+
747
+ def delete_overhang_analysis_job(self, job_id: str) -> requests.Response:
748
+ response = self.client.delete(
749
+ f'{self.domain}/api/{API_VERSION}/overhang/{job_id}',
750
+ headers=self._auth_headers(),
751
+ )
752
+
753
+ _raise_for_error(response)
754
+
755
+ return response
756
+
757
+ def delete_optimal_orientation_job(self, job_id: str) -> requests.Response:
758
+ response = self.client.delete(
759
+ f'{self.domain}/api/{API_VERSION}/orient/{job_id}',
760
+ headers=self._auth_headers(),
761
+ )
762
+
763
+ _raise_for_error(response)
764
+
765
+ return response
766
+
767
+
768
+
769
+ def start_repair_job(self, part_id: str) -> requests.Response:
770
+ return self._start_job(f'repair/{part_id}/start', { })
771
+
772
+ def wait_for_repair_job_to_complete(self, job_id: str) -> requests.Response:
773
+ return self._wait_for_job_to_finish('repair', job_id)
774
+
775
+ def delete_repair_job(self, job_id: str) -> requests.Response:
776
+ response = self.client.delete(
777
+ f'{self.domain}/api/{API_VERSION}/repair/{job_id}',
778
+ headers=self._auth_headers(),
779
+ )
780
+
781
+ _raise_for_error(response)
782
+
783
+ return response
784
+
785
+ def get_repaired_stl(self, job_id: str) -> bytes:
786
+ return self._download_file(f'repair/{job_id}/stl')
787
+
788
+
789
+ def start_transform_job(self, part_id: str, rotation: Any = None, scale: Any = None,
790
+ convert_to: Optional[Union[Units, str]] = None) -> requests.Response:
791
+ """Starts a transform: rotation (a list of {"axis", "degrees"} steps or a 3x3/4x4 matrix, lists or
792
+ numpy arrays), scale (a number or [sx, sy, sz]) and/or convert_to ("mm" or "inches")"""
793
+ return self._start_job(f'transform/{part_id}/start', transform_request_body(rotation, scale, convert_to))
794
+
795
+ def wait_for_transform_job_to_complete(self, job_id: str) -> requests.Response:
796
+ return self._wait_for_job_to_finish('transform', job_id)
797
+
798
+ def get_transform_job(self, job_id: str) -> requests.Response:
799
+ response = self.client.get(f'{self.domain}/api/{API_VERSION}/transform/{job_id}',
800
+ headers=self._auth_headers())
801
+ _raise_for_error(response)
802
+ return response
803
+
804
+ def get_transform_jobs_for_part(self, part_id: str, limit: Optional[int] = None,
805
+ cursor: Optional[str] = None) -> requests.Response:
806
+ return self._get_part_jobs('transform', part_id, limit, cursor)
807
+
808
+ def delete_transform_job(self, job_id: str) -> requests.Response:
809
+ """Deletes the job, not the part it made"""
810
+ response = self.client.delete(f'{self.domain}/api/{API_VERSION}/transform/{job_id}',
811
+ headers=self._auth_headers())
812
+ _raise_for_error(response)
813
+ return response
814
+
815
+ def start_slice_job(self, part_id: str, profile_id: str,
816
+ settings: Optional[SliceSettings] = None) -> requests.Response:
817
+ body: _SliceStartBody = {'profile_id': profile_id}
818
+ if settings is not None:
819
+ body['settings'] = settings
820
+ return self._start_job(f'slice/{part_id}/start', body)
821
+
822
+ def wait_for_slice_job_to_complete(self, job_id: str) -> requests.Response:
823
+ return self._wait_for_job_to_finish('slice', job_id)
824
+
825
+ def delete_slice_job(self, job_id: str) -> requests.Response:
826
+ response = self.client.delete(
827
+ f'{self.domain}/api/{API_VERSION}/slice/{job_id}',
828
+ headers=self._auth_headers(),
829
+ )
830
+
831
+ _raise_for_error(response)
832
+
833
+ return response
834
+
835
+ def download_gcode(self, job_id: str) -> bytes:
836
+ return self._download_file(f'slice/{job_id}/gcode')
837
+
838
+
839
+ def upload_printer_profile(self, filepath: str, label: str) -> str:
840
+ with open(filepath, "rb") as f:
841
+ filename = os.path.basename(filepath)
842
+
843
+ # include label as a form field
844
+ form_values = { 'label': label }
845
+
846
+ response = self.client.post(
847
+ f'{self.domain}/api/{API_VERSION}/slice/profiles',
848
+ files={'file': (filename, f)},
849
+ data=form_values,
850
+ headers=self._auth_headers(),
851
+ )
852
+
853
+
854
+ _raise_for_error(response)
855
+
856
+ profile_id = response.json().get('id')
857
+ return profile_id
858
+
859
+ def list_printer_profiles(self) -> list[PrinterProfileInfo]:
860
+ """The user's printer profiles, each with its `slicer` ("prusaslicer" or "bambu_studio") and
861
+ `slicer_version`"""
862
+ response = self._json_request('get', 'slice/profiles')
863
+ return response.json()
864
+
865
+ def list_presets(self, slicer: Optional[str] = None) -> PresetList:
866
+ """The built-in printers with the processes and filaments each can use. `slicer` ("prusaslicer"
867
+ or "bambu_studio") limits it to that slicer's printers"""
868
+ path = 'slice/presets' + (f'?slicer={slicer}' if slicer else '')
869
+ return self._json_request('get', path).json()
870
+
871
+ def create_profile_from_preset(self, printer: str, process: Optional[str] = None, filament: Optional[str] = None,
872
+ label: Optional[str] = None) -> PrinterProfileInfo:
873
+ """Saves a built-in printer as a printer profile. `process` and `filament` default to the printer's
874
+ defaults, and `label` to "<printer> · <process> · <filament>" from their names"""
875
+ body: dict[str, str] = {'printer': printer}
876
+ for key, value in (('process', process), ('filament', filament), ('label', label)):
877
+ if value is not None:
878
+ body[key] = value
879
+ return self._json_request('post', 'slice/profiles/from-preset', body).json()
880
+
881
+ def _json_request(self, method: str, path: str, body: Optional[object] = None) -> requests.Response:
882
+ response = getattr(self.client, method)(
883
+ f'{self.domain}/api/{API_VERSION}/{path}',
884
+ headers=self._auth_headers(),
885
+ **({'json': body} if body is not None else {}),
886
+ )
887
+
888
+ _raise_for_error(response)
889
+
890
+ return response
891
+
892
+ def create_quote_formula(self, formula: QuoteFormula) -> requests.Response:
893
+ return self._json_request('post', 'quote-formulas', formula)
894
+
895
+ def list_quote_formulas(self) -> requests.Response:
896
+ return self._json_request('get', 'quote-formulas')
897
+
898
+ def get_quote_formula(self, formula_id: str) -> requests.Response:
899
+ return self._json_request('get', f'quote-formulas/{formula_id}')
900
+
901
+ def update_quote_formula(self, formula_id: str, formula: QuoteFormula) -> requests.Response:
902
+ return self._json_request('put', f'quote-formulas/{formula_id}', formula)
903
+
904
+ def delete_quote_formula(self, formula_id: str) -> requests.Response:
905
+ return self._json_request('delete', f'quote-formulas/{formula_id}')
906
+
907
+ def create_quote(self, formula_id: str, items: list[QuoteItem]) -> requests.Response:
908
+ return self._json_request('post', 'quotes', {'formula_id': formula_id, 'items': items})
909
+
910
+ def get_quote(self, quote_id: str) -> requests.Response:
911
+ return self._json_request('get', f'quotes/{quote_id}')
912
+
913
+ def wait_for_quote_to_complete(self, quote_id: str) -> requests.Response:
914
+ return self._wait_for_job_to_finish('quotes', quote_id)
915
+
916
+ def preview_quote(self, formula: QuoteFormula, items: list[QuoteItem]) -> requests.Response:
917
+ return self._json_request('post', 'quotes/preview', {'formula': formula, 'items': items})
918
+
919
+ def create_webhook(self, url: str, job_types: Optional[list[str]] = None) -> requests.Response:
920
+ """Registers a webhook endpoint. The response's `secret` is only returned here"""
921
+ return self._json_request('post', 'webhooks', {'url': url, 'job_types': job_types})
922
+
923
+ def list_webhooks(self) -> requests.Response:
924
+ return self._json_request('get', 'webhooks')
925
+
926
+ def delete_webhook(self, webhook_id: str) -> requests.Response:
927
+ return self._json_request('delete', f'webhooks/{webhook_id}')
928
+
929
+ # run_<job>: start the job, wait for it and return it, or raise ProperMeshJobFailedError
930
+
931
+ def run_geometry_analysis(self, part_id: str, include_oriented_bounding_box: bool = False) -> GeometryAnalysisJob:
932
+ job: GeometryAnalysisJob = self._run_job('geometry',
933
+ self.start_geometry_analysis_job(part_id, include_oriented_bounding_box))
934
+ return job
935
+
936
+ def run_thickness_analysis(self, part_id: str, threshold: float) -> ThicknessAnalysisJob:
937
+ job: ThicknessAnalysisJob = self._run_job('thickness', self.start_thickness_analysis_job(part_id, threshold))
938
+ return job
939
+
940
+ def run_overhang_analysis(self, part_id: str, critical_angle: float, rotation: Any = None) -> OverhangAnalysisJob:
941
+ job: OverhangAnalysisJob = self._run_job('overhang',
942
+ self.start_overhang_analysis_job(part_id, critical_angle, rotation))
943
+ return job
944
+
945
+ def run_orientation(self, part_id: str) -> OptimalOrientationJob:
946
+ job: OptimalOrientationJob = self._run_job('orient', self.start_optimal_orientation_job(part_id))
947
+ return job
948
+
949
+ def run_repair(self, part_id: str) -> RepairJob:
950
+ job: RepairJob = self._run_job('repair', self.start_repair_job(part_id))
951
+ return job
952
+
953
+ def run_transform(self, part_id: str, rotation: Any = None, scale: Any = None,
954
+ convert_to: Optional[Union[Units, str]] = None) -> TransformJob:
955
+ """Transforms the part. The new part's id is the job's transformed_part_id"""
956
+ job: TransformJob = self._run_job('transform',
957
+ self.start_transform_job(part_id, rotation, scale, convert_to))
958
+ return job
959
+
960
+ def run_slice(self, part_id: str, profile_id: str, settings: Optional[SliceSettings] = None) -> SliceJob:
961
+ job: SliceJob = self._run_job('slice', self.start_slice_job(part_id, profile_id, settings))
962
+ return job
963
+
964
+ def run_quote(self, formula_id: str, items: list[QuoteItem]) -> QuoteJob:
965
+ job: QuoteJob = self._run_job('quotes', self.create_quote(formula_id, items))
966
+ return job
@@ -0,0 +1,8 @@
1
+ import enum
2
+
3
+
4
+ class Units(str, enum.Enum):
5
+ """The units a part's model is in. The API's own enum is src/units.py:UnitsEnum, and a test there
6
+ keeps the two in sync"""
7
+ mm = 'mm'
8
+ inches = 'inches'
@@ -0,0 +1,41 @@
1
+ """Checking that a webhook delivery came from Propermesh"""
2
+ import hashlib
3
+ import hmac
4
+ import time
5
+ from typing import Optional, Union
6
+
7
+
8
+ def _parse_signature(header: str) -> Optional[tuple[int, list[str]]]:
9
+ """The timestamp and v1 signatures in a Propermesh-Signature header ("t=...,v1=..."), or None if it's
10
+ malformed"""
11
+ timestamp: Optional[int] = None
12
+ signatures: list[str] = []
13
+ for item in header.split(','):
14
+ key, sep, value = item.strip().partition('=')
15
+ if not sep:
16
+ return None
17
+ if key == 't':
18
+ # isdigit alone takes characters int() rejects ("²"), and int() refuses huge numbers
19
+ if not (value.isascii() and value.isdecimal()) or len(value) > 12:
20
+ return None
21
+ timestamp = int(value)
22
+ elif key == 'v1':
23
+ signatures.append(value)
24
+ if timestamp is None or not signatures:
25
+ return None
26
+ return timestamp, signatures
27
+
28
+
29
+ def verify_webhook(body: Union[bytes, str], signature_header: str, secret: str, tolerance_seconds: int = 300,
30
+ now: Optional[float] = None) -> bool:
31
+ """Whether body (the raw request body, before any JSON parsing) was signed with your endpoint's secret
32
+ within the last tolerance_seconds. Pass the Propermesh-Signature header as signature_header"""
33
+ parsed = _parse_signature(signature_header or '')
34
+ if parsed is None:
35
+ return False
36
+ timestamp, signatures = parsed
37
+ if abs((time.time() if now is None else now) - timestamp) > tolerance_seconds:
38
+ return False
39
+ raw = body if isinstance(body, bytes) else body.encode()
40
+ expected = hmac.new(secret.encode(), f'{timestamp}.'.encode() + raw, hashlib.sha256).hexdigest()
41
+ return any(hmac.compare_digest(expected, signature) for signature in signatures)