nsfw-sherlock 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.
- nsfw_sherlock-0.1.0/.gitignore +7 -0
- nsfw_sherlock-0.1.0/CHANGELOG.md +3 -0
- nsfw_sherlock-0.1.0/LICENSE +21 -0
- nsfw_sherlock-0.1.0/PKG-INFO +90 -0
- nsfw_sherlock-0.1.0/README.md +62 -0
- nsfw_sherlock-0.1.0/nsfw_sherlock/__init__.py +39 -0
- nsfw_sherlock-0.1.0/nsfw_sherlock/client.py +369 -0
- nsfw_sherlock-0.1.0/nsfw_sherlock/models.py +279 -0
- nsfw_sherlock-0.1.0/pyproject.toml +46 -0
- nsfw_sherlock-0.1.0/tests/test_client.py +216 -0
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Michal Žídek
|
|
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,90 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: nsfw-sherlock
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Python client for the self-hosted NSFW Sherlock moderation API.
|
|
5
|
+
Project-URL: Homepage, https://github.com/M1chlCZ/nsfw_sherlock
|
|
6
|
+
Project-URL: Documentation, https://github.com/M1chlCZ/nsfw_sherlock/blob/main/Readme.md
|
|
7
|
+
Project-URL: Issues, https://github.com/M1chlCZ/nsfw_sherlock/issues
|
|
8
|
+
Author: M1chlCZ
|
|
9
|
+
License: MIT
|
|
10
|
+
License-File: LICENSE
|
|
11
|
+
Keywords: content-safety,moderation,nsfw,self-hosted
|
|
12
|
+
Classifier: Development Status :: 4 - Beta
|
|
13
|
+
Classifier: Intended Audience :: Developers
|
|
14
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
15
|
+
Classifier: Programming Language :: Python :: 3
|
|
16
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
18
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
19
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
20
|
+
Classifier: Topic :: Software Development :: Libraries
|
|
21
|
+
Requires-Python: >=3.10
|
|
22
|
+
Requires-Dist: httpx>=0.27
|
|
23
|
+
Provides-Extra: dev
|
|
24
|
+
Requires-Dist: build>=1.2; extra == 'dev'
|
|
25
|
+
Requires-Dist: pytest>=8; extra == 'dev'
|
|
26
|
+
Requires-Dist: ruff>=0.8; extra == 'dev'
|
|
27
|
+
Description-Content-Type: text/markdown
|
|
28
|
+
|
|
29
|
+
# nsfw-sherlock (Python)
|
|
30
|
+
|
|
31
|
+
A thin, typed Python client for a self-hosted
|
|
32
|
+
[NSFW Sherlock](https://github.com/M1chlCZ/nsfw_sherlock) server. The client
|
|
33
|
+
does not bundle a model or run inference; start the server first.
|
|
34
|
+
|
|
35
|
+
## Install
|
|
36
|
+
|
|
37
|
+
```sh
|
|
38
|
+
pip install nsfw-sherlock
|
|
39
|
+
```
|
|
40
|
+
|
|
41
|
+
## Quick start
|
|
42
|
+
|
|
43
|
+
```python
|
|
44
|
+
from nsfw_sherlock import Client
|
|
45
|
+
|
|
46
|
+
with Client("http://localhost:4000", api_key="optional-key") as client:
|
|
47
|
+
result = client.check("https://example.com/upload.jpg")
|
|
48
|
+
print(result.nsfw_pic)
|
|
49
|
+
```
|
|
50
|
+
|
|
51
|
+
`str` inputs are URLs. Pass a `Path` for a local file and `bytes` for an
|
|
52
|
+
in-memory image:
|
|
53
|
+
|
|
54
|
+
```python
|
|
55
|
+
from pathlib import Path
|
|
56
|
+
from nsfw_sherlock import Client
|
|
57
|
+
|
|
58
|
+
with Client() as client:
|
|
59
|
+
analysis = client.analyze(Path("photo.jpg"), policy="strict")
|
|
60
|
+
print(analysis.verdict, analysis.nsfw, analysis.policy)
|
|
61
|
+
for reason in analysis.reasons:
|
|
62
|
+
print(reason.rule, reason.label, reason.score, reason.threshold)
|
|
63
|
+
|
|
64
|
+
evidence = client.annotate(Path("photo.jpg"), max_width=1280)
|
|
65
|
+
Path("evidence.png").write_bytes(evidence)
|
|
66
|
+
```
|
|
67
|
+
|
|
68
|
+
## Methods
|
|
69
|
+
|
|
70
|
+
| Method | API |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `check(source, ...)` | `POST /pic/check` |
|
|
73
|
+
| `labels(source, ...)` | `POST /pic/labels` |
|
|
74
|
+
| `analyze(source, ...)` | `POST /pic/analyze` |
|
|
75
|
+
| `annotate(source, ..., max_width=1280, image_format="png")` | `POST /pic/annotate`, returns bytes |
|
|
76
|
+
| `batch(sources, ...)` | `POST /pic/batch` |
|
|
77
|
+
| `upload(data, ...)` | `POST /pic/upload` |
|
|
78
|
+
| `submit_batch(...)`, `submit_video(...)` | `POST /jobs` |
|
|
79
|
+
| `get_job(id)`, `list_jobs(...)`, `cancel_job(id)` | job endpoints |
|
|
80
|
+
| `openapi()` | `GET /openapi.json` |
|
|
81
|
+
|
|
82
|
+
All image methods accept `sensitivity` (0.1 to 10) and `policy` (for example
|
|
83
|
+
`strict`, `balanced`, `lenient`, or a policy configured on the server).
|
|
84
|
+
`batch` returns `CheckResult` or `ErrorResult` per image. Errors raise
|
|
85
|
+
`NSFWSherlockError`; a 429 raises `RateLimitError`. The client retries 429 and
|
|
86
|
+
5xx responses up to `retries` times and honours `Retry-After`.
|
|
87
|
+
|
|
88
|
+
## License
|
|
89
|
+
|
|
90
|
+
The SDK is MIT licensed, independent of the AGPL-3.0 server.
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# nsfw-sherlock (Python)
|
|
2
|
+
|
|
3
|
+
A thin, typed Python client for a self-hosted
|
|
4
|
+
[NSFW Sherlock](https://github.com/M1chlCZ/nsfw_sherlock) server. The client
|
|
5
|
+
does not bundle a model or run inference; start the server first.
|
|
6
|
+
|
|
7
|
+
## Install
|
|
8
|
+
|
|
9
|
+
```sh
|
|
10
|
+
pip install nsfw-sherlock
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Quick start
|
|
14
|
+
|
|
15
|
+
```python
|
|
16
|
+
from nsfw_sherlock import Client
|
|
17
|
+
|
|
18
|
+
with Client("http://localhost:4000", api_key="optional-key") as client:
|
|
19
|
+
result = client.check("https://example.com/upload.jpg")
|
|
20
|
+
print(result.nsfw_pic)
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
`str` inputs are URLs. Pass a `Path` for a local file and `bytes` for an
|
|
24
|
+
in-memory image:
|
|
25
|
+
|
|
26
|
+
```python
|
|
27
|
+
from pathlib import Path
|
|
28
|
+
from nsfw_sherlock import Client
|
|
29
|
+
|
|
30
|
+
with Client() as client:
|
|
31
|
+
analysis = client.analyze(Path("photo.jpg"), policy="strict")
|
|
32
|
+
print(analysis.verdict, analysis.nsfw, analysis.policy)
|
|
33
|
+
for reason in analysis.reasons:
|
|
34
|
+
print(reason.rule, reason.label, reason.score, reason.threshold)
|
|
35
|
+
|
|
36
|
+
evidence = client.annotate(Path("photo.jpg"), max_width=1280)
|
|
37
|
+
Path("evidence.png").write_bytes(evidence)
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
## Methods
|
|
41
|
+
|
|
42
|
+
| Method | API |
|
|
43
|
+
| --- | --- |
|
|
44
|
+
| `check(source, ...)` | `POST /pic/check` |
|
|
45
|
+
| `labels(source, ...)` | `POST /pic/labels` |
|
|
46
|
+
| `analyze(source, ...)` | `POST /pic/analyze` |
|
|
47
|
+
| `annotate(source, ..., max_width=1280, image_format="png")` | `POST /pic/annotate`, returns bytes |
|
|
48
|
+
| `batch(sources, ...)` | `POST /pic/batch` |
|
|
49
|
+
| `upload(data, ...)` | `POST /pic/upload` |
|
|
50
|
+
| `submit_batch(...)`, `submit_video(...)` | `POST /jobs` |
|
|
51
|
+
| `get_job(id)`, `list_jobs(...)`, `cancel_job(id)` | job endpoints |
|
|
52
|
+
| `openapi()` | `GET /openapi.json` |
|
|
53
|
+
|
|
54
|
+
All image methods accept `sensitivity` (0.1 to 10) and `policy` (for example
|
|
55
|
+
`strict`, `balanced`, `lenient`, or a policy configured on the server).
|
|
56
|
+
`batch` returns `CheckResult` or `ErrorResult` per image. Errors raise
|
|
57
|
+
`NSFWSherlockError`; a 429 raises `RateLimitError`. The client retries 429 and
|
|
58
|
+
5xx responses up to `retries` times and honours `Retry-After`.
|
|
59
|
+
|
|
60
|
+
## License
|
|
61
|
+
|
|
62
|
+
The SDK is MIT licensed, independent of the AGPL-3.0 server.
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
"""Python client for the self-hosted NSFW Sherlock moderation API."""
|
|
2
|
+
|
|
3
|
+
from .client import Client, ImageInput, NSFWSherlockError, RateLimitError
|
|
4
|
+
from .models import (
|
|
5
|
+
Analysis,
|
|
6
|
+
Box,
|
|
7
|
+
CheckResult,
|
|
8
|
+
ClassifierOutput,
|
|
9
|
+
Detection,
|
|
10
|
+
ErrorResult,
|
|
11
|
+
Job,
|
|
12
|
+
JobList,
|
|
13
|
+
Labels,
|
|
14
|
+
LabelsResult,
|
|
15
|
+
ModelInfo,
|
|
16
|
+
Reason,
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
__version__ = "0.1.0"
|
|
20
|
+
|
|
21
|
+
__all__ = [
|
|
22
|
+
"Analysis",
|
|
23
|
+
"Box",
|
|
24
|
+
"CheckResult",
|
|
25
|
+
"ClassifierOutput",
|
|
26
|
+
"Client",
|
|
27
|
+
"Detection",
|
|
28
|
+
"ErrorResult",
|
|
29
|
+
"ImageInput",
|
|
30
|
+
"Job",
|
|
31
|
+
"JobList",
|
|
32
|
+
"Labels",
|
|
33
|
+
"LabelsResult",
|
|
34
|
+
"ModelInfo",
|
|
35
|
+
"NSFWSherlockError",
|
|
36
|
+
"RateLimitError",
|
|
37
|
+
"Reason",
|
|
38
|
+
"__version__",
|
|
39
|
+
]
|
|
@@ -0,0 +1,369 @@
|
|
|
1
|
+
"""Synchronous Python client for the NSFW Sherlock API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import time
|
|
7
|
+
from collections.abc import Mapping, Sequence
|
|
8
|
+
from pathlib import Path
|
|
9
|
+
from typing import Any
|
|
10
|
+
|
|
11
|
+
import httpx
|
|
12
|
+
|
|
13
|
+
from .models import (
|
|
14
|
+
Analysis,
|
|
15
|
+
CheckResult,
|
|
16
|
+
ErrorResult,
|
|
17
|
+
Job,
|
|
18
|
+
JobList,
|
|
19
|
+
LabelsResult,
|
|
20
|
+
)
|
|
21
|
+
|
|
22
|
+
__all__ = ["Client", "ImageInput", "NSFWSherlockError", "RateLimitError"]
|
|
23
|
+
|
|
24
|
+
ImageInput = bytes | bytearray | memoryview | str | Path
|
|
25
|
+
|
|
26
|
+
_RETRY_STATUSES = frozenset({429, 500, 502, 503, 504})
|
|
27
|
+
_USER_AGENT = "nsfw-sherlock-python/0.1.0"
|
|
28
|
+
|
|
29
|
+
|
|
30
|
+
class NSFWSherlockError(Exception):
|
|
31
|
+
"""An API or transport error."""
|
|
32
|
+
|
|
33
|
+
def __init__(
|
|
34
|
+
self,
|
|
35
|
+
message: str,
|
|
36
|
+
*,
|
|
37
|
+
status_code: int | None = None,
|
|
38
|
+
payload: Mapping[str, Any] | None = None,
|
|
39
|
+
) -> None:
|
|
40
|
+
super().__init__(message)
|
|
41
|
+
self.status_code = status_code
|
|
42
|
+
self.payload = dict(payload or {})
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class RateLimitError(NSFWSherlockError):
|
|
46
|
+
"""The API rate limit is exhausted."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class Client:
|
|
50
|
+
"""A thin client for one NSFW Sherlock server.
|
|
51
|
+
|
|
52
|
+
The server must already be running. Export or pass an API key when the
|
|
53
|
+
server uses ``API_KEYS``.
|
|
54
|
+
"""
|
|
55
|
+
|
|
56
|
+
def __init__(
|
|
57
|
+
self,
|
|
58
|
+
base_url: str = "http://localhost:4000",
|
|
59
|
+
*,
|
|
60
|
+
api_key: str | None = None,
|
|
61
|
+
timeout: float = 30.0,
|
|
62
|
+
retries: int = 2,
|
|
63
|
+
transport: httpx.BaseTransport | None = None,
|
|
64
|
+
) -> None:
|
|
65
|
+
if retries < 0:
|
|
66
|
+
raise ValueError("retries must not be negative")
|
|
67
|
+
headers = {
|
|
68
|
+
"User-Agent": _USER_AGENT,
|
|
69
|
+
"Accept": "application/json",
|
|
70
|
+
}
|
|
71
|
+
if api_key:
|
|
72
|
+
headers["X-API-Key"] = api_key
|
|
73
|
+
self._client = httpx.Client(
|
|
74
|
+
base_url=base_url.rstrip("/"),
|
|
75
|
+
headers=headers,
|
|
76
|
+
timeout=timeout,
|
|
77
|
+
transport=transport,
|
|
78
|
+
)
|
|
79
|
+
self._retries = retries
|
|
80
|
+
|
|
81
|
+
def close(self) -> None:
|
|
82
|
+
"""Close the underlying HTTP connection pool."""
|
|
83
|
+
|
|
84
|
+
self._client.close()
|
|
85
|
+
|
|
86
|
+
def __enter__(self) -> Client:
|
|
87
|
+
return self
|
|
88
|
+
|
|
89
|
+
def __exit__(self, *_: object) -> None:
|
|
90
|
+
self.close()
|
|
91
|
+
|
|
92
|
+
def check(
|
|
93
|
+
self,
|
|
94
|
+
source: ImageInput,
|
|
95
|
+
*,
|
|
96
|
+
filename: str | None = None,
|
|
97
|
+
sensitivity: float | None = None,
|
|
98
|
+
policy: str | None = None,
|
|
99
|
+
) -> CheckResult:
|
|
100
|
+
"""Run the legacy boolean check."""
|
|
101
|
+
|
|
102
|
+
payload = self._payload(source, filename, sensitivity, policy)
|
|
103
|
+
response = self._request("POST", "/pic/check", json=payload)
|
|
104
|
+
return CheckResult.from_dict(self._document(response))
|
|
105
|
+
|
|
106
|
+
def labels(
|
|
107
|
+
self,
|
|
108
|
+
source: ImageInput,
|
|
109
|
+
*,
|
|
110
|
+
filename: str | None = None,
|
|
111
|
+
sensitivity: float | None = None,
|
|
112
|
+
policy: str | None = None,
|
|
113
|
+
) -> LabelsResult:
|
|
114
|
+
"""Return the five legacy label probabilities."""
|
|
115
|
+
|
|
116
|
+
payload = self._payload(source, filename, sensitivity, policy)
|
|
117
|
+
response = self._request("POST", "/pic/labels", json=payload)
|
|
118
|
+
return LabelsResult.from_dict(self._document(response))
|
|
119
|
+
|
|
120
|
+
def analyze(
|
|
121
|
+
self,
|
|
122
|
+
source: ImageInput,
|
|
123
|
+
*,
|
|
124
|
+
filename: str | None = None,
|
|
125
|
+
sensitivity: float | None = None,
|
|
126
|
+
policy: str | None = None,
|
|
127
|
+
) -> Analysis:
|
|
128
|
+
"""Return the full verdict, scores, detections and reasons."""
|
|
129
|
+
|
|
130
|
+
payload = self._payload(source, filename, sensitivity, policy)
|
|
131
|
+
response = self._request("POST", "/pic/analyze", json=payload)
|
|
132
|
+
return Analysis.from_dict(self._document(response))
|
|
133
|
+
|
|
134
|
+
def annotate(
|
|
135
|
+
self,
|
|
136
|
+
source: ImageInput,
|
|
137
|
+
*,
|
|
138
|
+
filename: str | None = None,
|
|
139
|
+
sensitivity: float | None = None,
|
|
140
|
+
policy: str | None = None,
|
|
141
|
+
max_width: int = 1280,
|
|
142
|
+
image_format: str = "png",
|
|
143
|
+
) -> bytes:
|
|
144
|
+
"""Return an annotated PNG or JPEG as raw bytes."""
|
|
145
|
+
|
|
146
|
+
if image_format not in ("png", "jpeg", "jpg"):
|
|
147
|
+
raise ValueError("image_format must be png or jpeg")
|
|
148
|
+
if not 320 <= max_width <= 4096:
|
|
149
|
+
raise ValueError("max_width must be between 320 and 4096")
|
|
150
|
+
payload = self._payload(source, filename, sensitivity, policy)
|
|
151
|
+
payload["maxWidth"] = max_width
|
|
152
|
+
payload["format"] = "jpeg" if image_format == "jpg" else image_format
|
|
153
|
+
response = self._request("POST", "/pic/annotate", json=payload)
|
|
154
|
+
return response.content
|
|
155
|
+
|
|
156
|
+
def batch(
|
|
157
|
+
self,
|
|
158
|
+
sources: Sequence[ImageInput],
|
|
159
|
+
*,
|
|
160
|
+
sensitivity: float | None = None,
|
|
161
|
+
policy: str | None = None,
|
|
162
|
+
) -> list[CheckResult | ErrorResult]:
|
|
163
|
+
"""Check several images in one request."""
|
|
164
|
+
|
|
165
|
+
if not sources:
|
|
166
|
+
raise ValueError("sources must not be empty")
|
|
167
|
+
images = [self._payload(source, None, sensitivity, policy) for source in sources]
|
|
168
|
+
response = self._request("POST", "/pic/batch", json={"images": images})
|
|
169
|
+
document = self._document(response)
|
|
170
|
+
results: list[CheckResult | ErrorResult] = []
|
|
171
|
+
for item in document.get("results") or []:
|
|
172
|
+
if item.get("hasError") or item.get("status") == "FAIL":
|
|
173
|
+
results.append(ErrorResult.from_dict(item))
|
|
174
|
+
else:
|
|
175
|
+
results.append(CheckResult.from_dict(item))
|
|
176
|
+
return results
|
|
177
|
+
|
|
178
|
+
def upload(
|
|
179
|
+
self,
|
|
180
|
+
data: bytes,
|
|
181
|
+
*,
|
|
182
|
+
sensitivity: float | None = None,
|
|
183
|
+
policy: str | None = None,
|
|
184
|
+
) -> CheckResult:
|
|
185
|
+
"""Check raw image bytes without base64 encoding."""
|
|
186
|
+
|
|
187
|
+
params = self._params(sensitivity, policy)
|
|
188
|
+
response = self._request(
|
|
189
|
+
"POST",
|
|
190
|
+
"/pic/upload",
|
|
191
|
+
params=params,
|
|
192
|
+
content=data,
|
|
193
|
+
headers={"Content-Type": "application/octet-stream"},
|
|
194
|
+
)
|
|
195
|
+
return CheckResult.from_dict(self._document(response))
|
|
196
|
+
|
|
197
|
+
def submit_batch(
|
|
198
|
+
self,
|
|
199
|
+
sources: Sequence[ImageInput],
|
|
200
|
+
*,
|
|
201
|
+
callback_url: str | None = None,
|
|
202
|
+
sensitivity: float | None = None,
|
|
203
|
+
policy: str | None = None,
|
|
204
|
+
) -> Job:
|
|
205
|
+
"""Start a background batch job."""
|
|
206
|
+
|
|
207
|
+
if not sources:
|
|
208
|
+
raise ValueError("sources must not be empty")
|
|
209
|
+
payload: dict[str, Any] = {
|
|
210
|
+
"images": [self._payload(source, None, sensitivity, policy) for source in sources]
|
|
211
|
+
}
|
|
212
|
+
if callback_url:
|
|
213
|
+
payload["callbackUrl"] = callback_url
|
|
214
|
+
response = self._request("POST", "/jobs", json=payload)
|
|
215
|
+
return self._job(response)
|
|
216
|
+
|
|
217
|
+
def submit_video(
|
|
218
|
+
self,
|
|
219
|
+
path: str | Path,
|
|
220
|
+
*,
|
|
221
|
+
callback_url: str | None = None,
|
|
222
|
+
sensitivity: float | None = None,
|
|
223
|
+
policy: str | None = None,
|
|
224
|
+
) -> Job:
|
|
225
|
+
"""Start a background video job from a local file."""
|
|
226
|
+
|
|
227
|
+
file_path = Path(path)
|
|
228
|
+
data: dict[str, str] = {}
|
|
229
|
+
if callback_url:
|
|
230
|
+
data["callbackUrl"] = callback_url
|
|
231
|
+
if sensitivity is not None:
|
|
232
|
+
data["sensitivity"] = str(sensitivity)
|
|
233
|
+
if policy:
|
|
234
|
+
data["policy"] = policy
|
|
235
|
+
response = self._request(
|
|
236
|
+
"POST",
|
|
237
|
+
"/jobs",
|
|
238
|
+
data=data,
|
|
239
|
+
files={"file": (file_path.name, file_path.read_bytes(), "application/octet-stream")},
|
|
240
|
+
)
|
|
241
|
+
return self._job(response)
|
|
242
|
+
|
|
243
|
+
def get_job(self, job_id: str) -> Job:
|
|
244
|
+
"""Fetch one background job."""
|
|
245
|
+
|
|
246
|
+
response = self._request("GET", f"/jobs/{job_id}")
|
|
247
|
+
return self._job(response)
|
|
248
|
+
|
|
249
|
+
def list_jobs(self, *, state: str | None = None, limit: int | None = None) -> JobList:
|
|
250
|
+
"""List kept jobs, newest first."""
|
|
251
|
+
|
|
252
|
+
params: dict[str, Any] = {}
|
|
253
|
+
if state:
|
|
254
|
+
params["state"] = state
|
|
255
|
+
if limit is not None:
|
|
256
|
+
params["limit"] = limit
|
|
257
|
+
response = self._request("GET", "/jobs", params=params)
|
|
258
|
+
document = self._document(response)
|
|
259
|
+
document.setdefault("jobs", [])
|
|
260
|
+
return JobList.from_dict(document)
|
|
261
|
+
|
|
262
|
+
def cancel_job(self, job_id: str) -> Mapping[str, Any]:
|
|
263
|
+
"""Cancel a queued or running job."""
|
|
264
|
+
|
|
265
|
+
response = self._request("DELETE", f"/jobs/{job_id}")
|
|
266
|
+
return self._document(response)
|
|
267
|
+
|
|
268
|
+
def openapi(self) -> Mapping[str, Any]:
|
|
269
|
+
"""Fetch the OpenAPI document served by the API."""
|
|
270
|
+
|
|
271
|
+
response = self._request("GET", "/openapi.json")
|
|
272
|
+
return self._document(response)
|
|
273
|
+
|
|
274
|
+
def _payload(
|
|
275
|
+
self,
|
|
276
|
+
source: ImageInput,
|
|
277
|
+
filename: str | None,
|
|
278
|
+
sensitivity: float | None,
|
|
279
|
+
policy: str | None,
|
|
280
|
+
) -> dict[str, Any]:
|
|
281
|
+
payload: dict[str, Any] = {}
|
|
282
|
+
if isinstance(source, (bytes, bytearray, memoryview)):
|
|
283
|
+
payload["base64"] = base64.b64encode(bytes(source)).decode("ascii")
|
|
284
|
+
if filename:
|
|
285
|
+
payload["filename"] = filename
|
|
286
|
+
elif isinstance(source, Path):
|
|
287
|
+
payload["base64"] = base64.b64encode(source.read_bytes()).decode("ascii")
|
|
288
|
+
payload["filename"] = filename or source.name
|
|
289
|
+
elif isinstance(source, str):
|
|
290
|
+
payload["url"] = source
|
|
291
|
+
else:
|
|
292
|
+
raise TypeError("source must be bytes, a Path or a URL string")
|
|
293
|
+
if sensitivity is not None:
|
|
294
|
+
if not 0.1 <= sensitivity <= 10:
|
|
295
|
+
raise ValueError("sensitivity must be between 0.1 and 10")
|
|
296
|
+
payload["sensitivity"] = sensitivity
|
|
297
|
+
if policy:
|
|
298
|
+
payload["policy"] = policy
|
|
299
|
+
return payload
|
|
300
|
+
|
|
301
|
+
def _params(self, sensitivity: float | None, policy: str | None) -> dict[str, Any]:
|
|
302
|
+
params: dict[str, Any] = {}
|
|
303
|
+
if sensitivity is not None:
|
|
304
|
+
if not 0.1 <= sensitivity <= 10:
|
|
305
|
+
raise ValueError("sensitivity must be between 0.1 and 10")
|
|
306
|
+
params["sensitivity"] = sensitivity
|
|
307
|
+
if policy:
|
|
308
|
+
params["policy"] = policy
|
|
309
|
+
return params
|
|
310
|
+
|
|
311
|
+
def _request(
|
|
312
|
+
self,
|
|
313
|
+
method: str,
|
|
314
|
+
path: str,
|
|
315
|
+
**kwargs: Any,
|
|
316
|
+
) -> httpx.Response:
|
|
317
|
+
attempt = 0
|
|
318
|
+
while True:
|
|
319
|
+
try:
|
|
320
|
+
response = self._client.request(method, path, **kwargs)
|
|
321
|
+
except httpx.HTTPError as error:
|
|
322
|
+
raise NSFWSherlockError(f"request failed: {error}") from error
|
|
323
|
+
if response.status_code not in _RETRY_STATUSES or attempt >= self._retries:
|
|
324
|
+
break
|
|
325
|
+
time.sleep(self._retry_delay(response, attempt))
|
|
326
|
+
attempt += 1
|
|
327
|
+
if response.status_code >= 400:
|
|
328
|
+
self._raise(response)
|
|
329
|
+
return response
|
|
330
|
+
|
|
331
|
+
@staticmethod
|
|
332
|
+
def _retry_delay(response: httpx.Response, attempt: int) -> float:
|
|
333
|
+
retry_after = response.headers.get("Retry-After", "")
|
|
334
|
+
try:
|
|
335
|
+
return min(max(float(retry_after), 0.0), 10.0)
|
|
336
|
+
except ValueError:
|
|
337
|
+
return min(0.5 * (2**attempt), 10.0)
|
|
338
|
+
|
|
339
|
+
@staticmethod
|
|
340
|
+
def _document(response: httpx.Response) -> dict[str, Any]:
|
|
341
|
+
try:
|
|
342
|
+
document = response.json()
|
|
343
|
+
except ValueError as error:
|
|
344
|
+
raise NSFWSherlockError("the server returned invalid JSON") from error
|
|
345
|
+
if not isinstance(document, dict):
|
|
346
|
+
raise NSFWSherlockError("the server returned a non-object response")
|
|
347
|
+
return document
|
|
348
|
+
|
|
349
|
+
def _job(self, response: httpx.Response) -> Job:
|
|
350
|
+
document = self._document(response)
|
|
351
|
+
job = document.get("job")
|
|
352
|
+
if not isinstance(job, dict):
|
|
353
|
+
raise NSFWSherlockError("the server returned no job")
|
|
354
|
+
return Job.from_dict(job)
|
|
355
|
+
|
|
356
|
+
@staticmethod
|
|
357
|
+
def _raise(response: httpx.Response) -> None:
|
|
358
|
+
message = f"HTTP {response.status_code}"
|
|
359
|
+
payload: dict[str, Any] = {}
|
|
360
|
+
try:
|
|
361
|
+
document = response.json()
|
|
362
|
+
except ValueError:
|
|
363
|
+
document = None
|
|
364
|
+
if isinstance(document, dict):
|
|
365
|
+
payload = document
|
|
366
|
+
message = str(document.get("errorMessage") or message)
|
|
367
|
+
if response.status_code == 429:
|
|
368
|
+
raise RateLimitError(message, status_code=response.status_code, payload=payload)
|
|
369
|
+
raise NSFWSherlockError(message, status_code=response.status_code, payload=payload)
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
"""Typed responses for the NSFW Sherlock API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from collections.abc import Mapping
|
|
6
|
+
from dataclasses import dataclass, field
|
|
7
|
+
from typing import Any
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _number(value: Any, default: float = 0.0) -> float:
|
|
11
|
+
try:
|
|
12
|
+
return float(value)
|
|
13
|
+
except (TypeError, ValueError):
|
|
14
|
+
return default
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _integer(value: Any, default: int | None = None) -> int | None:
|
|
18
|
+
try:
|
|
19
|
+
return int(value)
|
|
20
|
+
except (TypeError, ValueError):
|
|
21
|
+
return default
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
@dataclass(frozen=True)
|
|
25
|
+
class Labels:
|
|
26
|
+
"""The legacy five-label classifier scores."""
|
|
27
|
+
|
|
28
|
+
drawings: float = 0.0
|
|
29
|
+
hentai: float = 0.0
|
|
30
|
+
neutral: float = 0.0
|
|
31
|
+
porn: float = 0.0
|
|
32
|
+
sexy: float = 0.0
|
|
33
|
+
|
|
34
|
+
@classmethod
|
|
35
|
+
def from_dict(cls, data: Mapping[str, Any]) -> Labels:
|
|
36
|
+
return cls(
|
|
37
|
+
drawings=_number(data.get("drawings")),
|
|
38
|
+
hentai=_number(data.get("hentai")),
|
|
39
|
+
neutral=_number(data.get("neutral")),
|
|
40
|
+
porn=_number(data.get("porn")),
|
|
41
|
+
sexy=_number(data.get("sexy")),
|
|
42
|
+
)
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
@dataclass(frozen=True)
|
|
46
|
+
class Box:
|
|
47
|
+
"""A detection box in source-image pixels."""
|
|
48
|
+
|
|
49
|
+
x: float = 0.0
|
|
50
|
+
y: float = 0.0
|
|
51
|
+
w: float = 0.0
|
|
52
|
+
h: float = 0.0
|
|
53
|
+
|
|
54
|
+
@classmethod
|
|
55
|
+
def from_dict(cls, data: Mapping[str, Any]) -> Box:
|
|
56
|
+
return cls(
|
|
57
|
+
x=_number(data.get("x")),
|
|
58
|
+
y=_number(data.get("y")),
|
|
59
|
+
w=_number(data.get("w")),
|
|
60
|
+
h=_number(data.get("h")),
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
@dataclass(frozen=True)
|
|
65
|
+
class Detection:
|
|
66
|
+
"""One explicit or suggestive region."""
|
|
67
|
+
|
|
68
|
+
label: str = ""
|
|
69
|
+
score: float = 0.0
|
|
70
|
+
box: Box = field(default_factory=Box)
|
|
71
|
+
|
|
72
|
+
@classmethod
|
|
73
|
+
def from_dict(cls, data: Mapping[str, Any]) -> Detection:
|
|
74
|
+
return cls(
|
|
75
|
+
label=str(data.get("label", "")),
|
|
76
|
+
score=_number(data.get("score")),
|
|
77
|
+
box=Box.from_dict(data.get("box") or {}),
|
|
78
|
+
)
|
|
79
|
+
|
|
80
|
+
|
|
81
|
+
@dataclass(frozen=True)
|
|
82
|
+
class Reason:
|
|
83
|
+
"""One rule that supported the verdict."""
|
|
84
|
+
|
|
85
|
+
rule: str = ""
|
|
86
|
+
label: str = ""
|
|
87
|
+
score: float = 0.0
|
|
88
|
+
threshold: float = 0.0
|
|
89
|
+
verdict: str = ""
|
|
90
|
+
|
|
91
|
+
@classmethod
|
|
92
|
+
def from_dict(cls, data: Mapping[str, Any]) -> Reason:
|
|
93
|
+
return cls(
|
|
94
|
+
rule=str(data.get("rule", "")),
|
|
95
|
+
label=str(data.get("label", "")),
|
|
96
|
+
score=_number(data.get("score")),
|
|
97
|
+
threshold=_number(data.get("threshold")),
|
|
98
|
+
verdict=str(data.get("verdict", "")),
|
|
99
|
+
)
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
@dataclass(frozen=True)
|
|
103
|
+
class ClassifierOutput:
|
|
104
|
+
"""One classifier's raw scores."""
|
|
105
|
+
|
|
106
|
+
model: str = ""
|
|
107
|
+
scores: Mapping[str, float] = field(default_factory=dict)
|
|
108
|
+
|
|
109
|
+
@classmethod
|
|
110
|
+
def from_dict(cls, data: Mapping[str, Any]) -> ClassifierOutput:
|
|
111
|
+
scores = data.get("scores") or {}
|
|
112
|
+
return cls(
|
|
113
|
+
model=str(data.get("model", "")),
|
|
114
|
+
scores={str(key): _number(value) for key, value in scores.items()},
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
@dataclass(frozen=True)
|
|
119
|
+
class ModelInfo:
|
|
120
|
+
"""A model used for the analysis."""
|
|
121
|
+
|
|
122
|
+
id: str = ""
|
|
123
|
+
kind: str = ""
|
|
124
|
+
sha256: str = ""
|
|
125
|
+
|
|
126
|
+
@classmethod
|
|
127
|
+
def from_dict(cls, data: Mapping[str, Any]) -> ModelInfo:
|
|
128
|
+
return cls(
|
|
129
|
+
id=str(data.get("id", "")),
|
|
130
|
+
kind=str(data.get("kind", "")),
|
|
131
|
+
sha256=str(data.get("sha256", "")),
|
|
132
|
+
)
|
|
133
|
+
|
|
134
|
+
|
|
135
|
+
@dataclass(frozen=True)
|
|
136
|
+
class Analysis:
|
|
137
|
+
"""The full result of /pic/analyze or a video frame."""
|
|
138
|
+
|
|
139
|
+
verdict: str = ""
|
|
140
|
+
nsfw: float = 0.0
|
|
141
|
+
labels: Labels = field(default_factory=Labels)
|
|
142
|
+
detections: tuple[Detection, ...] = ()
|
|
143
|
+
reasons: tuple[Reason, ...] = ()
|
|
144
|
+
policy: str = ""
|
|
145
|
+
frames: int | None = None
|
|
146
|
+
frame: int | None = None
|
|
147
|
+
elapsed_ms: int = 0
|
|
148
|
+
photo: ClassifierOutput | None = None
|
|
149
|
+
anime: ClassifierOutput | None = None
|
|
150
|
+
models: tuple[ModelInfo, ...] = ()
|
|
151
|
+
|
|
152
|
+
@classmethod
|
|
153
|
+
def from_dict(cls, data: Mapping[str, Any]) -> Analysis:
|
|
154
|
+
photo = data.get("photo")
|
|
155
|
+
anime = data.get("anime")
|
|
156
|
+
return cls(
|
|
157
|
+
verdict=str(data.get("verdict", "")),
|
|
158
|
+
nsfw=_number(data.get("nsfw")),
|
|
159
|
+
labels=Labels.from_dict(data.get("labels") or {}),
|
|
160
|
+
detections=tuple(Detection.from_dict(item) for item in data.get("detections") or []),
|
|
161
|
+
reasons=tuple(Reason.from_dict(item) for item in data.get("reasons") or []),
|
|
162
|
+
policy=str(data.get("policy", "")),
|
|
163
|
+
frames=_integer(data.get("frames")),
|
|
164
|
+
frame=_integer(data.get("frame")),
|
|
165
|
+
elapsed_ms=_integer(data.get("elapsedMs"), 0) or 0,
|
|
166
|
+
photo=ClassifierOutput.from_dict(photo) if photo else None,
|
|
167
|
+
anime=ClassifierOutput.from_dict(anime) if anime else None,
|
|
168
|
+
models=tuple(ModelInfo.from_dict(item) for item in data.get("models") or []),
|
|
169
|
+
)
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
@dataclass(frozen=True)
|
|
173
|
+
class CheckResult:
|
|
174
|
+
"""The legacy boolean check."""
|
|
175
|
+
|
|
176
|
+
nsfw_pic: bool = False
|
|
177
|
+
nsfw_text: bool = False
|
|
178
|
+
status: str = ""
|
|
179
|
+
message: str = ""
|
|
180
|
+
|
|
181
|
+
@classmethod
|
|
182
|
+
def from_dict(cls, data: Mapping[str, Any]) -> CheckResult:
|
|
183
|
+
return cls(
|
|
184
|
+
nsfw_pic=bool(data.get("nsfwPic", False)),
|
|
185
|
+
nsfw_text=bool(data.get("nsfwText", False)),
|
|
186
|
+
status=str(data.get("status", "")),
|
|
187
|
+
message=str(data.get("message", "")),
|
|
188
|
+
)
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
@dataclass(frozen=True)
|
|
192
|
+
class LabelsResult:
|
|
193
|
+
"""The legacy five-label probabilities."""
|
|
194
|
+
|
|
195
|
+
drawings: float = 0.0
|
|
196
|
+
hentai: float = 0.0
|
|
197
|
+
neutral: float = 0.0
|
|
198
|
+
porn: float = 0.0
|
|
199
|
+
sexy: float = 0.0
|
|
200
|
+
nsfw_text: bool = False
|
|
201
|
+
status: str = ""
|
|
202
|
+
message: str = ""
|
|
203
|
+
|
|
204
|
+
@classmethod
|
|
205
|
+
def from_dict(cls, data: Mapping[str, Any]) -> LabelsResult:
|
|
206
|
+
return cls(
|
|
207
|
+
drawings=_number(data.get("drawings")),
|
|
208
|
+
hentai=_number(data.get("hentai")),
|
|
209
|
+
neutral=_number(data.get("neutral")),
|
|
210
|
+
porn=_number(data.get("porn")),
|
|
211
|
+
sexy=_number(data.get("sexy")),
|
|
212
|
+
nsfw_text=bool(data.get("nsfwText", False)),
|
|
213
|
+
status=str(data.get("status", "")),
|
|
214
|
+
message=str(data.get("message", "")),
|
|
215
|
+
)
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
@dataclass(frozen=True)
|
|
219
|
+
class ErrorResult:
|
|
220
|
+
"""One failed item in a batch."""
|
|
221
|
+
|
|
222
|
+
message: str = ""
|
|
223
|
+
status: str = ""
|
|
224
|
+
has_error: bool = True
|
|
225
|
+
|
|
226
|
+
@classmethod
|
|
227
|
+
def from_dict(cls, data: Mapping[str, Any]) -> ErrorResult:
|
|
228
|
+
return cls(
|
|
229
|
+
message=str(data.get("errorMessage", "")),
|
|
230
|
+
status=str(data.get("status", "")),
|
|
231
|
+
has_error=bool(data.get("hasError", True)),
|
|
232
|
+
)
|
|
233
|
+
|
|
234
|
+
|
|
235
|
+
@dataclass(frozen=True)
|
|
236
|
+
class Job:
|
|
237
|
+
"""A background batch or video job."""
|
|
238
|
+
|
|
239
|
+
id: str = ""
|
|
240
|
+
kind: str = ""
|
|
241
|
+
state: str = ""
|
|
242
|
+
result: Any = None
|
|
243
|
+
error: str = ""
|
|
244
|
+
created_at: str = ""
|
|
245
|
+
finished_at: str = ""
|
|
246
|
+
|
|
247
|
+
@classmethod
|
|
248
|
+
def from_dict(cls, data: Mapping[str, Any]) -> Job:
|
|
249
|
+
return cls(
|
|
250
|
+
id=str(data.get("id", "")),
|
|
251
|
+
kind=str(data.get("kind", "")),
|
|
252
|
+
state=str(data.get("state", "")),
|
|
253
|
+
result=data.get("result"),
|
|
254
|
+
error=str(data.get("error", "")),
|
|
255
|
+
created_at=str(data.get("createdAt", "")),
|
|
256
|
+
finished_at=str(data.get("finishedAt", "")),
|
|
257
|
+
)
|
|
258
|
+
|
|
259
|
+
|
|
260
|
+
@dataclass(frozen=True)
|
|
261
|
+
class JobList:
|
|
262
|
+
"""A page of kept jobs."""
|
|
263
|
+
|
|
264
|
+
jobs: tuple[Job, ...] = ()
|
|
265
|
+
counts: Mapping[str, int] = field(default_factory=dict)
|
|
266
|
+
status: str = ""
|
|
267
|
+
message: str = ""
|
|
268
|
+
|
|
269
|
+
@classmethod
|
|
270
|
+
def from_dict(cls, data: Mapping[str, Any]) -> JobList:
|
|
271
|
+
return cls(
|
|
272
|
+
jobs=tuple(Job.from_dict(item) for item in data.get("jobs") or []),
|
|
273
|
+
counts={
|
|
274
|
+
str(key): _integer(value, 0) or 0
|
|
275
|
+
for key, value in (data.get("counts") or {}).items()
|
|
276
|
+
},
|
|
277
|
+
status=str(data.get("status", "")),
|
|
278
|
+
message=str(data.get("message", "")),
|
|
279
|
+
)
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["hatchling>=1.27"]
|
|
3
|
+
build-backend = "hatchling.build"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "nsfw-sherlock"
|
|
7
|
+
version = "0.1.0"
|
|
8
|
+
description = "Python client for the self-hosted NSFW Sherlock moderation API."
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = { text = "MIT" }
|
|
12
|
+
authors = [{ name = "M1chlCZ" }]
|
|
13
|
+
keywords = ["moderation", "nsfw", "content-safety", "self-hosted"]
|
|
14
|
+
classifiers = [
|
|
15
|
+
"Development Status :: 4 - Beta",
|
|
16
|
+
"Intended Audience :: Developers",
|
|
17
|
+
"License :: OSI Approved :: MIT License",
|
|
18
|
+
"Programming Language :: Python :: 3",
|
|
19
|
+
"Programming Language :: Python :: 3.10",
|
|
20
|
+
"Programming Language :: Python :: 3.11",
|
|
21
|
+
"Programming Language :: Python :: 3.12",
|
|
22
|
+
"Programming Language :: Python :: 3.13",
|
|
23
|
+
"Topic :: Software Development :: Libraries",
|
|
24
|
+
]
|
|
25
|
+
dependencies = ["httpx>=0.27"]
|
|
26
|
+
|
|
27
|
+
[project.optional-dependencies]
|
|
28
|
+
dev = ["build>=1.2", "pytest>=8", "ruff>=0.8"]
|
|
29
|
+
|
|
30
|
+
[project.urls]
|
|
31
|
+
Homepage = "https://github.com/M1chlCZ/nsfw_sherlock"
|
|
32
|
+
Documentation = "https://github.com/M1chlCZ/nsfw_sherlock/blob/main/Readme.md"
|
|
33
|
+
Issues = "https://github.com/M1chlCZ/nsfw_sherlock/issues"
|
|
34
|
+
|
|
35
|
+
[tool.hatch.build.targets.wheel]
|
|
36
|
+
packages = ["nsfw_sherlock"]
|
|
37
|
+
|
|
38
|
+
[tool.pytest.ini_options]
|
|
39
|
+
testpaths = ["tests"]
|
|
40
|
+
|
|
41
|
+
[tool.ruff]
|
|
42
|
+
line-length = 100
|
|
43
|
+
target-version = "py310"
|
|
44
|
+
|
|
45
|
+
[tool.ruff.lint]
|
|
46
|
+
ignore = ["PYI034"]
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"""Client tests against an in-memory HTTP transport."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import httpx
|
|
9
|
+
import pytest
|
|
10
|
+
|
|
11
|
+
from nsfw_sherlock import Client, ErrorResult, NSFWSherlockError, RateLimitError
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
def make_client(handler, **kwargs) -> Client:
|
|
15
|
+
return Client("http://test", transport=httpx.MockTransport(handler), **kwargs)
|
|
16
|
+
|
|
17
|
+
|
|
18
|
+
def test_check_sends_a_url_and_the_api_key() -> None:
|
|
19
|
+
seen: dict[str, object] = {}
|
|
20
|
+
|
|
21
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
22
|
+
seen["method"] = request.method
|
|
23
|
+
seen["path"] = request.url.path
|
|
24
|
+
seen["key"] = request.headers.get("X-API-Key")
|
|
25
|
+
seen["body"] = json.loads(request.content)
|
|
26
|
+
return httpx.Response(
|
|
27
|
+
200,
|
|
28
|
+
json={"status": "ok", "message": "success", "nsfwPic": True, "nsfwText": False},
|
|
29
|
+
)
|
|
30
|
+
|
|
31
|
+
with make_client(handler, api_key="secret") as client:
|
|
32
|
+
result = client.check("https://example.com/a.jpg", sensitivity=1.5, policy="strict")
|
|
33
|
+
|
|
34
|
+
assert result.nsfw_pic is True and result.nsfw_text is False
|
|
35
|
+
assert seen == {
|
|
36
|
+
"method": "POST",
|
|
37
|
+
"path": "/pic/check",
|
|
38
|
+
"key": "secret",
|
|
39
|
+
"body": {
|
|
40
|
+
"url": "https://example.com/a.jpg",
|
|
41
|
+
"sensitivity": 1.5,
|
|
42
|
+
"policy": "strict",
|
|
43
|
+
},
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def test_analyze_parses_reasons_and_labels(tmp_path: Path) -> None:
|
|
48
|
+
image = tmp_path / "photo.jpg"
|
|
49
|
+
image.write_bytes(b"image-bytes")
|
|
50
|
+
seen: dict[str, object] = {}
|
|
51
|
+
|
|
52
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
53
|
+
seen["body"] = json.loads(request.content)
|
|
54
|
+
return httpx.Response(
|
|
55
|
+
200,
|
|
56
|
+
json={
|
|
57
|
+
"status": "ok",
|
|
58
|
+
"message": "success",
|
|
59
|
+
"verdict": "explicit",
|
|
60
|
+
"nsfw": 0.91,
|
|
61
|
+
"policy": "strict",
|
|
62
|
+
"frames": 2,
|
|
63
|
+
"frame": 2,
|
|
64
|
+
"labels": {
|
|
65
|
+
"drawings": 0.0,
|
|
66
|
+
"hentai": 0.0,
|
|
67
|
+
"neutral": 0.1,
|
|
68
|
+
"porn": 0.91,
|
|
69
|
+
"sexy": 0.2,
|
|
70
|
+
},
|
|
71
|
+
"detections": [
|
|
72
|
+
{"label": "EXPOSED", "score": 0.9, "box": {"x": 1, "y": 2, "w": 3, "h": 4}}
|
|
73
|
+
],
|
|
74
|
+
"reasons": [
|
|
75
|
+
{
|
|
76
|
+
"rule": "label",
|
|
77
|
+
"label": "porn",
|
|
78
|
+
"score": 0.91,
|
|
79
|
+
"threshold": 0.5,
|
|
80
|
+
"verdict": "explicit",
|
|
81
|
+
}
|
|
82
|
+
],
|
|
83
|
+
"elapsedMs": 42,
|
|
84
|
+
},
|
|
85
|
+
)
|
|
86
|
+
|
|
87
|
+
with make_client(handler) as client:
|
|
88
|
+
analysis = client.analyze(image, policy="strict")
|
|
89
|
+
|
|
90
|
+
assert analysis.verdict == "explicit"
|
|
91
|
+
assert analysis.policy == "strict"
|
|
92
|
+
assert analysis.frames == 2 and analysis.frame == 2
|
|
93
|
+
assert analysis.labels.porn == pytest.approx(0.91)
|
|
94
|
+
assert analysis.detections[0].box.w == 3
|
|
95
|
+
assert analysis.reasons[0].threshold == 0.5
|
|
96
|
+
assert seen["body"]["filename"] == "photo.jpg"
|
|
97
|
+
assert seen["body"]["base64"]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def test_annotate_returns_bytes_and_accepts_options() -> None:
|
|
101
|
+
seen: dict[str, object] = {}
|
|
102
|
+
|
|
103
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
104
|
+
seen["body"] = json.loads(request.content)
|
|
105
|
+
return httpx.Response(
|
|
106
|
+
200, content=b"\x89PNG\r\n\x1a\n", headers={"Content-Type": "image/png"}
|
|
107
|
+
)
|
|
108
|
+
|
|
109
|
+
with make_client(handler) as client:
|
|
110
|
+
data = client.annotate(b"image", max_width=640, image_format="jpeg")
|
|
111
|
+
|
|
112
|
+
assert data.startswith(b"\x89PNG")
|
|
113
|
+
assert seen["body"]["maxWidth"] == 640
|
|
114
|
+
assert seen["body"]["format"] == "jpeg"
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def test_batch_returns_results_and_errors() -> None:
|
|
118
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
119
|
+
body = json.loads(request.content)
|
|
120
|
+
assert len(body["images"]) == 2
|
|
121
|
+
return httpx.Response(
|
|
122
|
+
200,
|
|
123
|
+
json={
|
|
124
|
+
"status": "ok",
|
|
125
|
+
"message": "success",
|
|
126
|
+
"results": [
|
|
127
|
+
{"status": "ok", "message": "success", "nsfwPic": False, "nsfwText": False},
|
|
128
|
+
{"status": "FAIL", "hasError": True, "errorMessage": "bad image"},
|
|
129
|
+
],
|
|
130
|
+
},
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
with make_client(handler) as client:
|
|
134
|
+
results = client.batch([b"one", "https://example.com/two.jpg"], policy="lenient")
|
|
135
|
+
|
|
136
|
+
assert results[0].nsfw_pic is False # type: ignore[union-attr]
|
|
137
|
+
assert isinstance(results[1], ErrorResult)
|
|
138
|
+
assert results[1].message == "bad image"
|
|
139
|
+
|
|
140
|
+
|
|
141
|
+
def test_errors_and_retries() -> None:
|
|
142
|
+
calls = 0
|
|
143
|
+
|
|
144
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
145
|
+
nonlocal calls
|
|
146
|
+
calls += 1
|
|
147
|
+
if calls == 1:
|
|
148
|
+
return httpx.Response(
|
|
149
|
+
429, headers={"Retry-After": "0"}, json={"errorMessage": "slow down"}
|
|
150
|
+
)
|
|
151
|
+
return httpx.Response(
|
|
152
|
+
200, json={"status": "ok", "message": "success", "nsfwPic": False, "nsfwText": False}
|
|
153
|
+
)
|
|
154
|
+
|
|
155
|
+
with make_client(handler, retries=1) as client:
|
|
156
|
+
assert client.check(b"image").nsfw_pic is False
|
|
157
|
+
assert calls == 2
|
|
158
|
+
|
|
159
|
+
def bad_handler(_: httpx.Request) -> httpx.Response:
|
|
160
|
+
return httpx.Response(
|
|
161
|
+
400, json={"errorMessage": "bad request", "status": "FAIL", "hasError": True}
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
with make_client(bad_handler) as client, pytest.raises(NSFWSherlockError) as raised:
|
|
165
|
+
client.check(b"image")
|
|
166
|
+
assert raised.value.status_code == 400
|
|
167
|
+
assert "bad request" in str(raised.value)
|
|
168
|
+
|
|
169
|
+
with (
|
|
170
|
+
make_client(
|
|
171
|
+
lambda _: httpx.Response(429, json={"errorMessage": "rate limited"}), retries=0
|
|
172
|
+
) as client,
|
|
173
|
+
pytest.raises(RateLimitError),
|
|
174
|
+
):
|
|
175
|
+
client.check(b"image")
|
|
176
|
+
|
|
177
|
+
|
|
178
|
+
def test_jobs() -> None:
|
|
179
|
+
job = {
|
|
180
|
+
"id": "job-1",
|
|
181
|
+
"kind": "batch",
|
|
182
|
+
"state": "queued",
|
|
183
|
+
"createdAt": "2026-11-29T12:00:00Z",
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
def handler(request: httpx.Request) -> httpx.Response:
|
|
187
|
+
if request.method == "POST":
|
|
188
|
+
return httpx.Response(202, json={"status": "ok", "message": "success", "job": job})
|
|
189
|
+
if request.method == "DELETE":
|
|
190
|
+
return httpx.Response(200, json={"status": "ok", "message": "success"})
|
|
191
|
+
if request.url.path == "/jobs":
|
|
192
|
+
return httpx.Response(
|
|
193
|
+
200,
|
|
194
|
+
json={"status": "ok", "message": "success", "jobs": [job], "counts": {"queued": 1}},
|
|
195
|
+
)
|
|
196
|
+
return httpx.Response(
|
|
197
|
+
200, json={"status": "ok", "message": "success", "job": {**job, "state": "done"}}
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
with make_client(handler) as client:
|
|
201
|
+
created = client.submit_batch([b"image"])
|
|
202
|
+
assert created.id == "job-1"
|
|
203
|
+
fetched = client.get_job("job-1")
|
|
204
|
+
assert fetched.state == "done"
|
|
205
|
+
listing = client.list_jobs(state="queued", limit=10)
|
|
206
|
+
assert listing.counts["queued"] == 1
|
|
207
|
+
assert client.cancel_job("job-1")["status"] == "ok"
|
|
208
|
+
|
|
209
|
+
|
|
210
|
+
def test_openapi_contract() -> None:
|
|
211
|
+
spec_path = Path(__file__).resolve().parents[3] / "web" / "openapi.json"
|
|
212
|
+
spec = json.loads(spec_path.read_text())
|
|
213
|
+
assert spec["openapi"] == "3.1.0"
|
|
214
|
+
for path in ("/pic/check", "/pic/analyze", "/pic/annotate", "/jobs", "/openapi.json"):
|
|
215
|
+
assert path in spec["paths"]
|
|
216
|
+
assert "policy" in spec["components"]["schemas"]["PicRequest"]["properties"]
|