useknockout 0.8.0__tar.gz → 0.8.1__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.
@@ -1,7 +1,7 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: useknockout
3
- Version: 0.8.0
4
- Summary: Python SDK for useknockout — state-of-the-art background removal API.
3
+ Version: 0.8.1
4
+ Summary: Python SDK for useknockout, the open source background removal API.
5
5
  Project-URL: Homepage, https://useknockout.com
6
6
  Project-URL: Documentation, https://github.com/useknockout/python
7
7
  Project-URL: Repository, https://github.com/useknockout/python
@@ -9,7 +9,7 @@ Project-URL: Issues, https://github.com/useknockout/python/issues
9
9
  Author: useknockout
10
10
  License: MIT
11
11
  License-File: LICENSE
12
- Keywords: ai,background-removal,birefnet,image-processing,remove-background,useknockout
12
+ Keywords: ai,background-removal,birefnet,image-processing,open-source,remove-background,useknockout
13
13
  Classifier: Development Status :: 4 - Beta
14
14
  Classifier: Intended Audience :: Developers
15
15
  Classifier: License :: OSI Approved :: MIT License
@@ -30,20 +30,18 @@ Requires-Dist: pytest>=8.0; extra == 'dev'
30
30
  Requires-Dist: ruff>=0.6.0; extra == 'dev'
31
31
  Description-Content-Type: text/markdown
32
32
 
33
- ---
34
- project: projects/useknockout-python
35
- type: readme
36
- ---
33
+
37
34
 
38
35
  <div align="center">
39
36
 
40
37
  # 🥊 useknockout
41
38
 
42
- **State-of-the-art background removal API — Python SDK.**
39
+ **Python SDK for useknockout, the open source background removal API.**
43
40
 
44
41
  [![PyPI](https://img.shields.io/pypi/v/useknockout.svg)](https://pypi.org/project/useknockout/)
45
42
  [![Python](https://img.shields.io/pypi/pyversions/useknockout.svg)](https://pypi.org/project/useknockout/)
46
43
  [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
44
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/useknockout?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/useknockout)
47
45
 
48
46
  [Website](https://useknockout.com) ·
49
47
  [API repo](https://github.com/useknockout/api) ·
@@ -53,7 +51,7 @@ type: readme
53
51
 
54
52
  <img src="https://raw.githubusercontent.com/useknockout/api/main/docs/banner.png" width="800" alt="useknockout — background removal API for developers" />
55
53
 
56
- *Background removal, 40× cheaper than remove.bg. MIT licensed. Self-hostable.*
54
+ *Open source background removal and image processing. MIT licensed.*
57
55
 
58
56
  </div>
59
57
 
@@ -68,6 +66,9 @@ subject-aware image operations: background replacement, drop shadows, stickers a
68
66
  outlines, e-commerce / LinkedIn presets, super-resolution upscaling, face
69
67
  restoration, colorization, silhouettes, and inpainting.
70
68
 
69
+ The API is open source under the MIT license:
70
+ [github.com/useknockout/api](https://github.com/useknockout/api).
71
+
71
72
  The SDK is a thin, fully-typed wrapper over [`httpx`](https://www.python-httpx.org/).
72
73
  It ships both a synchronous client (`Knockout`) and an asynchronous one
73
74
  (`AsyncKnockout`) with identical method signatures. Every image-returning method
@@ -88,14 +89,15 @@ Requires Python 3.9+. The only runtime dependency is `httpx>=0.27.0`.
88
89
  ```python
89
90
  from useknockout import Knockout
90
91
 
91
- client = Knockout() # uses public beta token by default
92
+ client = Knockout() # uses the shared demo key
92
93
  png = client.remove("photo.jpg")
93
94
 
94
95
  with open("out.png", "wb") as f:
95
96
  f.write(png)
96
97
  ```
97
98
 
98
- That's it. Free during the public beta.
99
+ That's it, no sign-up needed to try it. The demo key is limited, so get your own
100
+ key before building on it (see [Authentication](#authentication)).
99
101
 
100
102
  ## Async
101
103
 
@@ -123,16 +125,24 @@ The client resolves its token by falling through three sources, in order:
123
125
 
124
126
  1. The `token=` constructor argument
125
127
  2. The `KNOCKOUT_TOKEN` environment variable
126
- 3. The public beta token (free, rate-limited — baked into the SDK)
128
+ 3. A shared demo key built into the SDK
127
129
 
128
130
  ```python
129
131
  client = Knockout(token="kno_...") # explicit
130
- client = Knockout() # env var or public beta token
132
+ client = Knockout() # env var or shared demo key
131
133
  ```
132
134
 
133
- The token is sent as a `Bearer` header on every request. Get your own token by
134
- emailing `troy@useknockout.com` (paid tier launches at $0.005/image — 40× cheaper
135
- than remove.bg).
135
+ The token is sent as a `Bearer` header on every request.
136
+
137
+ **Demo key limits.** It is for trying the API without an account. It only works
138
+ with `remove`, `replace_background`, `mask`, `sticker` and `compare`, output is
139
+ capped at 1536 px, and it has daily usage limits. Other image methods return an
140
+ error.
141
+
142
+ **Your own key.** Sign up at [useknockout.com/signin](https://useknockout.com/signin).
143
+ Free accounts get 30 images every month on the core tools, no card. Pay-as-you-go
144
+ is $0.02 per image and unlocks the rest. Current rates are on the
145
+ [pricing page](https://useknockout.com/pricing).
136
146
 
137
147
  ## Input types
138
148
 
@@ -152,7 +162,7 @@ client.remove(open("photo.jpg", "rb").read())# bytes
152
162
  ```python
153
163
  from useknockout import Knockout
154
164
 
155
- c = Knockout()
165
+ c = Knockout(token="kno_...") # your own key; the demo key covers only a few of these
156
166
 
157
167
  # --- Core background removal ---
158
168
  c.remove("photo.jpg") # returns PNG/WebP bytes
@@ -297,30 +307,14 @@ when available).
297
307
 
298
308
  | Constructor arg | Default | Purpose |
299
309
  | --- | --- | --- |
300
- | `token` | env var → public beta token | API token, sent as `Bearer` header |
301
- | `base_url` | `https://useknockout--api.modal.run` | API base URL (override for self-hosted) |
310
+ | `token` | env var → shared demo key | API token, sent as `Bearer` header |
311
+ | `base_url` | `https://useknockout--api.modal.run` | API base URL |
302
312
  | `timeout` | `60.0` | per-request timeout in seconds |
303
313
 
304
314
  | Environment variable | Purpose |
305
315
  | --- | --- |
306
316
  | `KNOCKOUT_TOKEN` | API token, used when `token=` is not passed |
307
317
 
308
- ## Self-host
309
-
310
- The API is open source and runs on Modal. Deploy your own copy:
311
-
312
- ```bash
313
- git clone https://github.com/useknockout/api
314
- cd api
315
- modal deploy main.py
316
- ```
317
-
318
- Then point the SDK at your deployment:
319
-
320
- ```python
321
- client = Knockout(token="your-token", base_url="https://your-deploy.modal.run")
322
- ```
323
-
324
318
  ## Project structure
325
319
 
326
320
  ```
@@ -1,341 +1,335 @@
1
- ---
2
- project: projects/useknockout-python
3
- type: readme
4
- ---
5
-
6
- <div align="center">
7
-
8
- # 🥊 useknockout
9
-
10
- **State-of-the-art background removal API — Python SDK.**
11
-
12
- [![PyPI](https://img.shields.io/pypi/v/useknockout.svg)](https://pypi.org/project/useknockout/)
13
- [![Python](https://img.shields.io/pypi/pyversions/useknockout.svg)](https://pypi.org/project/useknockout/)
14
- [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
15
-
16
- [Website](https://useknockout.com) ·
17
- [API repo](https://github.com/useknockout/api) ·
18
- [Node SDK](https://github.com/useknockout/node) ·
19
- [React SDK](https://github.com/useknockout/react) ·
20
- [CLI](https://github.com/useknockout/cli)
21
-
22
- <img src="https://raw.githubusercontent.com/useknockout/api/main/docs/banner.png" width="800" alt="useknockout — background removal API for developers" />
23
-
24
- *Background removal, 40× cheaper than remove.bg. MIT licensed. Self-hostable.*
25
-
26
- </div>
27
-
28
- ---
29
-
30
- ## What it is
31
-
32
- `useknockout` is the official Python SDK for the [useknockout](https://useknockout.com)
33
- background-removal API — a BiRefNet-powered image service that runs on
34
- [Modal](https://modal.com). Beyond plain cutouts, the API exposes a full suite of
35
- subject-aware image operations: background replacement, drop shadows, stickers and
36
- outlines, e-commerce / LinkedIn presets, super-resolution upscaling, face
37
- restoration, colorization, silhouettes, and inpainting.
38
-
39
- The SDK is a thin, fully-typed wrapper over [`httpx`](https://www.python-httpx.org/).
40
- It ships both a synchronous client (`Knockout`) and an asynchronous one
41
- (`AsyncKnockout`) with identical method signatures. Every image-returning method
42
- hands you **raw bytes**, so you can pipe results straight to a file, `BytesIO`,
43
- `PIL`, `numpy`, S3, or anywhere else bytes go. There are no heavy dependencies —
44
- no Pillow, no numpy — just `httpx`.
45
-
46
- ## Install
47
-
48
- ```bash
49
- pip install useknockout
50
- ```
51
-
52
- Requires Python 3.9+. The only runtime dependency is `httpx>=0.27.0`.
53
-
54
- ## Quickstart
55
-
56
- ```python
57
- from useknockout import Knockout
58
-
59
- client = Knockout() # uses public beta token by default
60
- png = client.remove("photo.jpg")
61
-
62
- with open("out.png", "wb") as f:
63
- f.write(png)
64
- ```
65
-
66
- That's it. Free during the public beta.
67
-
68
- ## Async
69
-
70
- `AsyncKnockout` mirrors the sync API one-for-one. Use it as an async context
71
- manager so the underlying `httpx.AsyncClient` is closed cleanly:
72
-
73
- ```python
74
- import asyncio
75
- from useknockout import AsyncKnockout
76
-
77
- async def main():
78
- async with AsyncKnockout() as client:
79
- png = await client.remove("photo.jpg")
80
- open("out.png", "wb").write(png)
81
-
82
- asyncio.run(main())
83
- ```
84
-
85
- The sync client is also a context manager (`with Knockout() as c: ...`) and exposes
86
- `close()` / `aclose()` if you prefer to manage the lifecycle manually.
87
-
88
- ## Authentication
89
-
90
- The client resolves its token by falling through three sources, in order:
91
-
92
- 1. The `token=` constructor argument
93
- 2. The `KNOCKOUT_TOKEN` environment variable
94
- 3. The public beta token (free, rate-limited — baked into the SDK)
95
-
96
- ```python
97
- client = Knockout(token="kno_...") # explicit
98
- client = Knockout() # env var or public beta token
99
- ```
100
-
101
- The token is sent as a `Bearer` header on every request. Get your own token by
102
- emailing `troy@useknockout.com` (paid tier launches at $0.005/image — 40× cheaper
103
- than remove.bg).
104
-
105
- ## Input types
106
-
107
- Every method that takes an image accepts a `FileInput`, which is any of:
108
-
109
- - `str` / `pathlib.Path` — a filesystem path the SDK reads for you
110
- - `bytes` / `bytearray` — raw image bytes you already have in memory
111
-
112
- ```python
113
- client.remove("photo.jpg") # path
114
- client.remove(Path("photo.jpg")) # Path
115
- client.remove(open("photo.jpg", "rb").read())# bytes
116
- ```
117
-
118
- ## All endpoints
119
-
120
- ```python
121
- from useknockout import Knockout
122
-
123
- c = Knockout()
124
-
125
- # --- Core background removal ---
126
- c.remove("photo.jpg") # returns PNG/WebP bytes
127
- c.remove_url("https://example.com/photo.jpg") # fetch + remove remote image
128
- c.remove_batch(["a.jpg", "b.jpg", "c.jpg"]) # up to 10 files -> JSON
129
- c.remove_batch_url(["https://...", "https://..."]) # up to 10 URLs -> JSON
130
-
131
- # --- Replace background ---
132
- c.replace_background("photo.jpg", bg_color="#000000")
133
- c.replace_background("photo.jpg", bg_url="https://example.com/bg.jpg")
134
-
135
- # --- Mask / crop ---
136
- c.mask("photo.jpg") # alpha mask only (grayscale PNG)
137
- c.smart_crop("photo.jpg", padding=24) # crop to subject bbox + padding
138
-
139
- # --- Effects ---
140
- c.shadow("photo.jpg", shadow_blur=14, shadow_opacity=0.45) # drop shadow
141
- c.sticker("photo.jpg", stroke_width=20) # WhatsApp-style thick outline
142
- c.outline("photo.jpg", outline_color="#000000", outline_width=4) # thin outline
143
- c.silhouette("photo.jpg", subject_color="#7C3AED") # two-tone silhouette portrait
144
-
145
- # --- Presets ---
146
- c.studio_shot("photo.jpg", aspect="1:1", shadow=True) # e-commerce
147
- c.studio_shot("photo.jpg", transparent=True) # transparent bg (PNG)
148
- c.studio_shot("photo.jpg", enhance=True) # brightness + saturation lift
149
- c.headshot("photo.jpg", bg_color="#FFFFFF") # LinkedIn 4:5 portrait
150
- c.headshot("photo.jpg", bg_blur=True, blur_radius=24) # blurred original bg
151
-
152
- # --- Enhancement ---
153
- c.upscale("photo.jpg", scale=4, model="swin2sr") # 2x/4x super-resolution
154
- c.upscale("photo.jpg", model="realesrgan", face_enhance=True) # legacy + GFPGAN
155
- c.face_restore("portrait.jpg") # GFPGAN v1.4 face restoration
156
- c.colorize("bw.jpg") # DDColor colorization
157
- c.inpaint("photo.jpg", bbox=(40, 40, 200, 150)) # LaMa inpainting
158
-
159
- # --- Marketing ---
160
- c.compare("photo.jpg") # before/after side-by-side
161
-
162
- # --- UX helpers ---
163
- c.preview("photo.jpg", max_dim=512) # fast low-res preview (~80ms warm)
164
- c.estimate("remove", width=1024, height=1024) # predict latency + cost (no processing)
165
-
166
- # --- Telemetry ---
167
- c.health() # service status + model info
168
- c.stats() # public usage counter
169
- ```
170
-
171
- Most methods return raw image **bytes**. The batch endpoints (`remove_batch`,
172
- `remove_batch_url`) and the telemetry / estimate endpoints (`health`, `stats`,
173
- `estimate`) return parsed JSON (`dict`). Pipe image bytes to
174
- `open(path, "wb").write(...)`, `BytesIO`, `PIL.Image.open(BytesIO(...))`, `numpy`,
175
- S3 — anywhere bytes go.
176
-
177
- ### Endpoint reference
178
-
179
- | Method | HTTP | Returns | Notes |
180
- | --- | --- | --- | --- |
181
- | `remove` | `POST /remove` | bytes | `format` is a query param |
182
- | `remove_url` | `POST /remove-url` | bytes | JSON body `{url, format}` |
183
- | `remove_batch` | `POST /remove-batch` | dict | up to 10 files; `format` is a query param |
184
- | `remove_batch_url` | `POST /remove-batch-url` | dict | up to 10 URLs |
185
- | `replace_background` | `POST /replace-bg` | bytes | `bg_color` or `bg_url` |
186
- | `mask` | `POST /mask` | bytes | grayscale alpha mask |
187
- | `smart_crop` | `POST /smart-crop` | bytes | `padding`, `transparent` |
188
- | `shadow` | `POST /shadow` | bytes | configurable drop shadow |
189
- | `sticker` | `POST /sticker` | bytes | thick stroke, transparent bg |
190
- | `outline` | `POST /outline` | bytes | thin stroke, transparent bg |
191
- | `silhouette` | `POST /silhouette` | bytes | two-tone; API ≥ v0.7.1 |
192
- | `studio_shot` | `POST /studio-shot` | bytes | e-commerce preset |
193
- | `headshot` | `POST /headshot` | bytes | LinkedIn 4:5 portrait |
194
- | `upscale` | `POST /upscale` | bytes | 2x/4x; `swin2sr` or `realesrgan` |
195
- | `face_restore` | `POST /face-restore` | bytes | GFPGAN v1.4 |
196
- | `colorize` | `POST /colorize` | bytes | DDColor; API ≥ v0.7.0 |
197
- | `inpaint` | `POST /inpaint` | bytes | LaMa; API ≥ v0.8.0 |
198
- | `compare` | `POST /compare` | bytes | before/after side-by-side |
199
- | `preview` | `POST /preview` | bytes | fast low-res preview |
200
- | `estimate` | `POST /estimate` | dict | predict latency + cost |
201
- | `health` | `GET /health` | dict | status + model info |
202
- | `stats` | `GET /stats` | dict | public usage counter |
203
-
204
- ### Enhancement endpoints in detail
205
-
206
- **`upscale`** — 2x or 4x super-resolution. `model="swin2sr"` (default) is sharper on
207
- real photos; `model="realesrgan"` is the legacy backend, better on anime /
208
- illustrations. `face_enhance=True` routes through GFPGAN (Real-ESRGAN backend only).
209
- `scale` must be `2` or `4`; `model` must be `"swin2sr"` or `"realesrgan"` — both are
210
- validated client-side and raise `ValueError` otherwise.
211
-
212
- **`face_restore`** — GFPGAN v1.4 portrait restoration for blurry / damaged / low-res
213
- faces. By default the background is preserved as-is; `bg_enhance=True` also upscales
214
- the background 2x via Real-ESRGAN. `only_center_face=True` restores just the most
215
- prominent face (faster).
216
-
217
- **`colorize`** — DDColor (Apache-2.0) colorization via a ConvNeXt-Large backbone
218
- (single feed-forward, ~500ms warm). Works on B&W or color input — color images are
219
- converted to grayscale internally first, making round-trip recoloring easy.
220
-
221
- **`inpaint`** — LaMa-based inpainting with three auto-detected modes:
222
-
223
- ```python
224
- c.inpaint("photo.jpg", mask="mask.png") # user-supplied mask
225
- c.inpaint("photo.jpg", bbox=(x, y, w, h)) # rectangular region
226
- c.inpaint("photo.jpg") # auto-subject (BiRefNet, inverted)
227
- ```
228
-
229
- `dilation` (0–32, default 8) expands the mask before LaMa runs to reduce ghost
230
- outlines.
231
-
232
- ## Errors
233
-
234
- All errors inherit from `KnockoutError`. The SDK maps HTTP status codes to typed
235
- subclasses, and wraps transport-level failures (`httpx.RequestError`) as a base
236
- `KnockoutError` with `code="unknown"`.
237
-
238
- ```python
239
- from useknockout import Knockout
240
- from useknockout.errors import (
241
- AuthError, # 401 / 403
242
- BadRequestError, # 400
243
- PayloadTooLargeError,# 413 (image too large)
244
- RateLimitError, # 429
245
- ServerError, # 5xx
246
- KnockoutError, # base class / network errors
247
- )
248
-
249
- try:
250
- png = client.remove("photo.jpg")
251
- except AuthError:
252
- ... # bad token
253
- except RateLimitError:
254
- ... # back off
255
- except KnockoutError as e:
256
- print(f"{e.code} ({e.status}): {e.message}")
257
- ```
258
-
259
- Each `KnockoutError` carries three attributes: `status` (HTTP code, or `None` for
260
- transport errors), `code` (a short machine-readable category like `"auth"` or
261
- `"rate_limit"`), and `message` (human-readable detail, taken from the response body
262
- when available).
263
-
264
- ## Configuration
265
-
266
- | Constructor arg | Default | Purpose |
267
- | --- | --- | --- |
268
- | `token` | env var → public beta token | API token, sent as `Bearer` header |
269
- | `base_url` | `https://useknockout--api.modal.run` | API base URL (override for self-hosted) |
270
- | `timeout` | `60.0` | per-request timeout in seconds |
271
-
272
- | Environment variable | Purpose |
273
- | --- | --- |
274
- | `KNOCKOUT_TOKEN` | API token, used when `token=` is not passed |
275
-
276
- ## Self-host
277
-
278
- The API is open source and runs on Modal. Deploy your own copy:
279
-
280
- ```bash
281
- git clone https://github.com/useknockout/api
282
- cd api
283
- modal deploy main.py
284
- ```
285
-
286
- Then point the SDK at your deployment:
287
-
288
- ```python
289
- client = Knockout(token="your-token", base_url="https://your-deploy.modal.run")
290
- ```
291
-
292
- ## Project structure
293
-
294
- ```
295
- useknockout-python/
296
- ├── pyproject.toml # hatchling build, deps, ruff config
297
- ├── README.md
298
- ├── LICENSE # MIT
299
- ├── dist/ # built wheel + sdist artifacts
300
- └── src/
301
- └── useknockout/
302
- ├── __init__.py # public exports (Knockout, AsyncKnockout, errors)
303
- ├── _version.py # __version__
304
- ├── client.py # synchronous Knockout client
305
- ├── async_client.py # asynchronous AsyncKnockout client
306
- ├── errors.py # KnockoutError hierarchy + raise_for_status
307
- └── _helpers.py # multipart/form helpers, token resolution, constants
308
- ```
309
-
310
- The package uses a `src/` layout and is built with [Hatchling](https://hatch.pypa.io/).
311
- Both clients share `_helpers.py` (multipart construction, form serialization, token
312
- resolution) and `errors.py` (status-to-exception mapping), keeping the sync and async
313
- surfaces in lockstep.
314
-
315
- ## Development
316
-
317
- ```bash
318
- pip install -e ".[dev]" # installs pytest, pytest-asyncio, ruff, mypy
319
- ruff check . # lint (line length 100; E, F, I, W, UP rules)
320
- mypy src # type-check
321
- pytest # run tests
322
- ```
323
-
324
- ## Notes
325
-
326
- - **No heavy deps.** `httpx` is the only runtime dependency. Image manipulation
327
- happens server-side; the SDK just moves bytes.
328
- - **Bytes in, bytes out.** Image-returning methods give you raw bytes — no implicit
329
- Pillow / numpy conversion, so you stay in control of the output pipeline.
330
- - **Sync + async parity.** `Knockout` and `AsyncKnockout` have identical method
331
- signatures; switch by adding/removing `await`.
332
- - **API version gating.** Some methods require a minimum API version: `colorize`
333
- needs API ≥ v0.7.0, `silhouette` ≥ v0.7.1, `inpaint` ≥ v0.8.0. The default
334
- hosted endpoint is kept current.
335
- - **`format` quirk.** `remove` and `remove_batch` pass `format` as a **query**
336
- parameter (the API reads it there), while form-based endpoints send it in the
337
- multipart body. The SDK handles this for you.
338
-
339
- ## License
340
-
341
- MIT. Use it however you want.
1
+
2
+
3
+ <div align="center">
4
+
5
+ # 🥊 useknockout
6
+
7
+ **Python SDK for useknockout, the open source background removal API.**
8
+
9
+ [![PyPI](https://img.shields.io/pypi/v/useknockout.svg)](https://pypi.org/project/useknockout/)
10
+ [![Python](https://img.shields.io/pypi/pyversions/useknockout.svg)](https://pypi.org/project/useknockout/)
11
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
12
+ [![PyPI Downloads](https://static.pepy.tech/personalized-badge/useknockout?period=total&units=INTERNATIONAL_SYSTEM&left_color=BLACK&right_color=GREEN&left_text=downloads)](https://pepy.tech/projects/useknockout)
13
+
14
+ [Website](https://useknockout.com) ·
15
+ [API repo](https://github.com/useknockout/api) ·
16
+ [Node SDK](https://github.com/useknockout/node) ·
17
+ [React SDK](https://github.com/useknockout/react) ·
18
+ [CLI](https://github.com/useknockout/cli)
19
+
20
+ <img src="https://raw.githubusercontent.com/useknockout/api/main/docs/banner.png" width="800" alt="useknockout — background removal API for developers" />
21
+
22
+ *Open source background removal and image processing. MIT licensed.*
23
+
24
+ </div>
25
+
26
+ ---
27
+
28
+ ## What it is
29
+
30
+ `useknockout` is the official Python SDK for the [useknockout](https://useknockout.com)
31
+ background-removal API — a BiRefNet-powered image service that runs on
32
+ [Modal](https://modal.com). Beyond plain cutouts, the API exposes a full suite of
33
+ subject-aware image operations: background replacement, drop shadows, stickers and
34
+ outlines, e-commerce / LinkedIn presets, super-resolution upscaling, face
35
+ restoration, colorization, silhouettes, and inpainting.
36
+
37
+ The API is open source under the MIT license:
38
+ [github.com/useknockout/api](https://github.com/useknockout/api).
39
+
40
+ The SDK is a thin, fully-typed wrapper over [`httpx`](https://www.python-httpx.org/).
41
+ It ships both a synchronous client (`Knockout`) and an asynchronous one
42
+ (`AsyncKnockout`) with identical method signatures. Every image-returning method
43
+ hands you **raw bytes**, so you can pipe results straight to a file, `BytesIO`,
44
+ `PIL`, `numpy`, S3, or anywhere else bytes go. There are no heavy dependencies —
45
+ no Pillow, no numpy — just `httpx`.
46
+
47
+ ## Install
48
+
49
+ ```bash
50
+ pip install useknockout
51
+ ```
52
+
53
+ Requires Python 3.9+. The only runtime dependency is `httpx>=0.27.0`.
54
+
55
+ ## Quickstart
56
+
57
+ ```python
58
+ from useknockout import Knockout
59
+
60
+ client = Knockout() # uses the shared demo key
61
+ png = client.remove("photo.jpg")
62
+
63
+ with open("out.png", "wb") as f:
64
+ f.write(png)
65
+ ```
66
+
67
+ That's it, no sign-up needed to try it. The demo key is limited, so get your own
68
+ key before building on it (see [Authentication](#authentication)).
69
+
70
+ ## Async
71
+
72
+ `AsyncKnockout` mirrors the sync API one-for-one. Use it as an async context
73
+ manager so the underlying `httpx.AsyncClient` is closed cleanly:
74
+
75
+ ```python
76
+ import asyncio
77
+ from useknockout import AsyncKnockout
78
+
79
+ async def main():
80
+ async with AsyncKnockout() as client:
81
+ png = await client.remove("photo.jpg")
82
+ open("out.png", "wb").write(png)
83
+
84
+ asyncio.run(main())
85
+ ```
86
+
87
+ The sync client is also a context manager (`with Knockout() as c: ...`) and exposes
88
+ `close()` / `aclose()` if you prefer to manage the lifecycle manually.
89
+
90
+ ## Authentication
91
+
92
+ The client resolves its token by falling through three sources, in order:
93
+
94
+ 1. The `token=` constructor argument
95
+ 2. The `KNOCKOUT_TOKEN` environment variable
96
+ 3. A shared demo key built into the SDK
97
+
98
+ ```python
99
+ client = Knockout(token="kno_...") # explicit
100
+ client = Knockout() # env var or shared demo key
101
+ ```
102
+
103
+ The token is sent as a `Bearer` header on every request.
104
+
105
+ **Demo key limits.** It is for trying the API without an account. It only works
106
+ with `remove`, `replace_background`, `mask`, `sticker` and `compare`, output is
107
+ capped at 1536 px, and it has daily usage limits. Other image methods return an
108
+ error.
109
+
110
+ **Your own key.** Sign up at [useknockout.com/signin](https://useknockout.com/signin).
111
+ Free accounts get 30 images every month on the core tools, no card. Pay-as-you-go
112
+ is $0.02 per image and unlocks the rest. Current rates are on the
113
+ [pricing page](https://useknockout.com/pricing).
114
+
115
+ ## Input types
116
+
117
+ Every method that takes an image accepts a `FileInput`, which is any of:
118
+
119
+ - `str` / `pathlib.Path` — a filesystem path the SDK reads for you
120
+ - `bytes` / `bytearray` — raw image bytes you already have in memory
121
+
122
+ ```python
123
+ client.remove("photo.jpg") # path
124
+ client.remove(Path("photo.jpg")) # Path
125
+ client.remove(open("photo.jpg", "rb").read())# bytes
126
+ ```
127
+
128
+ ## All endpoints
129
+
130
+ ```python
131
+ from useknockout import Knockout
132
+
133
+ c = Knockout(token="kno_...") # your own key; the demo key covers only a few of these
134
+
135
+ # --- Core background removal ---
136
+ c.remove("photo.jpg") # returns PNG/WebP bytes
137
+ c.remove_url("https://example.com/photo.jpg") # fetch + remove remote image
138
+ c.remove_batch(["a.jpg", "b.jpg", "c.jpg"]) # up to 10 files -> JSON
139
+ c.remove_batch_url(["https://...", "https://..."]) # up to 10 URLs -> JSON
140
+
141
+ # --- Replace background ---
142
+ c.replace_background("photo.jpg", bg_color="#000000")
143
+ c.replace_background("photo.jpg", bg_url="https://example.com/bg.jpg")
144
+
145
+ # --- Mask / crop ---
146
+ c.mask("photo.jpg") # alpha mask only (grayscale PNG)
147
+ c.smart_crop("photo.jpg", padding=24) # crop to subject bbox + padding
148
+
149
+ # --- Effects ---
150
+ c.shadow("photo.jpg", shadow_blur=14, shadow_opacity=0.45) # drop shadow
151
+ c.sticker("photo.jpg", stroke_width=20) # WhatsApp-style thick outline
152
+ c.outline("photo.jpg", outline_color="#000000", outline_width=4) # thin outline
153
+ c.silhouette("photo.jpg", subject_color="#7C3AED") # two-tone silhouette portrait
154
+
155
+ # --- Presets ---
156
+ c.studio_shot("photo.jpg", aspect="1:1", shadow=True) # e-commerce
157
+ c.studio_shot("photo.jpg", transparent=True) # transparent bg (PNG)
158
+ c.studio_shot("photo.jpg", enhance=True) # brightness + saturation lift
159
+ c.headshot("photo.jpg", bg_color="#FFFFFF") # LinkedIn 4:5 portrait
160
+ c.headshot("photo.jpg", bg_blur=True, blur_radius=24) # blurred original bg
161
+
162
+ # --- Enhancement ---
163
+ c.upscale("photo.jpg", scale=4, model="swin2sr") # 2x/4x super-resolution
164
+ c.upscale("photo.jpg", model="realesrgan", face_enhance=True) # legacy + GFPGAN
165
+ c.face_restore("portrait.jpg") # GFPGAN v1.4 face restoration
166
+ c.colorize("bw.jpg") # DDColor colorization
167
+ c.inpaint("photo.jpg", bbox=(40, 40, 200, 150)) # LaMa inpainting
168
+
169
+ # --- Marketing ---
170
+ c.compare("photo.jpg") # before/after side-by-side
171
+
172
+ # --- UX helpers ---
173
+ c.preview("photo.jpg", max_dim=512) # fast low-res preview (~80ms warm)
174
+ c.estimate("remove", width=1024, height=1024) # predict latency + cost (no processing)
175
+
176
+ # --- Telemetry ---
177
+ c.health() # service status + model info
178
+ c.stats() # public usage counter
179
+ ```
180
+
181
+ Most methods return raw image **bytes**. The batch endpoints (`remove_batch`,
182
+ `remove_batch_url`) and the telemetry / estimate endpoints (`health`, `stats`,
183
+ `estimate`) return parsed JSON (`dict`). Pipe image bytes to
184
+ `open(path, "wb").write(...)`, `BytesIO`, `PIL.Image.open(BytesIO(...))`, `numpy`,
185
+ S3 — anywhere bytes go.
186
+
187
+ ### Endpoint reference
188
+
189
+ | Method | HTTP | Returns | Notes |
190
+ | --- | --- | --- | --- |
191
+ | `remove` | `POST /remove` | bytes | `format` is a query param |
192
+ | `remove_url` | `POST /remove-url` | bytes | JSON body `{url, format}` |
193
+ | `remove_batch` | `POST /remove-batch` | dict | up to 10 files; `format` is a query param |
194
+ | `remove_batch_url` | `POST /remove-batch-url` | dict | up to 10 URLs |
195
+ | `replace_background` | `POST /replace-bg` | bytes | `bg_color` or `bg_url` |
196
+ | `mask` | `POST /mask` | bytes | grayscale alpha mask |
197
+ | `smart_crop` | `POST /smart-crop` | bytes | `padding`, `transparent` |
198
+ | `shadow` | `POST /shadow` | bytes | configurable drop shadow |
199
+ | `sticker` | `POST /sticker` | bytes | thick stroke, transparent bg |
200
+ | `outline` | `POST /outline` | bytes | thin stroke, transparent bg |
201
+ | `silhouette` | `POST /silhouette` | bytes | two-tone; API ≥ v0.7.1 |
202
+ | `studio_shot` | `POST /studio-shot` | bytes | e-commerce preset |
203
+ | `headshot` | `POST /headshot` | bytes | LinkedIn 4:5 portrait |
204
+ | `upscale` | `POST /upscale` | bytes | 2x/4x; `swin2sr` or `realesrgan` |
205
+ | `face_restore` | `POST /face-restore` | bytes | GFPGAN v1.4 |
206
+ | `colorize` | `POST /colorize` | bytes | DDColor; API ≥ v0.7.0 |
207
+ | `inpaint` | `POST /inpaint` | bytes | LaMa; API ≥ v0.8.0 |
208
+ | `compare` | `POST /compare` | bytes | before/after side-by-side |
209
+ | `preview` | `POST /preview` | bytes | fast low-res preview |
210
+ | `estimate` | `POST /estimate` | dict | predict latency + cost |
211
+ | `health` | `GET /health` | dict | status + model info |
212
+ | `stats` | `GET /stats` | dict | public usage counter |
213
+
214
+ ### Enhancement endpoints in detail
215
+
216
+ **`upscale`** — 2x or 4x super-resolution. `model="swin2sr"` (default) is sharper on
217
+ real photos; `model="realesrgan"` is the legacy backend, better on anime /
218
+ illustrations. `face_enhance=True` routes through GFPGAN (Real-ESRGAN backend only).
219
+ `scale` must be `2` or `4`; `model` must be `"swin2sr"` or `"realesrgan"` — both are
220
+ validated client-side and raise `ValueError` otherwise.
221
+
222
+ **`face_restore`** — GFPGAN v1.4 portrait restoration for blurry / damaged / low-res
223
+ faces. By default the background is preserved as-is; `bg_enhance=True` also upscales
224
+ the background 2x via Real-ESRGAN. `only_center_face=True` restores just the most
225
+ prominent face (faster).
226
+
227
+ **`colorize`** — DDColor (Apache-2.0) colorization via a ConvNeXt-Large backbone
228
+ (single feed-forward, ~500ms warm). Works on B&W or color input — color images are
229
+ converted to grayscale internally first, making round-trip recoloring easy.
230
+
231
+ **`inpaint`** — LaMa-based inpainting with three auto-detected modes:
232
+
233
+ ```python
234
+ c.inpaint("photo.jpg", mask="mask.png") # user-supplied mask
235
+ c.inpaint("photo.jpg", bbox=(x, y, w, h)) # rectangular region
236
+ c.inpaint("photo.jpg") # auto-subject (BiRefNet, inverted)
237
+ ```
238
+
239
+ `dilation` (0–32, default 8) expands the mask before LaMa runs to reduce ghost
240
+ outlines.
241
+
242
+ ## Errors
243
+
244
+ All errors inherit from `KnockoutError`. The SDK maps HTTP status codes to typed
245
+ subclasses, and wraps transport-level failures (`httpx.RequestError`) as a base
246
+ `KnockoutError` with `code="unknown"`.
247
+
248
+ ```python
249
+ from useknockout import Knockout
250
+ from useknockout.errors import (
251
+ AuthError, # 401 / 403
252
+ BadRequestError, # 400
253
+ PayloadTooLargeError,# 413 (image too large)
254
+ RateLimitError, # 429
255
+ ServerError, # 5xx
256
+ KnockoutError, # base class / network errors
257
+ )
258
+
259
+ try:
260
+ png = client.remove("photo.jpg")
261
+ except AuthError:
262
+ ... # bad token
263
+ except RateLimitError:
264
+ ... # back off
265
+ except KnockoutError as e:
266
+ print(f"{e.code} ({e.status}): {e.message}")
267
+ ```
268
+
269
+ Each `KnockoutError` carries three attributes: `status` (HTTP code, or `None` for
270
+ transport errors), `code` (a short machine-readable category like `"auth"` or
271
+ `"rate_limit"`), and `message` (human-readable detail, taken from the response body
272
+ when available).
273
+
274
+ ## Configuration
275
+
276
+ | Constructor arg | Default | Purpose |
277
+ | --- | --- | --- |
278
+ | `token` | env var → shared demo key | API token, sent as `Bearer` header |
279
+ | `base_url` | `https://useknockout--api.modal.run` | API base URL |
280
+ | `timeout` | `60.0` | per-request timeout in seconds |
281
+
282
+ | Environment variable | Purpose |
283
+ | --- | --- |
284
+ | `KNOCKOUT_TOKEN` | API token, used when `token=` is not passed |
285
+
286
+ ## Project structure
287
+
288
+ ```
289
+ useknockout-python/
290
+ ├── pyproject.toml # hatchling build, deps, ruff config
291
+ ├── README.md
292
+ ├── LICENSE # MIT
293
+ ├── dist/ # built wheel + sdist artifacts
294
+ └── src/
295
+ └── useknockout/
296
+ ├── __init__.py # public exports (Knockout, AsyncKnockout, errors)
297
+ ├── _version.py # __version__
298
+ ├── client.py # synchronous Knockout client
299
+ ├── async_client.py # asynchronous AsyncKnockout client
300
+ ├── errors.py # KnockoutError hierarchy + raise_for_status
301
+ └── _helpers.py # multipart/form helpers, token resolution, constants
302
+ ```
303
+
304
+ The package uses a `src/` layout and is built with [Hatchling](https://hatch.pypa.io/).
305
+ Both clients share `_helpers.py` (multipart construction, form serialization, token
306
+ resolution) and `errors.py` (status-to-exception mapping), keeping the sync and async
307
+ surfaces in lockstep.
308
+
309
+ ## Development
310
+
311
+ ```bash
312
+ pip install -e ".[dev]" # installs pytest, pytest-asyncio, ruff, mypy
313
+ ruff check . # lint (line length 100; E, F, I, W, UP rules)
314
+ mypy src # type-check
315
+ pytest # run tests
316
+ ```
317
+
318
+ ## Notes
319
+
320
+ - **No heavy deps.** `httpx` is the only runtime dependency. Image manipulation
321
+ happens server-side; the SDK just moves bytes.
322
+ - **Bytes in, bytes out.** Image-returning methods give you raw bytes — no implicit
323
+ Pillow / numpy conversion, so you stay in control of the output pipeline.
324
+ - **Sync + async parity.** `Knockout` and `AsyncKnockout` have identical method
325
+ signatures; switch by adding/removing `await`.
326
+ - **API version gating.** Some methods require a minimum API version: `colorize`
327
+ needs API ≥ v0.7.0, `silhouette` ≥ v0.7.1, `inpaint` ≥ v0.8.0. The default
328
+ hosted endpoint is kept current.
329
+ - **`format` quirk.** `remove` and `remove_batch` pass `format` as a **query**
330
+ parameter (the API reads it there), while form-based endpoints send it in the
331
+ multipart body. The SDK handles this for you.
332
+
333
+ ## License
334
+
335
+ MIT. Use it however you want.
@@ -4,8 +4,8 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "useknockout"
7
- version = "0.8.0"
8
- description = "Python SDK for useknockout — state-of-the-art background removal API."
7
+ version = "0.8.1"
8
+ description = "Python SDK for useknockout, the open source background removal API."
9
9
  readme = "README.md"
10
10
  license = { text = "MIT" }
11
11
  requires-python = ">=3.9"
@@ -16,6 +16,7 @@ keywords = [
16
16
  "birefnet",
17
17
  "ai",
18
18
  "image-processing",
19
+ "open-source",
19
20
  "useknockout",
20
21
  ]
21
22
  classifiers = [
@@ -1,47 +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
- ]
1
+ """
2
+ useknockout — state-of-the-art background removal API.
3
+
4
+ Quickstart:
5
+
6
+ from useknockout import Knockout
7
+
8
+ client = Knockout() # shared demo key, limited
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
+ ]
@@ -0,0 +1 @@
1
+ __version__ = "0.8.1"
@@ -366,7 +366,7 @@ class AsyncKnockout:
366
366
  ) -> Dict[str, Any]:
367
367
  """POST /video/remove — async video background removal. Returns the job
368
368
  dict; poll with get_job() or use video_remove_and_wait(). Paid tiers,
369
- $0.05/output-second, 30s/200MB caps."""
369
+ $0.10/output-second, 30s/200MB caps."""
370
370
  return await self._request_json(
371
371
  "POST",
372
372
  "/video/remove",
@@ -26,12 +26,12 @@ class Knockout:
26
26
 
27
27
  Args:
28
28
  token: API token. Falls back to ``KNOCKOUT_TOKEN`` env var, then to the
29
- public beta token.
30
- base_url: API base URL (override for self-hosted deployments).
29
+ shared demo key, which is limited (see the README).
30
+ base_url: API base URL.
31
31
  timeout: Per-request timeout in seconds.
32
32
 
33
33
  Example:
34
- >>> client = Knockout() # uses public beta token by default
34
+ >>> client = Knockout() # uses the shared demo key
35
35
  >>> png = client.remove("photo.jpg")
36
36
  >>> open("out.png", "wb").write(png)
37
37
  """
@@ -419,7 +419,7 @@ class Knockout:
419
419
  or use video_remove_and_wait().
420
420
 
421
421
  format: 'prores4444' (MOV, real 10-bit alpha), 'webm' (VP9 alpha), or
422
- 'mp4' (H.264 — requires bg_color). Paid tiers only, $0.05 per output
422
+ 'mp4' (H.264 — requires bg_color). Paid tiers only, $0.10 per output
423
423
  second, billed on success. Caps: 30s clip, 30fps, 200MB.
424
424
  """
425
425
  return self._request_json(
@@ -1 +0,0 @@
1
- __version__ = "0.7.0"
File without changes
File without changes
File without changes
File without changes