sherlock-api 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,20 @@
1
+ # Byte-compiled / cache
2
+ __pycache__/
3
+ *.py[cod]
4
+
5
+ # Environments
6
+ .venv/
7
+ venv/
8
+ .env
9
+
10
+ # Build artifacts
11
+ build/
12
+ dist/
13
+ *.egg-info/
14
+
15
+ # Tooling caches
16
+ .pytest_cache/
17
+ .mypy_cache/
18
+ .ruff_cache/
19
+ .coverage
20
+ htmlcov/
@@ -0,0 +1,72 @@
1
+ # Changelog
2
+
3
+ All notable changes to this project are documented here. This project adheres
4
+ to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
5
+
6
+ ## [0.1.0] - 2026-09-19
7
+
8
+ First packaged release. The code previously lived as loose top-level modules
9
+ that could only be imported from the repository root; it is now the installable
10
+ `sherlock-api` distribution exposing the `sherlock_api` package.
11
+
12
+ ### Added
13
+
14
+ - `pip install sherlock-api`, with `requests` and `Pillow` declared as
15
+ dependencies and `py.typed` shipped so type checkers see the inline hints.
16
+ - A single public import surface: `from sherlock_api import SherlockAPIClient, ...`.
17
+ - Exception hierarchy in `sherlock_api.exceptions` — `SherlockError`,
18
+ `SherlockConfigurationError`, `SherlockAPIError` and the status-specific
19
+ `SherlockBadRequestError` / `SherlockNotFoundError` / `SherlockTimeoutError` /
20
+ `SherlockServerError`. `SherlockAPIError` subclasses `RuntimeError` and
21
+ `SherlockConfigurationError` subclasses `ValueError`, so existing
22
+ `except RuntimeError` / `except ValueError` handlers keep working.
23
+ - Connection reuse via a `requests.Session`, a `request_timeout` (default 30 s)
24
+ applied to every call, and retries for connection errors and 502/503/504 on
25
+ GET/DELETE. `SherlockAPIClient` is now a context manager and has `close()`.
26
+ - `log_case_error/warning/info` and `log_image_error/warning/info`, matching the
27
+ batch-level helpers that already existed.
28
+ - `image_format` parameter on the `upload_image*` methods (previously always PNG).
29
+ - `SHERLOCK_URL` environment variable, alongside the existing `SHERLOCK_PORT`,
30
+ `SHERLOCK_PROCESS_ID`, `SHERLOCK_CASE_ID` and `SHERLOCK_BATCH_ID`.
31
+ - Docstrings throughout and return type annotations on every public method.
32
+
33
+ ### Fixed
34
+
35
+ - **`image_utils` imported a name that does not exist** (`post_file_from_memory`
36
+ from `file_utils`), which made the whole library unimportable.
37
+ - **Environment variables were read at import time**, because `os.getenv(...)`
38
+ sat in the constructor's default arguments. Any `SHERLOCK_*` variable set
39
+ after the module was first imported was silently ignored. They are now read
40
+ per instantiation.
41
+ - **No request had a client-side timeout**, so a call could hang forever.
42
+ `get_modal` widens its own timeout to outlast its server-side long poll.
43
+ - `get_file` compared `Content-Type` for exact equality and so rejected a
44
+ valid `application/octet-stream; charset=...`.
45
+ - The library called `print()` on the `post_notification` 404 path; it now logs
46
+ to the `sherlock_api.client` logger.
47
+ - Unbounded response bodies were interpolated into exception messages; they are
48
+ truncated to 500 characters.
49
+ - `sherlock_batch_id` was accepted by the constructor but never used; it is now
50
+ the fallback for `get_batch`, `get_images_for_batch` and `upload_image*`.
51
+ - `.txt` detection in `guess_extension_by_magic` no longer classifies any binary
52
+ containing a newline in its first 512 bytes as text.
53
+
54
+ ### Changed (breaking)
55
+
56
+ - Import paths. `from sherlock_api_client import SherlockAPIClient` becomes
57
+ `from sherlock_api import SherlockAPIClient`; the `*_utils` modules are now
58
+ `sherlock_api.cases`, `.batches`, `.images`, `.logs`, `.measurements`,
59
+ `.process`, `.files` and `.validation`.
60
+ - `post_modal`, `get_modal` and `delete_modal` take `process_id` as an optional
61
+ trailing argument that falls back to the client's process id, like every other
62
+ process method. `post_modal(process_id, modal)` becomes `post_modal(modal)`.
63
+ - The `upload_image*` methods take `decision_class` before `batch_id`, so that
64
+ the now-optional `batch_id` comes last.
65
+ - `upload_image_with_measurements` returns `(image, [measurement, ...])` instead
66
+ of `None`.
67
+ - `delete_measurement` and `delete_modal` are annotated `-> None` (unchanged
68
+ behaviour, they never returned anything).
69
+ - Request models are dataclasses. `CreateImageRequest.image_data` is now
70
+ `.image_hash`; the wire field is still `image_data`.
71
+ - `CreateMeasurementRequest.value` accepts `int` and `float` and stringifies
72
+ them, instead of requiring the caller to do it.
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright 2026 Kirill Meisser
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,218 @@
1
+ Metadata-Version: 2.5
2
+ Name: sherlock-api
3
+ Version: 0.1.0
4
+ Summary: Python client for the Sherlock REST API
5
+ Project-URL: Homepage, https://github.com/sherlockrobotics/sherlock-python-api
6
+ Project-URL: Repository, https://github.com/sherlockrobotics/sherlock-python-api
7
+ Project-URL: Issues, https://github.com/sherlockrobotics/sherlock-python-api/issues
8
+ Project-URL: Changelog, https://github.com/sherlockrobotics/sherlock-python-api/blob/main/CHANGELOG.md
9
+ Author: Kirill Meisser
10
+ License-Expression: Apache-2.0
11
+ License-File: LICENSE
12
+ Keywords: api,client,inspection,robotics,sherlock
13
+ Classifier: Development Status :: 3 - Alpha
14
+ Classifier: Intended Audience :: Developers
15
+ Classifier: Intended Audience :: Manufacturing
16
+ Classifier: Operating System :: OS Independent
17
+ Classifier: Programming Language :: Python :: 3
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: Topic :: Scientific/Engineering :: Image Processing
23
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
24
+ Classifier: Typing :: Typed
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: pillow<13,>=10
27
+ Requires-Dist: requests<3,>=2.31
28
+ Provides-Extra: dev
29
+ Requires-Dist: build; extra == 'dev'
30
+ Requires-Dist: mypy>=1.11; extra == 'dev'
31
+ Requires-Dist: pytest>=8; extra == 'dev'
32
+ Requires-Dist: responses>=0.25; extra == 'dev'
33
+ Requires-Dist: ruff>=0.6; extra == 'dev'
34
+ Requires-Dist: twine; extra == 'dev'
35
+ Requires-Dist: types-requests; extra == 'dev'
36
+ Description-Content-Type: text/markdown
37
+
38
+ # sherlock-api
39
+
40
+ Python client for the [Sherlock](https://github.com/kirillmeisser/sherlock-python-api) REST API.
41
+ Build your own Sherlock applications — create cases and batches, upload
42
+ inspection images with measurements, write log entries, and drive modal dialogs
43
+ and notifications in a running Sherlock process.
44
+
45
+ ## Install
46
+
47
+ ```bash
48
+ pip install sherlock-api
49
+ ```
50
+
51
+ Requires Python 3.10+.
52
+
53
+ ## Quickstart
54
+
55
+ ```python
56
+ from PIL import Image
57
+ from sherlock_api import (
58
+ SherlockAPIClient,
59
+ CreateCaseRequest,
60
+ CreateBatchRequest,
61
+ RobotPlatform,
62
+ DecisionClass,
63
+ )
64
+
65
+ with SherlockAPIClient(sherlock_port=8080) as client:
66
+ case = client.post_case(
67
+ CreateCaseRequest(
68
+ "Bushing inspection",
69
+ RobotPlatform.UNIVERSAL_ROBOTS,
70
+ "0A0E012F7772596B03D92AAA544763BB",
71
+ )
72
+ )
73
+ batch = client.post_batch(CreateBatchRequest(case["id"], "Batch 1"))
74
+
75
+ image, measurements = client.upload_image_with_measurements(
76
+ Image.open("part.png"),
77
+ "part.png",
78
+ DecisionClass.Ok,
79
+ [("diameter_mm", 12.04), ("roundness", 0.98)],
80
+ batch["id"],
81
+ )
82
+
83
+ client.log_batch_info(batch["id"], f"Uploaded {image['image_name']}")
84
+ ```
85
+
86
+ ## Configuration
87
+
88
+ Every constructor argument falls back to an environment variable. A script
89
+ launched *by* Sherlock gets these for free, so `SherlockAPIClient()` with no
90
+ arguments is usually all you need:
91
+
92
+ | Argument | Environment variable | Default |
93
+ | --- | --- | --- |
94
+ | `sherlock_url` | `SHERLOCK_URL` | `http://localhost` |
95
+ | `sherlock_port` | `SHERLOCK_PORT` | — (required) |
96
+ | `sherlock_process_id` | `SHERLOCK_PROCESS_ID` | `None` |
97
+ | `sherlock_case_id` | `SHERLOCK_CASE_ID` | `None` |
98
+ | `sherlock_batch_id` | `SHERLOCK_BATCH_ID` | `None` |
99
+
100
+ The three id defaults are used whenever you omit the corresponding argument —
101
+ `client.get_case()` reads `sherlock_case_id`, `client.get_batch()` reads
102
+ `sherlock_batch_id`, and the process methods read `sherlock_process_id`. Omitting
103
+ an argument that has no default raises `SherlockConfigurationError`.
104
+
105
+ Keyword-only options: `request_timeout` (seconds, default `30.0`), `max_retries`
106
+ (default `3`, applied to connection errors and 502/503/504 on GET and DELETE),
107
+ and `session` to supply your own `requests.Session`.
108
+
109
+ ## Modal dialogs
110
+
111
+ `post_modal` returns a modal id; `get_modal` long-polls for the operator's
112
+ answer and returns `DialogResult.NoResponse` if the poll expires. Its `timeout`
113
+ is in **milliseconds** and is enforced by the server — the client timeout is
114
+ widened automatically to outlast it.
115
+
116
+ ```python
117
+ from sherlock_api import (
118
+ CreateProcessModalDialogRequest,
119
+ DialogType,
120
+ DialogResult,
121
+ Language,
122
+ )
123
+
124
+ modal_id = client.post_modal(
125
+ CreateProcessModalDialogRequest(DialogType.YesNo, Language.English, "Part looks OK?")
126
+ )
127
+
128
+ result = client.get_modal(modal_id, timeout=30_000)
129
+ if result is DialogResult.NoResponse:
130
+ client.delete_modal(modal_id)
131
+ ```
132
+
133
+ ## Notifications
134
+
135
+ ```python
136
+ from sherlock_api import CreateNotificationRequest, NotificationAttachment
137
+
138
+ client.post_notification(
139
+ CreateNotificationRequest(
140
+ "Batch finished",
141
+ "42 parts inspected, 3 rejected.",
142
+ [NotificationAttachment("report.pdf", "application/pdf", pdf_bytes)],
143
+ )
144
+ )
145
+ ```
146
+
147
+ A notification sent to a process that no longer exists is logged as a warning
148
+ on the `sherlock_api.client` logger rather than raised — it is fire-and-forget.
149
+
150
+ ## API surface
151
+
152
+ | Area | Methods |
153
+ | --- | --- |
154
+ | Files | `get_file`, `post_file`, `post_file_from_memory` |
155
+ | Cases | `get_cases`, `get_case`, `post_case` |
156
+ | Batches | `get_batch`, `get_batches_for_case`, `post_batch` |
157
+ | Images | `get_image`, `get_images_for_batch`, `post_image`, `upload_image`, `upload_image_with_measurement`, `upload_image_with_measurements` |
158
+ | Logs | `get_log`, `post_log`, `log_{case,batch,image}_{error,warning,info}` |
159
+ | Measurements | `get_measurement`, `post_measurement`, `delete_measurement` |
160
+ | Processes | `get_process_state`, `is_process_running`, `get_env_state`, `get_env_vars`, `post_modal`, `get_modal`, `delete_modal`, `post_notification` |
161
+
162
+ Methods returning JSON return the parsed `dict` or `list` from the server as-is.
163
+
164
+ ## Errors
165
+
166
+ ```text
167
+ SherlockError
168
+ ├── SherlockConfigurationError (also a ValueError) missing port or id
169
+ └── SherlockAPIError (also a RuntimeError) unexpected HTTP status
170
+ ├── SherlockBadRequestError 400
171
+ ├── SherlockNotFoundError 404
172
+ ├── SherlockTimeoutError 408
173
+ └── SherlockServerError 5xx
174
+ ```
175
+
176
+ `SherlockAPIError` carries `.status_code`, `.reason`, `.body` (truncated to 500
177
+ characters), `.method` and `.url`.
178
+
179
+ ```python
180
+ from sherlock_api import SherlockNotFoundError
181
+
182
+ try:
183
+ client.get_case("0" * 32)
184
+ except SherlockNotFoundError as err:
185
+ print(err.status_code, err.url)
186
+ ```
187
+
188
+ Network-level failures (`requests.ConnectionError`, `requests.Timeout`)
189
+ propagate from `requests` unchanged.
190
+
191
+ ## Logging
192
+
193
+ The library logs to the `sherlock_api` logger and attaches a `NullHandler`, so
194
+ it stays silent until your application configures logging:
195
+
196
+ ```python
197
+ import logging
198
+
199
+ logging.basicConfig(level=logging.INFO)
200
+ ```
201
+
202
+ ## Development
203
+
204
+ ```bash
205
+ python -m venv .venv && source .venv/bin/activate
206
+ pip install -e ".[dev]"
207
+
208
+ pytest # offline, no Sherlock server needed
209
+ ruff check .
210
+ mypy src/
211
+ ```
212
+
213
+ `examples/smoke_check.py` exercises the process endpoints against a live
214
+ Sherlock instance.
215
+
216
+ ## License
217
+
218
+ Apache-2.0. See [LICENSE](LICENSE).
@@ -0,0 +1,181 @@
1
+ # sherlock-api
2
+
3
+ Python client for the [Sherlock](https://github.com/kirillmeisser/sherlock-python-api) REST API.
4
+ Build your own Sherlock applications — create cases and batches, upload
5
+ inspection images with measurements, write log entries, and drive modal dialogs
6
+ and notifications in a running Sherlock process.
7
+
8
+ ## Install
9
+
10
+ ```bash
11
+ pip install sherlock-api
12
+ ```
13
+
14
+ Requires Python 3.10+.
15
+
16
+ ## Quickstart
17
+
18
+ ```python
19
+ from PIL import Image
20
+ from sherlock_api import (
21
+ SherlockAPIClient,
22
+ CreateCaseRequest,
23
+ CreateBatchRequest,
24
+ RobotPlatform,
25
+ DecisionClass,
26
+ )
27
+
28
+ with SherlockAPIClient(sherlock_port=8080) as client:
29
+ case = client.post_case(
30
+ CreateCaseRequest(
31
+ "Bushing inspection",
32
+ RobotPlatform.UNIVERSAL_ROBOTS,
33
+ "0A0E012F7772596B03D92AAA544763BB",
34
+ )
35
+ )
36
+ batch = client.post_batch(CreateBatchRequest(case["id"], "Batch 1"))
37
+
38
+ image, measurements = client.upload_image_with_measurements(
39
+ Image.open("part.png"),
40
+ "part.png",
41
+ DecisionClass.Ok,
42
+ [("diameter_mm", 12.04), ("roundness", 0.98)],
43
+ batch["id"],
44
+ )
45
+
46
+ client.log_batch_info(batch["id"], f"Uploaded {image['image_name']}")
47
+ ```
48
+
49
+ ## Configuration
50
+
51
+ Every constructor argument falls back to an environment variable. A script
52
+ launched *by* Sherlock gets these for free, so `SherlockAPIClient()` with no
53
+ arguments is usually all you need:
54
+
55
+ | Argument | Environment variable | Default |
56
+ | --- | --- | --- |
57
+ | `sherlock_url` | `SHERLOCK_URL` | `http://localhost` |
58
+ | `sherlock_port` | `SHERLOCK_PORT` | — (required) |
59
+ | `sherlock_process_id` | `SHERLOCK_PROCESS_ID` | `None` |
60
+ | `sherlock_case_id` | `SHERLOCK_CASE_ID` | `None` |
61
+ | `sherlock_batch_id` | `SHERLOCK_BATCH_ID` | `None` |
62
+
63
+ The three id defaults are used whenever you omit the corresponding argument —
64
+ `client.get_case()` reads `sherlock_case_id`, `client.get_batch()` reads
65
+ `sherlock_batch_id`, and the process methods read `sherlock_process_id`. Omitting
66
+ an argument that has no default raises `SherlockConfigurationError`.
67
+
68
+ Keyword-only options: `request_timeout` (seconds, default `30.0`), `max_retries`
69
+ (default `3`, applied to connection errors and 502/503/504 on GET and DELETE),
70
+ and `session` to supply your own `requests.Session`.
71
+
72
+ ## Modal dialogs
73
+
74
+ `post_modal` returns a modal id; `get_modal` long-polls for the operator's
75
+ answer and returns `DialogResult.NoResponse` if the poll expires. Its `timeout`
76
+ is in **milliseconds** and is enforced by the server — the client timeout is
77
+ widened automatically to outlast it.
78
+
79
+ ```python
80
+ from sherlock_api import (
81
+ CreateProcessModalDialogRequest,
82
+ DialogType,
83
+ DialogResult,
84
+ Language,
85
+ )
86
+
87
+ modal_id = client.post_modal(
88
+ CreateProcessModalDialogRequest(DialogType.YesNo, Language.English, "Part looks OK?")
89
+ )
90
+
91
+ result = client.get_modal(modal_id, timeout=30_000)
92
+ if result is DialogResult.NoResponse:
93
+ client.delete_modal(modal_id)
94
+ ```
95
+
96
+ ## Notifications
97
+
98
+ ```python
99
+ from sherlock_api import CreateNotificationRequest, NotificationAttachment
100
+
101
+ client.post_notification(
102
+ CreateNotificationRequest(
103
+ "Batch finished",
104
+ "42 parts inspected, 3 rejected.",
105
+ [NotificationAttachment("report.pdf", "application/pdf", pdf_bytes)],
106
+ )
107
+ )
108
+ ```
109
+
110
+ A notification sent to a process that no longer exists is logged as a warning
111
+ on the `sherlock_api.client` logger rather than raised — it is fire-and-forget.
112
+
113
+ ## API surface
114
+
115
+ | Area | Methods |
116
+ | --- | --- |
117
+ | Files | `get_file`, `post_file`, `post_file_from_memory` |
118
+ | Cases | `get_cases`, `get_case`, `post_case` |
119
+ | Batches | `get_batch`, `get_batches_for_case`, `post_batch` |
120
+ | Images | `get_image`, `get_images_for_batch`, `post_image`, `upload_image`, `upload_image_with_measurement`, `upload_image_with_measurements` |
121
+ | Logs | `get_log`, `post_log`, `log_{case,batch,image}_{error,warning,info}` |
122
+ | Measurements | `get_measurement`, `post_measurement`, `delete_measurement` |
123
+ | Processes | `get_process_state`, `is_process_running`, `get_env_state`, `get_env_vars`, `post_modal`, `get_modal`, `delete_modal`, `post_notification` |
124
+
125
+ Methods returning JSON return the parsed `dict` or `list` from the server as-is.
126
+
127
+ ## Errors
128
+
129
+ ```text
130
+ SherlockError
131
+ ├── SherlockConfigurationError (also a ValueError) missing port or id
132
+ └── SherlockAPIError (also a RuntimeError) unexpected HTTP status
133
+ ├── SherlockBadRequestError 400
134
+ ├── SherlockNotFoundError 404
135
+ ├── SherlockTimeoutError 408
136
+ └── SherlockServerError 5xx
137
+ ```
138
+
139
+ `SherlockAPIError` carries `.status_code`, `.reason`, `.body` (truncated to 500
140
+ characters), `.method` and `.url`.
141
+
142
+ ```python
143
+ from sherlock_api import SherlockNotFoundError
144
+
145
+ try:
146
+ client.get_case("0" * 32)
147
+ except SherlockNotFoundError as err:
148
+ print(err.status_code, err.url)
149
+ ```
150
+
151
+ Network-level failures (`requests.ConnectionError`, `requests.Timeout`)
152
+ propagate from `requests` unchanged.
153
+
154
+ ## Logging
155
+
156
+ The library logs to the `sherlock_api` logger and attaches a `NullHandler`, so
157
+ it stays silent until your application configures logging:
158
+
159
+ ```python
160
+ import logging
161
+
162
+ logging.basicConfig(level=logging.INFO)
163
+ ```
164
+
165
+ ## Development
166
+
167
+ ```bash
168
+ python -m venv .venv && source .venv/bin/activate
169
+ pip install -e ".[dev]"
170
+
171
+ pytest # offline, no Sherlock server needed
172
+ ruff check .
173
+ mypy src/
174
+ ```
175
+
176
+ `examples/smoke_check.py` exercises the process endpoints against a live
177
+ Sherlock instance.
178
+
179
+ ## License
180
+
181
+ Apache-2.0. See [LICENSE](LICENSE).