In-Browser OCR in 2026: Tesseract.js (WASM) vs. Florence-2 Vision AI (Live Demo)
Compare classic Tesseract.js WebAssembly OCR (~4 MB) side-by-side with Microsoft's Florence-2 Vision-Language Model running 100% locally in your browser via WebGPU.
If you want to extract text from a screenshot, receipt, or whiteboard photo in a web app, you usually face two choices: send your user’s private image to a cloud Vision API, or run everything locally inside their browser tab.
After building in-browser neural TTS, client-side background removal, and Stockfish 19 chess in WebAssembly, I built a side-by-side In-Browser OCR Arena so you can pit Tesseract.js (WASM) directly against Microsoft’s Florence-2 Vision AI (onnx-community/Florence-2-base-ft) on the exact same image.
Wait: What Are These Two Models?
Both run 100% locally in your browser (check your Network tab—zero image bytes ever leave your device), and both use AI, just from completely different eras:
- Tesseract.js (WASM · ~4 MB): Originally built at HP in the 1980s and later upgraded by Google with LSTM neural networks, compiled to WebAssembly. It’s tiny, fast, and gives you exact word-level pixel coordinates—but assumes flat, black-ink-on-white-paper pages.
- Florence-2 (
Florence-2-base-ft) (WebGPU · ~230 MB): Microsoft’s multimodal Vision-Language Foundation Model running via@huggingface/transformers. Because it understands visual context, it can read faint text, tilted receipts, and handwritten whiteboards where traditional OCR falls apart.
| Dimension | Tesseract.js (WASM) | Florence-2 (<OCR> via WebGPU) |
|---|---|---|
| Download Size | ~4 MB (WASM + .traineddata) | ~230 MB (cached in browser) |
| Hardware | Any CPU (works everywhere) | WebGPU (falls back to WASM) |
| Speed | ~0.2–1.5s | ~1.5–8s |
| Languages | 100+ (must pick upfront, e.g. eng+heb) | English-centric, zero config |
| Word Bounding Boxes | Native (blocks → paragraphs → lines → words) | Optional via <OCR_WITH_REGION> |
| Best At | Clean screenshots, code, receipts | Striped/noisy photos, handwriting, faint text |
How the Zero-Backend Pipeline Works
flowchart LR
Input["🖼️ Image / Dragged Region"] --> Prep["🎛️ B&W Preprocess + Auto-Invert"]
Prep -->|"Clean pixels"| Tess["⚙️ Tesseract.js (WASM)<br/>PSM + Multi-Language"]
Input -->|"Original RGB pixels"| Flor["🧠 Florence-2 (WebGPU)<br/><OCR> / <OCR_WITH_REGION>"]
Tess --> Compare["📊 Side-by-Side Output + Confidence"]
Flor --> Compare
Four Engineering Details That Made It Actually Work
1. Passing <canvas> Directly (No Temporary blob: URLs)
When a user drops or pastes an image, URL.createObjectURL(blob) creates a temporary in-memory URL (blob:https://...). If you pass that string to a background Web Worker and revoke it too early, the worker’s fetch() crashes. Drawing onto an HTML5 <canvas> and passing the canvas element directly sends decoded pixels with zero URL lifetime bugs:
const { data } = await worker.recognize(canvas, { rectangle }, { text: true, blocks: true });
2. Visualizing Word Confidence & Layout Trees
Passing { text: true, blocks: true } tells Tesseract to return its full layout tree (Blocks → Paragraphs → Lines → Words) with per-word confidence (0–100) and bbox coordinates. We draw green boxes (>80%) and amber boxes (≤80%) over the image and show the exact word + confidence % on hover.
3. B&W Preprocessing & Center-Weighted Auto-Invert
Tesseract expects black ink on white paper—so dark-mode screenshots (like Demo 3: Dark Stack Trace) fail out of the box. Our B&W Preprocess toggle converts to grayscale, stretches contrast, and checks the center 50% luminance to auto-invert dark-mode images without accidentally inverting white-paper receipts photographed on a dark desk.
4. Exposing PSM (Page Segmentation Mode) & Region Selection
By default, Tesseract uses PSM 3 (Auto Page), which assumes a standard document. Switching to PSM 11 (Sparse) or PSM 6 (Single Block)—or dragging a box directly on the canvas to pass { rectangle }—stops Tesseract from trying to read background textures as text.
Try the 4 Demos Side-by-Side
Test Demo 1 (Receipt), Demo 2 (Striped Receipt), Demo 3 (Dark Stack Trace), and Demo 4 (Whiteboard) below—and click ▶ Run Florence-2 to see exactly where a tiny 4 MB WASM engine stops and a 230 MB Vision model takes over.
The Code
import { createWorker } from 'tesseract.js';
export interface OcrRect {
left: number;
top: number;
width: number;
height: number;
}
export interface OcrWord {
text: string;
confidence: number;
bbox: { x0: number; y0: number; x1: number; y1: number };
}
export interface TesseractResult {
text: string;
confidence: number;
words: OcrWord[];
}
const SCRIPT_TO_LANG: Record<string, string[]> = {
Hebrew: ['eng', 'heb'],
Arabic: ['eng', 'ara'],
Cyrillic: ['eng', 'rus'],
Japanese: ['eng', 'jpn'],
Han: ['eng', 'chi_sim'],
HanS: ['eng', 'chi_sim'],
HanT: ['eng', 'chi_tra'],
Hangul: ['eng', 'kor'],
Greek: ['eng', 'ell'],
Devanagari: ['eng', 'hin'],
Thai: ['eng', 'tha'],
Latin: ['eng'],
};
let activeWorker: any = null;
let activeLang = '';
let osdWorker: any = null;
/**
* Uses Tesseract's lightweight OSD model to guess the image's dominant script.
*/
export async function detectScriptLangs(canvas: HTMLCanvasElement): Promise<string[] | null> {
try {
if (!osdWorker) {
osdWorker = await createWorker('osd');
}
const res: any = await osdWorker.detect(canvas);
const script = res?.data?.script;
if (script && SCRIPT_TO_LANG[script]) {
return SCRIPT_TO_LANG[script];
}
} catch {
// Fall back to user-selected languages if OSD fails
}
return null;
}
/**
* Converts canvas pixels to high-contrast grayscale and auto-inverts dark-mode
* screenshots based on the center 50% luminance.
*/
export function preprocessCanvasForOcr(ctx: CanvasRenderingContext2D, width: number, height: number): void {
if (!width || !height) return;
const imgData = ctx.getImageData(0, 0, width, height);
const d = imgData.data;
let sumCenterLuma = 0;
let centerCount = 0;
const xStart = Math.floor(width * 0.25);
const xEnd = Math.ceil(width * 0.75);
const yStart = Math.floor(height * 0.25);
const yEnd = Math.ceil(height * 0.75);
const lumas = new Uint8Array(width * height);
for (let y = 0, p = 0; y < height; y++) {
for (let x = 0; x < width; x++, p++) {
const i = p * 4;
const l = 0.299 * d[i] + 0.587 * d[i + 1] + 0.114 * d[i + 2];
lumas[p] = l;
if (x >= xStart && x < xEnd && y >= yStart && y < yEnd) {
sumCenterLuma += l;
centerCount++;
}
}
}
const shouldInvert = sumCenterLuma / Math.max(1, centerCount) < 115;
for (let i = 0, p = 0; i < d.length; i += 4, p++) {
let v = lumas[p];
if (shouldInvert) v = 255 - v;
let norm = v / 255;
norm = Math.min(1, Math.max(0, (norm - 0.18) / 0.62));
const out = Math.round(norm * 255);
d[i] = out;
d[i + 1] = out;
d[i + 2] = out;
}
ctx.putImageData(imgData, 0, 0);
}
/**
* Runs Tesseract.js WASM OCR directly on a <canvas>, reusing the worker across runs.
*/
export async function runTesseractOcr(
canvas: HTMLCanvasElement,
options: {
lang: string;
psm?: string;
rectangle?: OcrRect | null;
onProgress?: (status: string, pct: number) => void;
}
): Promise<TesseractResult> {
const { lang, psm = '3', rectangle = null, onProgress } = options;
if (!activeWorker || activeLang !== lang) {
if (activeWorker) {
try { await activeWorker.terminate(); } catch {}
activeWorker = null;
}
activeWorker = await createWorker(lang, 1, {
logger: (m: any) => {
if (onProgress && (m.status || typeof m.progress === 'number')) {
onProgress(m.status || '', typeof m.progress === 'number' ? Math.round(m.progress * 100) : 0);
}
},
});
activeLang = lang;
}
await activeWorker.setParameters({ tessedit_pageseg_mode: psm as any });
const recognizeOpts = rectangle ? { rectangle } : {};
const { data } = await activeWorker.recognize(canvas, recognizeOpts, { text: true, blocks: true });
const words: OcrWord[] = [];
for (const block of data.blocks || []) {
for (const para of block.paragraphs || []) {
for (const line of para.lines || []) {
for (const w of line.words || []) {
if (w.text && w.bbox) {
words.push({ text: w.text, confidence: w.confidence, bbox: w.bbox });
}
}
}
}
}
return {
text: (data.text || '').trim() || '(No text detected)',
confidence: Math.round(data.confidence || 0),
words,
};
}import type { OcrRect } from './tesseractEngine';
let processor: any = null;
let tokenizer: any = null;
let model: any = null;
export function isFlorenceLoaded(): boolean {
return Boolean(model);
}
/**
* Runs Microsoft's Florence-2-base-ft Vision-Language Model 100% locally
* in the browser via WebGPU (with WASM fallback).
*/
export async function runFlorenceOcr(
image: HTMLImageElement,
options: {
task?: string;
region?: OcrRect | null;
onStatus?: (msg: string) => void;
} = {}
): Promise<string> {
const { task = '<OCR>', region = null, onStatus } = options;
const { Florence2ForConditionalGeneration, AutoProcessor, AutoTokenizer, RawImage, env } = await import(
/* @vite-ignore */ 'https://cdn.jsdelivr.net/npm/@huggingface/transformers@3/+esm'
);
env.allowLocalModels = false;
if (!processor || !tokenizer || !model) {
const hasWebGPU = typeof navigator !== 'undefined' && 'gpu' in navigator;
const device = hasWebGPU ? 'webgpu' : 'wasm';
onStatus?.(`Loading Florence-2 (${device.toUpperCase()})…`);
const modelId = 'onnx-community/Florence-2-base-ft';
processor = await AutoProcessor.from_pretrained(modelId);
tokenizer = await AutoTokenizer.from_pretrained(modelId);
model = await Florence2ForConditionalGeneration.from_pretrained(modelId, {
dtype: {
embed_tokens: hasWebGPU ? 'fp16' : 'fp32',
vision_encoder: hasWebGPU ? 'fp16' : 'fp32',
encoder_model: 'q4',
decoder_model_merged: 'q4',
},
device,
progress_callback: (p: any) => {
if (p?.status === 'progress' && typeof p.progress === 'number') {
onStatus?.(`Downloading ${Math.round(p.progress)}%…`);
}
},
});
}
onStatus?.('Running OCR…');
// Feed original full-color RGB pixels (cropped to region if selected)
const srcCanvas = document.createElement('canvas');
const imgW = image.naturalWidth || image.width;
const imgH = image.naturalHeight || image.height;
if (region) {
srcCanvas.width = region.width;
srcCanvas.height = region.height;
srcCanvas.getContext('2d')!.drawImage(
image,
region.left,
region.top,
region.width,
region.height,
0,
0,
region.width,
region.height
);
} else {
srcCanvas.width = imgW;
srcCanvas.height = imgH;
srcCanvas.getContext('2d')!.drawImage(image, 0, 0);
}
const rawImg = RawImage.fromCanvas(srcCanvas);
const prompts = processor.construct_prompts(task);
const textInputs = tokenizer(prompts);
const visionInputs = await processor(rawImg);
const generatedIds = await model.generate({
...textInputs,
...visionInputs,
max_new_tokens: 512,
});
const generatedText = tokenizer.batch_decode(generatedIds, { skip_special_tokens: false })[0];
const parsed = processor.post_process_generation(generatedText, task, rawImg.size);
const resultVal = parsed?.[task];
if (typeof resultVal === 'string') {
return resultVal.trim() || '(No text detected)';
}
if (resultVal?.labels) {
return resultVal.labels.join('\n') || '(No text detected)';
}
return JSON.stringify(parsed, null, 2);
}---
// 100% In-Browser OCR via Tesseract.js (WebAssembly)
---
<div id="ocr-arena" class="max-w-6xl mx-auto px-3 sm:px-6 space-y-5">
<!-- Top Bar -->
<div class="flex flex-wrap items-center justify-between gap-3 rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-neutral-50/80 dark:bg-neutral-900/70 px-4 py-3">
<div class="flex items-center gap-2.5">
<span id="ocr-status-dot" class="h-2.5 w-2.5 rounded-full bg-emerald-500"></span>
<span id="ocr-status-text" class="text-xs sm:text-sm font-medium text-neutral-700 dark:text-neutral-200">
Ready — upload, drop, or paste (⌘V / Ctrl+V) any image
</span>
</div>
<div class="flex flex-wrap items-center gap-2">
<!-- Multi-Select Language Picker + Auto-Detect -->
<div id="ocr-lang-picker" class="relative">
<button
id="ocr-lang-btn"
type="button"
class="inline-flex items-center gap-1.5 rounded-lg border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-950 px-2.5 py-1.5 text-xs font-mono font-medium text-neutral-800 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-900 transition cursor-pointer"
title="Select one or more OCR languages, or enable Auto-detect script"
>
<span>🌐</span>
<span id="ocr-lang-label">eng</span>
<span class="text-[10px] opacity-60">▾</span>
</button>
<div
id="ocr-lang-panel"
class="hidden absolute left-0 sm:right-0 sm:left-auto mt-1.5 w-72 rounded-xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-950 shadow-xl z-40 p-2.5 space-y-2"
>
<label class="flex items-center justify-between gap-2 rounded-lg bg-indigo-50/70 dark:bg-indigo-950/40 border border-indigo-200/80 dark:border-indigo-800/60 px-2.5 py-1.5 cursor-pointer select-none">
<span class="text-xs font-semibold text-indigo-800 dark:text-indigo-200">✨ Auto-detect script (OSD)</span>
<input id="ocr-auto-lang" type="checkbox" class="rounded border-indigo-300 text-indigo-600 focus:ring-indigo-500" />
</label>
<input
id="ocr-lang-search"
type="text"
placeholder="Search 100+ languages (e.g. hebrew, jpn)…"
class="w-full rounded-lg border border-neutral-200 dark:border-neutral-800 bg-neutral-50 dark:bg-neutral-900 px-2.5 py-1.5 text-xs text-neutral-800 dark:text-neutral-200 focus:outline-none focus:ring-2 focus:ring-indigo-500/40"
/>
<div id="ocr-lang-list" class="max-h-52 overflow-y-auto space-y-0.5 pr-1 text-xs"></div>
<div class="flex items-center justify-between pt-1.5 border-t border-neutral-200 dark:border-neutral-800">
<button id="ocr-lang-clear" type="button" class="text-[11px] font-medium text-neutral-500 hover:text-neutral-800 dark:hover:text-neutral-200 cursor-pointer">
Reset to eng
</button>
<button id="ocr-lang-apply" type="button" class="rounded-md bg-indigo-600 hover:bg-indigo-500 px-2.5 py-1 text-[11px] font-semibold text-white cursor-pointer">
Apply
</button>
</div>
</div>
</div>
<button type="button" data-demo-src="/demos/ocr/receipt-swiss.jpg" data-demo-lang="deu" class="ocr-demo-btn rounded-lg border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800 px-2.5 py-1.5 text-xs font-semibold text-neutral-800 dark:text-neutral-200 transition cursor-pointer">
🧾 Demo 1: Receipt
</button>
<button type="button" data-demo-src="/demos/ocr/receipt-store.jpg" data-demo-lang="eng" class="ocr-demo-btn rounded-lg border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800 px-2.5 py-1.5 text-xs font-semibold text-neutral-800 dark:text-neutral-200 transition cursor-pointer">
📸 Demo 2: Striped Receipt
</button>
<button type="button" data-demo-src="/demos/ocr/stacktrace.jpg" data-demo-lang="eng" class="ocr-demo-btn rounded-lg border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800 px-2.5 py-1.5 text-xs font-semibold text-neutral-800 dark:text-neutral-200 transition cursor-pointer">
💻 Demo 3: Dark Stack Trace
</button>
<button type="button" data-demo-src="/demos/ocr/whiteboard.jpg" data-demo-lang="eng" class="ocr-demo-btn rounded-lg border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-900 hover:bg-neutral-100 dark:hover:bg-neutral-800 px-2.5 py-1.5 text-xs font-semibold text-neutral-800 dark:text-neutral-200 transition cursor-pointer">
🖊️ Demo 4: Whiteboard
</button>
<button id="ocr-sample-btn" type="button" class="rounded-lg bg-indigo-600 hover:bg-indigo-500 px-3 py-1.5 text-xs font-semibold text-white transition cursor-pointer">
✨ Sample
</button>
</div>
</div>
<!-- Progress Bar -->
<div id="ocr-progress-wrap" class="hidden rounded-xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900 p-3 space-y-1.5">
<div class="flex items-center justify-between text-xs">
<span id="ocr-progress-label" class="font-medium text-neutral-700 dark:text-neutral-300">Loading WASM OCR engine…</span>
<span id="ocr-progress-pct" class="font-mono text-indigo-600 dark:text-indigo-400">0%</span>
</div>
<div class="h-2 w-full rounded-full bg-neutral-200 dark:bg-neutral-800 overflow-hidden">
<div id="ocr-progress-bar" class="h-full bg-indigo-600 transition-all duration-150" style="width: 0%"></div>
</div>
</div>
<!-- Main Workspace (Stacked vertically for full-width image + readable text output) -->
<div class="flex flex-col gap-5">
<!-- Top: Image Upload + Bounding Box Canvas -->
<div class="flex flex-col gap-3">
<div
id="ocr-dropzone"
class="relative flex flex-col items-center justify-center rounded-2xl border-2 border-dashed border-neutral-300 dark:border-neutral-700 bg-neutral-50/60 dark:bg-neutral-900/50 hover:border-indigo-500 dark:hover:border-indigo-400 transition min-h-[340px] p-4 overflow-hidden"
>
<input id="ocr-file-input" type="file" accept="image/*" class="hidden" />
<label id="ocr-empty-prompt" for="ocr-file-input" class="text-center space-y-2 cursor-pointer py-12 px-4 w-full">
<div class="text-4xl">📄</div>
<p class="text-sm font-semibold text-neutral-800 dark:text-neutral-200">
Drop an image here, click to browse, or press <kbd class="px-1.5 py-0.5 rounded bg-neutral-200 dark:bg-neutral-800 text-xs font-mono">Ctrl+V</kbd>
</p>
<p class="text-xs text-neutral-500 dark:text-neutral-400">
Screenshots, receipts, code snippets, or documents — stays 100% on your device.
</p>
</label>
<canvas id="ocr-canvas" class="hidden max-w-full max-h-[600px] rounded-xl shadow-sm cursor-crosshair touch-none"></canvas>
<div
id="ocr-hover-tip"
class="hidden pointer-events-none absolute z-30 rounded-lg bg-neutral-900/95 dark:bg-neutral-950/95 text-white px-2.5 py-1 text-[11px] font-mono shadow-lg border border-neutral-700 whitespace-nowrap"
></div>
</div>
<div class="flex flex-wrap items-center justify-between gap-2 text-xs text-neutral-500 dark:text-neutral-400 px-1">
<div class="flex flex-wrap items-center gap-3">
<label class="inline-flex items-center gap-2 cursor-pointer select-none">
<input id="ocr-toggle-boxes" type="checkbox" checked class="rounded border-neutral-300 text-indigo-600 focus:ring-indigo-500" />
<span>Boxes <span class="text-[10px] opacity-75">(<span class="text-emerald-600 dark:text-emerald-400">● >80%</span> <span class="text-amber-600 dark:text-amber-400">● ≤80%</span>)</span></span>
</label>
<label class="inline-flex items-center gap-1.5 cursor-pointer select-none" title="Grayscale, contrast boost, and auto-invert dark mode screenshots before OCR">
<input id="ocr-preprocess" type="checkbox" checked class="rounded border-neutral-300 text-indigo-600 focus:ring-indigo-500" />
<span>🎛️ B&W Preprocess</span>
</label>
<select
id="ocr-psm"
title="Tesseract Page Segmentation Mode (PSM)"
class="rounded-md border border-neutral-300 dark:border-neutral-700 bg-white dark:bg-neutral-950 px-2 py-0.5 text-[11px] font-mono text-neutral-700 dark:text-neutral-300"
>
<option value="3" selected>PSM: Auto (Page)</option>
<option value="11">PSM: Sparse (Signs/UI)</option>
<option value="6">PSM: Single Block (Code/Receipt)</option>
<option value="7">PSM: Single Line</option>
</select>
<label for="ocr-file-input" class="inline-flex items-center gap-1 font-medium text-indigo-600 dark:text-indigo-400 hover:underline cursor-pointer">
📁 Upload
</label>
<button id="ocr-clear-roi-btn" type="button" class="hidden rounded-md bg-indigo-50 dark:bg-indigo-950/60 border border-indigo-200 dark:border-indigo-800 px-2 py-0.5 text-[11px] font-semibold text-indigo-700 dark:text-indigo-300 hover:bg-indigo-100 dark:hover:bg-indigo-900/60 transition cursor-pointer">
✕ Clear Region
</button>
</div>
<span id="ocr-stats" class="font-mono">—</span>
</div>
</div>
<!-- Bottom: Side-by-Side Comparison (Tesseract.js WASM vs. Vision LLM) -->
<div class="grid grid-cols-1 md:grid-cols-2 gap-4">
<!-- Left: Tesseract.js WASM -->
<div class="flex flex-col rounded-2xl border border-neutral-200 dark:border-neutral-800 bg-white dark:bg-neutral-900/80 overflow-hidden">
<div class="flex items-center justify-between px-4 py-3 border-b border-neutral-200 dark:border-neutral-800 bg-neutral-50/70 dark:bg-neutral-950/60">
<span class="text-xs font-bold uppercase tracking-wider text-neutral-600 dark:text-neutral-400">
⚙️ Tesseract.js (WASM · ~4 MB)
</span>
<button id="ocr-copy-btn" type="button" class="rounded-lg bg-neutral-900 dark:bg-white text-white dark:text-neutral-900 px-3 py-1 text-xs font-semibold hover:opacity-90 transition cursor-pointer">
Copy Text
</button>
</div>
<textarea
id="ocr-output"
readonly
placeholder="Tesseract extracted text will appear here…"
class="w-full min-h-[260px] resize-y bg-transparent p-4 text-xs sm:text-sm font-mono leading-relaxed text-neutral-800 dark:text-neutral-200 focus:outline-none"
></textarea>
</div>
<!-- Right: In-Browser Vision LLM (Florence-2-base-ft) -->
<div class="flex flex-col rounded-2xl border border-indigo-200 dark:border-indigo-900/70 bg-white dark:bg-neutral-900/80 overflow-hidden">
<div class="flex flex-wrap items-center justify-between gap-2 px-4 py-2.5 border-b border-indigo-100 dark:border-indigo-900/60 bg-indigo-50/50 dark:bg-indigo-950/30">
<div class="flex items-center gap-2">
<span class="text-xs font-bold uppercase tracking-wider text-indigo-700 dark:text-indigo-300">
🧠 Vision AI (Florence-2)
</span>
<span id="vlm-stats" class="text-[11px] font-mono text-indigo-500 dark:text-indigo-400"></span>
</div>
<div class="flex flex-wrap items-center gap-2">
<label class="inline-flex items-center gap-1 text-[11px] font-medium text-indigo-700 dark:text-indigo-300 cursor-pointer select-none" title="Automatically run Florence-2 whenever an image or region is loaded (auto-enabled once cached)">
<input id="vlm-auto-run" type="checkbox" class="rounded border-indigo-300 text-indigo-600 focus:ring-indigo-500" />
<span>⚡ Auto</span>
</label>
<select id="vlm-task" class="rounded-lg border border-indigo-200 dark:border-indigo-800 bg-white dark:bg-neutral-950 px-2 py-1 text-[11px] font-mono text-indigo-700 dark:text-indigo-300">
<option value="<OCR>" selected><OCR></option>
<option value="<OCR_WITH_REGION>"><OCR_WITH_REGION></option>
<option value="<MORE_DETAILED_CAPTION>"><CAPTION></option>
</select>
<button id="vlm-run-btn" type="button" class="rounded-lg bg-indigo-600 hover:bg-indigo-500 disabled:opacity-50 px-3 py-1 text-xs font-semibold text-white transition cursor-pointer">
▶ Run Florence-2
</button>
<button id="vlm-copy-btn" type="button" class="rounded-lg border border-neutral-300 dark:border-neutral-700 px-2.5 py-1 text-xs font-semibold text-neutral-700 dark:text-neutral-200 hover:bg-neutral-100 dark:hover:bg-neutral-800 transition cursor-pointer">
Copy
</button>
</div>
</div>
<textarea
id="vlm-output"
readonly
placeholder="Click '▶ Run Florence-2' to run Microsoft's Florence-2-base-ft Vision model locally in your browser (WebGPU/WASM, ~230 MB first-time download) and compare against Tesseract…"
class="w-full min-h-[260px] resize-y bg-transparent p-4 text-xs sm:text-sm font-mono leading-relaxed text-neutral-800 dark:text-neutral-200 focus:outline-none"
></textarea>
</div>
</div>
</div>
</div>
<script>
import { languages as tesseractLanguages } from 'tesseract.js';
import {
detectScriptLangs,
preprocessCanvasForOcr,
runTesseractOcr,
type OcrRect,
type OcrWord,
} from '../lib/ocr/tesseractEngine';
import { isFlorenceLoaded, runFlorenceOcr } from '../lib/ocr/florenceEngine';
const fileInput = document.getElementById('ocr-file-input') as HTMLInputElement;
const dropzone = document.getElementById('ocr-dropzone')!;
const emptyPrompt = document.getElementById('ocr-empty-prompt')!;
const canvas = document.getElementById('ocr-canvas') as HTMLCanvasElement;
const ctx = canvas.getContext('2d')!;
const langPicker = document.getElementById('ocr-lang-picker')!;
const langBtn = document.getElementById('ocr-lang-btn')!;
const langLabel = document.getElementById('ocr-lang-label')!;
const langPanel = document.getElementById('ocr-lang-panel')!;
const autoLangCheckbox = document.getElementById('ocr-auto-lang') as HTMLInputElement;
const langSearch = document.getElementById('ocr-lang-search') as HTMLInputElement;
const langListEl = document.getElementById('ocr-lang-list')!;
const langClearBtn = document.getElementById('ocr-lang-clear')!;
const langApplyBtn = document.getElementById('ocr-lang-apply')!;
const sampleBtn = document.getElementById('ocr-sample-btn')!;
const copyBtn = document.getElementById('ocr-copy-btn')!;
const outputEl = document.getElementById('ocr-output') as HTMLTextAreaElement;
const statsEl = document.getElementById('ocr-stats')!;
const statusDot = document.getElementById('ocr-status-dot')!;
const statusText = document.getElementById('ocr-status-text')!;
const progressWrap = document.getElementById('ocr-progress-wrap')!;
const progressLabel = document.getElementById('ocr-progress-label')!;
const progressPct = document.getElementById('ocr-progress-pct')!;
const progressBar = document.getElementById('ocr-progress-bar')!;
const toggleBoxes = document.getElementById('ocr-toggle-boxes') as HTMLInputElement;
const preprocessCheckbox = document.getElementById('ocr-preprocess') as HTMLInputElement;
const psmSelect = document.getElementById('ocr-psm') as HTMLSelectElement;
const clearRoiBtn = document.getElementById('ocr-clear-roi-btn')!;
const hoverTip = document.getElementById('ocr-hover-tip')!;
const vlmRunBtn = document.getElementById('vlm-run-btn') as HTMLButtonElement;
const vlmCopyBtn = document.getElementById('vlm-copy-btn')!;
const vlmAutoEl = document.getElementById('vlm-auto-run') as HTMLInputElement;
const vlmTaskEl = document.getElementById('vlm-task') as HTMLSelectElement;
const vlmOutputEl = document.getElementById('vlm-output') as HTMLTextAreaElement;
const vlmStatsEl = document.getElementById('vlm-stats')!;
let currentImage: HTMLImageElement | null = null;
let lastWords: OcrWord[] = [];
let activeObjectUrl: string | null = null;
let currentWorkerLang = '';
let selectedLangs: string[] = ['eng'];
let autoDetectLang = false;
let pendingLangChanged = false;
let selectionRect: OcrRect | null = null;
let dragRect: OcrRect | null = null;
let dragStart: { x: number; y: number } | null = null;
function setStatus(busy: boolean, msg: string) {
statusDot.className = `h-2.5 w-2.5 rounded-full ${busy ? 'bg-amber-400 animate-pulse' : 'bg-emerald-500'}`;
statusText.textContent = msg;
}
function updateLangLabel() {
const joined = selectedLangs.join('+') || 'eng';
langLabel.textContent = autoDetectLang ? `Auto (${joined})` : joined;
}
function renderCanvas(includeOverlay = true) {
if (!currentImage) return;
canvas.width = currentImage.naturalWidth || currentImage.width;
canvas.height = currentImage.naturalHeight || currentImage.height;
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.drawImage(currentImage, 0, 0);
if (preprocessCheckbox.checked) {
preprocessCanvasForOcr(ctx, canvas.width, canvas.height);
}
if (!includeOverlay) return;
if (toggleBoxes.checked && lastWords.length > 0) {
ctx.lineWidth = Math.max(1.5, Math.round(canvas.width / 500));
for (const w of lastWords) {
const { x0, y0, x1, y1 } = w.bbox;
ctx.strokeStyle = w.confidence > 80 ? 'rgba(16, 185, 129, 0.85)' : 'rgba(245, 158, 11, 0.85)';
ctx.fillStyle = w.confidence > 80 ? 'rgba(16, 185, 129, 0.12)' : 'rgba(245, 158, 11, 0.12)';
ctx.fillRect(x0, y0, x1 - x0, y1 - y0);
ctx.strokeRect(x0, y0, x1 - x0, y1 - y0);
}
}
const activeBox = dragRect || selectionRect;
if (activeBox) {
ctx.save();
ctx.lineWidth = Math.max(2, Math.round(canvas.width / 400));
ctx.strokeStyle = 'rgba(99, 102, 241, 0.95)';
ctx.fillStyle = 'rgba(99, 102, 241, 0.14)';
ctx.setLineDash([8, 5]);
ctx.fillRect(activeBox.left, activeBox.top, activeBox.width, activeBox.height);
ctx.strokeRect(activeBox.left, activeBox.top, activeBox.width, activeBox.height);
ctx.restore();
}
}
async function runOcrOnImage(img: HTMLImageElement, roi: OcrRect | null = null) {
currentImage = img;
selectionRect = roi;
clearRoiBtn.classList.toggle('hidden', !selectionRect);
lastWords = [];
emptyPrompt.classList.add('hidden');
canvas.classList.remove('hidden');
renderCanvas(false);
progressWrap.classList.remove('hidden');
setStatus(true, selectionRect ? 'Running OCR on selected region…' : 'Running Tesseract WASM OCR locally…');
outputEl.value = '';
const t0 = performance.now();
try {
if (autoDetectLang) {
setStatus(true, 'Auto-detecting script (OSD)…');
const detected = await detectScriptLangs(canvas);
if (detected && detected.length > 0) {
selectedLangs = detected;
renderLangList(langSearch.value);
updateLangLabel();
setStatus(true, `Detected script → running ${selectedLangs.join('+')}…`);
}
}
const lang = selectedLangs.join('+') || 'eng';
currentWorkerLang = lang;
const result = await runTesseractOcr(canvas, {
lang,
psm: psmSelect.value,
rectangle: selectionRect,
onProgress: (status, pct) => {
if (status) progressLabel.textContent = status;
progressPct.textContent = `${pct}%`;
progressBar.style.width = `${pct}%`;
},
});
const elapsed = ((performance.now() - t0) / 1000).toFixed(2);
outputEl.value = result.text;
lastWords = result.words;
renderCanvas(true);
statsEl.textContent = `${lastWords.length} words · ${result.confidence}% avg conf · ${elapsed}s`;
setStatus(false, `Done in ${elapsed}s · drag on image to OCR a specific region`);
if (vlmAutoEl.checked || isFlorenceLoaded()) {
runFlorence2();
}
} catch (err: any) {
console.error('[OCR Error]', err);
renderCanvas(true);
setStatus(false, `OCR Error: ${err?.message || 'Failed'}`);
} finally {
setTimeout(() => progressWrap.classList.add('hidden'), 600);
}
}
function loadBlob(blob: Blob) {
if (activeObjectUrl) {
URL.revokeObjectURL(activeObjectUrl);
activeObjectUrl = null;
}
activeObjectUrl = URL.createObjectURL(blob);
const img = new Image();
img.onload = () => {
runOcrOnImage(img);
};
img.src = activeObjectUrl;
}
function generateSampleReceipt() {
const off = document.createElement('canvas');
off.width = 760;
off.height = 500;
const octx = off.getContext('2d')!;
octx.fillStyle = '#faf8f2';
octx.fillRect(0, 0, off.width, off.height);
octx.fillStyle = '#18181b';
octx.font = 'bold 30px monospace';
octx.fillText('MOGRABLOG COFFEE & CODE', 60, 75);
octx.font = '18px monospace';
octx.fillText('127.0.0.1 Localhost Ave, Browser Tab', 60, 110);
octx.fillText('----------------------------------------', 60, 145);
octx.fillText('1x WebAssembly Espresso $4.50', 60, 190);
octx.fillText('1x Zero-Backend Bagel $6.25', 60, 230);
octx.fillText('2x Client-Side Croissant $7.00', 60, 270);
octx.fillText('----------------------------------------', 60, 310);
octx.font = 'bold 22px monospace';
octx.fillText('TOTAL PAID (LOCAL): $17.75', 60, 355);
octx.font = '16px monospace';
octx.fillStyle = '#52525b';
octx.fillText('Invoice #2026-WASM-042 · Thank you!', 60, 415);
off.toBlob((blob) => {
if (blob) loadBlob(blob);
});
}
fileInput.addEventListener('change', () => {
const file = fileInput.files?.[0];
if (file) loadBlob(file);
});
dropzone.addEventListener('dragover', (e) => {
e.preventDefault();
dropzone.classList.add('border-indigo-500');
});
dropzone.addEventListener('dragleave', () => {
dropzone.classList.remove('border-indigo-500');
});
dropzone.addEventListener('drop', (e) => {
e.preventDefault();
dropzone.classList.remove('border-indigo-500');
const file = e.dataTransfer?.files?.[0];
if (file && file.type.startsWith('image/')) loadBlob(file);
});
window.addEventListener('paste', (e) => {
const items = e.clipboardData?.items || [];
for (const item of items) {
if (item.type.startsWith('image/')) {
const blob = item.getAsFile();
if (blob) loadBlob(blob);
break;
}
}
});
const POPULAR_CODES = ['eng', 'heb', 'spa', 'fra', 'deu', 'ara', 'rus', 'jpn', 'chi_sim', 'por', 'ita'];
let langDisplay: Intl.DisplayNames | null = null;
try { langDisplay = new Intl.DisplayNames(['en'], { type: 'language' }); } catch {}
const ALL_LANGS: Array<{ code: string; name: string }> = Object.entries(tesseractLanguages || {})
.map(([key, code]) => {
let label = key.replace(/_/g, ' ');
try {
const baseCode = String(code).split('_')[0];
const dn = langDisplay?.of(baseCode);
if (dn && dn.toLowerCase() !== baseCode.toLowerCase()) label = dn;
} catch {}
return { code: String(code), name: label };
})
.sort((a, b) => {
const ia = POPULAR_CODES.indexOf(a.code);
const ib = POPULAR_CODES.indexOf(b.code);
if (ia !== -1 && ib !== -1) return ia - ib;
if (ia !== -1) return -1;
if (ib !== -1) return 1;
return a.name.localeCompare(b.name);
});
function renderLangList(filter = '') {
const q = filter.trim().toLowerCase();
const items = ALL_LANGS.filter(
(l) => !q || l.code.toLowerCase().includes(q) || l.name.toLowerCase().includes(q)
);
langListEl.innerHTML = items.map((l) => {
const checked = selectedLangs.includes(l.code) ? 'checked' : '';
return `
<label class="flex items-center justify-between gap-2 rounded-lg px-2 py-1 hover:bg-neutral-100 dark:hover:bg-neutral-900 cursor-pointer select-none">
<span class="truncate text-neutral-800 dark:text-neutral-200">${l.name} <span class="font-mono text-[10px] text-neutral-400">(${l.code})</span></span>
<input type="checkbox" value="${l.code}" ${checked} class="ocr-lang-chk rounded border-neutral-300 text-indigo-600 focus:ring-indigo-500" />
</label>
`;
}).join('') || '<div class="px-2 py-3 text-center text-neutral-400">No matching languages</div>';
}
function persistAndApplyLang(rerun = true) {
if (selectedLangs.length === 0) selectedLangs = ['eng'];
const joined = selectedLangs.join('+');
updateLangLabel();
try {
localStorage.setItem('mograblog_ocr_lang', joined);
localStorage.setItem('mograblog_ocr_auto', String(autoDetectLang));
} catch {}
if (rerun && currentImage && (autoDetectLang || joined !== currentWorkerLang)) {
runOcrOnImage(currentImage, selectionRect);
}
}
// Restore saved preferences
try {
const savedAuto = localStorage.getItem('mograblog_ocr_auto');
if (savedAuto !== null) autoDetectLang = savedAuto === 'true';
autoLangCheckbox.checked = autoDetectLang;
const savedLang = localStorage.getItem('mograblog_ocr_lang');
if (savedLang && savedLang.trim()) {
selectedLangs = savedLang.split('+').map((s) => s.trim()).filter(Boolean);
}
const savedBoxes = localStorage.getItem('mograblog_ocr_boxes');
if (savedBoxes !== null) {
toggleBoxes.checked = savedBoxes === 'true';
}
} catch (e) {
console.warn('Failed to access localStorage:', e);
}
renderLangList();
updateLangLabel();
langBtn.addEventListener('click', (e) => {
e.stopPropagation();
const isHidden = langPanel.classList.contains('hidden');
if (isHidden) {
langPanel.classList.remove('hidden');
langSearch.focus();
} else {
langPanel.classList.add('hidden');
if (pendingLangChanged) {
pendingLangChanged = false;
persistAndApplyLang(true);
}
}
});
langPanel.addEventListener('click', (e) => e.stopPropagation());
document.addEventListener('click', (e) => {
if (!langPicker.contains(e.target as Node) && !langPanel.classList.contains('hidden')) {
langPanel.classList.add('hidden');
if (pendingLangChanged) {
pendingLangChanged = false;
persistAndApplyLang(true);
}
}
});
langSearch.addEventListener('input', () => renderLangList(langSearch.value));
langListEl.addEventListener('change', (e) => {
const chk = e.target as HTMLInputElement;
if (!chk.classList.contains('ocr-lang-chk')) return;
const code = chk.value;
if (chk.checked) {
if (!selectedLangs.includes(code)) selectedLangs.push(code);
} else {
selectedLangs = selectedLangs.filter((c) => c !== code);
}
if (selectedLangs.length === 0) selectedLangs = ['eng'];
autoDetectLang = false;
autoLangCheckbox.checked = false;
pendingLangChanged = true;
updateLangLabel();
});
autoLangCheckbox.addEventListener('change', () => {
autoDetectLang = autoLangCheckbox.checked;
pendingLangChanged = true;
updateLangLabel();
});
langClearBtn.addEventListener('click', () => {
selectedLangs = ['eng'];
autoDetectLang = false;
autoLangCheckbox.checked = false;
langSearch.value = '';
renderLangList();
pendingLangChanged = false;
langPanel.classList.add('hidden');
persistAndApplyLang(true);
});
langApplyBtn.addEventListener('click', () => {
pendingLangChanged = false;
langPanel.classList.add('hidden');
persistAndApplyLang(true);
});
sampleBtn.addEventListener('click', generateSampleReceipt);
document.querySelectorAll('.ocr-demo-btn').forEach((btn) => {
btn.addEventListener('click', () => {
const src = btn.getAttribute('data-demo-src');
const demoLang = btn.getAttribute('data-demo-lang');
if (!src) return;
if (demoLang && !autoDetectLang) {
selectedLangs = demoLang.split('+').map((s) => s.trim()).filter(Boolean);
renderLangList(langSearch.value);
updateLangLabel();
try { localStorage.setItem('mograblog_ocr_lang', selectedLangs.join('+')); } catch {}
}
setStatus(true, 'Loading demo image…');
const img = new Image();
img.onload = () => runOcrOnImage(img);
img.onerror = () => setStatus(false, 'Failed to load demo image');
img.src = src;
});
});
toggleBoxes.addEventListener('change', () => {
try { localStorage.setItem('mograblog_ocr_boxes', String(toggleBoxes.checked)); } catch {}
renderCanvas();
});
preprocessCheckbox.addEventListener('change', () => {
if (currentImage) runOcrOnImage(currentImage, selectionRect);
});
psmSelect.addEventListener('change', () => {
if (currentImage) runOcrOnImage(currentImage, selectionRect);
});
clearRoiBtn.addEventListener('click', () => {
if (currentImage) runOcrOnImage(currentImage, null);
});
function getCanvasCoords(e: PointerEvent) {
const rect = canvas.getBoundingClientRect();
const scaleX = canvas.width / (rect.width || 1);
const scaleY = canvas.height / (rect.height || 1);
return {
x: Math.max(0, Math.min(canvas.width, (e.clientX - rect.left) * scaleX)),
y: Math.max(0, Math.min(canvas.height, (e.clientY - rect.top) * scaleY)),
};
}
canvas.addEventListener('pointerdown', (e) => {
if (!currentImage || e.button !== 0) return;
hoverTip.classList.add('hidden');
canvas.setPointerCapture(e.pointerId);
dragStart = getCanvasCoords(e);
dragRect = { left: dragStart.x, top: dragStart.y, width: 0, height: 0 };
});
canvas.addEventListener('pointermove', (e) => {
if (!currentImage) return;
const pt = getCanvasCoords(e);
if (dragStart) {
dragRect = {
left: Math.round(Math.min(dragStart.x, pt.x)),
top: Math.round(Math.min(dragStart.y, pt.y)),
width: Math.round(Math.abs(pt.x - dragStart.x)),
height: Math.round(Math.abs(pt.y - dragStart.y)),
};
renderCanvas(true);
return;
}
if (!toggleBoxes.checked || lastWords.length === 0) {
hoverTip.classList.add('hidden');
return;
}
// Find tightest matching word box under cursor
let match: (typeof lastWords)[0] | null = null;
let bestArea = Infinity;
for (const w of lastWords) {
const { x0, y0, x1, y1 } = w.bbox;
if (pt.x >= x0 && pt.x <= x1 && pt.y >= y0 && pt.y <= y1) {
const area = (x1 - x0) * (y1 - y0);
if (area < bestArea) {
bestArea = area;
match = w;
}
}
}
if (match) {
const dzRect = dropzone.getBoundingClientRect();
const conf = Math.round(match.confidence);
const badgeColor = conf > 80 ? 'text-emerald-400' : 'text-amber-400';
hoverTip.innerHTML = `<span class="${badgeColor} font-bold">${conf}%</span> · ${match.text.replace(/</g, '<')}`;
hoverTip.style.left = `${Math.min(dzRect.width - 140, Math.max(8, e.clientX - dzRect.left + 12))}px`;
hoverTip.style.top = `${Math.max(8, e.clientY - dzRect.top - 32)}px`;
hoverTip.classList.remove('hidden');
} else {
hoverTip.classList.add('hidden');
}
});
canvas.addEventListener('pointerleave', () => {
hoverTip.classList.add('hidden');
});
const finishDrag = (e: PointerEvent) => {
if (!dragStart || !currentImage) return;
try { canvas.releasePointerCapture(e.pointerId); } catch {}
const finished = dragRect;
dragStart = null;
dragRect = null;
if (finished && finished.width >= 12 && finished.height >= 12) {
runOcrOnImage(currentImage, finished);
} else {
renderCanvas(true);
}
};
canvas.addEventListener('pointerup', finishDrag);
canvas.addEventListener('pointercancel', finishDrag);
copyBtn.addEventListener('click', async () => {
if (!outputEl.value) return;
await navigator.clipboard.writeText(outputEl.value);
copyBtn.textContent = 'Copied!';
setTimeout(() => (copyBtn.textContent = 'Copy Text'), 1500);
});
let vlmBusy = false;
try {
if (localStorage.getItem('mograblog_florence_cached') === '1') {
vlmAutoEl.checked = true;
}
} catch {}
vlmAutoEl.addEventListener('change', () => {
try { localStorage.setItem('mograblog_florence_cached', vlmAutoEl.checked ? '1' : '0'); } catch {}
if (vlmAutoEl.checked && currentImage && !vlmBusy) {
runFlorence2();
}
});
vlmTaskEl.addEventListener('change', () => {
if (currentImage && (vlmAutoEl.checked || isFlorenceLoaded()) && !vlmBusy) {
runFlorence2();
}
});
vlmCopyBtn.addEventListener('click', async () => {
if (!vlmOutputEl.value) return;
await navigator.clipboard.writeText(vlmOutputEl.value);
vlmCopyBtn.textContent = 'Copied!';
setTimeout(() => (vlmCopyBtn.textContent = 'Copy'), 1500);
});
async function runFlorence2() {
if (!currentImage || vlmBusy) {
if (!currentImage) vlmStatsEl.textContent = 'Load an image first';
return;
}
vlmBusy = true;
vlmRunBtn.disabled = true;
vlmOutputEl.value = '';
const t0 = performance.now();
try {
vlmOutputEl.value = await runFlorenceOcr(currentImage, {
task: vlmTaskEl.value || '<OCR>',
region: selectionRect,
onStatus: (msg) => { vlmStatsEl.textContent = msg; },
});
vlmAutoEl.checked = true;
try { localStorage.setItem('mograblog_florence_cached', '1'); } catch {}
const elapsed = ((performance.now() - t0) / 1000).toFixed(2);
vlmStatsEl.textContent = `Done in ${elapsed}s`;
} catch (err: any) {
console.error('[Florence-2 Error]', err);
vlmStatsEl.textContent = 'Error';
vlmOutputEl.value = `Florence-2 Error: ${err?.message || 'Failed to run model'}`;
} finally {
vlmBusy = false;
vlmRunBtn.disabled = false;
}
}
vlmRunBtn.addEventListener('click', runFlorence2);
</script>