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 — node/src/index.ts at main · useknockout/node Expand file tree/ Copy pathindex.tsMore file actions 1060 lines (977 loc) · 39.8 KB / Copy pathindex.tsFile metadata and controls1060 lines (977 loc) · 39.8 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 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 /** * @useknockout/node — official TypeScript / Node.js client for the useknockout API. * * Quick start: * * import { Knockout } from "@useknockout/node"; * * const client = new Knockout({ token: process.env.KNOCKOUT_TOKEN! }); * const png = await client.remove({ file: "./input.jpg" }); // Buffer of PNG bytes * await writeFile("out.png", png); */ import { readFile } from "node:fs/promises"; import { basename } from "node:path"; export const DEFAULT_BASE_URL = "https://useknockout--api.modal.run"; const SDK_VERSION = "0.4.0"; export type OutputFormat = "png" | "webp"; export type OpaqueFormat = "png" | "webp" | "jpg"; type FileInput = string | Buffer | Blob | ArrayBuffer | Uint8Array; export interface KnockoutOptions { /** API bearer token. Required unless your self-hosted instance has no auth. */ token?: string; /** Override the API base URL. Defaults to the hosted endpoint. */ baseUrl?: string; /** Per-request timeout in milliseconds. Default 60_000. */ timeoutMs?: number; /** Custom fetch (useful for edge runtimes / polyfills). Defaults to global fetch. */ fetch?: typeof fetch; } export interface RemoveInput { /** Local file path, Buffer, Blob, or ArrayBuffer of the image. */ file: string | Buffer | Blob | ArrayBuffer | Uint8Array; /** Optional filename — inferred from path when `file` is a string. */ filename?: string; /** Output format. Default "png". */ format?: OutputFormat; /** Edge finish. "hard" commits ambiguous edge pixels for a crisp product cut; keep "soft" (default) for hair and fur. */ edge?: "soft" | "hard"; /** Detection mode. "high_recall" runs a second pass that recovers low-contrast product edges. Paid tiers; roughly 2x latency. Default "standard". */ detect?: "standard" | "high_recall"; /** Remove background-colored contamination (e.g. backdrop strips) at mask edges. Default false. */ decontaminate?: boolean; } export interface RemoveUrlInput { /** Remote URL of the image to process. */ url: string; /** Output format. Default "png". */ format?: OutputFormat; /** Edge finish. "hard" commits ambiguous edge pixels; keep "soft" (default) for hair and fur. */ edge?: "soft" | "hard"; /** Detection mode. "high_recall" recovers low-contrast edges. Paid tiers; ~2x latency. Default "standard". */ detect?: "standard" | "high_recall"; /** Remove background-colored contamination at mask edges. Default false. */ decontaminate?: boolean; } export interface ReplaceBgInput { /** Local file path, Buffer, Blob, or ArrayBuffer of the foreground image. */ file: string | Buffer | Blob | ArrayBuffer | Uint8Array; /** Optional filename — inferred from path when `file` is a string. */ filename?: string; /** Hex color for the new background. Default "#FFFFFF". Ignored if `bgUrl` is set. */ bgColor?: string; /** Remote URL of an image to use as the new background. Takes precedence over `bgColor`. */ bgUrl?: string; /** Output format. "jpg" is smallest. Default "png". */ format?: OpaqueFormat; } export interface BatchInput { /** Array of local paths / buffers / blobs. Up to 10. */ files: Array<string | Buffer | Blob | ArrayBuffer | Uint8Array>; /** Optional filenames aligned to `files`. */ filenames?: string[]; /** Output format for each image. Default "png". */ format?: OutputFormat; } export interface BatchUrlInput { /** Remote URLs to process. Up to 10. */ urls: string[]; /** Output format for each image. Default "png". */ format?: OutputFormat; } export interface BatchResultItem { filename?: string; url?: string; success: boolean; format?: OutputFormat; size_bytes?: number; data_base64?: string; error?: string; } export interface BatchResponse { count: number; format: OutputFormat; results: BatchResultItem[]; } export interface MaskInput { file: FileInput; filename?: string; format?: OutputFormat; } export interface SmartCropInput { file: FileInput; filename?: string; /** Padding around the subject bbox, in pixels. Default 24. */ padding?: number; /** Return transparent cutout (true) or cropped region from original (false). Default true. */ transparent?: boolean; /** Detection mode. "high_recall" recovers low-contrast edges. Paid tiers; ~2x latency. Default "standard". */ detect?: "standard" | "high_recall"; /** Remove background-colored contamination at mask edges (also tightens the crop box). Default false. */ decontaminate?: boolean; format?: OpaqueFormat; } export interface ShadowInput { file: FileInput; filename?: string; bgColor?: string; bgUrl?: string; shadowColor?: string; shadowOffsetX?: number; shadowOffsetY?: number; shadowBlur?: number; shadowOpacity?: number; format?: OpaqueFormat; } export interface StickerInput { file: FileInput; filename?: string; /** Hex color for the outline. Default "#FFFFFF". */ strokeColor?: string; /** Outline width in pixels. Default 20. */ strokeWidth?: number; format?: OutputFormat; } export interface OutlineInput { file: FileInput; filename?: string; /** Hex color for the outline. Default "#000000". */ outlineColor?: string; /** Outline width in pixels. Default 4. */ outlineWidth?: number; format?: OutputFormat; } export interface StudioShotInput { file: FileInput; filename?: string; bgColor?: string; /** e.g. "1:1", "4:5", "16:9". Default "1:1". */ aspect?: string; padding?: number; shadow?: boolean; /** Keep a transparent background. Ignores bgColor and shadow; output is PNG (jpg is coerced). */ transparent?: boolean; /** Apply a subtle brightness + saturation lift to the subject for ecommerce-ready output. Default false. */ enhance?: boolean; /** Enhance strength, 0.0–0.5. Default 0.15 (subtle). Only applies when enhance is true. */ enhanceStrength?: number; /** Detection mode. "high_recall" recovers low-contrast edges. Paid tiers; ~2x latency. Default "standard". */ detect?: "standard" | "high_recall"; /** Remove background-colored contamination at mask edges. Default false. */ decontaminate?: boolean; format?: OpaqueFormat; } /** Anchor position for the main image in a collage. */ export type CollagePosition = "TL" | "T" | "TR" | "L" | "C" | "R" | "BL" | "B" | "BR"; export interface CollageInput { /** 2–9 images (local paths / buffers / blobs). First is the main unless mainIndex is set. */ files: FileInput[]; /** Optional filenames aligned to `files`. */ filenames?: string[]; /** Which image is the hero (0-based). Default 0. */ mainIndex?: number; /** Hero anchor. Default "BR". */ mainPosition?: CollagePosition; bgColor?: string; /** Canvas ratio, e.g. "1:1", "4:5". Default "1:1". */ aspect?: string; /** Padding inside each cell, px (0–200). Default 24. */ padding?: number; format?: OpaqueFormat; } /** Output container for /video/remove. */ export type VideoFormat = "prores4444" | "webm" | "mp4"; export interface VideoRemoveInput { /** Video file: mp4, mov, avi, webm, or mkv. Max 30 seconds / 200MB. */ file: FileInput; filename?: string; /** * prores4444 (default): MOV with a real 10-bit alpha channel — drops into * Resolve/Premiere/AE. webm: VP9 with alpha. mp4: H.264, requires bgColor. */ format?: VideoFormat; /** Composite frames onto a solid color instead of transparency. Required for mp4. */ bgColor?: string; /** 0–100 temporal alpha smoothing (default 30). Lower for fast-moving subjects. */ smoothing?: number; } export interface VideoJob { job_id: string; status: "queued" | "processing" | "done" | "error"; progress: number; seconds?: number; frames?: number; /** Signed download URL, present when status is "done". Valid ~1 hour. */ result_url?: string; error?: string; estimated_cost_units?: number; poll?: string; } export interface VideoWaitOptions { /** Poll interval in ms. Default 5000. */ pollIntervalMs?: number; /** Overall wait ceiling in ms. Default 900000 (15 min). */ timeoutMs?: number; /** Called after every poll with the current job state. */ onProgress?: (job: VideoJob) => void; } export interface CompareInput { file: FileInput; filename?: string; format?: OutputFormat; } export interface HeadshotInput { file: FileInput; filename?: string; /** Hex color for the background. Default "#FFFFFF". Ignored if `bgBlur` is true. */ bgColor?: string; /** Use a blurred copy of the original image as the background. Default false. */ bgBlur?: boolean; /** Gaussian blur radius for the background when `bgBlur` is true. Default 20. */ blurRadius?: number; /** Output aspect "W:H". Default "4:5" (portrait). */ aspect?: string; /** Padding around the subject bbox, in pixels. Default 64. */ padding?: number; /** Vertical headroom as a ratio of canvas height (0–0.5). Default 0.18. */ headTopRatio?: number; format?: OpaqueFormat; } export interface PreviewInput { file: FileInput; filename?: string; /** Long-edge cap in pixels (64–1024). Default 512. */ maxDim?: number; format?: OutputFormat; } export interface UpscaleInput { file: FileInput; filename?: string; /** Upscale factor: 2 or 4. Default 4. */ scale?: 2 | 4; /** * Backend. `swin2sr` (default, v0.6.0+) is sharper on real photos. * `realesrgan` is the legacy backend — better on anime/illustrations. */ model?: "swin2sr" | "realesrgan"; /** Route through GFPGAN to fix facial detail. Slower, use for portraits. Implies realesrgan. */ faceEnhance?: boolean; format?: OpaqueFormat; } export interface FaceRestoreInput { file: FileInput; filename?: string; /** Restore only the most prominent face (faster). Default false (all faces). */ onlyCenterFace?: boolean; /** Also upscale the background 2x via Real-ESRGAN. Default false (bg preserved as-is). */ bgEnhance?: boolean; format?: OpaqueFormat; } export interface ColorizeInput { file: FileInput; filename?: string; format?: OpaqueFormat; } export interface SilhouetteInput { file: FileInput; filename?: string; /** Hex color for the subject silhouette. Default "#7C3AED" (purple). */ subjectColor?: string; /** Hex color for the background. Default "#FFFFFF" (white). */ bgColor?: string; format?: OpaqueFormat; } export interface InpaintBbox { x: number; y: number; w: number; h: number; } export interface InpaintInput { file: FileInput; filename?: string; /** * Optional mask. White pixels = inpaint, black = keep. If omitted (and no * `bbox`), auto-subject mode runs BiRefNet on the input and inverts the * subject mask. */ mask?: FileInput; maskFilename?: string; /** Rectangular region to inpaint. Mutually exclusive with `mask`. */ bbox?: InpaintBbox; /** Mask dilation in pixels. Default 8, range 0..32. */ dilation?: number; format?: OpaqueFormat; } export interface EstimateInput { /** Endpoint name without leading slash, e.g. "remove" or "headshot". */ endpoint: string; width: number; height: number; } export interface EstimateResponse { endpoint: string; image_pixels: number; est_latency_ms_warm: number; est_latency_ms_cold: number; est_cost_usd: number; free_during_beta: boolean; note: string; } export interface StatsDay { date: string; count: number; } export interface StatsResponse { total_processed: number; today: number; last_7_days: StatsDay[]; error?: string; detail?: string; } export interface HealthResponse { status: string; model: string; } /** * Error thrown when the API returns a non-2xx response. */ export class KnockoutError extends Error { public readonly status: number; public readonly code: "auth" | "rate_limit" | "bad_request" | "payload_too_large" | "server" | "unknown"; public readonly body: string; constructor(status: number, body: string) { const code = KnockoutError.classify(status); super(`Knockout API error ${status} (${code}): ${body || "no body"}`); this.name = "KnockoutError"; this.status = status; this.code = code; this.body = body; } private static classify(status: number): KnockoutError["code"] { if (status === 401 || status === 403) return "auth"; if (status === 429) return "rate_limit"; if (status === 413) return "payload_too_large"; if (status >= 400 && status < 500) return "bad_request"; if (status >= 500) return "server"; return "unknown"; } } /** * useknockout API client. * * All methods return a `Buffer` (Node) of the processed image bytes. * Use `.toString("base64")` or `writeFile(path, buf)` to persist. */ export class Knockout { private readonly baseUrl: string; private readonly token: string | undefined; private readonly timeoutMs: number; private readonly fetchImpl: typeof fetch; constructor(options: KnockoutOptions = {}) { this.baseUrl = (options.baseUrl ?? DEFAULT_BASE_URL).replace(/\/+$/, ""); this.token = options.token; this.timeoutMs = options.timeoutMs ?? 60_000; const fetchRef = options.fetch ?? globalThis.fetch; if (!fetchRef) { throw new Error( "Global fetch is unavailable. Provide `options.fetch` or use Node 18+." ); } this.fetchImpl = fetchRef.bind(globalThis); } /** Hit GET /health — no auth required. */ async health(): Promise<HealthResponse> { const res = await this.request("GET", "/health"); const body = await res.text(); if (!res.ok) throw new KnockoutError(res.status, body); return JSON.parse(body) as HealthResponse; } /** * Public usage counter — total images processed all-time, today, and a 7-day breakdown. * Use for landing-page social proof. Eventually consistent across containers. */ async stats(): Promise<StatsResponse> { const res = await this.request("GET", "/stats"); const body = await res.text(); if (!res.ok) throw new KnockoutError(res.status, body); return JSON.parse(body) as StatsResponse; } /** * Predict latency + cost for an endpoint and image size without doing any GPU work. * * @example * const est = await client.estimate({ endpoint: "remove", width: 1024, height: 1024 }); */ async estimate(input: EstimateInput): Promise<EstimateResponse> { const res = await this.request("POST", "/estimate", { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ endpoint: input.endpoint, width: input.width, height: input.height, }), }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return (await res.json()) as EstimateResponse; } /** * Remove the background from an image, returning the cleaned PNG/WebP bytes. * * @example * const png = await client.remove({ file: "./input.jpg" }); */ async remove(input: RemoveInput): Promise<Buffer> { const format: OutputFormat = input.format ?? "png"; const { blob, filename } = await toBlob(input); const form = new FormData(); form.append("file", blob, filename); // format MUST be a form field — the API reads Form(...), query is ignored. form.append("format", format); if (input.edge) form.append("edge", input.edge); if (input.detect) form.append("detect", input.detect); if (input.decontaminate !== undefined) form.append("decontaminate", input.decontaminate ? "true" : "false"); const res = await this.request("POST", "/remove", { body: form, }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Remove the background from a remote URL, returning the cleaned PNG/WebP bytes. * * @example * const png = await client.removeUrl({ url: "https://example.com/cat.jpg" }); */ async removeUrl(input: RemoveUrlInput): Promise<Buffer> { const format: OutputFormat = input.format ?? "png"; const res = await this.request("POST", "/remove-url", { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ url: input.url, format, ...(input.edge ? { edge: input.edge } : {}), ...(input.detect ? { detect: input.detect } : {}), ...(input.decontaminate !== undefined ? { decontaminate: input.decontaminate } : {}), }), }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Replace the background with a solid color or a remote image. * * @example Solid color * const jpg = await client.replaceBackground({ file: "./cat.jpg", bgColor: "#FF5733", format: "jpg" }); * * @example Remote image as new background * const png = await client.replaceBackground({ * file: "./cat.jpg", * bgUrl: "https://example.com/beach.jpg", * }); */ async replaceBackground(input: ReplaceBgInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); // /replace-bg reads these as form fields (Form(...)), NOT query params. // Sending them in the query string makes the API silently use defaults // (white bg, png) regardless of what the caller passed. if (input.bgColor) form.append("bg_color", input.bgColor); if (input.bgUrl) form.append("bg_url", input.bgUrl); form.append("format", format); const res = await this.request("POST", "/replace-bg", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Remove the background from up to 10 images in a single call. * Returns a JSON object with base64-encoded result bytes per image. * * @example * const batch = await client.removeBatch({ * files: ["./a.jpg", "./b.jpg", "./c.jpg"], * format: "png", * }); * for (const r of batch.results) { * if (r.success) await writeFile(r.filename!, Buffer.from(r.data_base64!, "base64")); * } */ async removeBatch(input: BatchInput): Promise<BatchResponse> { const format: OutputFormat = input.format ?? "png"; if (input.files.length === 0) throw new Error("At least one file required"); if (input.files.length > 10) throw new Error("Max 10 files per batch"); const form = new FormData(); for (let i = 0; i < input.files.length; i++) { const name = input.filenames?.[i]; const { blob, filename } = await toBlob({ file: input.files[i]!, filename: name }); form.append("files", blob, filename); } const res = await this.request("POST", `/remove-batch?format=${format}`, { body: form, }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return (await res.json()) as BatchResponse; } /** * Return only the alpha mask as a grayscale PNG/WebP. * Useful when chaining into your own compositing pipeline. */ async mask(input: MaskInput): Promise<Buffer> { const format: OutputFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); form.append("format", format); const res = await this.request("POST", "/mask", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Auto-crop to the subject's tight bounding box with configurable padding. * Returns either a transparent cutout or a cropped region from the original image. */ async smartCrop(input: SmartCropInput): Promise<Buffer> { const transparent = input.transparent ?? true; const format: OpaqueFormat = (input.format as OpaqueFormat | undefined) ?? (transparent ? "png" : "jpg"); const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); form.append("padding", String(input.padding ?? 24)); form.append("transparent", transparent ? "true" : "false"); if (input.detect) form.append("detect", input.detect); if (input.decontaminate !== undefined) form.append("decontaminate", input.decontaminate ? "true" : "false"); form.append("format", format); const res = await this.request("POST", "/smart-crop", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Composite subject onto a new background with a configurable drop shadow. */ async shadow(input: ShadowInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.bgColor) form.append("bg_color", input.bgColor); if (input.bgUrl) form.append("bg_url", input.bgUrl); if (input.shadowColor) form.append("shadow_color", input.shadowColor); if (input.shadowOffsetX !== undefined) form.append("shadow_offset_x", String(input.shadowOffsetX)); if (input.shadowOffsetY !== undefined) form.append("shadow_offset_y", String(input.shadowOffsetY)); if (input.shadowBlur !== undefined) form.append("shadow_blur", String(input.shadowBlur)); if (input.shadowOpacity !== undefined) form.append("shadow_opacity", String(input.shadowOpacity)); form.append("format", format); const res = await this.request("POST", "/shadow", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Sticker style — subject with a thick outline on transparent background. * Perfect for WhatsApp / iMessage / Telegram stickers. */ async sticker(input: StickerInput): Promise<Buffer> { const format: OutputFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.strokeColor) form.append("stroke_color", input.strokeColor); if (input.strokeWidth !== undefined) form.append("stroke_width", String(input.strokeWidth)); form.append("format", format); const res = await this.request("POST", "/sticker", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Subject on transparent background with a thin configurable outline. */ async outline(input: OutlineInput): Promise<Buffer> { const format: OutputFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.outlineColor) form.append("outline_color", input.outlineColor); if (input.outlineWidth !== undefined) form.append("outline_width", String(input.outlineWidth)); form.append("format", format); const res = await this.request("POST", "/outline", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * E-commerce preset — cutout + tight crop + centered + optional shadow on a standard aspect canvas. */ async studioShot(input: StudioShotInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "jpg"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.bgColor) form.append("bg_color", input.bgColor); if (input.aspect) form.append("aspect", input.aspect); if (input.padding !== undefined) form.append("padding", String(input.padding)); if (input.shadow !== undefined) form.append("shadow", input.shadow ? "true" : "false"); if (input.transparent !== undefined) form.append("transparent", input.transparent ? "true" : "false"); if (input.enhance !== undefined) form.append("enhance", input.enhance ? "true" : "false"); if (input.enhanceStrength !== undefined) form.append("enhance_strength", String(input.enhanceStrength)); if (input.detect) form.append("detect", input.detect); if (input.decontaminate !== undefined) form.append("decontaminate", input.decontaminate ? "true" : "false"); form.append("format", format); const res = await this.request("POST", "/studio-shot", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Product collage — 2–9 photos, each background-removed and tight-cropped, * laid out around a main image on a solid canvas. * * Paid tiers only. Billed at N base-image units (each photo is a full model * pass), so a 9-photo collage costs 9× your per-image price. * * @example * const jpg = await client.collage({ * files: ["./main.jpg", "./acc1.jpg", "./acc2.jpg"], * mainPosition: "BR", * }); */ async collage(input: CollageInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "jpg"; if (input.files.length < 2 || input.files.length > 9) { throw new Error("collage requires 2-9 files"); } const form = new FormData(); for (let i = 0; i < input.files.length; i++) { const { blob, filename } = await toBlob({ file: input.files[i]!, filename: input.filenames?.[i], }); form.append("files", blob, filename); } if (input.mainIndex !== undefined) form.append("main_index", String(input.mainIndex)); if (input.mainPosition) form.append("main_position", input.mainPosition); if (input.bgColor) form.append("bg_color", input.bgColor); if (input.aspect) form.append("aspect", input.aspect); if (input.padding !== undefined) form.append("padding", String(input.padding)); form.append("format", format); // Collage is N model passes; a cold container + several images easily // exceeds the 60s single-image default. Scale the ceiling by file count // (never below the caller's configured timeout). const timeoutMs = Math.max(this.timeoutMs, 45_000 + input.files.length * 20_000); const res = await this.request("POST", "/collage", { body: form, timeoutMs }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Video background removal — async. Submits the clip and returns the job * descriptor immediately; poll with getJob(), or use videoRemoveAndWait(). * * Paid tiers only. Billed at $0.05 per output second, only on success. * Caps: 30s clip, 30fps processing, 200MB upload. * * @example * const job = await client.videoRemove({ file: "./clip.mp4" }); * const done = await client.videoRemoveAndWait({ file: "./clip.mp4" }); */ async videoRemove(input: VideoRemoveInput): Promise<VideoJob> { const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.format) form.append("format", input.format); if (input.bgColor) form.append("bg_color", input.bgColor); if (input.smoothing !== undefined) form.append("smoothing", String(input.smoothing)); // Submit uploads up to 200MB and probes server-side — give it headroom. const timeoutMs = Math.max(this.timeoutMs, 300_000); const res = await this.request("POST", "/video/remove", { body: form, timeoutMs }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return (await res.json()) as VideoJob; } /** Poll a video job once. */ async getJob(jobId: string): Promise<VideoJob> { const res = await this.request("GET", `/jobs/${jobId}`); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return (await res.json()) as VideoJob; } /** * Submit a video and poll until it finishes. Resolves with the final job * (status "done", result_url set) or throws on job error / wait timeout. */ async videoRemoveAndWait(input: VideoRemoveInput, opts: VideoWaitOptions = {}): Promise<VideoJob> { const interval = opts.pollIntervalMs ?? 5_000; const deadline = Date.now() + (opts.timeoutMs ?? 900_000); let job = await this.videoRemove(input); while (job.status === "queued" || job.status === "processing") { if (Date.now() > deadline) { throw new Error(`video job ${job.job_id} still ${job.status} after wait timeout`); } await new Promise((r) => setTimeout(r, interval)); job = await this.getJob(job.job_id); opts.onProgress?.(job); } if (job.status === "error") { throw new Error(`video job ${job.job_id} failed: ${job.error ?? "unknown error"}`); } return job; } /** * Before/after side-by-side preview — original on left, transparent cutout (on a checkerboard) on right. */ async compare(input: CompareInput): Promise<Buffer> { const format: OutputFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); form.append("format", format); const res = await this.request("POST", "/compare", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * LinkedIn-ready headshot preset — bg removal + portrait crop + center face + bg color or blur. * * @example Solid bg * const jpg = await client.headshot({ file: "./photo.jpg", bgColor: "#0A0A0A" }); * * @example Blurred original as bg * const jpg = await client.headshot({ file: "./photo.jpg", bgBlur: true, blurRadius: 24 }); */ async headshot(input: HeadshotInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "jpg"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.bgColor) form.append("bg_color", input.bgColor); if (input.bgBlur !== undefined) form.append("bg_blur", input.bgBlur ? "true" : "false"); if (input.blurRadius !== undefined) form.append("blur_radius", String(input.blurRadius)); if (input.aspect) form.append("aspect", input.aspect); if (input.padding !== undefined) form.append("padding", String(input.padding)); if (input.headTopRatio !== undefined) form.append("head_top_ratio", String(input.headTopRatio)); form.append("format", format); const res = await this.request("POST", "/headshot", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Fast low-res preview cutout (~80ms warm). Skips pymatting refinement and downscales * input to `maxDim` (default 512px on the long edge). Use for UX progress indicators. */ async preview(input: PreviewInput): Promise<Buffer> { const format: OutputFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); form.append("max_dim", String(input.maxDim ?? 512)); form.append("format", format); const res = await this.request("POST", "/preview", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * 2x / 4x super-resolution. Defaults to Swin2SR (SwinV2 transformer) for sharper * detail on real photos. Pass `model: "realesrgan"` for the legacy backend * (better on anime / illustrations). `faceEnhance: true` routes portraits * through GFPGAN. * * @example Cutout → 4x upscale (print-ready) * const png = await client.remove({ file: "./photo.jpg" }); * const big = await client.upscale({ file: png, scale: 4 }); */ async upscale(input: UpscaleInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); form.append("scale", String(input.scale ?? 4)); form.append("model", input.model ?? "swin2sr"); if (input.faceEnhance !== undefined) { form.append("face_enhance", input.faceEnhance ? "true" : "false"); } form.append("format", format); const res = await this.request("POST", "/upscale", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * GFPGAN v1.4 portrait restoration — fix blurry / damaged / low-res faces. * Background is upscaled 2x by Real-ESRGAN. Pairs with /headshot. */ async faceRestore(input: FaceRestoreInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.onlyCenterFace !== undefined) { form.append("only_center_face", input.onlyCenterFace ? "true" : "false"); } if (input.bgEnhance !== undefined) { form.append("bg_enhance", input.bgEnhance ? "true" : "false"); } form.append("format", format); const res = await this.request("POST", "/face-restore", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Colorize a black-and-white or grayscale photo (DDColor v0.7.0+). * * Apache-2.0 model, single feed-forward (no diffusion), ~500ms warm on L4. * Works on any input — color photos are converted to grayscale internally * before color is predicted, which makes round-trip recoloring easy too. * * @example * const buf = await client.colorize({ file: "./old-photo.jpg" }); * await writeFile("colorized.png", buf); */ async colorize(input: ColorizeInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); form.append("format", format); const res = await this.request("POST", "/colorize", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Inpaint a region of an image using LaMa (Apache-2.0). Three modes, * auto-detected from what you pass: * * 1. **auto-subject** — pass only `file`. BiRefNet derives the subject * mask, inverts it, and LaMa fills the subject region with plausible * background. Drop in a photo, get the subject erased. * 2. **mask** — pass `file` + `mask` (any image, white = inpaint). * 3. **bbox** — pass `file` + `bbox: { x, y, w, h }`. Rectangular region. * * `dilation` (0..32, default 8) expands the mask before LaMa runs to * reduce ghost outlines from tight masks. * * @example Auto-erase subject * const png = await client.inpaint({ file: "./photo.jpg" }); * * @example Erase a rectangular region * const png = await client.inpaint({ file: "./photo.jpg", bbox: { x: 100, y: 100, w: 300, h: 400 } }); */ async inpaint(input: InpaintInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.mask !== undefined) { const { blob: maskBlob, filename: maskFilename } = await toBlob({ file: input.mask, filename: input.maskFilename ?? "mask.png", }); form.append("mask", maskBlob, maskFilename); } if (input.bbox) { form.append("x", String(input.bbox.x)); form.append("y", String(input.bbox.y)); form.append("w", String(input.bbox.w)); form.append("h", String(input.bbox.h)); } if (input.dilation !== undefined) form.append("dilation", String(input.dilation)); form.append("format", format); const res = await this.request("POST", "/inpaint", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Two-tone silhouette portrait — subject in one solid color, bg in another. * Apple Music / Spotify avatar aesthetic. Reuses BiRefNet mask path; no new * model load, fast. * * @example * const png = await client.silhouette({ * file: "./portrait.jpg", * subjectColor: "#1E2960", * bgColor: "#F0857C", * }); */ async silhouette(input: SilhouetteInput): Promise<Buffer> { const format: OpaqueFormat = input.format ?? "png"; const { blob, filename } = await toBlob({ file: input.file, filename: input.filename }); const form = new FormData(); form.append("file", blob, filename); if (input.subjectColor) form.append("subject_color", input.subjectColor); if (input.bgColor) form.append("bg_color", input.bgColor); form.append("format", format); const res = await this.request("POST", "/silhouette", { body: form }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return Buffer.from(await res.arrayBuffer()); } /** * Remove the background from up to 10 remote image URLs in a single call. * * @example * const batch = await client.removeBatchUrl({ * urls: ["https://a.jpg", "https://b.jpg"], * }); */ async removeBatchUrl(input: BatchUrlInput): Promise<BatchResponse> { const format: OutputFormat = input.format ?? "png"; if (input.urls.length === 0) throw new Error("At least one URL required"); if (input.urls.length > 10) throw new Error("Max 10 URLs per batch"); const res = await this.request("POST", "/remove-batch-url", { headers: { "Content-Type": "application/json" }, body: JSON.stringify({ urls: input.urls, format }), }); if (!res.ok) throw new KnockoutError(res.status, await res.text()); return (await res.json()) as BatchResponse; } private async request( |
| 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. |