Files
SnapOtter/packages/ai/python/remove_bg.py
T
SnapOtterandGitHub 6e3a14ec6b fix: remove automatic third-party egress of user data + optional strict offline mode (OSM tiles, Scalar fonts, editor fonts, AI model downloads) (#422)
* fix: remove all automatic third-party egress (OSM tiles, Scalar fonts, editor Google Fonts, AI model download fallbacks)

Phone-home audit follow-up. The product no longer makes any automatic
third-party request; user-initiated click-outs stay, and production now
fails closed on missing AI models.

1. GPS leak via OSM tiles: the strip-metadata panel auto-loaded
   tile.openstreetmap.org tiles encoding the photo's GPS position. The
   Leaflet mini-map is gone; coordinates render as text plus an explicit
   View on map link (openstreetmap.org, opens on click only). Removed
   tile.openstreetmap.org from the CSP img-src, dropped the leaflet
   dependency, added the viewOnMap i18n key to all 21 locales.

2. Scalar docs fonts: /api/docs loaded Inter and JetBrains Mono from
   fonts.scalar.com. Scalar now renders with withDefaultFonts: false and
   both --scalar-font and --scalar-font-code pinned to system stacks;
   fonts.scalar.com removed from the docs CSP font-src. Verified by
   injecting GET /api/docs/: config carries withDefaultFonts false and
   the served page has no fonts.scalar.com reference.

3. Editor Google Fonts: the editor font picker built
   fonts.googleapis.com stylesheet URLs for 25 web fonts the served CSP
   already blocked. The remote loading path is deleted; the picker now
   offers system fonts only, with a SELF_HOSTED_FONTS seam (FontFace API,
   same origin) for bundling fonts later. Unknown families saved in old
   documents fall back to the browser default.

4. Python sidecar fails closed on model downloads: new
   packages/ai/python/offline_guard.py gates every runtime download
   fallback (inpaint, outpaint, restore, noise_removal, detect_faces,
   enhance_faces, face_landmarks, red_eye_removal, remove_bg, ocr,
   transcribe, upscale) behind SNAPOTTER_ALLOW_MODEL_DOWNLOAD=1 with an
   actionable error. Bundled models keep working untouched.

5. OCR and transcription library-internal downloads: unbundled PaddleOCR
   language and detection fallbacks now raise the guard error naming the
   language instead of resolving models over the network; faster-whisper
   gets local_files_only when downloads are off.

6. GFPGAN and CodeFormer cwd-relative weights: facexlib and
   codeformer-pip resolve helper weights relative to the process cwd and
   fetch them from GitHub when absent. They are now symlinked from the
   installed bundle files under MODELS_PATH/gfpgan/facelib before the
   libraries load, failing closed when unresolvable.

Defense in depth: HF_HUB_OFFLINE=1 and TRANSFORMERS_OFFLINE=1 are set in
the runtime image and in the sidecar spawn env; install_feature.py lifts
them for user-initiated bundle installs and restores them afterwards
(it can run in-process inside the dispatcher). SNAPOTTER_ALLOW_MODEL_DOWNLOAD
is documented in .env.example, default off.

Validation: typecheck 9/9 workspaces, Biome clean on touched files,
5178 unit tests pass, py_compile on all touched scripts, guard behavior
exercised in both dispatcher exec and per-request import modes, zero
remaining runtime references to the three hosts. Docker build and live
AI inference need post-merge verification on the GPU host.

Claude-Session: https://claude.ai/code/session_01XGB4pGvTvb7sUX4JN745U7

* fix: allow AI model downloads by default, make strict offline mode opt-in

Product call: ease of use first. The download gating from the previous
commit inverts its default: runtime model fetches (public model weights
only, never user data) are allowed out of the box so AI tools self-heal,
and SNAPOTTER_ALLOW_MODEL_DOWNLOAD=0 becomes the explicit strict offline
mode for airgapped deployments, where every fallback raises the
actionable error instead of fetching.

Changes: offline_guard blocks only on an explicit 0/false; the
unconditional HF_HUB_OFFLINE/TRANSFORMERS_OFFLINE image ENV is removed
and bridge.ts sets those flags for the sidecar only in strict mode;
.env.example documents the new default; install_feature's lift/restore
stays. All bundled-path preferences, pre-existence checks, and symlink
pre-placement remain, so installed bundles never trigger a download.
The OSM, Scalar font, and editor font fixes are unchanged.

Validation rerun: typecheck 9/9, Biome clean on touched files, 5178
unit tests pass, py_compile on touched scripts, guard behavior verified
for unset/1 (allowed) and 0/false (blocked with the new message).

Claude-Session: https://claude.ai/code/session_01XGB4pGvTvb7sUX4JN745U7
2026-07-04 05:46:52 +00:00

296 lines
9.6 KiB
Python

"""Background removal using rembg with state-of-the-art BiRefNet models."""
import sys
import json
import os
def emit_progress(percent, stage):
print(json.dumps({"progress": percent, "stage": stage}), file=sys.stderr, flush=True)
def _refine_edges(image_bytes, level):
"""Morphological mask refinement to reduce gray halos on edges.
level: 1=light, 2=medium, 3=strong
"""
import cv2
import numpy as np
from PIL import Image
import io
img = Image.open(io.BytesIO(image_bytes)).convert("RGBA")
arr = np.array(img)
alpha = arr[:, :, 3]
kernel_size = 1 + level
kernel = cv2.getStructuringElement(cv2.MORPH_ELLIPSE, (kernel_size, kernel_size))
alpha = cv2.morphologyEx(alpha, cv2.MORPH_CLOSE, kernel)
sigma = 0.3 + level * 0.3
alpha = cv2.GaussianBlur(alpha, (0, 0), sigma)
arr[:, :, 3] = alpha
out = Image.fromarray(arr, "RGBA")
buf = io.BytesIO()
out.save(buf, format="PNG")
return buf.getvalue()
def _decontaminate_edges(image_bytes):
"""Remove background color spill from semi-transparent edge pixels."""
import numpy as np
from PIL import Image
import io
img = Image.open(io.BytesIO(image_bytes)).convert("RGBA")
arr = np.array(img, dtype=np.float32)
alpha = arr[:, :, 3] / 255.0
rgb = arr[:, :, :3]
bg_mask = alpha < 0.04
if not np.any(bg_mask):
return image_bytes
bg_color = np.zeros(3, dtype=np.float32)
for c in range(3):
channel = rgb[:, :, c]
bg_pixels = channel[bg_mask]
if len(bg_pixels) > 0:
bg_color[c] = np.median(bg_pixels)
edge_mask = (alpha > 0.04) & (alpha < 0.96)
if not np.any(edge_mask):
return image_bytes
a = alpha[edge_mask, np.newaxis]
fg = rgb[edge_mask]
corrected = (fg - bg_color[np.newaxis, :] * (1.0 - a)) / np.maximum(a, 0.01)
corrected = np.clip(corrected, 0, 255)
rgb[edge_mask] = corrected
arr[:, :, :3] = rgb
result = np.clip(arr, 0, 255).astype(np.uint8)
out = Image.fromarray(result, "RGBA")
buf = io.BytesIO()
out.save(buf, format="PNG")
return buf.getvalue()
ALLOWED_MODELS = {
"u2net",
"isnet-general-use",
"bria-rmbg",
"birefnet-general-lite",
"birefnet-portrait",
"birefnet-general",
"birefnet-matting",
"birefnet-hr-matting",
}
_matting_registered = False
def _register_matting_session(sessions_class):
"""Register the BiRefNet-matting ONNX session for Ultra quality mode."""
global _matting_registered
if _matting_registered:
return
_matting_registered = True
import os
import pooch
from rembg.sessions.birefnet_general import BiRefNetSessionGeneral
class BiRefNetMattingSession(BiRefNetSessionGeneral):
@classmethod
def download_models(cls, *args, **kwargs):
fname = f"{cls.name(*args, **kwargs)}.onnx"
target = os.path.join(cls.u2net_home(*args, **kwargs), fname)
if not os.path.exists(target):
from offline_guard import ensure_download_allowed
ensure_download_allowed(f"Background removal model '{cls.name(*args, **kwargs)}'")
pooch.retrieve(
"https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/BiRefNet-matting-epoch_100.onnx",
None, # Skip checksum for GitHub release assets
fname=fname,
path=cls.u2net_home(*args, **kwargs),
progressbar=True,
)
return target
@classmethod
def name(cls, *args, **kwargs):
return "birefnet-matting"
sessions_class.append(BiRefNetMattingSession)
_hr_matting_registered = False
def _register_hr_matting_session(sessions_class):
"""Register the BiRefNet HR-matting ONNX session for 2048x2048 high-res matting."""
global _hr_matting_registered
if _hr_matting_registered:
return
_hr_matting_registered = True
import os
import numpy as np
import pooch
from PIL import Image
from rembg.sessions.birefnet_general import BiRefNetSessionGeneral
class BiRefNetHRMattingSession(BiRefNetSessionGeneral):
@classmethod
def download_models(cls, *args, **kwargs):
fname = f"{cls.name(*args, **kwargs)}.onnx"
target = os.path.join(cls.u2net_home(*args, **kwargs), fname)
if not os.path.exists(target):
from offline_guard import ensure_download_allowed
ensure_download_allowed(f"Background removal model '{cls.name(*args, **kwargs)}'")
pooch.retrieve(
"https://github.com/ZhengPeng7/BiRefNet/releases/download/v1/BiRefNet_HR-matting-epoch_135.onnx",
None,
fname=fname,
path=cls.u2net_home(*args, **kwargs),
progressbar=True,
)
return target
@classmethod
def name(cls, *args, **kwargs):
return "birefnet-hr-matting"
def predict(self, img, *args, **kwargs):
ort_outs = self.inner_session.run(
None,
self.normalize(
img, (0.485, 0.456, 0.406), (0.229, 0.224, 0.225), (2048, 2048)
),
)
pred = ort_outs[0][:, 0, :, :]
ma = np.max(pred)
mi = np.min(pred)
denom = ma - mi
pred = (pred - mi) / denom if denom > 0 else pred * 0
pred = np.squeeze(pred)
mask = Image.fromarray((pred * 255).astype("uint8"), mode="L")
mask = mask.resize(img.size, Image.LANCZOS)
return [mask]
sessions_class.append(BiRefNetHRMattingSession)
def main():
input_path = sys.argv[1]
output_path = sys.argv[2]
settings = json.loads(sys.argv[3]) if len(sys.argv) > 3 else {}
model = settings.get("model", "birefnet-general-lite")
if model not in ALLOWED_MODELS:
model = "birefnet-general-lite"
# Redirect stdout to stderr so library download/progress output
# cannot contaminate our JSON result on stdout.
stdout_fd = os.dup(1)
os.dup2(2, 1)
try:
from rembg import remove, new_session
from rembg.sessions import sessions_class
from gpu import onnx_providers
# Register BiRefNet-matting (Ultra quality) if not already present
_register_matting_session(sessions_class)
_register_hr_matting_session(sessions_class)
# Every built-in rembg session downloads its .onnx (pooch,
# GitHub/HuggingFace) when it is missing from the rembg home dir;
# strict offline mode blocks that fallback with a clear error.
# Mirrors rembg's own home resolution.
model_home = os.path.expanduser(
os.getenv("U2NET_HOME", os.path.join(os.getenv("XDG_DATA_HOME", "~"), ".u2net"))
)
if not os.path.exists(os.path.join(model_home, f"{model}.onnx")):
from offline_guard import ensure_download_allowed
ensure_download_allowed(f"Background removal model '{model}'")
emit_progress(10, "Loading model")
providers, device = onnx_providers()
try:
session = new_session(model, providers=providers)
except Exception as e:
if "CUDAExecutionProvider" in providers:
from gpu import emit_info
emit_info(f"GPU session failed ({e}), falling back to CPU")
session = new_session(model, providers=["CPUExecutionProvider"])
device = "cpu"
else:
raise
emit_progress(25, "Model loaded")
with open(input_path, "rb") as f:
input_data = f.read()
emit_progress(30, "Analyzing image")
use_alpha_matting = device != "cpu"
try:
output_data = remove(
input_data,
session=session,
alpha_matting=use_alpha_matting,
alpha_matting_foreground_threshold=240,
alpha_matting_background_threshold=10,
)
except Exception as e:
if use_alpha_matting:
emit_progress(35, "Retrying without alpha matting")
output_data = remove(input_data, session=session, alpha_matting=False)
else:
raise RuntimeError(
f"Background removal failed: {e}"
) from e
emit_progress(80, "Background removed")
edge_refine = settings.get("edgeRefine", 0)
decontaminate = settings.get("decontaminate", False)
if edge_refine and edge_refine > 0:
emit_progress(85, "Refining edges")
output_data = _refine_edges(output_data, int(edge_refine))
if decontaminate:
emit_progress(90, "Removing color spill")
output_data = _decontaminate_edges(output_data)
# Always return transparent PNG. All background compositing
# (solid color, gradient, blur, shadow) is handled by Node.js/Sharp.
emit_progress(95, "Saving result")
with open(output_path, "wb") as f:
f.write(output_data)
result = json.dumps({"success": True, "model": model, "device": device})
except ImportError as e:
print(f"[remove-bg] Import failed: {e}", file=sys.stderr, flush=True)
result = json.dumps(
{
"success": False,
"error": f"rembg import failed: {e}",
}
)
except Exception as e:
result = json.dumps({"success": False, "error": str(e)})
# Restore original stdout and write only our JSON result
os.dup2(stdout_fd, 1)
os.close(stdout_fd)
sys.stdout.write(result + "\n")
sys.stdout.flush()
if __name__ == "__main__":
main()