Skip to content

AI Engine Reference

The @snapotter/ai package coordinates native tools and Python runtimes for local ML operations. Most ML tools use a persistent Python sidecar for fast warm starts. OCR is intentionally separate: fast invokes the native Tesseract binary, while balanced and best use a dedicated persistent JSONL dispatcher pinned to the active immutable RapidOCR generation under /data/ai/v3. Each request holds a generation lease. During an upgrade, SnapOtter runs a smoke test on the candidate before activation, atomically switches to the new dispatcher, then drains the old generation before garbage collection.

NVIDIA CUDA is auto-detected and used by runtimes that support it. OCR uses CPU on every host, including systems with NVIDIA GPUs, avoiding CUDA and driver coupling for this tool.

Intel/AMD iGPU acceleration through VA-API, Quick Sync, or OpenCL is not supported for AI inference today. Mapping /dev/dri into a container does not accelerate these Python sidecar tools unless a CUDA-capable NVIDIA GPU is available.

19 Python sidecar AI tools across four modalities (image, audio, video, document), plus 2 tools with optional AI capabilities. All models run locally - no internet required after initial model download.

Architecture

Node.js Tool Route
      |
      v
 @snapotter/ai bridge.ts
      | (stdin/stdout JSON + stderr progress events)
      v
 +-- Native Tesseract + Ghostscript (fast image/PDF OCR)
 |
 +-- Isolated OCR runtime (persistent JSONL dispatcher)
 |     `-- RapidOCR + ONNX Runtime CPU + pinned PP-OCR models
 |
 `-- Python dispatcher (persistent process, "ai" profile)
      |
      |-- remove_bg.py        (rembg / BiRefNet)
      |-- upscale.py          (RealESRGAN)
      |-- inpaint.py          (LaMa ONNX)
      |-- outpaint.py         (LaMa canvas expansion)
      |-- detect_faces.py     (MediaPipe)
      |-- face_landmarks.py   (MediaPipe landmarks)
      |-- enhance_faces.py    (GFPGAN / CodeFormer)
      |-- colorize.py         (DDColor)
      |-- noise_removal.py    (SCUNet / tiered denoising)
      |-- red_eye_removal.py  (landmark + color analysis)
      |-- restore.py          (scratch repair + enhancement + denoising)
      |-- transcribe.py       (faster-whisper speech-to-text)
      +-- install_feature.py  (on-demand bundle installer)

A separate "docs" dispatcher profile replaces the AI allowlist with document-processing scripts (doc_pagecount, doc_health, doc_flatten, doc_redact, doc_text, doc_to_word, doc_metadata, doc_html_pdf) and skips heavy ML imports.

Timeouts: 300 s default; OCR and BiRefNet background removal get 600 s.

Feature Bundles

AI models are packaged by shared dependency stack, not one archive per tool. A feature bundle can enable several tools when they use the same model family, Python wheels, or native libraries. This keeps the release Docker image smaller and avoids storing duplicate copies of the same background matting, face detection, OCR, restoration, and speech models.

The Docker image ships the application plus the common runtime. Large model archives are downloaded on demand into the persistent /data/ai volume, then reused by every tool that needs them. If a bundle is already installed because another tool needed it, enabling a new dependent tool does not download that bundle again.

Most AI tools require one or more feature bundles before they can run. The admin UI installs those by tool through POST /api/v1/admin/tools/:toolId/features/install, which resolves the full bundle list, skips bundles that are already installed, and queues only the missing downloads. For example, enabling Passport Photo on a fresh instance queues background-removal and face-detection; enabling it after Background Removal is already installed queues only face-detection. OCR is the exception because fast needs no pack; install its optional accurate runtime through the UI or POST /api/v1/admin/features/ocr/install.

BundleSizeShared dependency groupTools that use it
background-removal4-5 GBrembg / BiRefNet background mattingremove-background, passport-photo, transparency-fixer, background-replace, blur-background
face-detection200-300 MBMediaPipe face detection and landmarksblur-faces, red-eye-removal, smart-crop
object-eraser-colorize1-2 GBLaMa inpainting/outpainting and DDColorerase-object, colorize, ai-canvas-expand
upscale-enhance5-6 GBRealESRGAN, GFPGAN / CodeFormer, denoisingupscale, enhance-faces, noise-removal
photo-restoration4-5 GBscratch repair and restoration pipelinerestore-photo
ocr~208-234 MiB download / ~409-488 MiB installedOptional RapidOCR 3.9.1, ONNX Runtime 1.20.1, and pinned PP-OCR modelsocr, ocr-pdf (balanced and best only)
transcription~600 MBfaster-whisper speech-to-text modelstranscribe-audio, auto-subtitles

Tools with cross-bundle dependencies:

ToolRequired bundlesWhy
passport-photobackground-removal, face-detectionRemoves the background, then uses face landmarks to frame the crop to passport and ID photo rules.
enhance-facesupscale-enhance, face-detectionDetects faces before running GFPGAN or CodeFormer enhancement on the selected face regions.

A tool is available only when all of its required bundles are installed, except OCR: its built-in fast tier remains available without the optional OCR pack. Partial installs are valid and are handled incrementally: installed bundles are reused, missing bundles are shown as downloads, and queued installs run one at a time so the shared Python environment is not modified concurrently.

Accurate OCR runtime installation

The accurate OCR pack is a platform-specific runtime for the official Linux amd64 or Linux arm64 container. The amd64 build uses Python 3.12; the arm64 build uses Python 3.11. Both builds run RapidOCR through ONNX Runtime's CPUExecutionProvider, so the same pack works on CPU-only and NVIDIA Docker hosts. The accurate runtime requires at least 4 GiB of effective memory: the configured container cgroup limit, otherwise host memory. A system below that signed compatibility minimum is rejected before download. This requirement does not apply to built-in Fast OCR. Bare-metal builds are rejected because their libc and Python ABI cannot be inferred safely; Fast OCR remains available when the host provides Tesseract and Ghostscript. Fast supports auto, en, de, es, fr, zh, and ja, but not Korean (ko). Korean therefore requires a supported accurate runtime and a balanced or best tier; unsupported hosts receive an explicit incompatibility response rather than a silent Fast fallback.

The optional artifact is about 208-234 MiB compressed and 409-488 MiB extracted, depending on architecture. The signed index binds the exact compressed and extracted byte counts enforced by the installer. Built-in Tesseract adds about 25 MiB to the official image and needs no files in /data/ai.

Online installation fetches a signed release index and the exact content-addressed artifact for the current platform. SnapOtter verifies the Ed25519 index signature, artifact size, SHA-256 digest, model digests, paths, file modes, and staged smoke test before atomically activating the new generation. A failed install leaves the prior healthy generation active.

For air-gapped installation, upload both the release's ocr-runtime-index.json and matching OCR runtime archive to POST /api/v1/admin/features/import using multipart fields named index and archive. Offline import applies the same signature, hash, extraction, compatibility, and smoke-test checks as online installation; an archive without its trusted signed index is rejected.


Background Removal

Tool route: remove-backgroundModel: rembg with BiRefNet (default) or U2-Net variants

ParameterTypeDefaultDescription
modelstring-Model variant (optional override)
backgroundTypestring"transparent"One of: transparent, color, gradient, blur, image
backgroundColorstring-Hex color for solid background
gradientColor1string-First gradient color
gradientColor2string-Second gradient color
gradientAnglenumber-Gradient angle in degrees
blurEnabledboolean-Enable background blur effect
blurIntensitynumber (0-100)-Blur intensity
shadowEnabledboolean-Enable drop shadow on subject
shadowOpacitynumber (0-100)-Shadow opacity
outputFormatstring-Output format: png, webp, or avif
edgeRefineinteger (0-3)-Edge refinement level
decontaminateboolean-Remove color bleed from edges

Background Replace

Tool route: background-replaceModel: rembg / BiRefNet (shared with remove-background)

Removes the background and replaces it with a solid color or gradient.

ParameterTypeDefaultDescription
backgroundType"color" | "gradient""color"Background mode
colorstring"#ffffff"Background hex color (when backgroundType is color)
gradientColor1string-First gradient hex color
gradientColor2string-Second gradient hex color
gradientAngleinteger (0-360)180Gradient angle in degrees
featherinteger (0-20)0Edge feathering radius
format"png" | "webp""png"Output format

Blur Background

Tool route: blur-backgroundModel: rembg / BiRefNet (shared with remove-background)

Blurs the background while keeping the subject sharp.

ParameterTypeDefaultDescription
intensityinteger (1-100)50Blur intensity
featherinteger (0-20)0Edge feathering radius
format"png" | "webp""png"Output format

Image Upscaling

Tool route: upscaleModel: RealESRGAN (with Lanczos fallback when unavailable)

ParameterTypeDefaultDescription
scalenumber2Upscale factor
modelstring"auto"Model variant
faceEnhancebooleanfalseApply GFPGAN face enhancement pass
denoisenumber0Denoising strength
formatstring"auto"Output format override
qualitynumber95Output quality (1-100)

OCR / Text Extraction

Tool route: ocrModels: Tesseract (fast); RapidOCR with PP-OCRv6 small models (balanced); PP-OCRv6 medium models with calibrated variant scoring (best)

ParameterTypeDefaultDescription
quality"fast" | "balanced" | "best"DynamicProcessing tier. Omitted quality selects the highest available tier in this order: best, balanced, fast. Korean never selects fast; without an accurate tier it returns the accurate-runtime install or compatibility error
languagestring"auto"Language: auto, en, de, fr, es, zh, ja, ko. Fast does not support ko
enhancebooleanTier-dependentImprove local contrast. Fast applies it directly; accurate tiers keep the variant only when calibrated scoring improves OCR. Defaults on for Best
enginestring-Deprecated compatibility alias. Maps tesseract to fast and the legacy paddleocr value to balanced; it does not load PaddlePaddle

Returns extracted text plus provenance metadata: engine, requested and actual quality, device, provider, degradation state, warnings, and accurate-runtime/model versions when applicable. Explicit quality requests never fall back to another tier. If balanced or best is unavailable, the API returns FEATURE_NOT_INSTALLED or FEATURE_INCOMPATIBLE instead of silently running fast. Explicit Fast or legacy tesseract with Korean returns FEATURE_INCOMPATIBLE, compatibilityReason: "fast-korean-unsupported", and accurate-pack guidance before a job is queued.

PDF OCR

Tool route: ocr-pdfModels: Same tier system as image OCR

Extracts text from scanned PDF documents using AI-powered OCR, page by page.

ParameterTypeDefaultDescription
quality"fast" | "balanced" | "best"DynamicProcessing tier. Omitted quality selects the highest available tier in this order: best, balanced, fast. Korean never selects fast; without an accurate tier it returns the accurate-runtime install or compatibility error
languagestring"auto"Language: auto, en, de, fr, es, zh, ja, ko. Fast does not support ko
pagesstring"all"Page selection: "all", "1-3", "1,3,5"
enhancebooleanTier-dependentImprove local contrast. Fast applies it directly; accurate tiers keep the variant only when calibrated scoring improves OCR. Defaults on for Best
enginestring-Deprecated compatibility alias. Maps tesseract to fast and the legacy paddleocr value to balanced; it does not load PaddlePaddle

The same no-downgrade and Korean compatibility rules apply to PDF OCR. PDF pages are rasterized before recognition, and one request can select at most 50 pages.

Face / PII Blur

Tool route: blur-facesModel: MediaPipe face detection

ParameterTypeDefaultDescription
blurRadiusnumber (1-100)30Gaussian blur radius
sensitivitynumber (0-1)0.5Detection confidence threshold

Face Enhancement

Tool route: enhance-facesModels: GFPGAN, CodeFormer

ParameterTypeDefaultDescription
model"auto" | "gfpgan" | "codeformer""auto"Enhancement model
strengthnumber (0-1)0.8Enhancement strength
sensitivitynumber (0-1)0.5Face detection threshold
onlyCenterFacebooleanfalseEnhance only the most central face

AI Colorization

Tool route: colorizeModel: DDColor (with OpenCV DNN fallback)

Converts black-and-white or grayscale photos to full color.

ParameterTypeDefaultDescription
intensitynumber (0-1)1.0Color saturation strength
model"auto" | "ddcolor" | "opencv""auto"Model variant

Noise Removal

Tool route: noise-removalModel: SCUNet (tiered denoising pipeline)

ParameterTypeDefaultDescription
tier"quick" | "balanced" | "quality" | "maximum""balanced"Processing tier
strengthnumber (0-100)50Denoising strength
detailPreservationnumber (0-100)50How much detail to preserve; higher keeps more texture
colorNoisenumber (0-100)30Color noise reduction strength
formatstring"original"Output format: original, png, jpeg, webp, avif, jxl
qualitynumber (1-100)90Output encoding quality

Red Eye Removal

Tool route: red-eye-removal

Detects face landmarks, locates eye regions, and corrects red-channel oversaturation.

ParameterTypeDefaultDescription
sensitivitynumber (0-100)50Red pixel detection threshold
strengthnumber (0-100)70Correction strength
formatstring-Output format override (optional)
qualitynumber (1-100)90Output quality

Photo Restoration

Tool route: restore-photo

Multi-step pipeline for old or damaged photos: scratch/tear detection and repair, face enhancement, denoising, and optional colorization.

ParameterTypeDefaultDescription
scratchRemovalbooleantrueDetect and repair scratches, tears
faceEnhancementbooleantrueApply face enhancement pass
fidelitynumber (0-1)0.7Face enhancement strength (higher = more conservative)
denoisebooleantrueApply denoising pass
denoiseStrengthnumber (0-100)25Denoising strength
colorizebooleanfalseColorize after restoration
colorizeStrengthnumber (0-100)85Colorization intensity

Passport Photo

Tool route: passport-photoModels: MediaPipe face landmarks + BiRefNet background removal

Two-phase workflow: analyze (detect face + remove background) then generate (crop, resize, tile). Supports 37+ countries across 6 regions.

Phase 1: Analyze

POST /api/v1/tools/image/passport-photo/analyze

Accepts an image file (multipart). Returns face landmark data, a base64 preview, and image dimensions.

Phase 2: Generate

POST /api/v1/tools/image/passport-photo/generate

Accepts a JSON body with the Phase 1 results plus generation settings:

ParameterTypeDefaultDescription
jobIdstring(required)Job ID from Phase 1
filenamestring(required)Original filename from Phase 1
countryCodestring(required)ISO country code (e.g., US, GB, IN)
documentTypestring"passport"Document type
bgColorstring"#FFFFFF"Background color hex
printLayoutstring"none"Print layout: none, 4x6, a4, letter
maxFileSizeKbnumber0Max file size in KB (0 = no limit)
dpinumber (72-1200)300Output DPI
customWidthMmnumber-Custom width in mm (overrides country spec)
customHeightMmnumber-Custom height in mm (overrides country spec)
zoomnumber (0.5-3)1Zoom factor
adjustXnumber0Horizontal position adjustment
adjustYnumber0Vertical position adjustment
landmarksobject(required)Landmarks from Phase 1
imageWidthnumber(required)Image width from Phase 1
imageHeightnumber(required)Image height from Phase 1

Object Erasing (Inpainting)

Tool route: erase-objectModel: LaMa via ONNX Runtime

The mask is sent as a second file part (fieldname mask), not as base64. White pixels in the mask indicate areas to erase. The format and quality settings are sent as top-level form fields.

ParameterTypeDefaultDescription
filefile(required)Source image (multipart)
maskfile(required)Mask image (multipart, fieldname mask, white = erase)
formatstring"auto"Output format: auto, png, jpg, jpeg, webp, tiff, gif, avif, heic, heif, jxl
qualityinteger (1-100)95Output quality

CUDA-accelerated when an NVIDIA GPU is available.

AI Canvas Expand

Tool route: ai-canvas-expandModel: LaMa-based outpainting

Expands the canvas of an image in any direction and fills new areas with AI-generated content that matches the existing image.

ParameterTypeDefaultDescription
extendTopinteger0Pixels to extend at the top
extendRightinteger0Pixels to extend at the right
extendBottominteger0Pixels to extend at the bottom
extendLeftinteger0Pixels to extend at the left
tier"fast" | "balanced" | "high""balanced"Quality tier
formatstring"auto"Output format: auto, png, jpg, jpeg, webp, tiff, gif, avif, heic, heif, jxl
qualityinteger (1-100)95Output quality

At least one extend direction must be greater than 0.

Smart Crop

Tool route: smart-cropModel: MediaPipe face detection (face mode only)

ParameterTypeDefaultDescription
modestring"subject"Crop strategy: subject, face, trim
strategy"attention" | "entropy""attention"Strategy for subject mode
widthinteger-Output width
heightinteger-Output height
paddinginteger (0-50)0Padding percentage around subject
facePresetstring"head-shoulders"Preset framing when mode=face
sensitivitynumber (0-1)0.5Face detection threshold
thresholdinteger (0-255)30Background detection threshold (trim mode)
padToSquarebooleanfalsePad trimmed result to a square
padColorstring"#ffffff"Background color for square padding
targetSizeinteger-Target size for padded output (pixels)
qualityinteger (1-100)-Output quality

Legacy mode values attention and content are accepted and mapped to subject and trim respectively.

Face presets:

PresetBest for
closeupHeadshots
head-shouldersProfile photos
upper-bodyLinkedIn / formal
half-bodyFull upper body

Transcribe Audio

Tool route: transcribe-audioModel: faster-whisper

Converts speech to text. Supports plain text, SRT, and VTT output formats.

ParameterTypeDefaultDescription
languagestring"auto"Language: auto, en, de, fr, es, zh, ja, ko, id, th, vi
outputFormat"txt" | "srt" | "vtt""txt"Output format

Auto Subtitles

Tool route: auto-subtitlesModel: faster-whisper (extracts audio from video, then transcribes)

Generates subtitle files from a video's audio track.

ParameterTypeDefaultDescription
languagestring"auto"Language: auto, en, de, fr, es, zh, ja, ko, id, th, vi
format"srt" | "vtt""srt"Output subtitle format

PNG Transparency Fixer

Tool route: transparency-fixerModel: BiRefNet HR-matting (2048x2048 resolution)

Fixes "fake transparent" PNGs where the background was removed but left behind fringing, halos, or semi-transparent artifacts. Uses BiRefNet's high-resolution matting model to produce a clean alpha channel, then applies configurable defringe processing to remove color contamination along edges.

OOM fallback chain: If BiRefNet HR-matting exceeds available memory, the tool automatically falls back to birefnet-general, then to u2net.

ParameterTypeDefaultDescription
defringenumber (0-100)30Edge defringe strength to remove color contamination
outputFormat"png" | "webp""png"Output image format
removeWatermarkbooleanfalseApply watermark removal pre-processing (median filter)
bash
curl -X POST http://localhost:1349/api/v1/tools/image/transparency-fixer \
  -H "Authorization: Bearer <token>" \
  -F "[email protected]" \
  -F 'settings={"defringe":30,"outputFormat":"png"}'

Tools with Optional AI Capabilities

The following tools are not Python sidecar tools but use AI features when certain options are enabled.

Image Enhancement

Tool route: image-enhancementEngine: Analysis-based (Sharp histogram and statistics)

Analyzes the image and applies automatic corrections for exposure, contrast, white balance, saturation, sharpness, and noise. Supports scene-specific modes.

ParameterTypeDefaultDescription
mode"auto" | "portrait" | "landscape" | "low-light" | "food" | "document""auto"Scene mode for tuning corrections
intensitynumber (0-100)50Overall correction strength
corrections.exposurebooleantrueApply exposure correction
corrections.contrastbooleantrueApply contrast correction
corrections.whiteBalancebooleantrueApply white balance correction
corrections.saturationbooleantrueApply saturation correction
corrections.sharpnessbooleantrueApply sharpness correction
corrections.denoisebooleantrueApply denoising
deepEnhancebooleanfalseEnable AI noise removal via SCUNet (requires upscale-enhance bundle)

An additional analysis endpoint is available at POST /api/v1/tools/image/image-enhancement/analyze which returns the detected corrections without applying them.

Content-Aware Resize (Seam Carving)

Tool route: content-aware-resizeEngine: Go caire binary (not Python - no GPU benefit)

Intelligently resizes images by removing low-energy seams, preserving important content.

ParameterTypeDefaultDescription
widthnumber-Target width
heightnumber-Target height
protectFacesbooleanfalseProtect detected face regions (requires face-detection bundle)
blurRadiusnumber (0-20)4Pre-blur for energy calculation
sobelThresholdnumber (1-20)2Edge sensitivity threshold
squarebooleanfalseForce square output