OCR Tutorial: Video Overlays, Multi-Page PDFs & Images with OCRia-nano-1¶
This hands-on tutorial walks you through Annolid's local CPU OCR workflow powered by llamaindex/OCRia-nano-1 — from generating a sample lab video and hybrid digital/scanned PDF, to running Cutie-style one-click Pred OCR on videos and PDFs, inspecting auto-loaded annotations on the canvas, extracting structured tables with LayoutNet, running reproducible CLI/Python pipelines, and registering your own custom AI models in the same pipeline.
Pred
AnnotationStore workflow
Prerequisites¶
Install the optional ONNX and PDF extras in your Annolid environment:
pip install "annolid[onnx,pdf]"
Pre-download and SHA-256 verify the pinned OCRia-nano-1 ONNX weights (plus optional LayoutNet for tables and semantic headings):
annolid-run ocr download --with-layout
annolid-run ocr status --with-layout --verify
Automatic first-run download
If you skip annolid-run ocr download, Annolid automatically downloads and verifies the ONNX weights on your first GUI or CLI OCR run (unless --no-download is passed). For compact English/Latin-only setups (~1.45 MB instead of ~13.3 MB), add --latin-only.
Step 1: Generate Sample Demo Files (Optional)¶
If you already have a lab video with burned-in timestamps or a scanned/digital PDF, jump straight to Step 2. Otherwise, run this short snippet to create a synthetic 3-second video (trial_demo.mp4) and a 3-page hybrid PDF (protocol_demo.pdf — born-digital page 1, raster-scanned page 2, born-digital page 3) under /tmp/annolid_ocr_demo:
from pathlib import Path
import cv2
import fitz
import numpy as np
out = Path("/tmp/annolid_ocr_demo")
out.mkdir(parents=True, exist_ok=True)
# 1. Synthetic 3-second (30-frame, 10 FPS) video with a top-left burned-in timestamp & trial ID
vid_path = out / "trial_demo.mp4"
writer = cv2.VideoWriter(str(vid_path), cv2.VideoWriter_fourcc(*"mp4v"), 10.0, (640, 360))
for i in range(30):
frame = np.full((360, 640, 3), 235, dtype=np.uint8)
# Dark header strip simulating a camera overlay
cv2.rectangle(frame, (0, 0), (340, 48), (20, 20, 20), -1)
cv2.putText(
frame,
f"TRIAL 04 00:00:{i // 10:02d}.{i % 10}",
(12, 33),
cv2.FONT_HERSHEY_SIMPLEX,
0.75,
(255, 255, 255),
2,
cv2.LINE_AA,
)
# Moving dark ellipse simulating an animal in the arena
cx = 160 + i * 10
cv2.ellipse(frame, (cx, 220), (36, 18), 0, 0, 360, (55, 55, 55), -1)
writer.write(frame)
writer.release()
# 2. Synthetic 3-page hybrid PDF (digital page 1, image-only scanned page 2, digital page 3)
pdf_path = out / "protocol_demo.pdf"
doc = fitz.open()
p0 = doc.new_page(width=540, height=360)
p0.insert_text((36, 56), "BEHAVIORAL ASSAY PROTOCOL — COHORT B", fontsize=15)
p0.insert_text((36, 98), "Subject ID: Mouse 42 | Session: Day 3 | Arena: Open Field", fontsize=11)
p1 = doc.new_page(width=540, height=360)
scan = np.full((400, 600, 3), 248, dtype=np.uint8)
cv2.putText(scan, "SCANNED LAB LOG: PAGE 2", (40, 110), cv2.FONT_HERSHEY_SIMPLEX, 1.0, (15, 15, 15), 2, cv2.LINE_AA)
cv2.putText(scan, "Dose: 2.5 mg/kg Temp: 22.4 C", (40, 190), cv2.FONT_HERSHEY_SIMPLEX, 0.9, (25, 25, 25), 2, cv2.LINE_AA)
ok, png_buf = cv2.imencode(".png", scan)
assert ok
p1.insert_image(fitz.Rect(20, 20, 520, 340), stream=png_buf.tobytes())
p2 = doc.new_page(width=540, height=360)
p2.insert_text((36, 64), "SUMMARY TABLE — TRIAL DURATIONS", fontsize=14)
p2.insert_text((36, 108), "Mouse 42: 184.2 s center exploration, 12 grooming bouts.", fontsize=11)
doc.save(str(pdf_path))
doc.close()
print("Created:", vid_path, "and", pdf_path)
Step 2: Cutie-Style Video OCR from the AI Dropdown¶
Video OCR works just like Cutie tracking — except you do not need a seed frame.
- Launch Annolid (
annolid) and open/tmp/annolid_ocr_demo/trial_demo.mp4(File → Open Video…). - In the main toolbar AI Model dropdown, select
OCRia-nano-1 (ONNX OCR). - (Optional, recommended for speed) Draw a rectangle around the top-left timestamp banner (
0,0,340,48) and label itocr_roi. - Alternatively, leave no
ocr_roishape on the canvas and type0,0,340,48in the toolbar Text Prompt box. - If you already labeled an animal polygon (e.g.,
mouse_1) or ran Cutie tracking on the same video, leave those shapes right where they are — OCR merges non-destructively and never erases your manual or tracked shapes. - Set Step Size in the toolbar to
5(or1to read every single frame). - Click the green
Predbutton. - Watch the progress bar and green predicted-frame markers fill across the seekbar.
- Clicking
Stopcancels cooperatively after the active frame while keeping all completed frames saved. - When the OCR Complete summary appears:
- The current frame reloads immediately showing the recognized polygon box and readable text badge (
TRIAL 04 00:00:00.0). - Scrub or play the video: every processed frame automatically loads its OCR shapes and caption from
trial_demo/trial_demo_annotations.ndjson. - Inspect the companion exports generated automatically inside
/tmp/annolid_ocr_demo/trial_demo/:trial_demo_annotations.ndjson(reloads automatically next time you open the video)trial_demo_ocr.srt(deduplicated SubRip timestamp captions)trial_demo_ocr.csv(one row per detected line with frame index, timestamp, confidence, and bbox)trial_demo_ocr.jsonandtrial_demo_ocr.md
Re-running OCR safely
If you adjust your ocr_roi or Step Size and click Pred again, Annolid replaces only previous OCR shapes (flags.ocr == true) while keeping your manual shapes, Cutie masks, and manually edited frame captions intact.
Step 3: Multi-Page PDF OCR (Two GUI Entry Points)¶
Annolid gives you two fast ways to OCR a multi-page PDF and inspect or edit every detected text box directly on the canvas.
Workflow A: One-Click from the PDF Viewer (Recommended for Reading + OCR)¶
- Choose File → Open PDF… and open
/tmp/annolid_ocr_demo/protocol_demo.pdf. - Browse the document normally in Annolid's PDF viewer (for example, flip to Page 2, the scanned page).
- In the right-side PDF Controls dock, click
OCR Pages (Annotate). - Annolid automatically:
- Closes the PDF viewer docks and opens
protocol_demo.pdfon the main canvas as a 200 DPI page stack (Step Size = 1), - Selects
OCRia-nano-1 (ONNX OCR)in the AI dropdown, - Runs background OCR across all pages (
Page 1andPage 3use PyMuPDF's instant born-digital text layer;Page 2runs OCRia-nano-1 ONNX automatically), - Saves per-page annotations to
protocol_demo/protocol_demo_annotations.ndjsonplusprotocol_demo_ocr.{md,csv,json}, and - Reloads Page 2 (the page you were reading) with editable OCR boxes displayed pixel-aligned over the scanned text.
- Use the seekbar or arrow keys to step across Pages 1, 2, and 3 — every page's OCR polygons and captions load automatically.
Workflow B: Open a PDF Directly on the Canvas¶
- Choose File → Open Video… and pick any
.pdffile (such asprotocol_demo.pdf). - Annolid loads the PDF directly via
PdfPageStackVideo(200 DPI,Step Size = 1). - (Optional) Draw an
ocr_roibox on a page to OCR only a header, form field, or table area. - Select
OCRia-nano-1 (ONNX OCR)in the AI dropdown and clickPred. - Edit any OCR box or description on the canvas and save (
Ctrl+S), or close and reopen the PDF later — your annotations reload automatically from<pdf_stem>_annotations.ndjson.
Step 4: Structured Tables & Batch Folders with OCR Studio¶
When you need LayoutNet table extraction (rowspan/colspan, Markdown/HTML tables, 13 semantic layout classes), custom DPI (72–600), forced OCR Only / Hybrid PDF modes, or batch image folders, open AI & Models → OCR Studio (OCRia-nano-1)…:
- Single frame or scanned image with tables:
- Open the Frame / Image tab.
- Click OCR Active Canvas (or Browse Image…), check LayoutNet (tables), and click Run.
- Switch between Formatted Markdown (headings + tables) and Detected Lines (confidence, script, layout class, bbox).
- Click Add OCR Boxes to Canvas to turn recognized lines into editable LabelMe polygons.
- Scanned PDFs or mixed figure pages:
- Open the PDF & Batch tab.
- Select your PDF (or an entire folder of scanned images).
- Choose PDF Mode:
Auto: fast digital extraction + automatic ONNX OCR on scanned pages.OCR Only: render every page at your chosen DPI and run OCRia-nano-1.Hybrid: keep digital PDF text and run OCRia-nano-1 on embedded raster figures/diagrams without duplicating overlapping lines.
- Toggle LayoutNet (tables) if the document contains tables or multi-section reports.
- Click Run and export to Markdown (
.md), CSV (.csv), JSON (.json), LabelMe JSONs, or*_annotations.ndjson. - Copy reproducible CLI commands:
- On the Models & Settings tab (or after any run), copy the equivalent
annolid-run ocr ...command to repeat the exact job on a cluster or in a script.
Step 5: Reproducible CLI, Python & Annolid Bot Workflows¶
Headless CLI (annolid-run ocr)¶
# 1. Video timestamp ROI -> SRT subtitles + Annolid NDJSON AnnotationStore
annolid-run ocr video /tmp/annolid_ocr_demo/trial_demo.mp4 \
--step 5 \
--roi 0,0,340,48 \
--output /tmp/annolid_ocr_demo/trial_demo/trial_demo_ocr.srt
annolid-run ocr video /tmp/annolid_ocr_demo/trial_demo.mp4 \
--step 5 \
--roi 0,0,340,48 \
--format ndjson \
--output /tmp/annolid_ocr_demo/trial_demo/trial_demo_annotations.ndjson
# 2. Hybrid PDF with LayoutNet tables -> Markdown
annolid-run ocr pdf /tmp/annolid_ocr_demo/protocol_demo.pdf \
--pdf-mode auto \
--dpi 200 \
--layout \
--output /tmp/annolid_ocr_demo/protocol_demo.md
Python Script (OcriaVideoProcessor & OcriaPdfProcessor)¶
from annolid.services.ocr_service import OcriaPdfProcessor, OcriaVideoProcessor
# Run Cutie-style video OCR with O(1) non-destructive AnnotationStore persistence
vid_proc = OcriaVideoProcessor(
video_path="/tmp/annolid_ocr_demo/trial_demo.mp4",
roi=(0, 0, 340, 48),
replace_existing_ocr=True,
)
print(vid_proc.process_video_frames(start_frame=0, end_frame=-1, step=5))
print("Outputs:", vid_proc.last_output_paths)
# Run Cutie-style PDF OCR at 200 DPI (aligned with PdfPageStackVideo)
pdf_proc = OcriaPdfProcessor(
pdf_path="/tmp/annolid_ocr_demo/protocol_demo.pdf",
dpi=200,
mode="auto",
replace_existing_ocr=True,
)
print(pdf_proc.process_pdf_pages(start_frame=0, end_frame=-1, step=1))
print(
f"Digital pages: {pdf_proc.last_digital_pages}, "
f"OCR pages: {pdf_proc.last_ocr_pages}, "
f"Total lines: {pdf_proc.last_total_lines}"
)
Annolid Bot Prompts¶
Inside the Annolid Bot dock, you can also run OCR conversationally on files in your workspace:
- "Check OCRia-nano-1 status and tell me if LayoutNet is installed."
- "Run OCR on
trial_demo.mp4every 15 frames inside ROI0,0,340,48and export SRT captions." - "Extract text from
protocol_demo.pdfwith OCR fallback and summarize the dosing parameters."
Step 6 (Developers): Adding a New AI Model Using the Same Pipeline¶
The OCR integration is built on Annolid's pluggable model registration and frame-result architecture. You can register a new frame-wise video or multi-page PDF AI model — with AI dropdown presence, background Pred execution, Cutie-style AnnotationStore saving/reloading, and cooperative Stop — in one call without modifying core GUI mixins:
from annolid.gui.models_registry import ModelConfig
from annolid.gui.prediction_adapters import register_video_frame_model
from annolid.services.frame_results import BaseVideoFrameProcessor, FramePredictionOutput
class BrightSpotDetector(BaseVideoFrameProcessor):
def infer_frame(self, frame_rgb, *, frame_index, timestamp_s, fps):
# Return canonical LabelMe shape dicts; FrameResultStore handles O(1)
# non-destructive merging into <video_stem>_annotations.ndjson.
return FramePredictionOutput(
shapes=[
{
"label": "roi_marker",
"points": [[10.0, 10.0], [60.0, 60.0]],
"shape_type": "rectangle",
"flags": {"bright_spot": True},
"confidence": 0.98,
}
],
caption=f"Detected at {timestamp_s:.2f}s",
)
register_video_frame_model(
ModelConfig(
display_name="Bright Spot Detector",
identifier="bright_spot_detector",
weight_file="bright_spot_v1.onnx",
family="bright_spot",
category="Custom models",
recommended=True,
requires_seed_shapes=False,
supports_video=True,
),
processor_factory=lambda ctx: BrightSpotDetector(
video_path=str(ctx.video_file),
results_folder=ctx.video_results_folder,
persist_json=ctx.persist_json,
replace_predicate=lambda s: bool((s.get("flags") or {}).get("bright_spot")),
),
replace=True,
)
For multi-page PDF models, subclass annolid.services.frame_results.BasePdfPageProcessor (implementing infer_page(...)) and return it from processor_factory when ctx.is_pdf_target() is True.
Next Steps¶
- Local OCR Reference (
OCRia-nano-1) — full flag reference, schema details, and troubleshooting. - Model Plugin Help — CLI and GUI plugin registration contracts.
- Workflows Overview — combining OCR overlays with Cutie tracking, Behavior Timeline, and Zone Analysis.