useknockout 0.0.1__py3-none-any.whl
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.
- useknockout/__init__.py +47 -0
- useknockout/_helpers.py +73 -0
- useknockout/_version.py +1 -0
- useknockout/async_client.py +325 -0
- useknockout/client.py +354 -0
- useknockout/errors.py +81 -0
- useknockout-0.0.1.dist-info/METADATA +191 -0
- useknockout-0.0.1.dist-info/RECORD +10 -0
- useknockout-0.0.1.dist-info/WHEEL +4 -0
- useknockout-0.0.1.dist-info/licenses/LICENSE +21 -0
useknockout/__init__.py
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
"""
|
|
2
|
+
useknockout — state-of-the-art background removal API.
|
|
3
|
+
|
|
4
|
+
Quickstart:
|
|
5
|
+
|
|
6
|
+
from useknockout import Knockout
|
|
7
|
+
|
|
8
|
+
client = Knockout(token="kno_public_beta_4d7e9f1a3c5b2e8d6a9f7c1b3e5d8a2f")
|
|
9
|
+
png_bytes = client.remove("photo.jpg")
|
|
10
|
+
open("out.png", "wb").write(png_bytes)
|
|
11
|
+
|
|
12
|
+
Async:
|
|
13
|
+
|
|
14
|
+
import asyncio
|
|
15
|
+
from useknockout import AsyncKnockout
|
|
16
|
+
|
|
17
|
+
async def main():
|
|
18
|
+
async with AsyncKnockout(token="...") as client:
|
|
19
|
+
png = await client.remove("photo.jpg")
|
|
20
|
+
open("out.png", "wb").write(png)
|
|
21
|
+
|
|
22
|
+
asyncio.run(main())
|
|
23
|
+
"""
|
|
24
|
+
|
|
25
|
+
from useknockout._version import __version__
|
|
26
|
+
from useknockout.client import Knockout
|
|
27
|
+
from useknockout.async_client import AsyncKnockout
|
|
28
|
+
from useknockout.errors import (
|
|
29
|
+
KnockoutError,
|
|
30
|
+
AuthError,
|
|
31
|
+
BadRequestError,
|
|
32
|
+
PayloadTooLargeError,
|
|
33
|
+
RateLimitError,
|
|
34
|
+
ServerError,
|
|
35
|
+
)
|
|
36
|
+
|
|
37
|
+
__all__ = [
|
|
38
|
+
"__version__",
|
|
39
|
+
"Knockout",
|
|
40
|
+
"AsyncKnockout",
|
|
41
|
+
"KnockoutError",
|
|
42
|
+
"AuthError",
|
|
43
|
+
"BadRequestError",
|
|
44
|
+
"PayloadTooLargeError",
|
|
45
|
+
"RateLimitError",
|
|
46
|
+
"ServerError",
|
|
47
|
+
]
|
useknockout/_helpers.py
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
"""Internal helpers shared by sync + async clients."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import os
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Any, Dict, List, Optional, Tuple, Union
|
|
8
|
+
|
|
9
|
+
FileInput = Union[str, Path, bytes, bytearray]
|
|
10
|
+
"""Anything the SDK accepts as image input.
|
|
11
|
+
|
|
12
|
+
- ``str`` / ``Path``: filesystem path to read.
|
|
13
|
+
- ``bytes`` / ``bytearray``: raw image bytes.
|
|
14
|
+
"""
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _to_bytes_and_name(file: FileInput, default_name: str = "image") -> Tuple[bytes, str]:
|
|
18
|
+
"""Normalize a FileInput to (bytes, filename) for httpx multipart."""
|
|
19
|
+
if isinstance(file, (bytes, bytearray)):
|
|
20
|
+
return bytes(file), default_name
|
|
21
|
+
if isinstance(file, (str, Path)):
|
|
22
|
+
path = Path(file)
|
|
23
|
+
return path.read_bytes(), path.name
|
|
24
|
+
raise TypeError(f"file must be path | bytes, got {type(file).__name__}")
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
def _multipart_files(
|
|
28
|
+
file: FileInput,
|
|
29
|
+
extra_files: Optional[List[FileInput]] = None,
|
|
30
|
+
) -> List[Tuple[str, Tuple[str, bytes, str]]]:
|
|
31
|
+
"""Build httpx-style files= argument for one or many uploads."""
|
|
32
|
+
files: List[Tuple[str, Tuple[str, bytes, str]]] = []
|
|
33
|
+
data, name = _to_bytes_and_name(file)
|
|
34
|
+
files.append(("file", (name, data, "application/octet-stream")))
|
|
35
|
+
if extra_files:
|
|
36
|
+
for f in extra_files:
|
|
37
|
+
d, n = _to_bytes_and_name(f)
|
|
38
|
+
files.append(("files", (n, d, "application/octet-stream")))
|
|
39
|
+
return files
|
|
40
|
+
|
|
41
|
+
|
|
42
|
+
def _multipart_batch(files_in: List[FileInput]) -> List[Tuple[str, Tuple[str, bytes, str]]]:
|
|
43
|
+
"""Build files= for /remove-batch (field name ``files``, repeated)."""
|
|
44
|
+
out: List[Tuple[str, Tuple[str, bytes, str]]] = []
|
|
45
|
+
for i, f in enumerate(files_in):
|
|
46
|
+
data, name = _to_bytes_and_name(f, default_name=f"image-{i}")
|
|
47
|
+
out.append(("files", (name, data, "application/octet-stream")))
|
|
48
|
+
return out
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def _form(data: Dict[str, Any]) -> Dict[str, str]:
|
|
52
|
+
"""Drop None values, stringify the rest, for httpx data= multipart fields."""
|
|
53
|
+
out: Dict[str, str] = {}
|
|
54
|
+
for k, v in data.items():
|
|
55
|
+
if v is None:
|
|
56
|
+
continue
|
|
57
|
+
if isinstance(v, bool):
|
|
58
|
+
out[k] = "true" if v else "false"
|
|
59
|
+
else:
|
|
60
|
+
out[k] = str(v)
|
|
61
|
+
return out
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _resolve_token(token: Optional[str]) -> Optional[str]:
|
|
65
|
+
"""Resolve token from arg or KNOCKOUT_TOKEN env var."""
|
|
66
|
+
if token:
|
|
67
|
+
return token
|
|
68
|
+
env = os.environ.get("KNOCKOUT_TOKEN", "").strip()
|
|
69
|
+
return env or None
|
|
70
|
+
|
|
71
|
+
|
|
72
|
+
DEFAULT_BASE_URL = "https://useknockout--api.modal.run"
|
|
73
|
+
PUBLIC_BETA_TOKEN = "kno_public_beta_4d7e9f1a3c5b2e8d6a9f7c1b3e5d8a2f"
|
useknockout/_version.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
__version__ = "0.0.1"
|
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
"""Asynchronous client for the useknockout API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from useknockout._helpers import (
|
|
10
|
+
DEFAULT_BASE_URL,
|
|
11
|
+
PUBLIC_BETA_TOKEN,
|
|
12
|
+
FileInput,
|
|
13
|
+
_form,
|
|
14
|
+
_multipart_batch,
|
|
15
|
+
_multipart_files,
|
|
16
|
+
_resolve_token,
|
|
17
|
+
)
|
|
18
|
+
from useknockout._version import __version__
|
|
19
|
+
from useknockout.errors import KnockoutError, raise_for_status
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class AsyncKnockout:
|
|
23
|
+
"""
|
|
24
|
+
Asynchronous client for the useknockout background-removal API.
|
|
25
|
+
|
|
26
|
+
Use as an async context manager to ensure the underlying httpx client closes:
|
|
27
|
+
|
|
28
|
+
async with AsyncKnockout() as client:
|
|
29
|
+
png = await client.remove("photo.jpg")
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
def __init__(
|
|
33
|
+
self,
|
|
34
|
+
token: Optional[str] = None,
|
|
35
|
+
*,
|
|
36
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
37
|
+
timeout: float = 60.0,
|
|
38
|
+
) -> None:
|
|
39
|
+
self.token = _resolve_token(token) or PUBLIC_BETA_TOKEN
|
|
40
|
+
self.base_url = base_url.rstrip("/")
|
|
41
|
+
self._http = httpx.AsyncClient(
|
|
42
|
+
base_url=self.base_url,
|
|
43
|
+
timeout=timeout,
|
|
44
|
+
headers={
|
|
45
|
+
"Authorization": f"Bearer {self.token}",
|
|
46
|
+
"User-Agent": f"useknockout-python/{__version__}",
|
|
47
|
+
},
|
|
48
|
+
)
|
|
49
|
+
|
|
50
|
+
async def __aenter__(self) -> "AsyncKnockout":
|
|
51
|
+
return self
|
|
52
|
+
|
|
53
|
+
async def __aexit__(self, exc_type, exc, tb) -> None:
|
|
54
|
+
await self.aclose()
|
|
55
|
+
|
|
56
|
+
async def aclose(self) -> None:
|
|
57
|
+
await self._http.aclose()
|
|
58
|
+
|
|
59
|
+
async def _request_bytes(
|
|
60
|
+
self,
|
|
61
|
+
method: str,
|
|
62
|
+
path: str,
|
|
63
|
+
*,
|
|
64
|
+
files=None,
|
|
65
|
+
data=None,
|
|
66
|
+
json=None,
|
|
67
|
+
) -> bytes:
|
|
68
|
+
try:
|
|
69
|
+
r = await self._http.request(method, path, files=files, data=data, json=json)
|
|
70
|
+
except httpx.RequestError as e:
|
|
71
|
+
raise KnockoutError(f"network error: {e}", code="unknown") from e
|
|
72
|
+
if r.status_code >= 400:
|
|
73
|
+
raise_for_status(r.status_code, r.content)
|
|
74
|
+
return r.content
|
|
75
|
+
|
|
76
|
+
async def _request_json(
|
|
77
|
+
self,
|
|
78
|
+
method: str,
|
|
79
|
+
path: str,
|
|
80
|
+
*,
|
|
81
|
+
files=None,
|
|
82
|
+
data=None,
|
|
83
|
+
json=None,
|
|
84
|
+
) -> Any:
|
|
85
|
+
try:
|
|
86
|
+
r = await self._http.request(method, path, files=files, data=data, json=json)
|
|
87
|
+
except httpx.RequestError as e:
|
|
88
|
+
raise KnockoutError(f"network error: {e}", code="unknown") from e
|
|
89
|
+
if r.status_code >= 400:
|
|
90
|
+
raise_for_status(r.status_code, r.content)
|
|
91
|
+
try:
|
|
92
|
+
return r.json()
|
|
93
|
+
except ValueError as e:
|
|
94
|
+
raise KnockoutError(f"invalid JSON response: {e}", code="server") from e
|
|
95
|
+
|
|
96
|
+
async def health(self) -> Dict[str, Any]:
|
|
97
|
+
return await self._request_json("GET", "/health")
|
|
98
|
+
|
|
99
|
+
async def stats(self) -> Dict[str, Any]:
|
|
100
|
+
return await self._request_json("GET", "/stats")
|
|
101
|
+
|
|
102
|
+
async def remove(self, file: FileInput, *, format: str = "png") -> bytes:
|
|
103
|
+
return await self._request_bytes(
|
|
104
|
+
"POST",
|
|
105
|
+
"/remove",
|
|
106
|
+
files=_multipart_files(file),
|
|
107
|
+
data=_form({"format": format}),
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
async def remove_url(self, url: str, *, format: str = "png") -> bytes:
|
|
111
|
+
return await self._request_bytes(
|
|
112
|
+
"POST",
|
|
113
|
+
"/remove-url",
|
|
114
|
+
json={"url": url, "format": format},
|
|
115
|
+
)
|
|
116
|
+
|
|
117
|
+
async def replace_background(
|
|
118
|
+
self,
|
|
119
|
+
file: FileInput,
|
|
120
|
+
*,
|
|
121
|
+
bg_color: str = "#FFFFFF",
|
|
122
|
+
bg_url: Optional[str] = None,
|
|
123
|
+
format: str = "png",
|
|
124
|
+
) -> bytes:
|
|
125
|
+
return await self._request_bytes(
|
|
126
|
+
"POST",
|
|
127
|
+
"/replace-bg",
|
|
128
|
+
files=_multipart_files(file),
|
|
129
|
+
data=_form({"bg_color": bg_color, "bg_url": bg_url, "format": format}),
|
|
130
|
+
)
|
|
131
|
+
|
|
132
|
+
async def remove_batch(
|
|
133
|
+
self,
|
|
134
|
+
files: List[FileInput],
|
|
135
|
+
*,
|
|
136
|
+
format: str = "png",
|
|
137
|
+
) -> Dict[str, Any]:
|
|
138
|
+
if len(files) > 10:
|
|
139
|
+
raise ValueError("max 10 files per batch")
|
|
140
|
+
return await self._request_json(
|
|
141
|
+
"POST",
|
|
142
|
+
"/remove-batch",
|
|
143
|
+
files=_multipart_batch(files),
|
|
144
|
+
data=_form({"format": format}),
|
|
145
|
+
)
|
|
146
|
+
|
|
147
|
+
async def remove_batch_url(self, urls: List[str], *, format: str = "png") -> Dict[str, Any]:
|
|
148
|
+
if len(urls) > 10:
|
|
149
|
+
raise ValueError("max 10 urls per batch")
|
|
150
|
+
return await self._request_json(
|
|
151
|
+
"POST",
|
|
152
|
+
"/remove-batch-url",
|
|
153
|
+
json={"urls": urls, "format": format},
|
|
154
|
+
)
|
|
155
|
+
|
|
156
|
+
async def mask(self, file: FileInput, *, format: str = "png") -> bytes:
|
|
157
|
+
return await self._request_bytes(
|
|
158
|
+
"POST",
|
|
159
|
+
"/mask",
|
|
160
|
+
files=_multipart_files(file),
|
|
161
|
+
data=_form({"format": format}),
|
|
162
|
+
)
|
|
163
|
+
|
|
164
|
+
async def smart_crop(
|
|
165
|
+
self,
|
|
166
|
+
file: FileInput,
|
|
167
|
+
*,
|
|
168
|
+
padding: int = 24,
|
|
169
|
+
transparent: bool = True,
|
|
170
|
+
format: str = "png",
|
|
171
|
+
) -> bytes:
|
|
172
|
+
return await self._request_bytes(
|
|
173
|
+
"POST",
|
|
174
|
+
"/smart-crop",
|
|
175
|
+
files=_multipart_files(file),
|
|
176
|
+
data=_form({"padding": padding, "transparent": transparent, "format": format}),
|
|
177
|
+
)
|
|
178
|
+
|
|
179
|
+
async def shadow(
|
|
180
|
+
self,
|
|
181
|
+
file: FileInput,
|
|
182
|
+
*,
|
|
183
|
+
bg_color: str = "#FFFFFF",
|
|
184
|
+
bg_url: Optional[str] = None,
|
|
185
|
+
shadow_color: str = "#000000",
|
|
186
|
+
shadow_offset_x: int = 8,
|
|
187
|
+
shadow_offset_y: int = 12,
|
|
188
|
+
shadow_blur: int = 14,
|
|
189
|
+
shadow_opacity: float = 0.45,
|
|
190
|
+
format: str = "png",
|
|
191
|
+
) -> bytes:
|
|
192
|
+
return await self._request_bytes(
|
|
193
|
+
"POST",
|
|
194
|
+
"/shadow",
|
|
195
|
+
files=_multipart_files(file),
|
|
196
|
+
data=_form(
|
|
197
|
+
{
|
|
198
|
+
"bg_color": bg_color,
|
|
199
|
+
"bg_url": bg_url,
|
|
200
|
+
"shadow_color": shadow_color,
|
|
201
|
+
"shadow_offset_x": shadow_offset_x,
|
|
202
|
+
"shadow_offset_y": shadow_offset_y,
|
|
203
|
+
"shadow_blur": shadow_blur,
|
|
204
|
+
"shadow_opacity": shadow_opacity,
|
|
205
|
+
"format": format,
|
|
206
|
+
}
|
|
207
|
+
),
|
|
208
|
+
)
|
|
209
|
+
|
|
210
|
+
async def sticker(
|
|
211
|
+
self,
|
|
212
|
+
file: FileInput,
|
|
213
|
+
*,
|
|
214
|
+
stroke_color: str = "#FFFFFF",
|
|
215
|
+
stroke_width: int = 20,
|
|
216
|
+
format: str = "png",
|
|
217
|
+
) -> bytes:
|
|
218
|
+
return await self._request_bytes(
|
|
219
|
+
"POST",
|
|
220
|
+
"/sticker",
|
|
221
|
+
files=_multipart_files(file),
|
|
222
|
+
data=_form(
|
|
223
|
+
{"stroke_color": stroke_color, "stroke_width": stroke_width, "format": format}
|
|
224
|
+
),
|
|
225
|
+
)
|
|
226
|
+
|
|
227
|
+
async def outline(
|
|
228
|
+
self,
|
|
229
|
+
file: FileInput,
|
|
230
|
+
*,
|
|
231
|
+
outline_color: str = "#000000",
|
|
232
|
+
outline_width: int = 4,
|
|
233
|
+
format: str = "png",
|
|
234
|
+
) -> bytes:
|
|
235
|
+
return await self._request_bytes(
|
|
236
|
+
"POST",
|
|
237
|
+
"/outline",
|
|
238
|
+
files=_multipart_files(file),
|
|
239
|
+
data=_form(
|
|
240
|
+
{"outline_color": outline_color, "outline_width": outline_width, "format": format}
|
|
241
|
+
),
|
|
242
|
+
)
|
|
243
|
+
|
|
244
|
+
async def studio_shot(
|
|
245
|
+
self,
|
|
246
|
+
file: FileInput,
|
|
247
|
+
*,
|
|
248
|
+
bg_color: str = "#FFFFFF",
|
|
249
|
+
aspect: str = "1:1",
|
|
250
|
+
padding: int = 48,
|
|
251
|
+
shadow: bool = True,
|
|
252
|
+
format: str = "jpg",
|
|
253
|
+
) -> bytes:
|
|
254
|
+
return await self._request_bytes(
|
|
255
|
+
"POST",
|
|
256
|
+
"/studio-shot",
|
|
257
|
+
files=_multipart_files(file),
|
|
258
|
+
data=_form(
|
|
259
|
+
{
|
|
260
|
+
"bg_color": bg_color,
|
|
261
|
+
"aspect": aspect,
|
|
262
|
+
"padding": padding,
|
|
263
|
+
"shadow": shadow,
|
|
264
|
+
"format": format,
|
|
265
|
+
}
|
|
266
|
+
),
|
|
267
|
+
)
|
|
268
|
+
|
|
269
|
+
async def compare(self, file: FileInput, *, format: str = "png") -> bytes:
|
|
270
|
+
return await self._request_bytes(
|
|
271
|
+
"POST",
|
|
272
|
+
"/compare",
|
|
273
|
+
files=_multipart_files(file),
|
|
274
|
+
data=_form({"format": format}),
|
|
275
|
+
)
|
|
276
|
+
|
|
277
|
+
async def headshot(
|
|
278
|
+
self,
|
|
279
|
+
file: FileInput,
|
|
280
|
+
*,
|
|
281
|
+
bg_color: str = "#FFFFFF",
|
|
282
|
+
bg_blur: bool = False,
|
|
283
|
+
blur_radius: int = 20,
|
|
284
|
+
aspect: str = "4:5",
|
|
285
|
+
padding: int = 64,
|
|
286
|
+
head_top_ratio: float = 0.18,
|
|
287
|
+
format: str = "jpg",
|
|
288
|
+
) -> bytes:
|
|
289
|
+
return await self._request_bytes(
|
|
290
|
+
"POST",
|
|
291
|
+
"/headshot",
|
|
292
|
+
files=_multipart_files(file),
|
|
293
|
+
data=_form(
|
|
294
|
+
{
|
|
295
|
+
"bg_color": bg_color,
|
|
296
|
+
"bg_blur": bg_blur,
|
|
297
|
+
"blur_radius": blur_radius,
|
|
298
|
+
"aspect": aspect,
|
|
299
|
+
"padding": padding,
|
|
300
|
+
"head_top_ratio": head_top_ratio,
|
|
301
|
+
"format": format,
|
|
302
|
+
}
|
|
303
|
+
),
|
|
304
|
+
)
|
|
305
|
+
|
|
306
|
+
async def preview(
|
|
307
|
+
self,
|
|
308
|
+
file: FileInput,
|
|
309
|
+
*,
|
|
310
|
+
max_dim: int = 512,
|
|
311
|
+
format: str = "png",
|
|
312
|
+
) -> bytes:
|
|
313
|
+
return await self._request_bytes(
|
|
314
|
+
"POST",
|
|
315
|
+
"/preview",
|
|
316
|
+
files=_multipart_files(file),
|
|
317
|
+
data=_form({"max_dim": max_dim, "format": format}),
|
|
318
|
+
)
|
|
319
|
+
|
|
320
|
+
async def estimate(self, endpoint: str, width: int, height: int) -> Dict[str, Any]:
|
|
321
|
+
return await self._request_json(
|
|
322
|
+
"POST",
|
|
323
|
+
"/estimate",
|
|
324
|
+
json={"endpoint": endpoint, "width": width, "height": height},
|
|
325
|
+
)
|
useknockout/client.py
ADDED
|
@@ -0,0 +1,354 @@
|
|
|
1
|
+
"""Synchronous client for the useknockout API."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any, Dict, List, Optional
|
|
6
|
+
|
|
7
|
+
import httpx
|
|
8
|
+
|
|
9
|
+
from useknockout._helpers import (
|
|
10
|
+
DEFAULT_BASE_URL,
|
|
11
|
+
PUBLIC_BETA_TOKEN,
|
|
12
|
+
FileInput,
|
|
13
|
+
_form,
|
|
14
|
+
_multipart_batch,
|
|
15
|
+
_multipart_files,
|
|
16
|
+
_resolve_token,
|
|
17
|
+
)
|
|
18
|
+
from useknockout._version import __version__
|
|
19
|
+
from useknockout.errors import KnockoutError, raise_for_status
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
class Knockout:
|
|
23
|
+
"""
|
|
24
|
+
Synchronous client for the useknockout background-removal API.
|
|
25
|
+
|
|
26
|
+
Args:
|
|
27
|
+
token: API token. Falls back to ``KNOCKOUT_TOKEN`` env var, then to the
|
|
28
|
+
public beta token.
|
|
29
|
+
base_url: API base URL (override for self-hosted deployments).
|
|
30
|
+
timeout: Per-request timeout in seconds.
|
|
31
|
+
|
|
32
|
+
Example:
|
|
33
|
+
>>> client = Knockout() # uses public beta token by default
|
|
34
|
+
>>> png = client.remove("photo.jpg")
|
|
35
|
+
>>> open("out.png", "wb").write(png)
|
|
36
|
+
"""
|
|
37
|
+
|
|
38
|
+
def __init__(
|
|
39
|
+
self,
|
|
40
|
+
token: Optional[str] = None,
|
|
41
|
+
*,
|
|
42
|
+
base_url: str = DEFAULT_BASE_URL,
|
|
43
|
+
timeout: float = 60.0,
|
|
44
|
+
) -> None:
|
|
45
|
+
self.token = _resolve_token(token) or PUBLIC_BETA_TOKEN
|
|
46
|
+
self.base_url = base_url.rstrip("/")
|
|
47
|
+
self._http = httpx.Client(
|
|
48
|
+
base_url=self.base_url,
|
|
49
|
+
timeout=timeout,
|
|
50
|
+
headers={
|
|
51
|
+
"Authorization": f"Bearer {self.token}",
|
|
52
|
+
"User-Agent": f"useknockout-python/{__version__}",
|
|
53
|
+
},
|
|
54
|
+
)
|
|
55
|
+
|
|
56
|
+
# ---- lifecycle ----
|
|
57
|
+
|
|
58
|
+
def __enter__(self) -> "Knockout":
|
|
59
|
+
return self
|
|
60
|
+
|
|
61
|
+
def __exit__(self, exc_type, exc, tb) -> None:
|
|
62
|
+
self.close()
|
|
63
|
+
|
|
64
|
+
def close(self) -> None:
|
|
65
|
+
self._http.close()
|
|
66
|
+
|
|
67
|
+
# ---- low-level transport ----
|
|
68
|
+
|
|
69
|
+
def _request_bytes(
|
|
70
|
+
self,
|
|
71
|
+
method: str,
|
|
72
|
+
path: str,
|
|
73
|
+
*,
|
|
74
|
+
files=None,
|
|
75
|
+
data=None,
|
|
76
|
+
json=None,
|
|
77
|
+
) -> bytes:
|
|
78
|
+
try:
|
|
79
|
+
r = self._http.request(method, path, files=files, data=data, json=json)
|
|
80
|
+
except httpx.RequestError as e:
|
|
81
|
+
raise KnockoutError(f"network error: {e}", code="unknown") from e
|
|
82
|
+
if r.status_code >= 400:
|
|
83
|
+
raise_for_status(r.status_code, r.content)
|
|
84
|
+
return r.content
|
|
85
|
+
|
|
86
|
+
def _request_json(
|
|
87
|
+
self,
|
|
88
|
+
method: str,
|
|
89
|
+
path: str,
|
|
90
|
+
*,
|
|
91
|
+
files=None,
|
|
92
|
+
data=None,
|
|
93
|
+
json=None,
|
|
94
|
+
) -> Any:
|
|
95
|
+
try:
|
|
96
|
+
r = self._http.request(method, path, files=files, data=data, json=json)
|
|
97
|
+
except httpx.RequestError as e:
|
|
98
|
+
raise KnockoutError(f"network error: {e}", code="unknown") from e
|
|
99
|
+
if r.status_code >= 400:
|
|
100
|
+
raise_for_status(r.status_code, r.content)
|
|
101
|
+
try:
|
|
102
|
+
return r.json()
|
|
103
|
+
except ValueError as e:
|
|
104
|
+
raise KnockoutError(f"invalid JSON response: {e}", code="server") from e
|
|
105
|
+
|
|
106
|
+
# ---- public API ----
|
|
107
|
+
|
|
108
|
+
def health(self) -> Dict[str, Any]:
|
|
109
|
+
"""GET /health — service status + model info."""
|
|
110
|
+
return self._request_json("GET", "/health")
|
|
111
|
+
|
|
112
|
+
def stats(self) -> Dict[str, Any]:
|
|
113
|
+
"""GET /stats — public usage counter (total + today + last 7 days)."""
|
|
114
|
+
return self._request_json("GET", "/stats")
|
|
115
|
+
|
|
116
|
+
def remove(self, file: FileInput, *, format: str = "png") -> bytes:
|
|
117
|
+
"""POST /remove — remove background, return transparent PNG/WebP bytes."""
|
|
118
|
+
return self._request_bytes(
|
|
119
|
+
"POST",
|
|
120
|
+
"/remove",
|
|
121
|
+
files=_multipart_files(file),
|
|
122
|
+
data=_form({"format": format}),
|
|
123
|
+
)
|
|
124
|
+
|
|
125
|
+
def remove_url(self, url: str, *, format: str = "png") -> bytes:
|
|
126
|
+
"""POST /remove-url — fetch remote image, return transparent PNG/WebP."""
|
|
127
|
+
return self._request_bytes(
|
|
128
|
+
"POST",
|
|
129
|
+
"/remove-url",
|
|
130
|
+
json={"url": url, "format": format},
|
|
131
|
+
)
|
|
132
|
+
|
|
133
|
+
def replace_background(
|
|
134
|
+
self,
|
|
135
|
+
file: FileInput,
|
|
136
|
+
*,
|
|
137
|
+
bg_color: str = "#FFFFFF",
|
|
138
|
+
bg_url: Optional[str] = None,
|
|
139
|
+
format: str = "png",
|
|
140
|
+
) -> bytes:
|
|
141
|
+
"""POST /replace-bg — composite subject onto solid color or remote bg image."""
|
|
142
|
+
return self._request_bytes(
|
|
143
|
+
"POST",
|
|
144
|
+
"/replace-bg",
|
|
145
|
+
files=_multipart_files(file),
|
|
146
|
+
data=_form({"bg_color": bg_color, "bg_url": bg_url, "format": format}),
|
|
147
|
+
)
|
|
148
|
+
|
|
149
|
+
def remove_batch(
|
|
150
|
+
self,
|
|
151
|
+
files: List[FileInput],
|
|
152
|
+
*,
|
|
153
|
+
format: str = "png",
|
|
154
|
+
) -> Dict[str, Any]:
|
|
155
|
+
"""POST /remove-batch — up to 10 multipart uploads in one call."""
|
|
156
|
+
if len(files) > 10:
|
|
157
|
+
raise ValueError("max 10 files per batch")
|
|
158
|
+
return self._request_json(
|
|
159
|
+
"POST",
|
|
160
|
+
"/remove-batch",
|
|
161
|
+
files=_multipart_batch(files),
|
|
162
|
+
data=_form({"format": format}),
|
|
163
|
+
)
|
|
164
|
+
|
|
165
|
+
def remove_batch_url(self, urls: List[str], *, format: str = "png") -> Dict[str, Any]:
|
|
166
|
+
"""POST /remove-batch-url — up to 10 remote URLs in one call."""
|
|
167
|
+
if len(urls) > 10:
|
|
168
|
+
raise ValueError("max 10 urls per batch")
|
|
169
|
+
return self._request_json(
|
|
170
|
+
"POST",
|
|
171
|
+
"/remove-batch-url",
|
|
172
|
+
json={"urls": urls, "format": format},
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
def mask(self, file: FileInput, *, format: str = "png") -> bytes:
|
|
176
|
+
"""POST /mask — return alpha mask only (grayscale)."""
|
|
177
|
+
return self._request_bytes(
|
|
178
|
+
"POST",
|
|
179
|
+
"/mask",
|
|
180
|
+
files=_multipart_files(file),
|
|
181
|
+
data=_form({"format": format}),
|
|
182
|
+
)
|
|
183
|
+
|
|
184
|
+
def smart_crop(
|
|
185
|
+
self,
|
|
186
|
+
file: FileInput,
|
|
187
|
+
*,
|
|
188
|
+
padding: int = 24,
|
|
189
|
+
transparent: bool = True,
|
|
190
|
+
format: str = "png",
|
|
191
|
+
) -> bytes:
|
|
192
|
+
"""POST /smart-crop — crop to subject bbox + padding."""
|
|
193
|
+
return self._request_bytes(
|
|
194
|
+
"POST",
|
|
195
|
+
"/smart-crop",
|
|
196
|
+
files=_multipart_files(file),
|
|
197
|
+
data=_form({"padding": padding, "transparent": transparent, "format": format}),
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
def shadow(
|
|
201
|
+
self,
|
|
202
|
+
file: FileInput,
|
|
203
|
+
*,
|
|
204
|
+
bg_color: str = "#FFFFFF",
|
|
205
|
+
bg_url: Optional[str] = None,
|
|
206
|
+
shadow_color: str = "#000000",
|
|
207
|
+
shadow_offset_x: int = 8,
|
|
208
|
+
shadow_offset_y: int = 12,
|
|
209
|
+
shadow_blur: int = 14,
|
|
210
|
+
shadow_opacity: float = 0.45,
|
|
211
|
+
format: str = "png",
|
|
212
|
+
) -> bytes:
|
|
213
|
+
"""POST /shadow — subject on bg with configurable drop shadow."""
|
|
214
|
+
return self._request_bytes(
|
|
215
|
+
"POST",
|
|
216
|
+
"/shadow",
|
|
217
|
+
files=_multipart_files(file),
|
|
218
|
+
data=_form(
|
|
219
|
+
{
|
|
220
|
+
"bg_color": bg_color,
|
|
221
|
+
"bg_url": bg_url,
|
|
222
|
+
"shadow_color": shadow_color,
|
|
223
|
+
"shadow_offset_x": shadow_offset_x,
|
|
224
|
+
"shadow_offset_y": shadow_offset_y,
|
|
225
|
+
"shadow_blur": shadow_blur,
|
|
226
|
+
"shadow_opacity": shadow_opacity,
|
|
227
|
+
"format": format,
|
|
228
|
+
}
|
|
229
|
+
),
|
|
230
|
+
)
|
|
231
|
+
|
|
232
|
+
def sticker(
|
|
233
|
+
self,
|
|
234
|
+
file: FileInput,
|
|
235
|
+
*,
|
|
236
|
+
stroke_color: str = "#FFFFFF",
|
|
237
|
+
stroke_width: int = 20,
|
|
238
|
+
format: str = "png",
|
|
239
|
+
) -> bytes:
|
|
240
|
+
"""POST /sticker — subject + thick outline on transparent bg."""
|
|
241
|
+
return self._request_bytes(
|
|
242
|
+
"POST",
|
|
243
|
+
"/sticker",
|
|
244
|
+
files=_multipart_files(file),
|
|
245
|
+
data=_form(
|
|
246
|
+
{"stroke_color": stroke_color, "stroke_width": stroke_width, "format": format}
|
|
247
|
+
),
|
|
248
|
+
)
|
|
249
|
+
|
|
250
|
+
def outline(
|
|
251
|
+
self,
|
|
252
|
+
file: FileInput,
|
|
253
|
+
*,
|
|
254
|
+
outline_color: str = "#000000",
|
|
255
|
+
outline_width: int = 4,
|
|
256
|
+
format: str = "png",
|
|
257
|
+
) -> bytes:
|
|
258
|
+
"""POST /outline — subject + thin outline on transparent bg."""
|
|
259
|
+
return self._request_bytes(
|
|
260
|
+
"POST",
|
|
261
|
+
"/outline",
|
|
262
|
+
files=_multipart_files(file),
|
|
263
|
+
data=_form(
|
|
264
|
+
{"outline_color": outline_color, "outline_width": outline_width, "format": format}
|
|
265
|
+
),
|
|
266
|
+
)
|
|
267
|
+
|
|
268
|
+
def studio_shot(
|
|
269
|
+
self,
|
|
270
|
+
file: FileInput,
|
|
271
|
+
*,
|
|
272
|
+
bg_color: str = "#FFFFFF",
|
|
273
|
+
aspect: str = "1:1",
|
|
274
|
+
padding: int = 48,
|
|
275
|
+
shadow: bool = True,
|
|
276
|
+
format: str = "jpg",
|
|
277
|
+
) -> bytes:
|
|
278
|
+
"""POST /studio-shot — e-commerce preset (cutout + crop + center + shadow)."""
|
|
279
|
+
return self._request_bytes(
|
|
280
|
+
"POST",
|
|
281
|
+
"/studio-shot",
|
|
282
|
+
files=_multipart_files(file),
|
|
283
|
+
data=_form(
|
|
284
|
+
{
|
|
285
|
+
"bg_color": bg_color,
|
|
286
|
+
"aspect": aspect,
|
|
287
|
+
"padding": padding,
|
|
288
|
+
"shadow": shadow,
|
|
289
|
+
"format": format,
|
|
290
|
+
}
|
|
291
|
+
),
|
|
292
|
+
)
|
|
293
|
+
|
|
294
|
+
def compare(self, file: FileInput, *, format: str = "png") -> bytes:
|
|
295
|
+
"""POST /compare — side-by-side before/after image."""
|
|
296
|
+
return self._request_bytes(
|
|
297
|
+
"POST",
|
|
298
|
+
"/compare",
|
|
299
|
+
files=_multipart_files(file),
|
|
300
|
+
data=_form({"format": format}),
|
|
301
|
+
)
|
|
302
|
+
|
|
303
|
+
def headshot(
|
|
304
|
+
self,
|
|
305
|
+
file: FileInput,
|
|
306
|
+
*,
|
|
307
|
+
bg_color: str = "#FFFFFF",
|
|
308
|
+
bg_blur: bool = False,
|
|
309
|
+
blur_radius: int = 20,
|
|
310
|
+
aspect: str = "4:5",
|
|
311
|
+
padding: int = 64,
|
|
312
|
+
head_top_ratio: float = 0.18,
|
|
313
|
+
format: str = "jpg",
|
|
314
|
+
) -> bytes:
|
|
315
|
+
"""POST /headshot — LinkedIn-ready portrait preset."""
|
|
316
|
+
return self._request_bytes(
|
|
317
|
+
"POST",
|
|
318
|
+
"/headshot",
|
|
319
|
+
files=_multipart_files(file),
|
|
320
|
+
data=_form(
|
|
321
|
+
{
|
|
322
|
+
"bg_color": bg_color,
|
|
323
|
+
"bg_blur": bg_blur,
|
|
324
|
+
"blur_radius": blur_radius,
|
|
325
|
+
"aspect": aspect,
|
|
326
|
+
"padding": padding,
|
|
327
|
+
"head_top_ratio": head_top_ratio,
|
|
328
|
+
"format": format,
|
|
329
|
+
}
|
|
330
|
+
),
|
|
331
|
+
)
|
|
332
|
+
|
|
333
|
+
def preview(
|
|
334
|
+
self,
|
|
335
|
+
file: FileInput,
|
|
336
|
+
*,
|
|
337
|
+
max_dim: int = 512,
|
|
338
|
+
format: str = "png",
|
|
339
|
+
) -> bytes:
|
|
340
|
+
"""POST /preview — fast low-res preview (~80ms warm)."""
|
|
341
|
+
return self._request_bytes(
|
|
342
|
+
"POST",
|
|
343
|
+
"/preview",
|
|
344
|
+
files=_multipart_files(file),
|
|
345
|
+
data=_form({"max_dim": max_dim, "format": format}),
|
|
346
|
+
)
|
|
347
|
+
|
|
348
|
+
def estimate(self, endpoint: str, width: int, height: int) -> Dict[str, Any]:
|
|
349
|
+
"""POST /estimate — predict latency + cost without processing."""
|
|
350
|
+
return self._request_json(
|
|
351
|
+
"POST",
|
|
352
|
+
"/estimate",
|
|
353
|
+
json={"endpoint": endpoint, "width": width, "height": height},
|
|
354
|
+
)
|
useknockout/errors.py
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
"""Typed errors raised by the useknockout SDK."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Optional
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class KnockoutError(Exception):
|
|
9
|
+
"""
|
|
10
|
+
Base error raised by the useknockout SDK.
|
|
11
|
+
|
|
12
|
+
Attributes:
|
|
13
|
+
status: HTTP status code (or None for transport errors).
|
|
14
|
+
code: Short machine-readable error category.
|
|
15
|
+
message: Human-readable message.
|
|
16
|
+
"""
|
|
17
|
+
|
|
18
|
+
def __init__(
|
|
19
|
+
self,
|
|
20
|
+
message: str,
|
|
21
|
+
*,
|
|
22
|
+
status: Optional[int] = None,
|
|
23
|
+
code: str = "unknown",
|
|
24
|
+
) -> None:
|
|
25
|
+
super().__init__(message)
|
|
26
|
+
self.status = status
|
|
27
|
+
self.code = code
|
|
28
|
+
self.message = message
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
class AuthError(KnockoutError):
|
|
32
|
+
"""401 / 403 — token missing or invalid."""
|
|
33
|
+
|
|
34
|
+
def __init__(self, message: str, *, status: int) -> None:
|
|
35
|
+
super().__init__(message, status=status, code="auth")
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class BadRequestError(KnockoutError):
|
|
39
|
+
"""400 — bad input (invalid format, missing fields, etc.)."""
|
|
40
|
+
|
|
41
|
+
def __init__(self, message: str) -> None:
|
|
42
|
+
super().__init__(message, status=400, code="bad_request")
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
class PayloadTooLargeError(KnockoutError):
|
|
46
|
+
"""413 — image exceeds size limit."""
|
|
47
|
+
|
|
48
|
+
def __init__(self, message: str) -> None:
|
|
49
|
+
super().__init__(message, status=413, code="payload_too_large")
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
class RateLimitError(KnockoutError):
|
|
53
|
+
"""429 — rate limit exceeded."""
|
|
54
|
+
|
|
55
|
+
def __init__(self, message: str) -> None:
|
|
56
|
+
super().__init__(message, status=429, code="rate_limit")
|
|
57
|
+
|
|
58
|
+
|
|
59
|
+
class ServerError(KnockoutError):
|
|
60
|
+
"""5xx — server-side failure."""
|
|
61
|
+
|
|
62
|
+
def __init__(self, message: str, status: int) -> None:
|
|
63
|
+
super().__init__(message, status=status, code="server")
|
|
64
|
+
|
|
65
|
+
|
|
66
|
+
def raise_for_status(status: int, body: bytes) -> None:
|
|
67
|
+
"""Map an HTTP error status to the appropriate KnockoutError subclass."""
|
|
68
|
+
text = body.decode("utf-8", errors="replace") if body else ""
|
|
69
|
+
detail = text or f"HTTP {status}"
|
|
70
|
+
|
|
71
|
+
if status == 401 or status == 403:
|
|
72
|
+
raise AuthError(detail, status=status)
|
|
73
|
+
if status == 400:
|
|
74
|
+
raise BadRequestError(detail)
|
|
75
|
+
if status == 413:
|
|
76
|
+
raise PayloadTooLargeError(detail)
|
|
77
|
+
if status == 429:
|
|
78
|
+
raise RateLimitError(detail)
|
|
79
|
+
if 500 <= status < 600:
|
|
80
|
+
raise ServerError(detail, status=status)
|
|
81
|
+
raise KnockoutError(detail, status=status, code="unknown")
|
|
@@ -0,0 +1,191 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: useknockout
|
|
3
|
+
Version: 0.0.1
|
|
4
|
+
Summary: Python SDK for useknockout — state-of-the-art background removal API.
|
|
5
|
+
Project-URL: Homepage, https://useknockout.com
|
|
6
|
+
Project-URL: Documentation, https://github.com/useknockout/python
|
|
7
|
+
Project-URL: Repository, https://github.com/useknockout/python
|
|
8
|
+
Project-URL: Issues, https://github.com/useknockout/python/issues
|
|
9
|
+
Author: useknockout
|
|
10
|
+
License: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: ai,background-removal,birefnet,image-processing,remove-background,useknockout
|
|
13
|
+
Classifier: Development Status :: 4 - Beta
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.9
|
|
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 :: Multimedia :: Graphics
|
|
23
|
+
Classifier: Topic :: Scientific/Engineering :: Image Processing
|
|
24
|
+
Requires-Python: >=3.9
|
|
25
|
+
Requires-Dist: httpx>=0.27.0
|
|
26
|
+
Provides-Extra: dev
|
|
27
|
+
Requires-Dist: mypy>=1.10; extra == 'dev'
|
|
28
|
+
Requires-Dist: pytest-asyncio>=0.23; extra == 'dev'
|
|
29
|
+
Requires-Dist: pytest>=8.0; extra == 'dev'
|
|
30
|
+
Requires-Dist: ruff>=0.6.0; extra == 'dev'
|
|
31
|
+
Description-Content-Type: text/markdown
|
|
32
|
+
|
|
33
|
+
<div align="center">
|
|
34
|
+
|
|
35
|
+
# 🥊 useknockout
|
|
36
|
+
|
|
37
|
+
**State-of-the-art background removal API — Python SDK.**
|
|
38
|
+
|
|
39
|
+
[](https://pypi.org/project/useknockout/)
|
|
40
|
+
[](https://pypi.org/project/useknockout/)
|
|
41
|
+
[](LICENSE)
|
|
42
|
+
|
|
43
|
+
[Website](https://useknockout.com) ·
|
|
44
|
+
[API repo](https://github.com/useknockout/api) ·
|
|
45
|
+
[Node SDK](https://github.com/useknockout/node) ·
|
|
46
|
+
[React SDK](https://github.com/useknockout/react) ·
|
|
47
|
+
[CLI](https://github.com/useknockout/cli)
|
|
48
|
+
|
|
49
|
+
<img src="https://raw.githubusercontent.com/useknockout/api/main/docs/banner.png" width="800" alt="useknockout — background removal API for developers" />
|
|
50
|
+
|
|
51
|
+
*Background removal, 40× cheaper than remove.bg. MIT licensed. Self-hostable.*
|
|
52
|
+
|
|
53
|
+
</div>
|
|
54
|
+
|
|
55
|
+
---
|
|
56
|
+
|
|
57
|
+
## Install
|
|
58
|
+
|
|
59
|
+
```bash
|
|
60
|
+
pip install useknockout
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
## Quickstart
|
|
64
|
+
|
|
65
|
+
```python
|
|
66
|
+
from useknockout import Knockout
|
|
67
|
+
|
|
68
|
+
client = Knockout() # uses public beta token by default
|
|
69
|
+
png = client.remove("photo.jpg")
|
|
70
|
+
|
|
71
|
+
with open("out.png", "wb") as f:
|
|
72
|
+
f.write(png)
|
|
73
|
+
```
|
|
74
|
+
|
|
75
|
+
That's it. Free during the public beta.
|
|
76
|
+
|
|
77
|
+
## Async
|
|
78
|
+
|
|
79
|
+
```python
|
|
80
|
+
import asyncio
|
|
81
|
+
from useknockout import AsyncKnockout
|
|
82
|
+
|
|
83
|
+
async def main():
|
|
84
|
+
async with AsyncKnockout() as client:
|
|
85
|
+
png = await client.remove("photo.jpg")
|
|
86
|
+
open("out.png", "wb").write(png)
|
|
87
|
+
|
|
88
|
+
asyncio.run(main())
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
## Authentication
|
|
92
|
+
|
|
93
|
+
The client falls back through three sources in order:
|
|
94
|
+
|
|
95
|
+
1. The `token=` argument
|
|
96
|
+
2. The `KNOCKOUT_TOKEN` environment variable
|
|
97
|
+
3. The public beta token (free, rate-limited, in the README of the API repo)
|
|
98
|
+
|
|
99
|
+
Get your own token by emailing `troy@useknockout.com` (paid tier launches at $0.005/image — 40× cheaper than remove.bg).
|
|
100
|
+
|
|
101
|
+
## All endpoints
|
|
102
|
+
|
|
103
|
+
```python
|
|
104
|
+
from useknockout import Knockout
|
|
105
|
+
|
|
106
|
+
c = Knockout()
|
|
107
|
+
|
|
108
|
+
# Remove background
|
|
109
|
+
c.remove("photo.jpg") # returns PNG bytes
|
|
110
|
+
c.remove_url("https://example.com/photo.jpg")
|
|
111
|
+
c.remove_batch(["a.jpg", "b.jpg", "c.jpg"]) # up to 10
|
|
112
|
+
c.remove_batch_url(["https://...", "https://..."])
|
|
113
|
+
|
|
114
|
+
# Replace background
|
|
115
|
+
c.replace_background("photo.jpg", bg_color="#000000")
|
|
116
|
+
c.replace_background("photo.jpg", bg_url="https://example.com/bg.jpg")
|
|
117
|
+
|
|
118
|
+
# Mask only
|
|
119
|
+
c.mask("photo.jpg") # returns grayscale PNG
|
|
120
|
+
|
|
121
|
+
# Crop to subject
|
|
122
|
+
c.smart_crop("photo.jpg", padding=24)
|
|
123
|
+
|
|
124
|
+
# Effects
|
|
125
|
+
c.shadow("photo.jpg", shadow_blur=14, shadow_opacity=0.45)
|
|
126
|
+
c.sticker("photo.jpg", stroke_width=20) # WhatsApp-style
|
|
127
|
+
c.outline("photo.jpg", outline_color="#000000", outline_width=4)
|
|
128
|
+
|
|
129
|
+
# Presets
|
|
130
|
+
c.studio_shot("photo.jpg", aspect="1:1", shadow=True) # e-commerce
|
|
131
|
+
c.headshot("photo.jpg", bg_color="#FFFFFF") # LinkedIn 4:5 portrait
|
|
132
|
+
c.headshot("photo.jpg", bg_blur=True, blur_radius=24) # blurred original bg
|
|
133
|
+
|
|
134
|
+
# Marketing
|
|
135
|
+
c.compare("photo.jpg") # before/after side-by-side
|
|
136
|
+
|
|
137
|
+
# UX helpers
|
|
138
|
+
c.preview("photo.jpg", max_dim=512) # ~80ms warm
|
|
139
|
+
c.estimate("remove", width=1024, height=1024) # predict latency + cost
|
|
140
|
+
|
|
141
|
+
# Telemetry
|
|
142
|
+
c.health()
|
|
143
|
+
c.stats() # public usage counter
|
|
144
|
+
```
|
|
145
|
+
|
|
146
|
+
Every method that returns an image returns raw bytes. Pipe to `open(path, "wb").write(...)`, `BytesIO`, `PIL.Image.open(BytesIO(...))`, `numpy`, S3 — anywhere bytes go.
|
|
147
|
+
|
|
148
|
+
## Errors
|
|
149
|
+
|
|
150
|
+
All errors inherit from `KnockoutError`:
|
|
151
|
+
|
|
152
|
+
```python
|
|
153
|
+
from useknockout import Knockout
|
|
154
|
+
from useknockout.errors import (
|
|
155
|
+
AuthError, # 401 / 403
|
|
156
|
+
BadRequestError, # 400
|
|
157
|
+
PayloadTooLargeError,# 413 (>25 MB)
|
|
158
|
+
RateLimitError, # 429
|
|
159
|
+
ServerError, # 5xx
|
|
160
|
+
KnockoutError, # base class / network errors
|
|
161
|
+
)
|
|
162
|
+
|
|
163
|
+
try:
|
|
164
|
+
png = client.remove("photo.jpg")
|
|
165
|
+
except AuthError:
|
|
166
|
+
... # bad token
|
|
167
|
+
except RateLimitError:
|
|
168
|
+
... # back off
|
|
169
|
+
except KnockoutError as e:
|
|
170
|
+
print(f"{e.code} ({e.status}): {e.message}")
|
|
171
|
+
```
|
|
172
|
+
|
|
173
|
+
## Self-host
|
|
174
|
+
|
|
175
|
+
The API is open source and runs on Modal. Deploy your own copy:
|
|
176
|
+
|
|
177
|
+
```bash
|
|
178
|
+
git clone https://github.com/useknockout/api
|
|
179
|
+
cd api
|
|
180
|
+
modal deploy main.py
|
|
181
|
+
```
|
|
182
|
+
|
|
183
|
+
Then point the SDK at your deployment:
|
|
184
|
+
|
|
185
|
+
```python
|
|
186
|
+
client = Knockout(token="your-token", base_url="https://your-deploy.modal.run")
|
|
187
|
+
```
|
|
188
|
+
|
|
189
|
+
## License
|
|
190
|
+
|
|
191
|
+
MIT. Use it however you want.
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
useknockout/__init__.py,sha256=KpaX9NOIkapmd-itHE0omFKhProwoLh4Mgh2oVNC0HQ,1045
|
|
2
|
+
useknockout/_helpers.py,sha256=S1b0gB5j5a8BzzqMuPnt7NR43r3ONiVMRBV3sOF78Qo,2528
|
|
3
|
+
useknockout/_version.py,sha256=sXLh7g3KC4QCFxcZGBTpG2scR7hmmBsMjq6LqRptkRg,22
|
|
4
|
+
useknockout/async_client.py,sha256=Gt3Pqi7cw8FmzzQ4C-FvZXI13oD79zAIn2xsVv-Z-L8,9417
|
|
5
|
+
useknockout/client.py,sha256=vEf14FcEH16maBNTREP6FgyOec2xidkZgA9yW9Lw0D0,10733
|
|
6
|
+
useknockout/errors.py,sha256=nfrVmsuigyu_AOyEx6Mu21m_JUD_pw__pLlu0DvJYhU,2334
|
|
7
|
+
useknockout-0.0.1.dist-info/METADATA,sha256=Z0h_7812O5NWREJWFlX06JEG1AgzJfTyjdtLSi5BVbE,5640
|
|
8
|
+
useknockout-0.0.1.dist-info/WHEEL,sha256=QccIxa26bgl1E6uMy58deGWi-0aeIkkangHcxk2kWfw,87
|
|
9
|
+
useknockout-0.0.1.dist-info/licenses/LICENSE,sha256=24acC5PwCXEpk8m2X05gkxpPNeWRNo9_uk0mSa4uMKY,1068
|
|
10
|
+
useknockout-0.0.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 useknockout
|
|
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.
|