@klerio-dev/kocr
v0.2.0
Published
KOCR — Vietnamese OCR SDK (PaddleOCR detection + Tesseract vie + VN correction stack), fully client-side.
Maintainers
Readme
@klerio-dev/kocr
Vietnamese OCR that runs entirely in the browser. PaddleOCR text detection
- Tesseract
vierecognition + a Vietnamese correction stack (regex/phrase rules, a syllable bigram language model, and a BiLSTM diacritic tagger), all running client-side via WebAssembly. Documents never leave the machine — there is no OCR server and no upload.
Accuracy: ~4.9% CER on a 23-page benchmark of Vietnamese government documents (a mix of scans and text PDFs).
You give the SDK a rasterized page on an HTMLCanvasElement; you get back the
detected lines with their polygons and confidences, reading-order plain text,
and markdown with tables reconstructed.
Live demo and product page: https://kocr.klerio.vn
Contents
- Requirements
- Install
- Quickstart
- License keys
- Integration
- API reference
- Assets and hosting
- Performance
- Troubleshooting
- Third-party components
- License
Requirements
- Any modern evergreen browser with WebAssembly and Web Workers. No GPU or WebGPU dependency.
- No special response headers — the pipeline runs single-threaded and needs
neither COOP/COEP nor
crossOriginIsolated. - The SDK touches the DOM: it must run in a document context, not in a Web Worker and not on a server.
- ~30 MB of models and WASM, downloaded once per browser cache — see Assets and hosting.
Install
npm i @klerio-dev/kocrThen stage the runtime assets into your public directory:
npx kocr copy-assets public/kocrThe CLI is named kocr (the bin name is unchanged by the package scope). Serve
that directory same-origin under a single prefix and pass the same prefix
as assetBase (default /kocr). Re-run copy-assets after every upgrade.
Wire it into predev/prebuild so a fresh clone or a CI build never ships
without the assets, and .gitignore the destination — it is generated output,
~30 MB of binaries.
Quickstart
import { Kocr } from "@klerio-dev/kocr";
const ocr = new Kocr();
await ocr.init({
licenseKey: "KOCR1....", // not needed on localhost — see License keys
assetBase: "/kocr", // must match the copy-assets destination
ortProxy: true, // keeps your UI responsive; recommended
onStatus: (msg) => console.log(msg),
});
const { lines, text, markdown, width, height, timings } =
await ocr.recognizePage(canvas);
console.log(text); // reading-order plain text
console.log(markdown); // headings, columns, ruled tables
console.log(lines.length, timings.totalMs);
await ocr.dispose(); // frees the WASM workersinit() is idempotent — calling it again on the same instance is safe and
cheap. recognizePage() throws if init() has not completed.
Using a framework with a server-render or prerender step? Load the SDK with
await import("@klerio-dev/kocr")from client code instead of the static import above — see Integration.
Getting a canvas
Rasterization is yours to do. Aim for roughly 200 DPI — what the pipeline is tuned for and what its accuracy figures were measured at. Lower costs accuracy; higher mostly costs detection time.
async function canvasFromImage(file: Blob): Promise<HTMLCanvasElement> {
const bitmap = await createImageBitmap(file);
const canvas = document.createElement("canvas");
canvas.width = bitmap.width;
canvas.height = bitmap.height;
canvas.getContext("2d")!.drawImage(bitmap, 0, 0);
bitmap.close();
return canvas;
}For PDFs, render with your own PDF library (for example pdfjs-dist) at a
scale that puts the page near 200 DPI — from 72 DPI PDF user space that is
about 200 / 72 ≈ 2.78 — then pass the resulting canvas.
License keys
Running the SDK on any host other than a local development host requires a
signed license key. Request one at https://klerio.vn, then pass it as
licenseKey to init().
A key is a single opaque string of the form KOCR1.<payload>.<signature>. Copy
it exactly as delivered — no whitespace, no line breaks. Most apps inject it at
build time from an environment variable their bundler exposes to client code
(for example process.env.NEXT_PUBLIC_KOCR_LICENSE); the key has to reach the
browser.
Each key is issued for a list of domains and an expiry date. init()
verifies it locally — signature, then expiry, then domain — with no network
call, no telemetry, and no license server, before any asset is fetched.
Keys are safe to ship in client bundles. By design: a key is a signed statement of "these domains, until this date". It contains no secret, unlocks nothing on a domain it does not list, and cannot be used to reach any Klerio service.
Domain matching
The SDK compares the browser's location.hostname against the domain list.
| Entry in your key | Matches | Does not match |
|---|---|---|
| example.com | example.com exactly | www.example.com, app.example.com |
| *.example.com | example.com, www.example.com, app.example.com, a.b.example.com | example.org, notexample.com |
- A wildcard entry also covers the bare apex — you do not need both.
- Matching is on the hostname only; port, protocol, and path are irrelevant.
- Preview and staging domains need covering too — if you deploy to per-branch preview URLs, ask for a wildcard that spans them.
- Adding a deployment domain requires a new key; the list is signed.
Local development
On localhost, 127.0.0.1, and [::1] the SDK skips license verification
entirely — no licenseKey is required. Anything else, including a LAN IP
such as 192.168.1.10 or a tunnel hostname, is treated as production and needs
a key that covers it.
Error codes
Failures throw a KocrLicenseError from init(), carrying a code:
import { Kocr, KocrLicenseError } from "@klerio-dev/kocr";
const ocr = new Kocr();
try {
await ocr.init({ licenseKey, assetBase: "/kocr", ortProxy: true });
} catch (err) {
if (err instanceof KocrLicenseError) {
console.error(err.code, err.message);
} else {
throw err;
}
}| code | Meaning | What to do |
|---|---|---|
| malformed | No key was supplied on a non-development host, or the string is not a readable KOCR1 key — wrong prefix, wrong number of .-separated parts, or an unreadable payload/signature. | Check that your environment variable actually reached the browser bundle (a common cause is an empty value at build time), and that the key was copied verbatim. |
| bad-signature | The key is well-formed but its signature does not verify. | The key was altered in transit — truncation, a line break, a stray quote, or a transformation by a secrets tool. Re-copy it exactly as delivered; if it still fails, ask for a reissue. |
| expired | The key's expiry date is in the past, according to the browser's clock. | Renew the license. If the key should still be valid, check the machine's system clock — verification uses the client's time. |
| domain | The key does not list the hostname the page is served from. The message names the rejected hostname. | Request a key covering it (or a wildcard), or serve the app from a licensed hostname. In local development, use localhost / 127.0.0.1 rather than a LAN IP. |
Branch on err.code; treat err.message as a human-readable string for logs.
Integration
Two setups are verified:
| Setup | ortAssets | Config needed | ortProxy | detectionWorker |
|---|---|---|---|---|
| Next.js (App Router) — full-featured path | "self-hosted" (default) | resolveAlias stubs in next.config.ts | true — recommended | not supported here |
| Vite | "bundler" | none | false — see the trade-offs | rejected by the SDK |
Two rules apply to every framework:
- Import it lazily, from client code only —
await import("@klerio-dev/kocr")inside an effect or event handler. A static top-level import breaks any server-rendered or prerendered build, because the engine dependencies execute Node-only code at module scope when evaluated on a server; lazy loading also keeps the multi-megabyte engine chunk out of your initial download. Type-only imports are erased at compile time and are always safe. - Serve the assets same-origin under the prefix you pass as
assetBase.
Next.js (App Router)
Keep one engine instance per app, initialized once:
// lib/ocr.ts — imported only from client components
import type { Kocr, KocrPageOutput } from "@klerio-dev/kocr";
type Sdk = typeof import("@klerio-dev/kocr");
let sdk: Sdk | null = null;
let enginePromise: Promise<Kocr> | null = null;
export function getEngine(onStatus?: (msg: string) => void): Promise<Kocr> {
enginePromise ??= (async () => {
sdk = await import("@klerio-dev/kocr"); // never at module scope — SSR would evaluate it
const engine = new sdk.Kocr();
await engine.init({
licenseKey: process.env.NEXT_PUBLIC_KOCR_LICENSE ?? "",
assetBase: "/kocr",
ortProxy: true,
onStatus,
});
return engine;
})().catch((err: unknown) => {
enginePromise = null; // let a retry start clean
throw err;
});
return enginePromise;
}
export async function recognize(canvas: HTMLCanvasElement): Promise<KocrPageOutput> {
return (await getEngine()).recognizePage(canvas);
}KocrLicenseError is a runtime value, so instanceof needs the module you
dynamically imported — hence the sdk reference kept above.
Bundler stubs (required)
The engine dependencies are emscripten bundles that statically reference things
a browser bundler cannot resolve. Without these aliases the app fails to compile
the moment it imports the SDK (and Next may crash while pretty-printing that
error against a 10 MB source file). Add to next.config.ts:
import type { NextConfig } from "next";
const nextConfig: NextConfig = {
turbopack: {
// The OCR SDK's engine deps are emscripten bundles that statically
// reference things a browser bundler cannot resolve. Without these
// aliases the app fails to compile the moment it imports `@klerio-dev/kocr`.
resolveAlias: {
// `@techstark/opencv-js` requires fs/path/crypto in its dead Node branch.
fs: { browser: "./stubs/empty.js" },
path: { browser: "./stubs/empty.js" },
crypto: { browser: "./stubs/empty.js" },
// ORT's wasm-locator trick inside Paddle's worker chunk:
// `new URL("ort.bundle.min.mjs", import.meta.url)` on a dead file: branch.
"ort.bundle.min.mjs": "./stubs/empty.js",
"./assets/worker-entry-C9UNuyOJ.js": "./stubs/empty.js",
},
},
};
export default nextConfig;And create stubs/empty.js next to it:
// Browser stub for Node built-ins that emscripten glue code requires inside
// its dead `ENVIRONMENT_IS_NODE` branch. Turbopack resolves those requires
// statically even though they never run in a browser.
export default {};| Alias key | Why it is needed |
|---|---|
| fs, path, crypto | The detector's OpenCV build calls require("fs" \| "path" \| "crypto") inside its dead ENVIRONMENT_IS_NODE branch. That branch never runs in a browser, but Turbopack resolves the requires statically and reports "Module not found". Scoping them to { browser: ... } leaves your server code's real modules untouched. |
| ort.bundle.min.mjs | ONNX Runtime locates its own WASM with new URL("ort.bundle.min.mjs", import.meta.url) on a dead file: branch. The SDK self-hosts its runtime from assetBase, so this reference is dead code — but it still has to resolve. |
| ./assets/worker-entry-C9UNuyOJ.js | The detector's ~11 MB worker chunk, dragged into the module graph by a new URL(..., import.meta.url) reference. Left in, it triggers the "Module not found" cascade and the crash while formatting the error. |
The last key contains a build hash. After an upgrade that moves the detector dependency, the hash can change and the stale alias silently stops matching — the symptom is a build error naming a different
./assets/worker-entry-*.jspath. Copy the new file name from the error message into the alias key.
Static export (output: "export") needs nothing extra: the SDK requires no
server runtime.
Vite
Vite is supported through ortAssets: "bundler". No vite.config changes
are needed — no aliases, no plugins, no optimizeDeps entries. Both vite
(dev) and vite build + vite preview were smoke-tested end to end, producing
full recognition (34 lines on our sample page, identical in both).
const { Kocr } = await import("@klerio-dev/kocr");
const ocr = new Kocr();
await ocr.init({
licenseKey: "KOCR1....",
assetBase: "/kocr",
ortAssets: "bundler", // required on Vite
ortProxy: false, // the default — see the caveats below
});Still run npx kocr copy-assets public/kocr and keep assetBase pointing at
it: ortAssets only changes where ONNX Runtime's own loader and WASM come
from. The default "self-hosted" pin fails on Vite because its dev server
refuses the dynamic import() of a .mjs living in public/, which surfaces
as ONNX Runtime reporting no available backend; "bundler" lets ORT resolve
those assets from node_modules instead.
Caveats:
ortProxymust stayfalse. The dev server toleratesortProxy: true, but a production build with it enabled breaks at runtime. The cost is that detection runs on the main thread — roughly 3.4 s of synchronous WebAssembly per page, which freezes the page for the duration, so recognize on an explicit user action and avoid animated indicators. See Performance.detectionWorkeris rejected.init()throws immediately if you combine it with bundler mode:kocr: detectionWorker is not supported with ortAssets: "bundler" — the detection worker would fetch onnxruntime-web from a third-party CDN at a mismatched version. Use self-hosted assets for detectionWorker.With no pinned
wasmPathsthe detector's worker path falls back to a hardcodedhttps://cdn.jsdelivr.net/npm/[email protected]/dist/URL — a third-party CDN at a mismatched version. Keep"self-hosted"if you needdetectionWorker.Bundle size: ORT's JSEP build lands in your output. Unpinned, ONNX Runtime resolves its default WebGPU-capable (JSEP) WASM — a single ~26.8 MB asset — and your bundler emits it. Hosts with a per-file size limit will reject it (Cloudflare Pages, for example, caps files at 25 MB). For those hosts the self-hosted Next.js path is the supported route, since
copy-assetsstages the smaller plain (non-JSEP) WASM. Aliasingonnxruntime-webto a plain-WASM entry point in your Vite config is an avenue you can explore; it is not verified and no recipe is documented.
Other frameworks
SvelteKit, Nuxt, Astro, and Remix build on Vite, so bundler mode is the right starting point there too — keep the dynamic import inside client-only code so the module is never evaluated during SSR or prerendering. Those stacks are not individually smoke-tested; get in touch at https://klerio.vn.
API reference
The package is ESM only, with two entry points:
| Import | Contents |
|---|---|
| @klerio-dev/kocr | Kocr, KocrInitOptions, KocrPageOutput, OcrLine, KocrLicenseError, LicenseErrorCode, plus everything below |
| @klerio-dev/kocr/serialize | serializePage, readingOrder, OcrLine, PageDims, SerializedPage — no engine code |
class Kocr
declare class Kocr {
init(opts?: KocrInitOptions): Promise<void>;
recognizePage(canvas: HTMLCanvasElement): Promise<KocrPageOutput>;
dispose(): Promise<void>;
}One instance owns one engine — a detector session and a small pool of recognition workers. Create one per application, not one per page.
init(opts?)— verifies the license (skipped on local hosts), then loads the detector, recognition workers, and correction models fromassetBase. Idempotent. Rejects with aKocrLicenseErroron any license problem before any asset is fetched; other failures reject with a plainError.recognizePage(canvas)— recognizes one page rasterized at ~200 DPI. ThrowsError("Kocr not initialized — call init() first.")ifinit()has not completed ordispose()has been called since. Not reentrant — never run two calls concurrently on one instance. The canvas is only read.dispose()— terminates the workers and releases the detector session. Call it when your OCR view unmounts;init()revives the instance.
KocrInitOptions
interface KocrInitOptions {
licenseKey?: string;
assetBase?: string;
detectionWorker?: boolean;
ortProxy?: boolean;
ortAssets?: "self-hosted" | "bundler";
onStatus?: (msg: string) => void;
}| Field | Default | Description |
|---|---|---|
| licenseKey | — | Your signed key, KOCR1.…. Required on every host except localhost, 127.0.0.1, and [::1]. |
| assetBase | "/kocr" | Same-origin URL prefix the runtime assets are served from. Must match your npx kocr copy-assets <dest> destination. No trailing slash. |
| detectionWorker | false | Runs text detection in the detector's own Worker. Requires a bundler that can resolve that worker chunk; it does not work under Next.js, and it cannot be combined with ortAssets: "bundler". Leave it at the default. |
| ortProxy | false | Runs ONNX Runtime inference in its own Worker (ort.env.wasm.proxy), so the ~3.4 s of detection per page stops freezing the host page. Set this to true on the self-hosted path; output is identical. Leave it off on Vite, where a production build with it enabled breaks at runtime. |
| ortAssets | "self-hosted" | Where ONNX Runtime's own WASM and loader assets come from. "self-hosted" pins them to ${assetBase}/ort/ort-wasm-simd-threaded.{mjs,wasm} — the layout copy-assets writes, and the required mode for Next.js/webpack. "bundler" pins nothing: ORT resolves its assets via import.meta.url and your bundler emits them from node_modules — use this on Vite-class bundlers. Only ORT resolution changes; everything else is still fetched from assetBase, so copy-assets is required either way. Cannot be combined with detectionWorker: true — init() throws. |
| onStatus | — | Called with short progress messages during init(), for example "Loading Paddle det + Tesseract vie workers…". English only, informational, not a stable API — display it verbatim or ignore it, but do not parse it. |
KocrPageOutput
interface KocrPageOutput {
lines: OcrLine[];
text: string;
markdown: string;
width: number;
height: number;
timings: { totalMs: number; detMs: number; recMs: number };
}| Field | Description |
|---|---|
| lines | Every recognized line, in detection order — not reading order. This is the array your UI should key edits against. |
| text | Plain text in reading order, one line per entry, joined with \n. Lines classified as stamp are excluded; cross-line corrections (words split across a line break) are applied. |
| markdown | The same page as markdown, built from a layout tree: headings, columns, and ruled tables rendered as \| cells \|. Only content lines appear — both stamp and signature lines are excluded. |
| width, height | Pixel dimensions of the canvas you passed in. Persist them alongside lines if you ever intend to re-serialize edited lines. |
| timings.detMs | Text detection time in milliseconds — typically the bulk of the page. |
| timings.recMs | Line recognition time in milliseconds, across the worker pool. |
| timings.totalMs | detMs + recMs. It does not include your own rasterization or the one-time init(). |
OcrLine
interface OcrLine {
poly: [number, number][];
text: string;
score: number;
kind?: "content" | "signature" | "stamp";
}| Field | Description |
|---|---|
| poly | The line's polygon in source-page pixel coordinates — the same space as width/height, so you can draw it straight onto a rendering of the page. |
| text | The recognized and corrected text for that line. |
| score | Recognition confidence, 0 to 1. Useful for highlighting low-confidence lines in a proofreading UI. |
| kind | Line classification when the pipeline could determine one: "content" (body text), "signature" (signature/administrative block), "stamp" (stamp or seal text). Absent means content. Preserve this field when passing lines back to serializePage — the ordering, filtering, and layout passes read it. |
KocrLicenseError
type LicenseErrorCode = "malformed" | "bad-signature" | "expired" | "domain";
declare class KocrLicenseError extends Error {
constructor(code: LicenseErrorCode, message: string);
code: LicenseErrorCode;
}Thrown by init() when license verification fails. See
Error codes.
@klerio-dev/kocr/serialize
import { serializePage, readingOrder, type OcrLine } from "@klerio-dev/kocr/serialize";This entry point imports none of the OCR engines — plain computation over
the lines array: no WebAssembly, no workers, no DOM. Safe to import into a
light bundle (a viewer or editor route that never runs OCR), into a Web Worker,
or on the server. Both functions are also re-exported from the main entry.
interface PageDims { width: number; height: number }
interface SerializedPage { text: string; markdown: string }
function serializePage(lines: OcrLine[], dims: PageDims): SerializedPage;
function readingOrder(lines: OcrLine[]): number[];serializePage(lines, dims)rebuilds{ text, markdown }exactly asrecognizePage()does — same reading order, stamp filtering, cross-line correction, layout-tree markdown. Use it whenever a person has edited the OCR output. Do not patch the recognizedtextstring:textis reading-order and already filtered and corrected, whilelinesis detection-order, so the two are not aligned and patching cannot be made correct. One known difference: ruled-table detection reads the page's pixels, gone by the time a user edits, sodimsdrives a projection-based fallback and table markdown on an edited page can be slightly less precise; untouched pages keep the originalmarkdownverbatim.readingOrder(lines)returns the original indices oflinesin reading order — not the lines themselves, and stamps included. It is the bridge between the two orders your UI juggles: display lines in reading order, but key every edit, removal, and selection by the original index, which is whatserializePageconsumes.
Applying user edits and re-serializing:
import { serializePage, type OcrLine } from "@klerio-dev/kocr/serialize";
interface PageState {
lines: OcrLine[]; // KocrPageOutput.lines, untouched
width: number; // KocrPageOutput.width / .height
height: number;
edits: Map<number, string>; // original line index → replacement text
removed: Set<number>; // original line indices to drop
}
function linesForExport(page: PageState): OcrLine[] {
return page.lines
.map((line, i) => {
const edited = page.edits.get(i);
// Keep poly and kind — the ordering, filtering and layout passes read them.
return edited === undefined || edited === line.text
? line
: { ...line, text: edited };
})
.filter((_, i) => !page.removed.has(i));
}
export function exportPage(page: PageState): { text: string; markdown: string } {
return serializePage(linesForExport(page), {
width: page.width,
height: page.height,
});
}Assets and hosting
npx kocr copy-assets public/kocr produces exactly this:
public/kocr/
├── models/
│ ├── PP-OCRv6_small_det_onnx_infer.tar text detector weights
│ ├── PP-OCRv6_tiny_rec_onnx_infer.tar companion model required by the detector SDK
│ ├── vi-diacritic-tagger.onnx Vietnamese diacritic corrector
│ └── vi-diacritic-tagger.json its vocabulary/config
├── lm/
│ └── vi-legal-lm.json Vietnamese syllable bigram language model
├── ort/
│ ├── ort-wasm-simd-threaded.mjs ONNX Runtime loader
│ └── ort-wasm-simd-threaded.wasm ONNX Runtime WebAssembly
├── tess/
│ ├── worker.min.js Tesseract worker script
│ └── core/ Tesseract WebAssembly core
└── tessdata/
└── vie.traineddata.gz Vietnamese recognition dataDo not rename, flatten, or reorganize anything inside the prefix — the engine
resolves every one of these paths relative to assetBase.
| Component | Approximate size |
|---|---|
| models/*.tar (both detector tars) | ~14 MB, of which the detector itself is ~9.4 MB |
| models/vi-diacritic-tagger.onnx | ~5 MB |
| lm/vi-legal-lm.json | ~2 MB |
| ort/, tess/, tessdata/ | the remainder |
| Total first-load download | ~30 MB |
Hosting requirements
- Same origin.
assetBaseis a path prefix on your own origin, not a CDN URL. A CDN in front of your origin is fine; a separate asset host is not supported. - No special headers (no COOP/COEP, no
crossOriginIsolated). - Static files only. No server runtime, no range requests, no special MIME
configuration beyond serving
.wasm,.mjs,.json,.tar, and.gzas ordinary files. Static exports and object storage both work.
Cache headers. These files are content-stable for a given version and are the bulk of the first-visit cost, so cache them hard:
Cache-Control: public, max-age=31536000, immutablecopy-assets writes the same file names for every version, so an immutable
cache can leave a returning visitor with a stale mix of old and new assets after
an upgrade. Make the prefix part of the version instead —
npx kocr copy-assets public/kocr/v2 with assetBase: "/kocr/v2" — and bump
both together. Otherwise use a shorter max-age, drop immutable, and purge
the CDN on deploy. Compression is worth enabling for the .json, .mjs, and
.wasm entries; .tar and .gz are already compressed.
With ortAssets: "bundler" the staged ort/ files go unused (your bundler
supplies ORT instead), but copy-assets is still required for everything else.
Performance
Figures below were measured in Chromium on a laptop reporting
navigator.hardwareConcurrency = 14, recognizing a 2.2 MB scanned Vietnamese
document page at ~200 DPI. Treat them as a reference point, not a guarantee.
First init() versus warm init()
| | What happens | Cost |
|---|---|---|
| Cold (empty HTTP cache) | ~30 MB downloaded from assetBase, then the detector session and worker pool are built | Dominated by the download — on the order of 30–60 s on a first visit |
| Warm (assets cached) | Same construction, assets read from the browser cache | A few seconds |
| Repeat call on the same instance | License re-verified; the engine is not rebuilt | Negligible |
Call init() when the user enters your OCR flow, not on the first
recognizePage(), and drive a progress indicator from onStatus.
Per page
| Field | Stage | Reference measurement |
|---|---|---|
| detMs | Text detection — one ONNX model over the whole page | ~3.3–3.6 s |
| recMs | Line recognition across the worker pool, plus the Vietnamese correction stack | ~0.5–0.8 s (derived by subtraction) |
| totalMs | detMs + recMs | ~4.2 s |
Budget roughly 4–9 s per page across the hardware your users actually have.
detMs is set by the page's pixel dimensions, not its text — rasterizing well
above 200 DPI buys little accuracy and costs detection time directly; recMs
scales with the number of detected lines, divided by the pool size. init()
starts a pool of Tesseract workers sized from navigator.hardwareConcurrency
(two cores left for the host page, capped at 3, minimum 1) — nothing to
configure, and no benefit in your own line-level parallelism.
Keeping the UI responsive
Detection is ~3.4 s of synchronous WebAssembly. Where it runs is the single biggest factor in how your app feels:
| Configuration | Worst main-thread task | Frames painted during a page | Outcome |
|---|---|---|---|
| ortProxy: false (default) | 3779 ms | 38 in 4.6 s | The page is frozen: no scrolling, no button feedback, no spinner animation |
| ortProxy: true | 70 ms | 244 in 4.2 s | The page stays fully interactive |
Output is identical between the two and the proxy costs nothing in wall-clock
time. Set ortProxy: true on the self-hosted path; on Vite it has to stay off
(see Integration).
One page at a time. A Kocr instance is not reentrant, and there is nothing
to gain: detection and the worker pool already saturate the cores. Drain a queue
sequentially, guarded by a flag claimed synchronously before the first await,
and record a failure on the page that caused it so one bad page does not strand
the rest.
Memory. The engine holds WebAssembly heaps for the detector plus each
recognition worker while initialized — call dispose() when the user leaves
your OCR flow. Page canvases are large (A4 at 200 DPI ≈ 1650 × 2340 px), so
rasterize one page at a time and release each canvas once recognizePage()
resolves. Persist lines plus width/height, not bitmaps:
@klerio-dev/kocr/serialize rebuilds text and markdown from lines alone.
Troubleshooting
Console warnings about "Parameter not found". During init() or
recognition the console may show Error: Parameter not found: …. The
recognition engine is configured with a set of parameters, some of which the
compiled Vietnamese runtime does not define; it logs a message for each one and
carries on with its defaults. Impact: none — these are logged, not thrown.
Ignore them.
License errors. init() rejected with a KocrLicenseError — see
Error codes.
Works on localhost, fails once deployed. Almost always code: "domain":
verification is skipped entirely on local hosts, so a missing or wrong key is
invisible until you deploy. Check the hostname named in the error, whether your
key covers it (example.com does not cover www.example.com), whether preview
domains are covered, and whether your build actually injected the key into the
deployed bundle.
Assets 404, or init() hangs. Check that copy-assets ran in the
environment that produced the deployed build; that assetBase matches the
destination exactly (no trailing slash, no stripped path segment); that the
prefix is same-origin; that no deployment step flattened directories or
excluded .wasm/.tar files; and that you re-ran copy-assets after
upgrading.
no available backend found on Vite. ONNX Runtime is being pinned to the
self-hosted copy, which is the wrong mode for Vite — pass
ortAssets: "bundler" and leave ortProxy off. See Vite.
Next.js build failures (Module not found: Can't resolve 'fs', a
worker-entry-*.js path, or the dev server exiting with
RangeError: Maximum call stack size exceeded) — add the resolveAlias stub
block, see Bundler stubs.
Server-side crash or prerender failure — a static top-level import in a module the server renders. Import the SDK lazily from client code only.
Kocr not initialized — call init() first. — recognizePage() ran before
init() resolved, or after dispose(). Await the same init() promise in
every path that recognizes a page.
Blank or missing results. An empty lines array means the detector found
no text: usually a blank canvas (rasterization resolved before the page was
drawn), a resolution far below ~200 DPI, or a page with no text. If text is
empty but lines exist, check lines[i].kind — stamp lines are excluded from
text, and markdown additionally excludes signature lines; the raw lines
array always contains everything.
Still stuck? Collect the error code and message, the onStatus messages
leading up to it, the failing request URL if any, and your browser version, and
get in touch at https://klerio.vn.
Third-party components
This package redistributes tesseract.js, PaddleOCR (JS SDK + PP-OCRv6 models),
onnxruntime-web, and @tesseract.js-data/vie. See THIRD_PARTY_NOTICES.md in
the package for the full component/license table and license texts.
License
Commercial. See the LICENSE file in the package. Production use requires a
license key — request one at https://klerio.vn.
