Local OCR with OCRia-nano-1 (Videos, PDFs & Images)¶
Annolid integrates llamaindex/OCRia-nano-1 — an 8.1M-parameter local CPU OCR pipeline from LlamaIndex — directly through ONNX Runtime with no PyTorch, GPU, or cloud API requirement.
Pred + OCR Studio + CLI
*_annotations.ndjson
Looking for a hands-on walkthrough?
Follow the OCR Tutorial: Video Overlays, Multi-Page PDFs & Images to generate a ready-to-run demo video and hybrid PDF and walk through every GUI, CLI, and Python workflow step by step.
Architecture & Data Flow¶
flowchart LR
A["Input: Video / PDF / Image / Folder"] --> B["GUI AI Dropdown + Pred<br/>or OCR Studio / CLI / Bot"]
B --> C{"Input Type"}
C -->|"Video"| D["OcriaVideoProcessor<br/>(step + optional ocr_roi)"]
C -->|"PDF"| E["OcriaPdfProcessor<br/>(auto / ocr_only / hybrid @ 200 DPI)"]
C -->|"Image"| F["ocr_image()<br/>(8-bit, 16-bit & float TIFF)"]
D --> G["FrameResultStore (O(1) merge)<br/><stem>_annotations.ndjson"]
E --> G
D --> H["Sidecars: _ocr.csv, .srt, .json, .md"]
E --> I["Sidecars: _ocr.md, .csv, .json"]
F --> J["Editable Canvas Shapes"]
G --> K["Auto-load on Canvas & Timeline Scrub"]
What You Can OCR¶
- Video frames & overlays: Read burned-in camera timestamps, trial counters, cage IDs, arena displays, oscilloscope labels, or subtitles across sampled frames. Restrict OCR to a drawn canvas
ocr_roishape (or prompt coordinatesx1,y1,x2,y2) for speed, deduplicate unchanged consecutive frames into timeline events, jump directly to detected frames in the GUI, and export.srtcaptions,.csv,.json,.md, per-frame LabelMe.jsonfiles, or Annolid's*_annotations.ndjsonAnnotationStore. - Multi-page PDFs (born-digital, scanned & hybrid): Open PDFs directly as navigable canvas page stacks (
PdfPageStackVideoat 200 DPI) or launch OCR with one click from the PDF Viewer's OCR Pages (Annotate) button. Reuse crisp native PDF text boxes via PyMuPDF on digital pages and automatically run OCRia-nano-1 on scanned/image-only pages (auto), force ONNX OCR on every page (ocr_only), or combine both for figures/diagrams (hybrid). - Images & image folders: Detect oriented text lines and word bounding boxes on single images (
.png,.jpg,.jpeg,.tif/.tiffincluding 12-bit/16-bit & float scientific TIFFs,.webp,.bmp) or entire directories, adding editable polygons or rectangles directly onto the canvas. - Native LayoutNet tables & semantic blocks (
--layout): Optional native ONNX Runtime execution oftablenet.onnx(~17.2 MB) detects spanning-cell tables (rowspan/colspan, header rows, GFM Markdown and semantic HTML output) and classifies lines/blocks into 13 layout classes (Title,Heading,Text,List,Table,Caption,Footnote,Code,Formula,KeyValue,FigureText,PageHeader,PageFooter) on both scanned and born-digital pages — with noliteparsedependency required. - Multilingual scripts: Automatically routes lines across four specialized INT8 CTC recognizers (Latin, CJK, RTL Arabic/Hebrew with BiDi bracket mirroring and embedded LTR phrase handling, and World ~17 scripts) with automatic sideways/upside-down orientation handling, multi-column gutter splitting, adaptive small-print re-detection, and optional dense large-page tiling.
Prerequisites & Model Weights¶
Install Annolid's lightweight ONNX extra (plus pdf for PDF OCR and canvas PDF page stacks):
pip install "annolid[onnx,pdf]"
On lean annolid[gui] installs, Annolid also prompts to install the ocr / pdf runtime automatically on demand when you first invoke OCR or open a PDF.
Download and SHA-256 verify the pinned v1.0.0 ONNX weights (~13.3 MB multilingual, ~1.45 MB with --latin-only, plus optional ~17.2 MB tablenet.onnx with --with-layout):
# Full multilingual pack (Latin + CJK + RTL + World, ~13.3 MB)
annolid-run ocr download
# Multilingual + native ONNX LayoutNet (tablenet.onnx, +17.2 MB)
annolid-run ocr download --with-layout
# Compact Latin-only pack (~1.45 MB)
annolid-run ocr download --latin-only
# Verify local weights and runtimes
annolid-run ocr status --with-layout --verify
Model Storage & Offline / Air-Gapped Machines¶
- Default weight directory:
~/.annolid/models/ocria_nano_1(override withANNOLID_OCRIA_MODEL_DIRor--model-dir). - Existing LiteParse cache reuse: if you previously ran
lit models pull ocria-nano, Annolid automatically detects and reuses~/.cache/liteparse/models/ocria-nano. - Air-gapped lab workstations: Run
annolid-run ocr download --with-layouton an online machine, copy~/.annolid/models/ocria_nano_1to the offline workstation, and pass--no-download(CLI) or setANNOLID_OCRIA_MODEL_DIR=/path/to/ocria_nano_1.
GUI Workflows¶
1. Cutie-Style Video OCR from the AI Dropdown (Pred)¶
- Open a video in Annolid (File → Open Video…).
- Select
OCRia-nano-1 (ONNX OCR)from the toolbar AI Model dropdown. - (Optional) Limit OCR to a burned-in timestamp, cage ID, or counter strip:
- Draw a rectangle or polygon on the canvas and label it
ocr_roi(orocr roi/ocr-roi), or - Type pixel coordinates
x1,y1,x2,y2into the toolbar Text Prompt box. - Set the toolbar Step Size spinbox (e.g.,
1for every frame,10or30for periodic timestamp overlays). - Click the green
Predbutton — no seed label frame is required. - Live progress updates on the seekbar and slider marks just like Cutie tracking.
- Click
Stopat any time to cancel cooperatively: completed frames stay saved inAnnotationStore, and existing completed sidecars (_ocr.{csv,srt,json,md}) are not overwritten by partial runs. - When finished, the active frame reloads immediately and scrubbing or playing the video automatically loads each frame's OCR polygons, text badges, and captions. Reopening the video later reloads the saved OCR annotations automatically.
2. Cutie-Style Multi-Page PDF OCR (Canvas Page-Stack & PDF Viewer)¶
Annolid supports two seamless GUI entry points for multi-page PDFs — both store per-page OCR results in <pdf_stem>/<pdf_stem>_annotations.ndjson at 200 DPI so boxes align pixel-for-pixel with every rendered page on the canvas:
Option A: One-click from the integrated PDF Viewer¶
- Open any PDF as usual via File → Open PDF….
- In the right-side PDF Controls dock, click
OCR Pages (Annotate). - Annolid switches the PDF into Canvas Page-Stack mode, selects
OCRia-nano-1 (ONNX OCR), runs background OCR across all pages (1..N) with live progress, and lands back on the page you were reading with editable OCR bounding boxes loaded.
(If you trigger Pred with OCRia-nano-1 (ONNX OCR) selected while a PDF is open in the PDF Viewer, Annolid also detects the active PDF automatically, runs full-document OCR, and opens the annotated pages on the canvas.)
Option B: Open a PDF directly on the Canvas¶
- Choose File → Open Video… and select a
.pdffile. - Annolid opens the PDF with
PdfPageStackVideo(200 DPI, Step Size automatically set to1so no pages are skipped). - Navigate pages with the seekbar or arrow keys, optionally draw an
ocr_roiregion on any page, selectOCRia-nano-1 (ONNX OCR), and clickPred. - Born-digital pages reuse PyMuPDF's embedded text layer instantaneously (no ONNX overhead) while scanned/image-only pages automatically invoke OCRia-nano-1. Scrubbing across pages loads every page's saved OCR boxes, captions, and metadata instantly.
3. Single-Image OCR from the AI Dropdown (Pred)¶
- Open any image (
.png,.jpg,.tif/.tiff,.webp,.bmp). - Select
OCRia-nano-1 (ONNX OCR)and optionally draw anocr_roibox. - Click
Pred— recognized text polygons are added onto the canvas non-destructively (preserving manual shapes and replacing prior OCR boxes).
4. Full Workspace: OCR Studio¶
Open AI & Models → OCR Studio (OCRia-nano-1)… when you want interactive tables, LayoutNet controls, custom PDF modes (auto / ocr_only / hybrid), DPI tuning, batch image folders, or model inspection:
| Tab | Capabilities |
|---|---|
| Frame / Image | Click OCR Active Canvas or browse any image; click From Selection to crop to the selected canvas shape; toggle LayoutNet (tables) for structured table/block parsing; inspect per-line confidence, script, layout class, and bboxes; click Add OCR Boxes to Canvas. |
| Video Frames | Choose Start, End, Every N frames, and optional ROI; double-click any detected row to jump the video player to that frame; export .srt, .csv, .json, .md, per-frame LabelMe .json, or *_annotations.ndjson. |
| PDF & Batch | OCR the currently open PDF or browse any PDF / image folder with Auto, OCR Only, or Hybrid mode, custom DPI (72–600), page range, and optional LayoutNet (tables); export Markdown, Text, JSON, CSV, LabelMe JSONs, or NDJSON. |
| Models & Settings | Inspect ONNX artifacts (including tablenet.onnx), download or SHA-256 verify weights, switch between multilingual and Latin-only packs, or copy the reproducible annolid-run ocr CLI command. |
Saved Outputs & Annotation Schema¶
Running video or PDF OCR via Pred writes results into <media_stem>/ beside the source file:
| File | Produced For | Contents |
|---|---|---|
<stem>/<stem>_annotations.ndjson |
Videos & PDFs | Canonical append-only AnnotationStore with per-frame / per-page LabelMe records (auto-loaded on canvas scrub and reopen). |
<stem>/<stem>_000000000.json (optional) |
Videos & PDFs when persist_labelme_json=True |
Per-frame / per-page LabelMe JSON mirror. |
<stem>/<stem>_ocr.md |
Videos & PDFs | Combined Markdown transcript (with LayoutNet headings and GFM/HTML tables when enabled). |
<stem>/<stem>_ocr.csv |
Videos & PDFs | Flat tabular export (frame_index, page_index, timestamp_s, text, confidence, script, x1..y2, used_ocr, backend). |
<stem>/<stem>_ocr.json |
Videos & PDFs | Full structured OCRDocumentResult JSON (lines, words, polygons, tables, layout blocks, timeline events). |
<stem>/<stem>_ocr.srt |
Videos | SubRip subtitles built from deduplicated consecutive video OCR timeline spans. |
Data-Integrity Guarantees¶
- Non-destructive shape merging: Existing manual annotations and Cutie/YOLO/keypoint tracks on any frame or PDF page are preserved. Re-running OCR replaces only prior OCR shapes (
flags.ocr == trueorocr_modelpresent) so repeated runs stay idempotent. - Manual caption preservation: Existing non-empty frame captions are never overwritten by automatic OCR text.
- Full metadata round-trip: Each OCR shape stores
description(recognized text, rendered as a canvas badge),flags: {"ocr": true},ocr_text,ocr_confidence,ocr_script,ocr_model, optionalocr_layout_class, and optionalocr_words. Annolid's store-backed loader preserves all shape metadata and frame-levelotherData["ocr"]across reload. - Atomic writes & Stop safety: All JSON/text exports use atomic replacement, and stopping an in-progress run preserves already-written frames in
AnnotationStorewithout overwriting prior complete_ocr.{csv,srt,json,md}sidecars.
CLI Reference (annolid-run ocr)¶
# Inspect runtimes and SHA-256 verify local weights
annolid-run ocr status --with-layout --verify
# Download weights (add --latin-only for 1.45 MB pack, --with-layout for tablenet.onnx)
annolid-run ocr download --with-layout
# Auto-detect input kind (image, video, PDF, or directory)
annolid-run ocr run scan.pdf --layout --output scan.md
annolid-run ocr run frame.png --output frame.json --format labelme --shape-type polygon
annolid-run ocr run ./scanned_images/ --recursive --output batch.csv
# Read burned-in video timestamps from a top-left ROI every 30 frames -> SRT + NDJSON store
annolid-run ocr video session.mp4 --step 30 --roi 0,0,420,60 --output timestamps.srt
annolid-run ocr video session.mp4 --frames 0,150,300 --output session/session_annotations.ndjson --format ndjson
# Force OCRia-nano-1 + LayoutNet on a scanned PDF at 250 DPI
annolid-run ocr pdf lab_notebook_scan.pdf --pdf-mode ocr_only --layout --dpi 250 --output notebook.md
Common CLI Flags¶
| Flag | Applies To | Description |
|---|---|---|
--output, -o |
run, video, pdf |
Output path (format inferred from .md, .txt, .json, .csv, .srt, .ndjson unless --format is set). |
--format |
run, video, pdf |
Explicit export format: auto, markdown, txt, json, csv, srt, labelme, ndjson. |
--roi x1,y1,x2,y2 |
run, video, pdf |
Restrict OCR to pixel bounding box (x1, y1, x2, y2). |
--step N |
run, video |
Process every Nth frame (default 30 in CLI ocr video). |
--start-frame, --end-frame |
run, video |
Inclusive 0-based frame range (-1 = last frame). |
--frames 0,30,60 |
run, video |
Explicit comma-separated frame indices. |
--pdf-mode |
run, pdf |
auto (digital fast-path + OCR fallback), ocr_only, or hybrid. |
--dpi N |
run, pdf |
PDF render resolution (72–600, default 200). |
--start-page, --end-page, --max-pages |
run, pdf |
1-based PDF page range limits. |
--layout |
run, video, pdf |
Enable native ONNX LayoutNet (tablenet.onnx) for tables and 13 semantic layout classes. |
--tiling |
run, video, pdf |
Enable overlapping tile OCR for dense high-resolution pages. |
--latin-only |
download, run, video, pdf |
Use the compact ~1.45 MB Latin recognizer pack. |
--min-conf FLOAT |
run, video, pdf |
Filter exported LabelMe shapes below confidence threshold (0.0–1.0). |
--model-dir DIR / --no-download |
all subcommands | Pin a custom weight directory or disable automatic downloads for offline use. |
Python API¶
One-Shot Service Functions¶
from annolid.domain.ocr import OCROptions
from annolid.services.ocr_service import (
export_ocr_result,
ocr_image,
ocr_pdf,
ocr_video,
)
# 1. Single image or NumPy RGB array (with optional native LayoutNet tables/blocks)
page = ocr_image("frame.png", options=OCROptions(enable_layout=True))
print(page.markdown)
print(len(page.tables), "table(s) detected")
# 2. Video timestamps inside an ROI -> SRT + Annolid NDJSON AnnotationStore
vid_res = ocr_video("trial.mp4", step=30, roi=(0, 0, 420, 60), deduplicate=True)
export_ocr_result(vid_res, "trial_ocr.srt", fmt="srt")
export_ocr_result(
vid_res,
"trial/trial_annotations.ndjson",
fmt="ndjson",
replace_existing_ocr=True,
)
# 3. Scanned or born-digital PDF with LayoutNet tables
pdf_res = ocr_pdf(
"scanned_paper.pdf",
mode="auto",
dpi=200,
options=OCROptions(enable_layout=True),
)
export_ocr_result(pdf_res, "scanned_paper.md", fmt="markdown")
Cutie-Compatible Batch Processors (OcriaVideoProcessor & OcriaPdfProcessor)¶
Use the processor classes when you want $O(1)$ batched AnnotationStore persistence, non-destructive merging with manual/tracked shapes, progress callbacks, and cooperative cancellation:
from annolid.services.ocr_service import OcriaPdfProcessor, OcriaVideoProcessor
# Video processor -> writes trial/trial_annotations.ndjson + _ocr.{csv,srt,json,md}
vid_proc = OcriaVideoProcessor(
video_path="trial.mp4",
roi=(0, 0, 420, 60),
persist_json=False,
replace_existing_ocr=True,
)
print(vid_proc.process_video_frames(start_frame=0, end_frame=-1, step=15))
# Multi-page PDF processor -> writes paper/paper_annotations.ndjson + _ocr.{md,csv,json}
pdf_proc = OcriaPdfProcessor(
pdf_path="paper.pdf",
dpi=200,
mode="auto",
replace_existing_ocr=True,
)
print(pdf_proc.process_pdf_pages(start_frame=0, end_frame=-1, step=1))
To plug your own frame-wise or PDF-page AI model into Annolid's AI dropdown, background Pred runner, and AnnotationStore pipeline using BaseVideoFrameProcessor, BasePdfPageProcessor, and register_video_frame_model(), see Model Plugin Help.
Annolid Bot Agent Tools¶
Annolid Bot exposes workspace-sandboxed OCR tools for conversational workflows:
ocr_status: Check whether OCRia-nano-1 weights and local ONNX/PDF runtimes are installed.run_ocr: Run OCRia-nano-1 on any allowed workspace image, video, PDF, or image folder with optional ROI cropping, LayoutNet tables, and file export.extract_pdf_text(..., ocr_fallback=True): Automatically falls back to OCRia-nano-1 on scanned PDF pages with no embedded text layer.
Troubleshooting¶
| Symptom | Cause & Fix |
|---|---|
onnxruntime missing when clicking Pred |
Install with pip install "annolid[onnx]" (or accept Annolid's automatic runtime installer prompt). |
| PyMuPDF missing when opening or OCR'ing a PDF | Install with pip install "annolid[pdf]" (or pip install "annolid[onnx,pdf]"). |
PDF pages skipped when clicking Pred |
Check the toolbar Step Size spinbox (1 processes every page). Opening a .pdf via Open Video or clicking OCR Pages (Annotate) sets Step Size = 1 automatically. |
| Born-digital PDF has figures/charts with raster text that were skipped | Switch PDF mode from auto to hybrid (merges embedded PDF text with ONNX OCR on non-overlapping figure text) or ocr_only in OCR Studio or via --pdf-mode hybrid. |
| Small or dense text missed on high-resolution scans | Enable Tiling (--tiling) and/or increase --dpi (e.g., 250–300) for PDFs. |
| Video OCR is slow on long recordings | Draw an ocr_roi box around only the timestamp/label strip and increase Step Size (e.g., 15 or 30 frames). |
| Air-gapped machine cannot download Hugging Face weights | Pre-download once on an online machine with annolid-run ocr download --with-layout, transfer ~/.annolid/models/ocria_nano_1, and set ANNOLID_OCRIA_MODEL_DIR. |
Attribution & License¶
- Model weights:
llamaindex/OCRia-nano-1by LlamaIndex (OCRia-nano-1 Model License, OpenRAIL-M). - ONNX pipeline specification: aligned with LlamaIndex's Apache-2.0
run-llama/liteparsereference implementation.