GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — python/src/useknockout/client.py at main · useknockout/python Expand file tree/ Copy pathclient.pyMore file actions 667 lines (608 loc) · 21.2 KB / Copy pathclient.pyFile metadata and controls667 lines (608 loc) · 21.2 KB 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 """Synchronous client for the useknockout API.""" from __future__ import annotations from typing import Any, Dict, List, Optional, Tuple import httpx from useknockout._helpers import ( DEFAULT_BASE_URL, PUBLIC_BETA_TOKEN, FileInput, _form, _multipart_batch, _multipart_files, _resolve_token, _to_bytes_and_name, ) from useknockout._version import __version__ from useknockout.errors import KnockoutError, raise_for_status class Knockout: """ Synchronous client for the useknockout background-removal API. Args: token: API token. Falls back to ``KNOCKOUT_TOKEN`` env var, then to the public beta token. base_url: API base URL (override for self-hosted deployments). timeout: Per-request timeout in seconds. Example: >>> client = Knockout() # uses public beta token by default >>> png = client.remove("photo.jpg") >>> open("out.png", "wb").write(png) """ def __init__( self, token: Optional[str] = None, *, base_url: str = DEFAULT_BASE_URL, timeout: float = 60.0, ) -> None: self.token = _resolve_token(token) or PUBLIC_BETA_TOKEN self.base_url = base_url.rstrip("/") self._http = httpx.Client( base_url=self.base_url, timeout=timeout, headers={ "Authorization": f"Bearer {self.token}", "User-Agent": f"useknockout-python/{__version__}", }, ) # ---- lifecycle ---- def __enter__(self) -> "Knockout": return self def __exit__(self, exc_type, exc, tb) -> None: self.close() def close(self) -> None: self._http.close() # ---- low-level transport ---- def _request_bytes( self, method: str, path: str, *, files=None, data=None, json=None, params=None, timeout=None, ) -> bytes: try: kwargs = {"files": files, "data": data, "json": json, "params": params} if timeout is not None: kwargs["timeout"] = timeout r = self._http.request(method, path, **kwargs) except httpx.RequestError as e: raise KnockoutError(f"network error: {e}", code="unknown") from e if r.status_code >= 400: raise_for_status(r.status_code, r.content) return r.content def _request_json( self, method: str, path: str, *, files=None, data=None, json=None, params=None, timeout=None, ) -> Any: try: kwargs = {"files": files, "data": data, "json": json, "params": params} if timeout is not None: kwargs["timeout"] = timeout r = self._http.request(method, path, **kwargs) except httpx.RequestError as e: raise KnockoutError(f"network error: {e}", code="unknown") from e if r.status_code >= 400: raise_for_status(r.status_code, r.content) try: return r.json() except ValueError as e: raise KnockoutError(f"invalid JSON response: {e}", code="server") from e # ---- public API ---- def health(self) -> Dict[str, Any]: """GET /health — service status + model info.""" return self._request_json("GET", "/health") def stats(self) -> Dict[str, Any]: """GET /stats — public usage counter (total + today + last 7 days).""" return self._request_json("GET", "/stats") def remove( self, file: FileInput, *, format: str = "png", edge: str = "soft", detect: str = "standard", decontaminate: bool = False, ) -> bytes: """POST /remove — remove background, return transparent PNG/WebP bytes. edge: "soft" (default) or "hard" — hard commits ambiguous edge pixels for a crisp product cut; keep soft for hair and fur. detect: "standard" (default) or "high_recall" — second pass recovers low-contrast product edges. Paid tiers; roughly 2x latency. decontaminate: remove background-colored contamination at mask edges. """ # NOTE: the API reads ALL of these as Form fields — they must go in the # multipart body. (A previous version sent format as a query param, # which the API silently ignored.) return self._request_bytes( "POST", "/remove", files=_multipart_files(file), data=_form({ "format": format, "edge": edge, "detect": detect, "decontaminate": decontaminate, }), ) def remove_url( self, url: str, *, format: str = "png", edge: str = "soft", detect: str = "standard", decontaminate: bool = False, ) -> bytes: """POST /remove-url — fetch remote image, return transparent PNG/WebP.""" return self._request_bytes( "POST", "/remove-url", json={ "url": url, "format": format, "edge": edge, "detect": detect, "decontaminate": decontaminate, }, ) def replace_background( self, file: FileInput, *, bg_color: str = "#FFFFFF", bg_url: Optional[str] = None, format: str = "png", ) -> bytes: """POST /replace-bg — composite subject onto solid color or remote bg image.""" return self._request_bytes( "POST", "/replace-bg", files=_multipart_files(file), data=_form({"bg_color": bg_color, "bg_url": bg_url, "format": format}), ) def remove_batch( self, files: List[FileInput], *, format: str = "png", ) -> Dict[str, Any]: """POST /remove-batch — up to 10 multipart uploads in one call.""" if len(files) > 10: raise ValueError("max 10 files per batch") # /remove-batch reads `format` as a QUERY param (bare default in the API). return self._request_json( "POST", "/remove-batch", files=_multipart_batch(files), params={"format": format}, ) def remove_batch_url(self, urls: List[str], *, format: str = "png") -> Dict[str, Any]: """POST /remove-batch-url — up to 10 remote URLs in one call.""" if len(urls) > 10: raise ValueError("max 10 urls per batch") return self._request_json( "POST", "/remove-batch-url", json={"urls": urls, "format": format}, ) def mask(self, file: FileInput, *, format: str = "png") -> bytes: """POST /mask — return alpha mask only (grayscale).""" return self._request_bytes( "POST", "/mask", files=_multipart_files(file), data=_form({"format": format}), ) def smart_crop( self, file: FileInput, *, padding: int = 24, transparent: bool = True, format: str = "png", detect: str = "standard", decontaminate: bool = False, ) -> bytes: """POST /smart-crop — crop to subject bbox + padding.""" return self._request_bytes( "POST", "/smart-crop", files=_multipart_files(file), data=_form({ "padding": padding, "transparent": transparent, "format": format, "detect": detect, "decontaminate": decontaminate, }), ) def shadow( self, file: FileInput, *, bg_color: str = "#FFFFFF", bg_url: Optional[str] = None, shadow_color: str = "#000000", shadow_offset_x: int = 8, shadow_offset_y: int = 12, shadow_blur: int = 14, shadow_opacity: float = 0.45, format: str = "png", ) -> bytes: """POST /shadow — subject on bg with configurable drop shadow.""" return self._request_bytes( "POST", "/shadow", files=_multipart_files(file), data=_form( { "bg_color": bg_color, "bg_url": bg_url, "shadow_color": shadow_color, "shadow_offset_x": shadow_offset_x, "shadow_offset_y": shadow_offset_y, "shadow_blur": shadow_blur, "shadow_opacity": shadow_opacity, "format": format, } ), ) def sticker( self, file: FileInput, *, stroke_color: str = "#FFFFFF", stroke_width: int = 20, format: str = "png", ) -> bytes: """POST /sticker — subject + thick outline on transparent bg.""" return self._request_bytes( "POST", "/sticker", files=_multipart_files(file), data=_form( {"stroke_color": stroke_color, "stroke_width": stroke_width, "format": format} ), ) def outline( self, file: FileInput, *, outline_color: str = "#000000", outline_width: int = 4, format: str = "png", ) -> bytes: """POST /outline — subject + thin outline on transparent bg.""" return self._request_bytes( "POST", "/outline", files=_multipart_files(file), data=_form( {"outline_color": outline_color, "outline_width": outline_width, "format": format} ), ) def studio_shot( self, file: FileInput, *, bg_color: str = "#FFFFFF", aspect: str = "1:1", padding: int = 48, shadow: bool = True, transparent: bool = False, enhance: bool = False, enhance_strength: float = 0.15, format: str = "jpg", detect: str = "standard", decontaminate: bool = False, ) -> bytes: """POST /studio-shot — e-commerce preset (cutout + crop + center + shadow). Set ``transparent=True`` to keep a transparent background (bg_color and shadow are ignored; output is PNG, jpg is coerced). Set ``enhance=True`` for a subtle brightness + saturation lift on the subject (ecommerce-ready). ``enhance_strength`` (0.0-0.5, default 0.15) controls the amount and only applies when ``enhance`` is True. """ return self._request_bytes( "POST", "/studio-shot", files=_multipart_files(file), data=_form( { "bg_color": bg_color, "aspect": aspect, "padding": padding, "shadow": shadow, "transparent": transparent, "enhance": enhance, "enhance_strength": enhance_strength, "format": format, "detect": detect, "decontaminate": decontaminate, } ), ) def collage( self, files: List[FileInput], *, main_index: int = 0, main_position: str = "BR", bg_color: str = "#FFFFFF", aspect: str = "1:1", padding: int = 24, format: str = "jpg", ) -> bytes: """POST /collage — lay 2-9 background-removed photos around a main image. ``main_index`` picks the hero (0-based); ``main_position`` anchors it (TL, T, TR, L, C, R, BL, B, BR). Paid tiers only. Billed at N base-image units (each photo is a full model pass), so 9 photos = 9x your per-image price. """ if not 2 <= len(files) <= 9: raise ValueError("collage requires 2-9 files") # N model passes + possible cold start easily exceeds the 60s single-image # default; scale the ceiling by file count. return self._request_bytes( "POST", "/collage", files=_multipart_batch(files), data=_form( { "main_index": main_index, "main_position": main_position, "bg_color": bg_color, "aspect": aspect, "padding": padding, "format": format, } ), timeout=45.0 + len(files) * 20.0, ) def video_remove( self, file: FileInput, *, format: str = "prores4444", bg_color: Optional[str] = None, smoothing: int = 30, ) -> Dict[str, Any]: """POST /video/remove — async video background removal. Returns the job dict immediately ({job_id, status, seconds, ...}); poll with get_job() or use video_remove_and_wait(). format: 'prores4444' (MOV, real 10-bit alpha), 'webm' (VP9 alpha), or 'mp4' (H.264 — requires bg_color). Paid tiers only, $0.05 per output second, billed on success. Caps: 30s clip, 30fps, 200MB. """ return self._request_json( "POST", "/video/remove", files=_multipart_files(file), data=_form({"format": format, "bg_color": bg_color, "smoothing": smoothing}), timeout=300.0, # uploads up to 200MB + server-side probe ) def get_job(self, job_id: str) -> Dict[str, Any]: """GET /jobs/{job_id} — poll a video job once.""" return self._request_json("GET", f"/jobs/{job_id}") def video_remove_and_wait( self, file: FileInput, *, format: str = "prores4444", bg_color: Optional[str] = None, smoothing: int = 30, poll_interval: float = 5.0, timeout: float = 900.0, ) -> Dict[str, Any]: """Submit a video and block until it finishes. Returns the final job dict (status 'done', result_url set). Raises KnockoutError on job failure or wait timeout.""" import time as _time job = self.video_remove(file, format=format, bg_color=bg_color, smoothing=smoothing) deadline = _time.monotonic() + timeout while job.get("status") in ("queued", "processing"): if _time.monotonic() > deadline: raise KnockoutError(f"video job {job.get('job_id')} still running after {timeout}s", code="timeout") _time.sleep(poll_interval) job = self.get_job(job["job_id"]) if job.get("status") == "error": raise KnockoutError(f"video job {job.get('job_id')} failed: {job.get('error')}", code="job_error") return job def compare(self, file: FileInput, *, format: str = "png") -> bytes: """POST /compare — side-by-side before/after image.""" return self._request_bytes( "POST", "/compare", files=_multipart_files(file), data=_form({"format": format}), ) def headshot( self, file: FileInput, *, bg_color: str = "#FFFFFF", bg_blur: bool = False, blur_radius: int = 20, aspect: str = "4:5", padding: int = 64, head_top_ratio: float = 0.18, format: str = "jpg", ) -> bytes: """POST /headshot — LinkedIn-ready portrait preset.""" return self._request_bytes( "POST", "/headshot", files=_multipart_files(file), data=_form( { "bg_color": bg_color, "bg_blur": bg_blur, "blur_radius": blur_radius, "aspect": aspect, "padding": padding, "head_top_ratio": head_top_ratio, "format": format, } ), ) def preview( self, file: FileInput, *, max_dim: int = 512, format: str = "png", ) -> bytes: """POST /preview — fast low-res preview (~80ms warm).""" return self._request_bytes( "POST", "/preview", files=_multipart_files(file), data=_form({"max_dim": max_dim, "format": format}), ) def estimate(self, endpoint: str, width: int, height: int) -> Dict[str, Any]: """POST /estimate — predict latency + cost without processing.""" return self._request_json( "POST", "/estimate", json={"endpoint": endpoint, "width": width, "height": height}, ) def upscale( self, file: FileInput, *, scale: int = 4, model: str = "swin2sr", face_enhance: bool = False, format: str = "png", ) -> bytes: """POST /upscale — 2x/4x super-resolution. ``model="swin2sr"`` (default, v0.6.0+) is sharper on real photos. ``model="realesrgan"`` is the legacy backend — better on anime / illustrations. ``face_enhance=True`` routes through GFPGAN (Real-ESRGAN backend). """ if scale not in (2, 4): raise ValueError("scale must be 2 or 4") if model not in ("swin2sr", "realesrgan"): raise ValueError("model must be 'swin2sr' or 'realesrgan'") return self._request_bytes( "POST", "/upscale", files=_multipart_files(file), data=_form({ "scale": scale, "model": model, "face_enhance": face_enhance, "format": format, }), ) def face_restore( self, file: FileInput, *, only_center_face: bool = False, bg_enhance: bool = False, format: str = "png", ) -> bytes: """POST /face-restore — GFPGAN v1.4 portrait restoration. Fixes blurry / damaged / low-res faces. By default the background is preserved as-is. ``bg_enhance=True`` also upscales the background 2x via Real-ESRGAN. ``only_center_face=True`` restores just the most prominent face (faster). """ return self._request_bytes( "POST", "/face-restore", files=_multipart_files(file), data=_form( { "only_center_face": only_center_face, "bg_enhance": bg_enhance, "format": format, } ), ) def colorize( self, file: FileInput, *, format: str = "png", ) -> bytes: """POST /colorize — DDColor (Apache-2.0) image colorization. Predicts plausible color from grayscale luminance via a ConvNeXt-Large backbone (single feed-forward, ~500ms warm). Works on B&W or color input — color images are converted to grayscale internally before prediction, which makes round-trip recoloring straightforward. Added in v0.1.0; requires API ≥ v0.7.0. """ return self._request_bytes( "POST", "/colorize", files=_multipart_files(file), data=_form({"format": format}), ) def silhouette( self, file: FileInput, *, subject_color: str = "#7C3AED", bg_color: str = "#FFFFFF", format: str = "png", ) -> bytes: """POST /silhouette — two-tone silhouette portrait. Subject filled with one solid color, background filled with another. Apple Music / Spotify avatar style. Reuses BiRefNet's mask path; no new model load. Added in v0.1.1; requires API ≥ v0.7.1. """ return self._request_bytes( "POST", "/silhouette", files=_multipart_files(file), data=_form({ "subject_color": subject_color, "bg_color": bg_color, "format": format, }), ) def inpaint( self, file: FileInput, *, mask: Optional[FileInput] = None, bbox: Optional[Tuple[int, int, int, int]] = None, dilation: int = 8, format: str = "png", ) -> bytes: """POST /inpaint — LaMa-based image inpainting. Three auto-detected modes: - ``mask`` provided → user-supplied mask - ``bbox=(x, y, w, h)`` → rectangular region - neither → auto-subject (BiRefNet, inverted) ``dilation`` (0..32, default 8) expands the mask before LaMa runs to reduce ghost outlines. Added in v0.2.0; requires API ≥ v0.8.0. """ files = _multipart_files(file) if mask is not None: mdata, mname = _to_bytes_and_name(mask, default_name="mask.png") files.append(("mask", (mname, mdata, "application/octet-stream"))) data = {"dilation": str(int(dilation)), "format": format} if bbox is not None: x, y, w, h = bbox data.update({"x": str(int(x)), "y": str(int(y)), "w": str(int(w)), "h": str(int(h))}) return self._request_bytes( "POST", "/inpaint", files=files, data=_form(data), ) |
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |