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/async_client.py at main · useknockout/python Expand file tree/ Copy pathasync_client.pyMore file actions 569 lines (528 loc) · 17 KB / Copy pathasync_client.pyFile metadata and controls569 lines (528 loc) · 17 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 """Asynchronous 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 AsyncKnockout: """ Asynchronous client for the useknockout background-removal API. Use as an async context manager to ensure the underlying httpx client closes: async with AsyncKnockout() as client: png = await client.remove("photo.jpg") """ 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.AsyncClient( base_url=self.base_url, timeout=timeout, headers={ "Authorization": f"Bearer {self.token}", "User-Agent": f"useknockout-python/{__version__}", }, ) async def __aenter__(self) -> "AsyncKnockout": return self async def __aexit__(self, exc_type, exc, tb) -> None: await self.aclose() async def aclose(self) -> None: await self._http.aclose() async 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 = await 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 async 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 = await 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 async def health(self) -> Dict[str, Any]: return await self._request_json("GET", "/health") async def stats(self) -> Dict[str, Any]: return await self._request_json("GET", "/stats") async def remove( self, file: FileInput, *, format: str = "png", edge: str = "soft", detect: str = "standard", decontaminate: bool = False, ) -> bytes: # All params are Form fields — they must ride in the multipart body. return await self._request_bytes( "POST", "/remove", files=_multipart_files(file), data=_form({ "format": format, "edge": edge, "detect": detect, "decontaminate": decontaminate, }), ) async def remove_url( self, url: str, *, format: str = "png", edge: str = "soft", detect: str = "standard", decontaminate: bool = False, ) -> bytes: return await self._request_bytes( "POST", "/remove-url", json={ "url": url, "format": format, "edge": edge, "detect": detect, "decontaminate": decontaminate, }, ) async def replace_background( self, file: FileInput, *, bg_color: str = "#FFFFFF", bg_url: Optional[str] = None, format: str = "png", ) -> bytes: return await self._request_bytes( "POST", "/replace-bg", files=_multipart_files(file), data=_form({"bg_color": bg_color, "bg_url": bg_url, "format": format}), ) async def remove_batch( self, files: List[FileInput], *, format: str = "png", ) -> Dict[str, Any]: 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 await self._request_json( "POST", "/remove-batch", files=_multipart_batch(files), params={"format": format}, ) async def remove_batch_url(self, urls: List[str], *, format: str = "png") -> Dict[str, Any]: if len(urls) > 10: raise ValueError("max 10 urls per batch") return await self._request_json( "POST", "/remove-batch-url", json={"urls": urls, "format": format}, ) async def mask(self, file: FileInput, *, format: str = "png") -> bytes: return await self._request_bytes( "POST", "/mask", files=_multipart_files(file), data=_form({"format": format}), ) async def smart_crop( self, file: FileInput, *, padding: int = 24, transparent: bool = True, format: str = "png", detect: str = "standard", decontaminate: bool = False, ) -> bytes: return await self._request_bytes( "POST", "/smart-crop", files=_multipart_files(file), data=_form({ "padding": padding, "transparent": transparent, "format": format, "detect": detect, "decontaminate": decontaminate, }), ) async 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: return await 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, } ), ) async def sticker( self, file: FileInput, *, stroke_color: str = "#FFFFFF", stroke_width: int = 20, format: str = "png", ) -> bytes: return await self._request_bytes( "POST", "/sticker", files=_multipart_files(file), data=_form( {"stroke_color": stroke_color, "stroke_width": stroke_width, "format": format} ), ) async def outline( self, file: FileInput, *, outline_color: str = "#000000", outline_width: int = 4, format: str = "png", ) -> bytes: return await self._request_bytes( "POST", "/outline", files=_multipart_files(file), data=_form( {"outline_color": outline_color, "outline_width": outline_width, "format": format} ), ) async 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: return await 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, } ), ) async 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 — 2-9 photos laid out around a main image. Paid tiers only; billed at N base-image units (9 photos = 9x per-image price).""" if not 2 <= len(files) <= 9: raise ValueError("collage requires 2-9 files") return await 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, ) async 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; poll with get_job() or use video_remove_and_wait(). Paid tiers, $0.05/output-second, 30s/200MB caps.""" return await self._request_json( "POST", "/video/remove", files=_multipart_files(file), data=_form({"format": format, "bg_color": bg_color, "smoothing": smoothing}), timeout=300.0, ) async def get_job(self, job_id: str) -> Dict[str, Any]: """GET /jobs/{job_id} — poll a video job once.""" return await self._request_json("GET", f"/jobs/{job_id}") async 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 await completion. Returns the final job dict; raises KnockoutError on job failure or wait timeout.""" import asyncio as _asyncio import time as _time job = await 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") await _asyncio.sleep(poll_interval) job = await 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 async def compare(self, file: FileInput, *, format: str = "png") -> bytes: return await self._request_bytes( "POST", "/compare", files=_multipart_files(file), data=_form({"format": format}), ) async 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: return await 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, } ), ) async def preview( self, file: FileInput, *, max_dim: int = 512, format: str = "png", ) -> bytes: return await self._request_bytes( "POST", "/preview", files=_multipart_files(file), data=_form({"max_dim": max_dim, "format": format}), ) async def estimate(self, endpoint: str, width: int, height: int) -> Dict[str, Any]: return await self._request_json( "POST", "/estimate", json={"endpoint": endpoint, "width": width, "height": height}, ) async def upscale( self, file: FileInput, *, scale: int = 4, model: str = "swin2sr", face_enhance: bool = False, format: str = "png", ) -> bytes: 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 await self._request_bytes( "POST", "/upscale", files=_multipart_files(file), data=_form({ "scale": scale, "model": model, "face_enhance": face_enhance, "format": format, }), ) async def face_restore( self, file: FileInput, *, only_center_face: bool = False, bg_enhance: bool = False, format: str = "png", ) -> bytes: return await self._request_bytes( "POST", "/face-restore", files=_multipart_files(file), data=_form( { "only_center_face": only_center_face, "bg_enhance": bg_enhance, "format": format, } ), ) async def colorize( self, file: FileInput, *, format: str = "png", ) -> bytes: """POST /colorize — DDColor (Apache-2.0) image colorization. Async.""" return await self._request_bytes( "POST", "/colorize", files=_multipart_files(file), data=_form({"format": format}), ) async def silhouette( self, file: FileInput, *, subject_color: str = "#7C3AED", bg_color: str = "#FFFFFF", format: str = "png", ) -> bytes: """POST /silhouette — two-tone silhouette portrait. Async.""" return await self._request_bytes( "POST", "/silhouette", files=_multipart_files(file), data=_form({ "subject_color": subject_color, "bg_color": bg_color, "format": format, }), ) async 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. Async.""" 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 await 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. |