useknockout 0.4.0__tar.gz → 0.6.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,373 @@
1
+ Metadata-Version: 2.4
2
+ Name: useknockout
3
+ Version: 0.6.0
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
+ ---
34
+ project: projects/useknockout-python
35
+ type: readme
36
+ ---
37
+
38
+ <div align="center">
39
+
40
+ # 🥊 useknockout
41
+
42
+ **State-of-the-art background removal API — Python SDK.**
43
+
44
+ [![PyPI](https://img.shields.io/pypi/v/useknockout.svg)](https://pypi.org/project/useknockout/)
45
+ [![Python](https://img.shields.io/pypi/pyversions/useknockout.svg)](https://pypi.org/project/useknockout/)
46
+ [![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
47
+
48
+ [Website](https://useknockout.com) ·
49
+ [API repo](https://github.com/useknockout/api) ·
50
+ [Node SDK](https://github.com/useknockout/node) ·
51
+ [React SDK](https://github.com/useknockout/react) ·
52
+ [CLI](https://github.com/useknockout/cli)
53
+
54
+ <img src="https://raw.githubusercontent.com/useknockout/api/main/docs/banner.png" width="800" alt="useknockout — background removal API for developers" />
55
+
56
+ *Background removal, 40× cheaper than remove.bg. MIT licensed. Self-hostable.*
57
+
58
+ </div>
59
+
60
+ ---
61
+
62
+ ## What it is
63
+
64
+ `useknockout` is the official Python SDK for the [useknockout](https://useknockout.com)
65
+ background-removal API — a BiRefNet-powered image service that runs on
66
+ [Modal](https://modal.com). Beyond plain cutouts, the API exposes a full suite of
67
+ subject-aware image operations: background replacement, drop shadows, stickers and
68
+ outlines, e-commerce / LinkedIn presets, super-resolution upscaling, face
69
+ restoration, colorization, silhouettes, and inpainting.
70
+
71
+ The SDK is a thin, fully-typed wrapper over [`httpx`](https://www.python-httpx.org/).
72
+ It ships both a synchronous client (`Knockout`) and an asynchronous one
73
+ (`AsyncKnockout`) with identical method signatures. Every image-returning method
74
+ hands you **raw bytes**, so you can pipe results straight to a file, `BytesIO`,
75
+ `PIL`, `numpy`, S3, or anywhere else bytes go. There are no heavy dependencies —
76
+ no Pillow, no numpy — just `httpx`.
77
+
78
+ ## Install
79
+
80
+ ```bash
81
+ pip install useknockout
82
+ ```
83
+
84
+ Requires Python 3.9+. The only runtime dependency is `httpx>=0.27.0`.
85
+
86
+ ## Quickstart
87
+
88
+ ```python
89
+ from useknockout import Knockout
90
+
91
+ client = Knockout() # uses public beta token by default
92
+ png = client.remove("photo.jpg")
93
+
94
+ with open("out.png", "wb") as f:
95
+ f.write(png)
96
+ ```
97
+
98
+ That's it. Free during the public beta.
99
+
100
+ ## Async
101
+
102
+ `AsyncKnockout` mirrors the sync API one-for-one. Use it as an async context
103
+ manager so the underlying `httpx.AsyncClient` is closed cleanly:
104
+
105
+ ```python
106
+ import asyncio
107
+ from useknockout import AsyncKnockout
108
+
109
+ async def main():
110
+ async with AsyncKnockout() as client:
111
+ png = await client.remove("photo.jpg")
112
+ open("out.png", "wb").write(png)
113
+
114
+ asyncio.run(main())
115
+ ```
116
+
117
+ The sync client is also a context manager (`with Knockout() as c: ...`) and exposes
118
+ `close()` / `aclose()` if you prefer to manage the lifecycle manually.
119
+
120
+ ## Authentication
121
+
122
+ The client resolves its token by falling through three sources, in order:
123
+
124
+ 1. The `token=` constructor argument
125
+ 2. The `KNOCKOUT_TOKEN` environment variable
126
+ 3. The public beta token (free, rate-limited — baked into the SDK)
127
+
128
+ ```python
129
+ client = Knockout(token="kno_...") # explicit
130
+ client = Knockout() # env var or public beta token
131
+ ```
132
+
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).
136
+
137
+ ## Input types
138
+
139
+ Every method that takes an image accepts a `FileInput`, which is any of:
140
+
141
+ - `str` / `pathlib.Path` — a filesystem path the SDK reads for you
142
+ - `bytes` / `bytearray` — raw image bytes you already have in memory
143
+
144
+ ```python
145
+ client.remove("photo.jpg") # path
146
+ client.remove(Path("photo.jpg")) # Path
147
+ client.remove(open("photo.jpg", "rb").read())# bytes
148
+ ```
149
+
150
+ ## All endpoints
151
+
152
+ ```python
153
+ from useknockout import Knockout
154
+
155
+ c = Knockout()
156
+
157
+ # --- Core background removal ---
158
+ c.remove("photo.jpg") # returns PNG/WebP bytes
159
+ c.remove_url("https://example.com/photo.jpg") # fetch + remove remote image
160
+ c.remove_batch(["a.jpg", "b.jpg", "c.jpg"]) # up to 10 files -> JSON
161
+ c.remove_batch_url(["https://...", "https://..."]) # up to 10 URLs -> JSON
162
+
163
+ # --- Replace background ---
164
+ c.replace_background("photo.jpg", bg_color="#000000")
165
+ c.replace_background("photo.jpg", bg_url="https://example.com/bg.jpg")
166
+
167
+ # --- Mask / crop ---
168
+ c.mask("photo.jpg") # alpha mask only (grayscale PNG)
169
+ c.smart_crop("photo.jpg", padding=24) # crop to subject bbox + padding
170
+
171
+ # --- Effects ---
172
+ c.shadow("photo.jpg", shadow_blur=14, shadow_opacity=0.45) # drop shadow
173
+ c.sticker("photo.jpg", stroke_width=20) # WhatsApp-style thick outline
174
+ c.outline("photo.jpg", outline_color="#000000", outline_width=4) # thin outline
175
+ c.silhouette("photo.jpg", subject_color="#7C3AED") # two-tone silhouette portrait
176
+
177
+ # --- Presets ---
178
+ c.studio_shot("photo.jpg", aspect="1:1", shadow=True) # e-commerce
179
+ c.studio_shot("photo.jpg", transparent=True) # transparent bg (PNG)
180
+ c.studio_shot("photo.jpg", enhance=True) # brightness + saturation lift
181
+ c.headshot("photo.jpg", bg_color="#FFFFFF") # LinkedIn 4:5 portrait
182
+ c.headshot("photo.jpg", bg_blur=True, blur_radius=24) # blurred original bg
183
+
184
+ # --- Enhancement ---
185
+ c.upscale("photo.jpg", scale=4, model="swin2sr") # 2x/4x super-resolution
186
+ c.upscale("photo.jpg", model="realesrgan", face_enhance=True) # legacy + GFPGAN
187
+ c.face_restore("portrait.jpg") # GFPGAN v1.4 face restoration
188
+ c.colorize("bw.jpg") # DDColor colorization
189
+ c.inpaint("photo.jpg", bbox=(40, 40, 200, 150)) # LaMa inpainting
190
+
191
+ # --- Marketing ---
192
+ c.compare("photo.jpg") # before/after side-by-side
193
+
194
+ # --- UX helpers ---
195
+ c.preview("photo.jpg", max_dim=512) # fast low-res preview (~80ms warm)
196
+ c.estimate("remove", width=1024, height=1024) # predict latency + cost (no processing)
197
+
198
+ # --- Telemetry ---
199
+ c.health() # service status + model info
200
+ c.stats() # public usage counter
201
+ ```
202
+
203
+ Most methods return raw image **bytes**. The batch endpoints (`remove_batch`,
204
+ `remove_batch_url`) and the telemetry / estimate endpoints (`health`, `stats`,
205
+ `estimate`) return parsed JSON (`dict`). Pipe image bytes to
206
+ `open(path, "wb").write(...)`, `BytesIO`, `PIL.Image.open(BytesIO(...))`, `numpy`,
207
+ S3 — anywhere bytes go.
208
+
209
+ ### Endpoint reference
210
+
211
+ | Method | HTTP | Returns | Notes |
212
+ | --- | --- | --- | --- |
213
+ | `remove` | `POST /remove` | bytes | `format` is a query param |
214
+ | `remove_url` | `POST /remove-url` | bytes | JSON body `{url, format}` |
215
+ | `remove_batch` | `POST /remove-batch` | dict | up to 10 files; `format` is a query param |
216
+ | `remove_batch_url` | `POST /remove-batch-url` | dict | up to 10 URLs |
217
+ | `replace_background` | `POST /replace-bg` | bytes | `bg_color` or `bg_url` |
218
+ | `mask` | `POST /mask` | bytes | grayscale alpha mask |
219
+ | `smart_crop` | `POST /smart-crop` | bytes | `padding`, `transparent` |
220
+ | `shadow` | `POST /shadow` | bytes | configurable drop shadow |
221
+ | `sticker` | `POST /sticker` | bytes | thick stroke, transparent bg |
222
+ | `outline` | `POST /outline` | bytes | thin stroke, transparent bg |
223
+ | `silhouette` | `POST /silhouette` | bytes | two-tone; API ≥ v0.7.1 |
224
+ | `studio_shot` | `POST /studio-shot` | bytes | e-commerce preset |
225
+ | `headshot` | `POST /headshot` | bytes | LinkedIn 4:5 portrait |
226
+ | `upscale` | `POST /upscale` | bytes | 2x/4x; `swin2sr` or `realesrgan` |
227
+ | `face_restore` | `POST /face-restore` | bytes | GFPGAN v1.4 |
228
+ | `colorize` | `POST /colorize` | bytes | DDColor; API ≥ v0.7.0 |
229
+ | `inpaint` | `POST /inpaint` | bytes | LaMa; API ≥ v0.8.0 |
230
+ | `compare` | `POST /compare` | bytes | before/after side-by-side |
231
+ | `preview` | `POST /preview` | bytes | fast low-res preview |
232
+ | `estimate` | `POST /estimate` | dict | predict latency + cost |
233
+ | `health` | `GET /health` | dict | status + model info |
234
+ | `stats` | `GET /stats` | dict | public usage counter |
235
+
236
+ ### Enhancement endpoints in detail
237
+
238
+ **`upscale`** — 2x or 4x super-resolution. `model="swin2sr"` (default) is sharper on
239
+ real photos; `model="realesrgan"` is the legacy backend, better on anime /
240
+ illustrations. `face_enhance=True` routes through GFPGAN (Real-ESRGAN backend only).
241
+ `scale` must be `2` or `4`; `model` must be `"swin2sr"` or `"realesrgan"` — both are
242
+ validated client-side and raise `ValueError` otherwise.
243
+
244
+ **`face_restore`** — GFPGAN v1.4 portrait restoration for blurry / damaged / low-res
245
+ faces. By default the background is preserved as-is; `bg_enhance=True` also upscales
246
+ the background 2x via Real-ESRGAN. `only_center_face=True` restores just the most
247
+ prominent face (faster).
248
+
249
+ **`colorize`** — DDColor (Apache-2.0) colorization via a ConvNeXt-Large backbone
250
+ (single feed-forward, ~500ms warm). Works on B&W or color input — color images are
251
+ converted to grayscale internally first, making round-trip recoloring easy.
252
+
253
+ **`inpaint`** — LaMa-based inpainting with three auto-detected modes:
254
+
255
+ ```python
256
+ c.inpaint("photo.jpg", mask="mask.png") # user-supplied mask
257
+ c.inpaint("photo.jpg", bbox=(x, y, w, h)) # rectangular region
258
+ c.inpaint("photo.jpg") # auto-subject (BiRefNet, inverted)
259
+ ```
260
+
261
+ `dilation` (0–32, default 8) expands the mask before LaMa runs to reduce ghost
262
+ outlines.
263
+
264
+ ## Errors
265
+
266
+ All errors inherit from `KnockoutError`. The SDK maps HTTP status codes to typed
267
+ subclasses, and wraps transport-level failures (`httpx.RequestError`) as a base
268
+ `KnockoutError` with `code="unknown"`.
269
+
270
+ ```python
271
+ from useknockout import Knockout
272
+ from useknockout.errors import (
273
+ AuthError, # 401 / 403
274
+ BadRequestError, # 400
275
+ PayloadTooLargeError,# 413 (image too large)
276
+ RateLimitError, # 429
277
+ ServerError, # 5xx
278
+ KnockoutError, # base class / network errors
279
+ )
280
+
281
+ try:
282
+ png = client.remove("photo.jpg")
283
+ except AuthError:
284
+ ... # bad token
285
+ except RateLimitError:
286
+ ... # back off
287
+ except KnockoutError as e:
288
+ print(f"{e.code} ({e.status}): {e.message}")
289
+ ```
290
+
291
+ Each `KnockoutError` carries three attributes: `status` (HTTP code, or `None` for
292
+ transport errors), `code` (a short machine-readable category like `"auth"` or
293
+ `"rate_limit"`), and `message` (human-readable detail, taken from the response body
294
+ when available).
295
+
296
+ ## Configuration
297
+
298
+ | Constructor arg | Default | Purpose |
299
+ | --- | --- | --- |
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) |
302
+ | `timeout` | `60.0` | per-request timeout in seconds |
303
+
304
+ | Environment variable | Purpose |
305
+ | --- | --- |
306
+ | `KNOCKOUT_TOKEN` | API token, used when `token=` is not passed |
307
+
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
+ ## Project structure
325
+
326
+ ```
327
+ useknockout-python/
328
+ ├── pyproject.toml # hatchling build, deps, ruff config
329
+ ├── README.md
330
+ ├── LICENSE # MIT
331
+ ├── dist/ # built wheel + sdist artifacts
332
+ └── src/
333
+ └── useknockout/
334
+ ├── __init__.py # public exports (Knockout, AsyncKnockout, errors)
335
+ ├── _version.py # __version__
336
+ ├── client.py # synchronous Knockout client
337
+ ├── async_client.py # asynchronous AsyncKnockout client
338
+ ├── errors.py # KnockoutError hierarchy + raise_for_status
339
+ └── _helpers.py # multipart/form helpers, token resolution, constants
340
+ ```
341
+
342
+ The package uses a `src/` layout and is built with [Hatchling](https://hatch.pypa.io/).
343
+ Both clients share `_helpers.py` (multipart construction, form serialization, token
344
+ resolution) and `errors.py` (status-to-exception mapping), keeping the sync and async
345
+ surfaces in lockstep.
346
+
347
+ ## Development
348
+
349
+ ```bash
350
+ pip install -e ".[dev]" # installs pytest, pytest-asyncio, ruff, mypy
351
+ ruff check . # lint (line length 100; E, F, I, W, UP rules)
352
+ mypy src # type-check
353
+ pytest # run tests
354
+ ```
355
+
356
+ ## Notes
357
+
358
+ - **No heavy deps.** `httpx` is the only runtime dependency. Image manipulation
359
+ happens server-side; the SDK just moves bytes.
360
+ - **Bytes in, bytes out.** Image-returning methods give you raw bytes — no implicit
361
+ Pillow / numpy conversion, so you stay in control of the output pipeline.
362
+ - **Sync + async parity.** `Knockout` and `AsyncKnockout` have identical method
363
+ signatures; switch by adding/removing `await`.
364
+ - **API version gating.** Some methods require a minimum API version: `colorize`
365
+ needs API ≥ v0.7.0, `silhouette` ≥ v0.7.1, `inpaint` ≥ v0.8.0. The default
366
+ hosted endpoint is kept current.
367
+ - **`format` quirk.** `remove` and `remove_batch` pass `format` as a **query**
368
+ parameter (the API reads it there), while form-based endpoints send it in the
369
+ multipart body. The SDK handles this for you.
370
+
371
+ ## License
372
+
373
+ MIT. Use it however you want.