DEV Community

Cover image for Image AI in the browser or on a CPU server: what we run where, and why
kalp m
kalp m

Posted on Fully Autonomous

Image AI in the browser or on a CPU server: what we run where, and why

oMyImage is a free set of image tools: compress, resize, convert, and a handful of AI ones like removing a background or an unwanted object. We wanted as much as possible to run in the browser, so photos stay on the user's device. Some of it does. Some of it can't, and the reasons turned out to be more interesting than "the model is too big".

Our server has no GPU. It's four virtual CPUs shared with the PDF tools on our sister site. That one fact shaped almost every decision below.

Key takeaways

  • A 28 MB ONNX model runs fine in the browser on the CPU. You don't need WebGPU for everything.
  • Route by decoded pixels, not file size. Safari silently returns blank canvases above its area limit.
  • On a CPU-only server, check the input size before starting the job, or one photo can take every core.
  • Licences can decide architecture. HEIC decoding runs on our server for licensing reasons, not speed.

What runs where

Two columns. In the browser: object and watermark removal (MI-GAN, ONNX Runtime Web, CPU), face detection for blurring (MediaPipe BlazeFace), plus all the plain tools like compress and resize. On the server: background removal (rembg with U2-Net), upscale and unblur (Real-ESRGAN), and HEIC conversion (ImageMagick with libheif).

Object removal in the browser: a 28 MB model in two pieces

To remove an object or watermark you paint over it, and MI-GAN fills the hole. It's an MIT-licensed inpainting model, and the ONNX file is 28,079,181 bytes.

Our host, Cloudflare Pages, rejects any single file over 25 MiB. So the model ships as two parts. The browser fetches both in parallel, streams them into one preallocated buffer (which also drives the progress bar), then checks the SHA-256 before trusting it:

export const MODEL = {
  parts: [
    { url: "/models/migan_pipeline_v2.6f1f3530.part1.bin", bytes: 14_000_000 },
    { url: "/models/migan_pipeline_v2.6f1f3530.part2.bin", bytes: 14_079_181 },
  ],
  bytes: 28_079_181,
  sha256: "6f1f3530a1a2324b19752018ce756088b07973cda8d7d890034ace5c8a48c40b",
} as const;
šŸ”“ Live TV: mishrakalpesh/image ai in the browser or on a cpu server what we run where and why b - Jadwal Siaran Langsung šŸ”“ Live TV: mishrakalpesh/image ai in the browser or on a cpu server what we run where and why b - Jadwal Siaran Langsung

The first 8 characters of the hash are in the file name, so the files can be cached for a year with immutable. There's no IndexedDB or Cache API code at all. The plain HTTP cache does the job.

Why the CPU and not WebGPU

ONNX Runtime Web runs here on WebAssembly, on the CPU. Its WebGPU builds are 27 MB each, again over the per-file limit, and our notes put MI-GAN at about a second on a laptop CPU anyway.

It also runs on one thread:

// One thread: several need cross-origin isolation (COOP/COEP headers),
// which would break the Google Drive picker and sign-in popups. MI-GAN is
// small enough not to need them. The proxy runs inference in ORT's own
// worker so the page keeps responding.
ort.env.wasm.numThreads = 1;
ort.env.wasm.proxy = true;
šŸ”“ Live TV: mishrakalpesh/image ai in the browser or on a cpu server what we run where and why b - Jadwal Siaran Langsung šŸ”“ Live TV: mishrakalpesh/image ai in the browser or on a cpu server what we run where and why b - Jadwal Siaran Langsung

Multi-threaded WebAssembly needs SharedArrayBuffer, which needs cross-origin isolation headers, which break third-party popups. For a model this small, one thread in a worker was the better trade.

One small bug shaped the pipeline. MI-GAN works on a 512 px crop around the hole. If you mark two small spots in opposite corners, one crop around both is nearly the whole image, shrunk to 512 px, and the fill comes out blurry. So separate marks are found on a 16 px grid and filled one region at a time, each with some surrounding context.

Face blurring, and keeping "nothing leaves your device" true

Face blurring uses MediaPipe's BlazeFace model. The model is only 0.23 MB, but the WebAssembly runtime is 11.8 MB, and we host both ourselves. MediaPipe's examples load from a CDN, but our page says nothing leaves the device, and that should be literally true.

Route by pixels, not bytes

Our first rule copied the PDF site's: files up to 15 MB stay in the browser. For images, that was wrong in both directions.

  • A 48-megapixel phone photo is about 8 MB as a JPEG, so it stayed local. Decoded, it's bigger than Safari's canvas limit of 16,777,216 pixels. Safari didn't throw. It returned a canvas that looked valid, ignored every draw, and we saved a blank image and reported success.
  • A 12-megapixel PNG of 34 MB went to the server for no reason, since 12 MP is well within every browser's limit.

The router now decides on decoded pixel area, and probes the canvas instead of trusting it. It paints the far corner and reads it back. Over the limit, Safari hands back zeros. We tested it with a 1,000-megapixel canvas that "worked" and returned [0,0]. If the probe fails, the tool retries on the server.

Background removal: slow for the wrong reason

Background removal runs rembg with the U²-Net model on the server. It takes about 6 to 7 seconds per image. We assumed bigger images were slower. They aren't: the time is almost all spent loading the 168 MB model into a fresh process on every request. Image size barely matters, so there's no size cap on this route. (Keeping the model loaded in a long-running worker is the obvious next step.)

Upscaling on a CPU: 3.5 minutes for a small photo

Upscaling uses Real-ESRGAN through its ncnn/Vulkan build. With no GPU, Vulkan falls back to Mesa's software renderer on the same four CPUs.

Bar chart: upscaling a 512Ɨ384 image to 2048Ɨ1536 on a 4-vCPU server took 209 seconds with the realesrgan-x4plus model and 8 seconds with realesr-animevideov3, about 26 times faster.

On a 512Ɨ384 test image, the standard x4plus model took 3 minutes 29 seconds and 12 minutes of CPU time. The much smaller realesr-animevideov3 model took 8 seconds. A normal 12-megapixel phone photo with x4plus would have pinned every core for tens of minutes and hit nginx's 300-second timeout while still running.

So production uses the smaller model (yes, an anime-video model on photos; it does a decent job, and the trade-off is written down), and the size is checked before the process starts:

const MAX_UPSCALE_PIXELS = Number(process.env.IMAGE_UPSCALE_MAX_PIXELS ?? 2_000_000);
šŸ”“ Live TV: mishrakalpesh/image ai in the browser or on a cpu server what we run where and why b - Jadwal Siaran Langsung šŸ”“ Live TV: mishrakalpesh/image ai in the browser or on a cpu server what we run where and why b - Jadwal Siaran Langsung

Anything larger gets a clear 413 instead of a timeout. Two smaller lessons from the same tool:

  • It runs at the model's native scale, then resizes down with Lanczos. 2Ɨ made from a 4Ɨ result is sharper than a 2Ɨ model.
  • It used to always return PNG. A 400 KB JPEG came back as a lossless PNG many times larger. Results are now encoded in the input's format.

HEIC: decided by a licence

iPhone photos are HEIC, and people want JPG. There are several JavaScript HEIC decoders, but they're all the same Emscripten build of libheif, which is LGPL-3.0. Sending it to the browser counts as distributing it, which brings source and relinking obligations. Running it on our server is just running a service.

We couldn't use our usual image library either. sharp's prebuilt binaries include libheif with only the AVIF decoder, not HEVC. So HEIC goes to ImageMagick built with libheif, on the server. It's the one tool where the user-facing text says plainly that the file is uploaded.

Keeping one small server alive

All of this shares four CPUs, so the heavy image routes go through a small queue:

  • At most 2 heavy jobs at once, and up to 8 waiting.
  • When the queue is full, the server returns 503 with Retry-After: 5 instead of accepting more.
  • Clients that disconnect are dropped from the queue.

The queue is bounded on purpose. An unbounded queue holds every waiting upload in memory, which is a reliable way to hit the process manager's memory limit and restart the API for everyone.

Results are deleted after an hour. One easy-to-miss detail: scratch folders must be named omyimage-<label>-… with that trailing hyphen, because the cleanup only deletes folders matching a strict pattern. Without it, files from crashed jobs would pile up in /tmp forever.

If I started again

  1. Try the CPU first. A small ONNX model in a worker covers more than you'd expect.
  2. Probe the canvas. Never trust Safari to fail loudly.
  3. On a CPU-only box, measure each model once and cap input size before you start the job.
  4. Read the licence of every decoder you ship to the browser.
  5. Bound every queue.

You can try the tools on oMyImage: remove background runs on the server, and compress image runs entirely in your browser. Questions welcome in the comments.

Top comments (0)