@haatlabs-core/provider-background
v0.10.0
Published
Background removal through a rembg service.
Readme
@haatlabs-core/provider-background
Install
pnpm add @haatlabs-core/provider-backgroundIt leaves one package to your app, so the app holds one copy: sharp.
What it does
Background removal by a rembg service, called directly or through a services gateway.
cutoutFromService(baseUrl, image, options) returns the cut-out (an RGBA PNG the size of the
image); outlineFromService returns its alpha channel as a grey PNG. The image must be a
WebP the caller made itself. Every answer is checked as a file from a stranger: a PNG by
its bytes, with alpha, the size sent, at most 25 megapixels, at most 30 MiB. sharp is a
peer: the app's own, with its settings, is the one used. The package leaves sharp's globals
to the app; on a small host, call sharp.cache(false) and sharp.concurrency(1).
Options
model (BACKGROUND_MODEL, u2netp, by default), fetch, timeoutMs (10 s),
maxReplyBytes (30 MiB), maxImageBytes (20 MiB, the gateway's own cap: a larger image is
refused before any request, not transient), gatewayKey, call and signal.
Errors
BackgroundRemovalError(message, transient, { retryAfterMs?, cause? }). transient: the
service is away, slow, busy or failing (a 429 or 5xx, no answer, a time out); otherwise the
same image would get the same answer. A 429 or 5xx carries retryAfterMs from its
Retry-After (seconds or a date, at most five minutes). The message never quotes the
service. A caller's abort is rethrown as theirs.
Gateway and deadlines
With gatewayKey, call (tier, priority, deadlineMs) goes to the gateway, tier 4 in the
background without one. The time limit is timeoutMs, or call.deadlineMs when that is
sooner (localTimeoutMs; a deadline that is not a finite number is none), and the gateway is
given that limit, never longer. The deadline is this call's: a caller's retry starts it again;
pass signal for a hard limit. Through the gateway a refused status carries an
UpstreamStatusError as its cause: isGatewayRefusal(error) is true for the gateway's 401
and 403.
Fixtures
@haatlabs-core/provider-background/fixtures: backgroundFixtures.image (an 8 x 6 WebP) and
backgroundFixtures.cutout (the RGBA PNG answered for it, which passes every check). Made
with sharp in the shape rembg answers, not recorded; each read is a fresh copy.
Testing
pnpm --filter @haatlabs-core/provider-background test: unit tests against a fake fetch.
Hosted services
Without a rembg service of your own, createBackgroundRemover({ mode: 'haatlabs', apiKey })
sends the image (at most 5 MB) to the Haatlabs API on RapidAPI and reads the signed cut-out it
answers with: a PNG with an alpha channel, which may be smaller than the image when the API
scaled a large one down. createBackgroundRemover({ mode: 'service', baseUrl, gatewayKey }) is
cutoutFromService. See @haatlabs-core/services and https://haatlabs.shop/docs/services/
