Skip to content

Click-to-segment component with a key-holding backend

Segment one object with a few clicks in the browser. A small backend holds the credentials (an API key, or on the free tier only a project ID), keeps each image once, and sends every click to sam-lite together with all earlier clicks; the browser gets a polygon back and never sees the key. A click simulator drives the backend the way a person would and measures how many clicks an object needs, how well the polygon fits and what it costs.

Models: sam-lite · Without a key: Smoke run · Languages: Python, TypeScript, Go · Try in Playground (opens in a new tab) · Source on GitHub (opens in a new tab)

An annotation tool, a photo editor or a product catalogue wants “click on the thing, get its outline”. The model call is easy; the parts around it decide whether it can go on a public page:

  • The key must not reach the browser. Anything in the page can be read by its visitors, so a backend makes the calls and the page talks only to that backend.
  • Every click is a call with a list price. sam-lite lists 0.01 credits per refinement plus 0.2 for encoding the image. Stack caches the encoding, so the clicks after the first one are usually 0.01, but the cache is not guaranteed and a budget has to plan for a miss on every click. On the free tier the calls are not charged, but they count against the project’s limits.
  • The model keeps no state. POST /v1/refine takes all points of the object every time. The backend does the same: it stores images, not clicks, so a reload or a second tab cannot get out of step.
  • Visitors share one project or account. Whatever limit applies to it (the free tier’s per-minute and daily limits, or an account’s rate limit) is shared by everyone who uses the page. The backend limits each session, and the client file waits when the server answers 429, so one busy visitor cannot use up the minute for everyone.
  • Click latency is felt. An interactive call that has not finished within 2 s fails with a retryable 504, and the backend reports the time of each Stack call so that the page can show it. Latency seen from a client depends on its network path to the API, so the measurements of this use case do not include it.

The backend implements one HTTP contract in every language, contract/02-backend.yaml:

Request Answer
POST /api/images (raw image bytes) {imageId, width, height}; with a key the image is uploaded to Stack once per content and its handle cached; on the free tier the backend keeps the bytes (up to 4 MiB) and sends them inline with each click
POST /api/refine {imageId, points, box?} {polygon, bbox, area, score, model, costCredits, listCredits, cache, latencyMs}
GET /api/usage clicks, credits, cache hits and the ledger rows of the session
GET /api/health readiness, language and client version

Every request except /api/health carries X-Session-Id, an identifier the page chooses (one per page load). Points and polygons use the coordinates of the Stack API: pixels of the image with its EXIF orientation applied, x to the right, y down. Errors have one shape, {"error": {"code", "message", "retryable", "retryAfterMs"}}; the contract lists how Stack errors map to the backend’s codes.

POST /v1/refine returns a simplified polygon with holes by default, so the backend passes Stack’s polygon through and decodes no mask.

<stack-segmenter> is a native Web Component: no framework and no runtime dependency, about 400 lines of TypeScript in web/stack-segmenter.ts (opens in a new tab), with its own minimal styles in a shadow root. The parts that need no browser (coordinate mapping, the point list, the request queue, polygon to path) are in web/logic.ts (opens in a new tab), and node --test covers them in web/logic.test.ts. The component file is organised in the regions upload, click, request, draw and export.

  • Clicks. Left click adds a positive point (on the object); right click or Alt+click adds a negative point (leave this out). Undo (button or Ctrl/Cmd+Z) removes the last point, Clear removes all. Every click sends all points, because POST /api/refine keeps no click state.
  • One request at a time. A click made while a request is in flight waits; clicks that pile up are sent together in one follow-up request, and the answer to a request that is already out of date is dropped.
  • Scaling. Click positions are converted to pixels of the image itself (naturalWidth x naturalHeight, EXIF orientation applied, the coordinates of the API) and the polygon, with its holes, is drawn back at the displayed size, again after every resize.
  • Numbers. Score, number of points, credits charged for the last click, cache hit or miss with the latency, and the session’s calls and credits (from GET /api/usage).
  • Errors. 429 and 503 that the backend marks retryable are repeated after retryAfterMs (at most three times); 404 image_not_found uploads the image again once. Everything else is shown as one plain sentence chosen by the error code; the backend’s own text is never displayed.
  • Keyboard. The buttons are real buttons with labels. The image area takes focus: arrow keys move a cursor (Shift for bigger steps), Enter or Space adds a positive point, Shift+Enter or Alt+Enter a negative one.
cd use-cases/02-click-to-segment/web
pnpm install
pnpm build # tsc: browser-ready ES modules and index.html in dist/
cd ../typescript
node main.ts --port 8080 # with FOLDBUN_API_KEY set; serves ../web/dist

Open http://127.0.0.1:8080/, choose or drop an image and click. The backend serves the files of --static <dir> (default ../web/dist): GET / is index.html and GET /<name> a file directly in that directory, nothing else (contract/02-backend.yaml, “Static files”).

<script type="module" src="/stack-segmenter.js"></script>
<stack-segmenter id="seg" model="sam-lite" src="/photo.jpg"></stack-segmenter>
<script>
document.getElementById("seg").addEventListener("segment", (e) => {
console.log(e.detail.polygon); // [{outer: [x0, y0, x1, y1, ...], holes: [[...]]}], pixels of the original image
});
</script>

Copy stack-segmenter.js and logic.js from web/dist/ to the site, next to each other.

Attribute Meaning
backend Base URL of the backend. Default: the page’s own origin.
model Model to ask for (sam-lite or sam3), only if the backend’s SEGMENTER_MODELS allows it. Default: the backend’s first model.
src URL of an image to load. Without it, the person chooses a file or drops one on the component. It must be readable by the page.

Properties: backend, model and src mirror the attributes; sessionId is the identifier of this page load (crypto.randomUUID()); load(fileOrUrl) loads an image; undo() and clear(); toJSON() is the current result or null.

The segment event fires after every answer. detail is {imageId, width, height, model, score, points, polygon}; polygon is the backend’s list of parts, each with an outer ring and optional holes, in pixels of the original image. The Export JSON button saves the same object as segment.json.

Style it with CSS custom properties on the element: --seg-accent, --seg-positive, --seg-negative, --seg-fill, --seg-text, --seg-muted, --seg-surface, --seg-border, --seg-hover and --seg-radius. web/index.html is a small demo page that sets them.

The component calls only the three routes of this backend, POST /api/images, POST /api/refine and GET /api/usage. The backend holds the Foldbun Stack API key (or, on the free tier, the project ID), uploads each image once when it has a key, calls Stack and returns the result without account details. The page therefore cannot leak the key, and the backend is the place for limits (per-session rate limits, SEGMENTER_MODELS, FOLDBUN_MAX_CREDITS). A session is an accounting unit, not authentication: put the backend behind the site’s own login when the page is public.

The backend sends no CORS headers, so the page and the backend must share one origin: either let the backend serve the page (as above), or put both behind one reverse proxy that routes /api/ to the backend. A page on another origin cannot call it with backend="https://...".

Setup and run in each language

Commands for the smoke set, run from the repository root. The smoke set needs no API key: it runs on the free tier. The full set needs a key; the cap makes the client refuse calls that could exceed it.

Requires: Python 3.12, uv 0.5

cd use-cases/02-click-to-segment/python
uv sync --frozen
uv run --frozen python main.py --manifest ../assets/smoke/manifest.json --out out
# Full set: the full dataset is a release asset of the repository and needs an API key; unpack it and pass its manifest.
export FOLDBUN_API_KEY="fbs_..."
export FOLDBUN_MAX_CREDITS=63
uv run --frozen python main.py --manifest ../assets/full.json --out out
# no key needed: the backend runs on the free tier. To charge a key instead, set FOLDBUN_API_KEY="fbs_..."
# and optionally FOLDBUN_MAX_CREDITS=2 (the client refuses calls that could pass it)
cd use-cases/02-click-to-segment/typescript
pnpm install
node main.ts --port 8080 # listening on http://127.0.0.1:8080
# or: cd ../python && uv run main.py --port 8080 # the same backend in Python
# or: cd ../go && go run . --port 8080 # the same backend in Go

In a second terminal:

S=demo-1
curl -s -H "X-Session-Id: $S" -H "Content-Type: image/jpeg" --data-binary @../assets/smoke/images/77bfbbef28ac344c.jpg \
http://127.0.0.1:8080/api/images
curl -s -H "X-Session-Id: $S" -H "Content-Type: application/json" \
-d '{"imageId": "im_...", "points": [{"x": 521, "y": 424}]}' http://127.0.0.1:8080/api/refine
curl -s -H "X-Session-Id: $S" http://127.0.0.1:8080/api/usage

Options, the same in the three languages: --port (default 8080), --host (default 127.0.0.1) and --static DIR (default ../web/dist), the directory of the page: its index.html is answered at / and the files directly inside it at /<name>. SEGMENTER_MODELS is the comma-separated list of models a request may name (default sam-lite; add sam3 to compare). The backend sends no CORS headers: serve the page and the backend from the same origin.

To measure a backend, the harness starts it on a free port and runs the click simulator: uv run python -m harness live --uc 02 against the real API, or uv run python -m harness check --uc 02 against the offline fake API.

The full set (30 objects, each with a ground-truth mask, 5 MB) is a release asset of the repository (see datasets/README.md). Its manifest is committed as assets/full.json with a limit of 10 clicks per object; the images, masks and ground truth are in the archive. Extract it into assets/ and run the reference backend (TypeScript) through the simulator from the repository root. The full run needs FOLDBUN_API_KEY (the harness exits without one). At most 63 credits at list price (30 objects x 10 clicks x 0.21 if no click ever hit the cache), about 9 when the cache works. The run takes a few minutes because the simulator clicks at most once per second against the real API.

tar xzf 02-click-to-segment-full.tar.gz -C use-cases/02-click-to-segment/assets
export FOLDBUN_API_KEY="fbs_..."
uv run python -m harness live --size full --uc 02 --max-credits 63 --dry-run # the plan, nothing is sent
uv run python -m harness refresh --size full --uc 02 --max-credits 63 # runs, scores, writes expected/full.json and expected/full-summary.json, then `uv run python -m harness snippets`

harness live runs the same and only checks the result against the floors in usecase.toml [quality]. Only sam-lite is measured; a sam3 comparison pass is not part of the harness.

The imageId is derived from the bytes, so the same file has the same id in every session and every language, and a second upload costs nothing. With a key the bytes are also uploaded to Stack once; on the free tier there is no upload, and the backend sends the image inline with each click.

Source: python/backend.py (opens in a new tab)

def _upload_image(self, req: Request, s: Session) -> dict:
self._limit(s.upload)
content_type = (req.headers.get("Content-Type") or "").split(";")[0].strip().lower()
if content_type not in IMAGE_TYPES:
raise ApiError(415, "unsupported_media_type", "send the raw bytes as image/jpeg, image/png or image/webp")
data = req.read_body(IMAGE_BYTES)
if not data:
raise invalid("the body is empty: send the raw bytes of the image")
size = None
if self.free: # no upload will answer with the size, so read it from the bytes
if len(data) > FREE_IMAGE_BYTES:
raise ApiError(413, "payload_too_large", f"at most {FREE_IMAGE_BYTES} bytes without an API key (the free tier takes images up to 4 MiB)")
size = image_size(data)
if size is None:
raise invalid("the body is not a readable jpeg, png or webp image")
image_id = "im_" + hashlib.sha256(data).hexdigest()[:32]
with self._lock:
pending = self._images.get(image_id)
owner = pending is None
if pending is None:
pending = self._images[image_id] = Future()
self._images.move_to_end(image_id) # most recently used goes last
while len(self._images) > MAX_IMAGES:
self._images.popitem(last=False)
if owner:
# With a key: one Stack upload per distinct content; the client file keeps the bytes and uploads again if
# Stack evicts them. Concurrent uploads of the same bytes wait for this one instead of uploading again.
# Free tier: there are no uploads; this cache keeps the bytes and every click sends them inline.
try:
if size:
pending.set_result(Image(None, size[0], size[1], data))
else:
u = self.stack.upload(data, content_type)
pending.set_result(Image(u["id"], u["width"], u["height"]))
except BaseException as exc:
with self._lock:
if self._images.get(image_id) is pending:
del self._images[image_id]
pending.set_exception(exc)
try:
img = pending.result()
except Exception as exc:
raise from_stack(exc) from exc
with self._lock:
s.uploads += 1
return {"imageId": image_id, "width": img.width, "height": img.height}

The page sends all points of the object; the backend checks them against the image size and forwards them with an explicit positive to POST /v1/refine.

Source: python/backend.py (opens in a new tab)

def _refine(self, req: Request, s: Session) -> dict:
self._limit(s.refine)
try:
doc = json.loads(req.read_body(REFINE_BYTES).decode("utf-8"))
except (ValueError, RecursionError):
raise invalid("the body is not JSON") from None
image_id, points, box, model = parse_refine(doc, self.models)
with self._lock:
pending = self._images.get(image_id)
if pending is not None:
self._images.move_to_end(image_id)
not_found = ApiError(404, "image_not_found", "unknown imageId: upload the image again")
if pending is None:
raise not_found
try:
img = pending.result()
except Exception:
raise not_found from None
check_bounds(points, box, img)
# Stateless: every click sends all points of the object. The body is the same in every language.
image = sc.image_base64(img.data) if img.handle is None else sc.image_handle(img.handle)
call: dict = {"model": model, "image": image, "points": points}
if box:
call["box"] = box
t = time.monotonic()
try:
result = self.stack.post("/v1/refine", call, tag=s.tag)
except sc.StackError as exc:
self.log(f"stack error: {exc}")
raise from_stack(exc) from exc
latency_ms = round((time.monotonic() - t) * 1000)
with self._lock:
s.clicks += 1
# Stack returns the outline as a simplified polygon with holes by default: no mask decoding needed here.
inst = (result.get("instances") or [{}])[0]
return {
"polygon": inst.get("polygon") or [],
"bbox": inst.get("bbox") or [0, 0, 0, 0],
"area": inst.get("area", 0),
"score": inst.get("score", 0),
"model": result.get("model") or model,
"costCredits": result.get("cost", 0),
"listCredits": (result.get("billing") or {}).get("total", 0),
"cache": "hit" if result.get("cache") == "hit" else "miss",
"latencyMs": latency_ms,
}

Each session has two token buckets: 60 refinements per minute with a burst of 10, and 10 uploads per minute with a burst of 5. Over the limit the answer is 429 rate_limited with Retry-After. These are the backend’s own limits; if Stack itself answers 429, the backend’s client waits for the Retry-After it sends and the page sees at most a retryable error.

Source: python/backend.py (opens in a new tab)

class RateLimit:
"""Token bucket: `per_minute` sustained, `burst` at once. take() returns 0 when allowed, else the wait in ms."""
def __init__(self, per_minute: float, burst: float, now: float):
self.per_minute, self.burst, self.tokens, self.at = per_minute, burst, burst, now
def take(self, now: float) -> int:
self.tokens = min(self.burst, self.tokens + (now - self.at) * self.per_minute / 60_000)
self.at = now
if self.tokens >= 1:
self.tokens -= 1
return 0
return math.ceil((1 - self.tokens) * 60_000 / self.per_minute)
@dataclass
class Session:
id: str
tag: str # ledger tag of this session's calls in the client file
seen: float
refine: RateLimit
upload: RateLimit
uploads: int = 0
clicks: int = 0

Stack’s messages can mention the account, so they are logged and not forwarded; the page sees the backend’s code and, for upstream errors, Stack’s code.

Source: python/backend.py (opens in a new tab)

class ApiError(Exception):
"""A backend error, sent as {"error": {code, message, retryable, retryAfterMs, upstreamCode?, requestId?}}."""
def __init__(self, status, code, message, retryable=False, retry_after_ms=0, upstream_code=None, request_id=None):
super().__init__(message)
self.status, self.code, self.message = status, code, message
self.retryable, self.retry_after_ms = retryable, retry_after_ms
self.upstream_code, self.request_id = upstream_code, request_id
self.allow: str | None = None # Allow header of a 405
def body(self) -> dict:
err = {"code": self.code, "message": self.message, "retryable": self.retryable, "retryAfterMs": self.retry_after_ms}
if self.upstream_code:
err["upstreamCode"] = self.upstream_code
if self.request_id:
err["requestId"] = self.request_id
return {"error": err}
# What the backend says when the free tier refuses for good: its own text, never Stack's.
FREE_REFUSED = {
"daily_limit_reached": "the daily limit of the free tier is used up (it resets at 00:00 UTC); start the backend with FOLDBUN_API_KEY to continue now",
"free_tier_unavailable": "the free tier is not available; start the backend with FOLDBUN_API_KEY",
}
def from_stack(err: BaseException) -> ApiError:
"""Map an error of the client file (after its own retries) to the backend's error. Stack's message is not forwarded."""
if isinstance(err, ApiError):
return err
if isinstance(err, sc.BudgetExceeded):
return ApiError(503, "credit_cap", "the backend's credit cap is reached")
if isinstance(err, sc.MissingApiKey): # a call that only a key can make
return ApiError(502, "upstream_refused", "this needs an API key: start the backend with FOLDBUN_API_KEY", False, 0, err.code)
if isinstance(err, sc.StackError):
if err.retryable or err.code in sc.RETRY_CODES: # rate_limited and free_busy that outlived the client's waits
return ApiError(503, "upstream_busy", "Foldbun Stack is busy; try again", True, max(1000, err.retry_after_ms), err.code, err.request_id)
message = FREE_REFUSED.get(err.code, "Foldbun Stack refused the call")
return ApiError(502, "upstream_refused", message, False, 0, err.code, err.request_id)
if isinstance(err, OSError | http.client.HTTPException | ValueError): # no usable answer (for example, not JSON)
return ApiError(503, "upstream_busy", "Foldbun Stack is busy; try again", True, 1000, "network_error")
return ApiError(500, "internal", "internal error")

The session’s rows of the client’s ledger: the page can show what the clicks cost, and the simulator copies the rows into result.json.

Source: python/backend.py (opens in a new tab)

def _usage(self, req: Request, s: Session) -> dict:
calls = self.stack.calls(s.tag)
billed = [c for c in calls if not c["replayed"]]
with self._lock:
uploads, clicks = s.uploads, s.clicks
return {
"sessionId": s.id,
"uploads": uploads,
"clicks": clicks,
"costCredits": round(sum(c["charged"] for c in billed), 6),
"listCredits": round(sum(c["list"] for c in billed), 6),
"cacheHits": sum(1 for c in calls if c["cache"] == "hit"),
"cacheMisses": sum(1 for c in calls if c["cache"] == "miss"),
"calls": calls,
}

Source: python/main.py (opens in a new tab)

# No key: the free tier, and the backend sends the image inline with every click. With FOLDBUN_API_KEY: it uploads
# each image once and sends its handle. The base URL, project and credit cap come from FOLDBUN_API_BASE,
# FOLDBUN_PROJECT_ID and FOLDBUN_MAX_CREDITS.
client = sc.StackClient()
models = [m.strip() for m in (os.environ.get("SEGMENTER_MODELS") or "sam-lite").split(",") if m.strip()]
server = Server(args.host, args.port, Backend(client, models=models, static_dir=args.static))
def stop(signum, frame):
threading.Thread(target=server.shutdown).start() # serve_forever runs in this thread: shutdown must be called from another
for sig in (signal.SIGTERM, signal.SIGINT):
signal.signal(sig, stop)
print(f"listening on http://{args.host}:{server.server_address[1]}", flush=True)
print("mode: " + ("free tier (images are sent inline with every click)" if client.free else "API key (images are uploaded once)"), flush=True)
server.serve_forever()
server.server_close()

harness/clickbot.py drives any backend through the contract, so the languages can be compared one to one. It follows the usual protocol of interactive segmentation: the first click is the point of the ground-truth mask farthest from its boundary; each later click is the point farthest from the boundary of the largest wrong region, positive where the object was missed and negative where the polygon covers too much. It stops at IoU 0.90 or after the click limit (smoke 4, full 10), and against the real API it clicks at most once per second.

It reports NoC@85 and NoC@90 (clicks until the IoU reaches 0.85 or 0.90; an object that never gets there counts as the limit), the mean IoU after k clicks, credits per object and the cache hit rate. planning_credits_per_object counts the image encoding fee on every click; list_credits_per_object is what the recorded run was priced at, where clicks that found the encoding still cached did not pay it. A cache hit is not promised, so plan with the first number. It does not report time per click: that depends on the network path between the reader and the API, not on the service.

Until a live run is recorded, the numbers below come from the offline fake API. Its refinement replays the results recorded from the real smoke run for the requests it has seen, and is a rectangle around the positive clicks otherwise: it shows that the simulator, the backend and the accounting work and agree across languages, not how well sam-lite segments.

Smoke set (3 objects, at most 4 clicks), offline:

Metric Value
objects 3
objects_ok 3
noc85_mean 1.333
noc85_reached 1
noc90_mean 1.333
noc90_reached 1
miou_at_1 0.885
miou_at_2 0.9424
miou_at_3 0.9424
miou_at_4 0.9424
clicks_per_object 1.333
list_credits_per_object 0.213333
planning_credits_per_object 0.28
charged_credits_per_object 0
cache_hit_rate 0.25

Full set (30 objects, at most 10 clicks), live run; filled in from expected/full-summary.json once a maintainer has recorded one:

Metric Value
objects 30
objects_ok 30
noc85_mean 1.5
noc85_reached 1
noc90_mean 1.8
noc90_reached 0.967
miou_at_1 0.7706
miou_at_2 0.8975
miou_at_3 0.9338
miou_at_4 0.9429
miou_at_5 0.9473
miou_at_6 0.949
miou_at_7 0.9489
miou_at_8 0.9487
miou_at_9 0.9485
miou_at_10 0.9213
clicks_per_object 1.8
list_credits_per_object 0.024667
planning_credits_per_object 0.378
charged_credits_per_object 0.024667
cache_hit_rate 0.9815

With sam-lite, one object segmented in k clicks costs 0.2 + 0.01 k credits at list price when only the first click misses the encoding cache, and at most 0.21 k when every click misses. Uploads are free. A smoke run is free on the free tier: the run prints the list price labelled “free tier, not charged”. A keyed run is charged this much.

Run Calls List price (credits) Charged (credits)
smoke 4 0.64 0
full 54 0.74 0.74
  • Thin or transparent objects (cables, glass, hair, fences) need many clicks.
  • The first click pays for the encoding (0.2 credits with sam-lite). The cache is not guaranteed, so plan each click as a miss.
  • One object at a time. To find every object of a kind in an image, use text prompts instead (use case 01).
  • The backend is a sample, not an access control. A session identifier only separates visitors for counting and limits; put the backend behind the site’s own login before it goes on a public page.
  • State lives in memory. After a restart the page has to upload its image again (404 image_not_found), and the client keeps every image’s bytes and every ledger row for the life of the process.

See Images (opens in a new tab), Rate limits (opens in a new tab) and Billing (opens in a new tab) in the documentation.

The smoke set is 3 objects (a goose, a bird and a platter) from the validation split of Open Images V7: images CC BY 2.0 by their authors, resized to at most 1,024 px; segmentation masks CC BY 4.0 by Google LLC, resized to the image. Attribution: assets/smoke/ATTRIBUTION.csv. Rights holders can request removal of an image or dataset through the contact page (opens in a new tab).