Metadata-Version: 2.4
Name: rust_ocr_transformer
Version: 0.3.0
Classifier: Programming Language :: Rust
Classifier: Programming Language :: Python :: 3
Classifier: License :: OSI Approved :: Apache Software License
Classifier: Topic :: Multimedia :: Video
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
License-File: LICENSE
Summary: Pure-Rust OCR pipeline for images and video: resident ONNX models, SSIM frame sampling, temporal dedup, timestamped text and SRT for RAG ingestion.
Keywords: ocr,video,subtitle,rag,vector-db,onnx
Author: rust_ocr_transformer contributors
License: Apache-2.0
Requires-Python: >=3.9
Description-Content-Type: text/markdown; charset=UTF-8; variant=GFM
Project-URL: Repository, https://github.com/arabangoo/rust_ocr_transformer

# rust_ocr_transformer

> **A unified vision inference and processing framework, written in Rust.**
>
> It streams images and video through `decode -> preprocess -> neural-network inference -> postprocess -> structured output`.
> It is an orchestration layer where per-task models (text detection/recognition, classification, object detection, layout, segmentation) plug in behind traits and swap out freely. The default inference runs on **pure Rust (`tract`), zero FFI, CPU**.

This document is the **developer manual** for the library. It covers the design principles, the public API, per-task behavior and maturity, CLI and Python usage, model preparation, service integration, how to add a new task or backend, and the build and test workflow.

**Key references**

1. DBNet: Real-time Scene Text Detection with Differentiable Binarization (text detection + DB post-processing) - https://arxiv.org/abs/1911.08947
2. CRNN: An End-to-End Trainable Neural Network for Image-based Sequence Recognition (CNN+RNN+CTC sequence recognition) - https://arxiv.org/abs/1507.05717
3. SVTR: Scene Text Recognition with a Single Visual Model (PP-OCRv5 recognition backbone) - https://arxiv.org/abs/2205.00159
4. PP-OCR: A Practical Ultra Lightweight OCR System (the lightweight OCR model family embedded here) - https://arxiv.org/abs/2009.09941
5. Image Quality Assessment: From Error Visibility to Structural Similarity (SSIM, the video frame-sampling gate) - https://ece.uwaterloo.ca/~z70wang/research/ssim/

---

## Table of Contents

1. [Key Features](#1-key-features)
2. [Quick Start](#2-quick-start)
3. [Installation and Cargo Features](#3-installation-and-cargo-features)
4. [Architecture](#4-architecture)
5. [Common Type Reference](#5-common-type-reference)
6. [Public API Reference](#6-public-api-reference)
7. [Per-Task Behavior and Maturity](#7-per-task-behavior-and-maturity)
8. [Video Timeline Processing](#8-video-timeline-processing)
9. [CLI Tool (`roct`)](#9-cli-tool-roct)
10. [Python Bindings (PyO3)](#10-python-bindings-pyo3)
11. [Model Preparation (ONNX Models and Dictionaries)](#11-model-preparation-onnx-models-and-dictionaries)
12. [Embedding into a Service Pipeline](#12-embedding-into-a-service-pipeline)
13. [Adding a New Task or Backend](#13-adding-a-new-task-or-backend)
14. [Build, Feature Combinations, and Testing](#14-build-feature-combinations-and-testing)
15. [Directory Layout](#15-directory-layout)
16. [License](#16-license)
17. [Changelog](#17-changelog)

---

## 1. Key Features

The underrated part of a vision pipeline is **pre/post-processing and orchestration**. No matter how good the model is, results collapse when input normalization, detection post-processing, or decoding conventions are off. This library is not a single do-everything model; it aims to be the **framework** that owns the systems engineering above and below the model.

| Principle | What it means |
|---|---|
| **Plug the model in, don't bake it in** | The "intelligence" belongs to the model behind the trait. The framework handles decode, preprocessing, post-processing, and assembly. Same input, same model, same result (deterministic). |
| **Task-level abstraction** | Text detection/recognition, classification, object detection, layout, and segmentation are each separated behind their own trait. A new model plugs in by implementing a single trait. |
| **Pure Rust by default, zero FFI** | The default inference engine is `tract` (a pure-Rust ONNX runtime). No C++ ONNX Runtime, CUDA, or subprocess. A CPU single binary and a clean abi3 wheel. When you need speed or GPU, add `ort` as an opt-in. |
| **Video as a first-class citizen** | A still image is the degenerate case of a video with one frame. The same pipeline takes both, and video adds SSIM sampling and timeline merging. |

### "Understanding" lives outside the core

What this framework produces is **structured vision results**, up to "what is where" (text, boxes, classes, coordinates). **Understanding and reasoning**, such as "interpret this receipt as JSON" or "assess the damaged area in this accident photo", belong to large VLMs/LLMs. That work is delegated outside the core (to a server, for example), and this framework produces its input. For pure character recognition, small specialized models are more accurate, deterministic, and cheaper than frontier LLMs, so the core is kept LLM-free.

---

## 2. Quick Start

### Rust library (OCR)

```rust
use rust_ocr_transformer::OcrSession;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Load the models once. The session validates the dictionary against the model
    // and reuses the loaded models for every image you pass in.
    let session = OcrSession::new("models/det.onnx", "models/rec.onnx", "models/dict.txt")?;

    for path in ["page1.png", "page2.png"] {
        let out = session.recognize_path(path, /* auto_rotate */ false)?;
        for r in &out.regions {
            println!("[{:.2}] ({},{}) {}", r.confidence, r.bbox.x, r.bbox.y, r.text);
        }
    }
    Ok(())
}
```

If you need full control over each stage, compose the task traits yourself with `OcrEngine::new(detector, recognizer)` ([section 6.2](#62-ocrengine-composing-the-ocr-task)). See [section 11](#11-model-preparation-onnx-models-and-dictionaries) for how to obtain the model and dictionary files.

### CLI

```bash
cargo build --release --features cli
./target/release/roct image page1.png page2.png \
  --det-model models/det.onnx --rec-model models/rec.onnx --dict models/dict.txt
```

### Python

```python
import json
import rust_ocr_transformer as roct

# Load the models once, then reuse the session for many images
session = roct.OcrSession("models/det.onnx", "models/rec.onnx", "models/dict.txt")
for r in json.loads(session.recognize("page.png")):
    print(r["confidence"], r["text"])
```

---

## 3. Installation and Cargo Features

`Cargo.toml`:

```toml
[dependencies]
rust_ocr_transformer = { git = "https://github.com/arabangoo/rust_ocr_transformer", tag = "v0.3.0" }
```

### Feature list

| Feature | Enables | Notes |
|---|---|---|
| **`tract`** | pure-Rust ONNX inference backend | on by default. No C++ FFI. `tract-onnx` |
| `video` | video decode (Phase 2) | `ffmpeg-next`. Placeholder only for now, not yet implemented |
| **`cli`** | the `roct` binary | `clap`. An opt-in that does not leak to library consumers. |
| **`python`** | PyO3 cdylib bindings | `pyo3` (abi3) |

```toml
# default = ["tract"]  # pure-Rust recognition backend, zero FFI

# core IP only (types, traits, sampling, merging, pre/post-processing); inject the backend yourself
rust_ocr_transformer = { version = "0.1", default-features = false }
```

> The default (`tract`) build requires no external `.so/.dll` and no subprocess. If speed or GPU becomes the bottleneck, the plan is to add an `ort` (ONNX Runtime, C++ FFI) backend behind the same trait as an opt-in feature (not yet implemented; we do not create dead features up front).

---

## 4. Architecture

```text
decode -> preprocess -> task model (trait) -> postprocess -> structured output
 Frame    preprocess    tasks::*             postprocess    FrameAnalysis
                        (model plug point)                  + SRT/JSON/plaintext
```

The heart of it is the **task-trait layer**. Each task (detection, recognition, classification, object detection, layout, segmentation) takes a common [`Frame`](#5-common-type-reference) as input and produces a per-task result type. The model enters as an implementation of that trait, so the core pipeline assembles purely at the task level without knowing which model is used.

- **Decode**: an image/video becomes a [`Frame`](#5-common-type-reference). An image is a one-frame video.
- **Preprocess**: [`preprocess`](#63-preprocessing-preprocess): letterbox resize, normalization, NCHW tensorization. Reused across tasks.
- **Inference**: the model behind a [`tasks`](#61-task-traits) trait ([`backends::tract`](#133-the-tract-backend-reference)).
- **Postprocess**: [`postprocess`](#64-postprocessing-postprocess): non-maximum suppression (NMS), softmax, connectionist temporal classification (CTC) decoding, DB boxes.
- **Output**: [`FrameAnalysis`](#5-common-type-reference) gathers results from multiple tasks, and video is emitted as [SRT/JSON](#8-video-timeline-processing).

---

## 5. Common Type Reference

The `types` module. Result types implement `serde::{Serialize, Deserialize}`, so they can be dumped straight to JSON.

```rust
/// One pipeline unit. An image is the degenerate case of a video with a single frame.
pub struct Frame {
    pub image:     image::DynamicImage,
    pub index:     u64,        // frame index within the video (0 for an image)
    pub timestamp: Timestamp,  // presentation time in ms (0 for an image)
}
// Frame::from_path(p) / Frame::from_image(img) / Frame::new(img, index, ts)

/// Rectangular region in pixel coordinates (origin at top-left).
pub struct BBox { pub x: u32, pub y: u32, pub width: u32, pub height: u32 }
```

### Per-task result types

```rust
pub struct TextBox     { pub bbox: BBox, pub confidence: f32 }                  // detection
pub struct Crop        { pub image: image::DynamicImage, pub bbox: BBox }       // between detection and recognition
pub struct Recognized  { pub text: String, pub confidence: f32, pub bbox: BBox }// recognition
pub struct Detection   { pub bbox: BBox, pub label: String, pub score: f32 }    // object detection
pub struct Classification { pub label: String, pub score: f32 }                 // classification
pub struct LayoutRegion { pub bbox: BBox, pub kind: String, pub score: f32 }    // layout
pub struct Mask        { pub width: u32, pub height: u32, pub classes: Vec<u8> }// segmentation

/// One image's OCR result from OcrSession. Boxes are always in the ORIGINAL image's
/// coordinates, even when the image was rotated before reading.
pub struct OcrOutput {
    pub rotation: u32,             // degrees the image was rotated clockwise before reading (0/90/180/270)
    pub width:    u32,             // original image width
    pub height:   u32,             // original image height
    pub regions:  Vec<Recognized>, // in reading order
}

/// Combined analysis of one frame: a structured-output container that gathers multiple task outputs.
pub struct FrameAnalysis {
    pub recognized:      Vec<Recognized>,
    pub detections:      Vec<Detection>,
    pub classifications: Vec<Classification>,
    pub layout:          Vec<LayoutRegion>,
}
```

### Video timeline types

```rust
pub struct Timestamp(pub u64);   // milliseconds. to_srt() -> "HH:MM:SS,mmm"
pub struct Segment { pub start: Timestamp, pub end: Timestamp, pub text: String }
```

---

## 6. Public API Reference

### 6.1 Task Traits

The `tasks` module. This is where models plug in. All are `Send + Sync` (shareable across threads).

```rust
pub trait TextDetector:   Send + Sync { fn detect(&self, frame: &Frame) -> Result<Vec<TextBox>>; }
pub trait TextRecognizer: Send + Sync { fn recognize(&self, crops: &[Crop]) -> Result<Vec<Recognized>>; }
pub trait ObjectDetector: Send + Sync { fn detect_objects(&self, frame: &Frame) -> Result<Vec<Detection>>; }
pub trait Classifier:     Send + Sync { fn classify(&self, frame: &Frame) -> Result<Vec<Classification>>; }
pub trait LayoutAnalyzer: Send + Sync { fn analyze_layout(&self, frame: &Frame) -> Result<Vec<LayoutRegion>>; }
pub trait Segmenter:      Send + Sync { fn segment(&self, frame: &Frame) -> Result<Mask>; }
```

### 6.2 OcrEngine: composing the OCR task

An OCR pipeline that composes a detector and a recognizer. Other tasks are assembled directly through their own traits.

```rust
OcrEngine::new(detector: D, recognizer: R) -> OcrEngine<D, R>   // D: TextDetector, R: TextRecognizer
fn read(&self, frame: &Frame) -> Result<Vec<Recognized>>        // detect -> crop -> recognize
fn detector(&self) -> &D
fn recognizer(&self) -> &R

// helper: crop the frame by detection boxes into a list of Crops
crop_regions(frame: &Frame, boxes: &[TextBox]) -> Vec<Crop>
```

### 6.3 Preprocessing (`preprocess`)

Task-agnostic reusable functions that turn an image into a model input tensor (NCHW f32).

```rust
pub const IMAGENET_MEAN: [f32; 3];  // [0.485, 0.456, 0.406]
pub const IMAGENET_STD:  [f32; 3];  // [0.229, 0.224, 0.225]

// letterbox (keep aspect ratio + pad) + per-channel normalization -> (data[3*h*w], scale). scale maps boxes back.
fn letterbox_chw(img: &DynamicImage, in_h: usize, in_w: usize, mean: [f32;3], std: [f32;3]) -> (Vec<f32>, f32)

// fixed height, keep aspect ratio, right-pad width with 0, normalize to [-1,1] -> NCHW (for text recognition)
fn fixed_height_chw(img: &DynamicImage, in_h: usize, in_w: usize) -> Vec<f32>

// force square/fixed-size resize (ignore aspect ratio) + per-channel normalization -> NCHW (for global-structure models like classification / orientation)
fn resize_chw(img: &DynamicImage, in_h: usize, in_w: usize, mean: [f32;3], std: [f32;3]) -> Vec<f32>

// the same three functions with an explicit channel order: letterbox_chw_ordered,
// resize_chw_ordered, fixed_height_chw_ordered (last argument: ChannelOrder::Rgb | ChannelOrder::Bgr)
pub enum ChannelOrder { Rgb, Bgr }

// width a crop gets when resized to height in_h with its aspect ratio kept (used to pick the recognizer width)
fn aspect_width(img_w: u32, img_h: u32, in_h: usize) -> usize
```

The unsuffixed functions keep RGB order for backward compatibility. The PaddleOCR backends use BGR, which is the order PaddleOCR models are trained and served with (OpenCV decoding).

`fixed_height_chw` never clips: when the aspect-preserving width exceeds `in_w`, the line is **squeezed horizontally**. Strong squeezing smears glyphs and leaves fewer CTC time steps (width / 8) than characters, which is why `TractTextRecognizer` picks an input width that fits each crop ([section 7](#7-per-task-behavior-and-maturity)).

### 6.4 Postprocessing (`postprocess`)

The model-agnostic pure logic is covered by unit tests.

```rust
fn softmax(logits: &[f32]) -> Vec<f32>            // numerically stable softmax
fn argmax(v: &[f32]) -> (usize, f32)              // top-1 (index, value)
fn iou(a: &BBox, b: &BBox) -> f32                 // intersection over union
fn nms(boxes: &[(BBox, f32)], iou_threshold: f32) -> Vec<usize>   // non-maximum suppression -> kept indices
fn ctc_greedy_decode(probs: &[f32], t: usize, c: usize, dict: &[String]) -> (String, f32)  // CTC; input must be per-step probabilities, never panics on a short tensor
fn connected_boxes(prob: &[f32], w: usize, h: usize, threshold: f32, min_area: usize)
    -> Vec<(usize, usize, usize, usize, f32)>     // DB detection post-processing (connected-component boxes)
fn reading_order(boxes: &[BBox]) -> Vec<usize>   // indices sorting detection boxes into reading order (top-to-bottom rows, left-to-right within a row)
fn xy_cut_order(boxes: &[BBox], min_gap: usize) -> Vec<usize>  // recursive XY-Cut reading order (handles multi-column, tables, side-by-side panels)
```

### 6.5 Error Types

```rust
pub enum VisionError {
    Io(std::io::Error),
    Decode(String),        // image/video decode failure
    Backend(String),       // model load/inference error (absorbs concrete backend errors into a string)
    NotWired(&'static str),// call to a not-yet-wired feature
    Unsupported(String),
}
pub type OcrError = VisionError;          // backward-compatible alias for the old name
pub type Result<T> = std::result::Result<T, VisionError>;
```

> The error types do not depend on optional dependencies (`tract`, etc.). Concrete backend errors are absorbed into strings, so the crate always compiles under any feature combination.

---

## 7. Per-Task Behavior and Maturity

| Task | trait / backend | Status |
|---|---|---|
| Text detection + recognition (OCR) | `TextDetector`/`TextRecognizer`, `TractTextDetector`/`TractTextRecognizer`, `OcrEngine`, `OcrSession` | **Verified working.** End-to-end verified on real screen photos (phone-shot 4000x3000) with a PP-OCRv5 Korean model, and covered by real-model regression tests (`tests/real_models.rs`). Includes dictionary validation, width-adaptive recognition, DB unclip and box filtering, reading-order sorting, and automatic orientation correction with original-frame coordinates (see [Screen Capture and Photo OCR](#94-screen-capture-and-photo-ocr)). |
| Image classification | `Classifier`, `TractClassifier` | Compiles and structurally complete, **accuracy not verified with a real model** |
| Object detection | `ObjectDetector`, `TractObjectDetector` | Compiles. **Assumes an output layout of `[N,6]` = (x1,y1,x2,y2,score,cls)**, which varies by model, so verify and adapt |
| Layout analysis | `LayoutAnalyzer` | **Trait definition only** (a specialization of object detection with layout labels) |
| Segmentation | `Segmenter`, `Mask` | **Trait definition only** (no concrete backend yet) |
| Video timeline | `SamplingGate`, `TemporalMerger` | Working and tested ([section 8](#8-video-timeline-processing)). But video **decode is not implemented** (Phase 2) |

Verification and limitation notes:

- **The dictionary is validated against the model at load time.** The recognition model's class indices and the character dictionary must correspond 1:1, so `TractTextRecognizer::new` runs the model once and compares its class count with the dictionary. `classes = entries + 1` (blank) is accepted as is. `classes = entries + 2` means the model has PaddleOCR's trailing space class, so a space is appended to the dictionary; before 0.3.0 that class was silently dropped and every space between words disappeared. Any other count is a load error, because a dictionary from another model or language shifts every character (a Chinese dictionary on a Korean model turns Hangul into Chinese characters). See [section 11](#11-model-preparation-onnx-models-and-dictionaries).
- **The recognizer picks an input width per crop.** A line crop is resized to height 48 with its aspect ratio kept, and the smallest width bucket that fits is used (default 320, 640, 960, 1280, 1920, 2560, 3200; set with `with_width_buckets`). Each bucket model is loaded the first time it is needed and reused afterwards; if the model cannot be loaded at a width (a fixed-width model), the base width is used instead. Forcing every line into width 320 squeezed long lines until recognition returned nothing and dropped digits from amounts and dates. Crops are recognized on several threads (`with_threads`, default = CPU count up to 8).
- **Detection boxes are filtered.** A box is kept only when its shorter side is at least 3 px in the detection map and the mean probability inside its rectangle is at least 0.6 (`with_box_threshold`, the same definition as PaddleOCR's `det_db_box_thresh`). This removes the dot-sized boxes that used to produce stray characters. `OcrSession` also drops results whose text is empty or whose confidence is below 0.5 (`OcrConfig::min_text_confidence`).
- **DB unclip is applied.** DB detection predicts a region shrunk relative to the glyphs, so before cropping, boxes are re-expanded the same way as PaddleOCR (offset `d = area×ratio/perimeter`, default ratio 1.5) to prevent glyph edges (especially the first character) from being clipped. Tune it with `TractTextDetector::with_unclip(ratio)`. On clean Korean, accuracy dropped noticeably from glyph clipping without unclip and was measured to normalize once applied.
- **Reading-order sorting (XY-Cut).** Connected-component extraction follows raster-scan order, so words come out scrambled. The detector recovers reading order with a recursive XY-Cut (`postprocess::xy_cut_order`): it projects boxes onto Y to cut horizontal bands (rows), then projects each band onto X to cut vertical columns, recursively, so even complex layouts (multi-column, tables, side-by-side panels such as a table plus its description) read the left column fully before moving to the next (the effect is confirmed on the panel structure of screen photos straightened with `--auto-rotate`). Sorting uses the tight boxes before unclip, because expanded boxes overlap between lines and interfere with the projection split. Adjust the split gap with `with_xycut_gap`; a simple line-grouping version (`reading_order`) also remains in the public API. Note one limit of the rule-based cut: when two columns have lines on exactly the same rows with gaps between the rows, the Y cut comes first and the page is read row by row across both columns. That is the right order for a key-value table and the wrong order for a two-column article, and projection alone cannot tell them apart.
- **Detection boxes are axis-aligned** (no rotated unclip). This is sufficient for horizontal subtitles and on-screen text, but skewed individual lines are a target for future work.
- **Detection resolution has an upper bound and no upscaling by default.** The long side of the detection input is the image's own long side, capped at `det_long` (default 1600, rounded to a multiple of 32), so high-resolution photos are reduced but small screenshots are not enlarged. The short side is rounded up to a multiple of 128 and the rest is letterbox padding, which keeps the number of distinct detector shapes (and model loads) small. Set `OcrConfig::upscale = true` (CLI `--upscale`) to enlarge small images up to `det_long`, which can help very small glyphs at the cost of detection time.
- **Automatic orientation correction.** A screen photo shot with the phone held sideways is entirely rotated. `auto_rotate` picks, among 0/90/180/270 degrees, the orientation whose high-confidence (0.8 or more) regions contain the most characters. The orientation classifier (PP-LCNet doc-ori) frequently gets the direction wrong (especially 90 vs 270) on out-of-distribution inputs like screen photos, so the recognition score is used as the metric instead (recognition confidence bottoms out when the input is sideways or upside down). The 0-degree read is accepted without trying other directions when at least 8 regions are confident, or when at least 70% of the regions are confident and the mean confidence is 0.85 or more; before 0.3.0 the rule was "8 confident regions" only, so an upright image with a few lines always paid for four reads. **Boxes are returned in the original image's coordinates** and `OcrOutput::rotation` reports the rotation that was applied.
- **Remaining limitation: small, dense text.** Small form text loses accuracy at the resolution limit. `--upscale` or a higher `--det-long` helps at the cost of time; super-resolution preprocessing is not planned as a default because restored images can contain strokes that were not in the original.
- **Speed.** Use `OcrSession` (Rust, Python, or the CLI with several paths) so the models are loaded once. Loading the 88MB server detector takes tens of seconds per shape, so the mobile detector is the practical choice for large batches. Detection inference is the largest cost per image; see the measurements in the [changelog](#17-changelog).
- **Channel order.** PaddleOCR models are trained and served on OpenCV's BGR images, so the PaddleOCR backends feed BGR (`ChannelOrder::Bgr`, configurable). On our synthetic regression set the BGR and RGB results were identical, so this follows the training condition rather than a measured gain.
- **Dynamic-input ONNX handling.** PaddleOCR ONNX has dynamic input dimensions, so the backend statically fixes the raw proto's input dimensions at load time before parsing. tract was confirmed able to run both detection (DB) and recognition (CRNN/SVTR).

---

## 8. Video Timeline Processing

What makes text extraction from video different: instead of recognizing every frame, only frames that changed are recognized, and duplicates across adjacent frames are merged into time segments.

### 8.1 SSIM sampling gate

If the structural similarity (SSIM) to the previous keyframe is high enough, the frame is dropped. In a 30fps video, subtitles change only a few frames per second, so the pass rate can be lowered to single-digit percent, cutting the recognition calls themselves.

```rust
let mut gate = SamplingGate::new(0.98)         // threshold (higher drops fewer). with_scale adjusts the comparison size
    .with_roi(Roi { x: 0.0, y: 0.75, width: 1.0, height: 0.25 }) // optional: compare only the subtitle band
    .with_blocks(4)                            // optional: judge by the most-changed of 4x4 cells
    .with_max_interval(2_000);                 // optional: admit at least once every 2 s (frame timestamps)
if gate.admit(&frame) {                        // true = admit (new frame), false = skip (same as previous)
    // OCR only this frame
}
ssim(&gray_a, &gray_b) -> f64                  // global SSIM of two grayscale images
```

A single SSIM over the whole downscaled frame barely moves when only a small subtitle changes, so a gate with default settings can skip a real subtitle change. Restricting the comparison to the subtitle region (`with_roi`) or using the lowest cell SSIM (`with_blocks`) keeps small changes visible. `with_max_interval` is a safety net that re-reads a frame periodically even when nothing seems to change. The defaults are unchanged from earlier versions (global SSIM, no forced admits).

### 8.2 Temporal merging

Recognition results from adjacent frames that pass the gate may be nearly the same text. Using normalized Levenshtein similarity, "a continuous run of the same subtitle" is merged into a single `(start, end, text)` segment.

```rust
let mut merger = TemporalMerger::new(0.8)       // similarity threshold
    .with_max_gap(10_000);                       // optional: split identical text seen again after 10 s
if let Some(seg) = merger.push_scored(timestamp, text, confidence) { /* subtitle changed -> previous segment */ }
let last = merger.finish_at(video_end);          // end of stream -> close the last segment at the video's end
```

Timing and text rules:

- A segment ends at the time the change was **first observed** (a different text or an empty observation). Frames skipped by the gate were judged identical to the keyframe, so the subtitle was still on screen until then. `finish()` closes the last segment at its last observation; use `finish_at(t)` when the stream end time is known.
- An empty (or whitespace) text closes the open segment: it is read as "no subtitle on screen". If an OCR miss should not end a subtitle, do not push empty results.
- A timestamp earlier than the previous observation is ignored and counted (`out_of_order()`).
- The segment text is the **weighted medoid** of the observed strings: the observed string with the smallest confidence-weighted edit distance to all others. A single misread does not take over the segment just because it is longer (before 0.3.0 the longest string won, so one extra digit could replace a correct amount).

### 8.3 Output serialization (`emit`)

```rust
emit::to_srt(&segments)  -> String          // SRT subtitles
emit::to_json(&segments) -> Result<String>  // JSON array (timestamps in ms)
emit::to_plain(&segments)-> String          // text only, joined by newlines
```

---

## 9. CLI Tool (`roct`)

Built with `--features cli`.

```bash
cargo build --release --features cli
```

| Subcommand | Arguments | Behavior |
|---|---|---|
| `image` | `<path>...` `--det-model` `--rec-model` `--dict` `[--auto-rotate]` `[--det-long N]` `[--upscale]` `[--min-confidence F]` `[--json]` | image OCR (detection + recognition) for one or more images; the models are loaded once for all of them. `--auto-rotate` for automatic orientation correction, `--det-long` for the detection long-side cap (default 1600), `--upscale` to enlarge small images up to that cap, `--min-confidence` to drop weak results (default 0.5). Prints `[score] (x,y,w,h) text` per region (with a `== path` header when several images are given), or one JSON object per image with `--json`. Boxes are in original image coordinates. |
| `classify` | `<path>` `--model` `--labels` | image classification (top-k) |
| `ssim` | `<a> <b>` | prints the structural similarity of two images (the sampling-gate metric) |
| `srt` | `<segments.json>` | time-segment JSON -> SRT subtitles (stdout) |
| `video` | `<path>` | video OCR. Phase 2, currently returns a `NotWired` error |

```bash
# Image OCR (a straight input like a scan/screenshot)
roct image page.png --det-model models/det.onnx --rec-model models/rec.onnx --dict models/dict.txt

# Many images in one process, JSON lines with rotation and original size
roct image shots/*.png --json --auto-rotate \
  --det-model models/det.onnx --rec-model models/rec.onnx --dict models/dict.txt

# Image classification (model + label list)
roct classify cat.jpg --model models/cls.onnx --labels models/imagenet.txt

# segment JSON -> SRT
roct srt segments.json > out.srt
```

### 9.4 Screen Capture and Photo OCR

For a phone-shot screen photo or a high-resolution capture, two things are decisive: orientation and detection resolution. Use `--auto-rotate` to straighten the orientation automatically, and `--det-long` to set how far a large photo is reduced for detection.

```bash
# Screen-photo OCR (automatic orientation correction, detection long side capped at 1600)
roct image photo.jpg \
  --det-model models/det.onnx --rec-model models/rec.onnx --dict models/dict.txt \
  --auto-rotate --det-long 1600
```

Behavior and options:

- **`--auto-rotate`**: picks, among 0/90/180/270 degrees, the orientation whose confident regions contain the most characters. A straight input is checked at 0 degrees once and passes quickly; all four orientations are tried only when 0 degrees does not read well. The printed boxes are in the coordinates of the file you passed in, and `--json` reports the applied `rotation`.
- **`--det-long N`**: the upper bound of the detection input's long side (rounded to a multiple of 32, default 1600). Images smaller than this are detected at their own size unless `--upscale` is given.
- **Fine tuning**: the DB unclip ratio (default 1.5), the box score threshold (default 0.6), and the XY-Cut split gap (default 8) are set through `OcrConfig` or the detector builders (`TractTextDetector::with_unclip` / `with_box_threshold` / `with_xycut_gap`).
- **Speed**: the large server det is slow to load. For large batches, using the lightweight mobile det to quickly find the orientation is practical. See [section 11](#11-model-preparation-onnx-models-and-dictionaries) for the detection/recognition models and dictionaries.

---

## 10. Python Bindings (PyO3)

Built with **abi3 (stable ABI)**, so a single wheel is compatible with Python 3.9+ (a pure-Rust wheel with no C++ runtime dependency).

From Python you use `OcrSession` for image OCR (or the one-shot `recognize_image`) and the core utilities. The caller provides the model and dictionary files (see [section 11](#11-model-preparation-onnx-models-and-dictionaries)). Video processing (`read_video`) will be added together with video decode (Phase 2).

### Installation

```bash
# After PyPI publication: no Rust toolchain needed
pip install rust_ocr_transformer

# From source (latest main / before publication): requires a Rust toolchain on the install machine
pip install "git+https://github.com/arabangoo/rust_ocr_transformer"
```

### API

```python
import json
import rust_ocr_transformer as roct

roct.__version__                              # "0.3.0"

# A session loads and validates the models once and is reused for every image.
session = roct.OcrSession("models/det.onnx", "models/rec.onnx", "models/dict.txt",
                          det_long=1600, upscale=False, min_confidence=0.5, threads=0)

# List of regions as a JSON string (boxes in original image coordinates)
for r in json.loads(session.recognize("page.png")):
    print(r["confidence"], r["text"], r["bbox"])   # {"x":..,"y":..,"width":..,"height":..}

# A phone-shot screen photo: automatic orientation correction, with the applied rotation reported
detail = json.loads(session.recognize_detailed("photo.jpg", auto_rotate=True))
print(detail["rotation"], detail["width"], detail["height"], len(detail["regions"]))

session.detector_loads                        # how many detector shapes were loaded so far

# One-shot helper (loads the models on every call; prefer OcrSession for more than one image)
out = roct.recognize_image("page.png", "models/det.onnx", "models/rec.onnx", "models/dict.txt",
                           auto_rotate=False, det_long=1600)

# Core utilities
roct.image_ssim("a.png", "b.png")             # structural similarity of two images (0.0-1.0)
roct.segments_to_srt(segments_json)           # time-segment JSON string -> SRT subtitle string
```

`OcrSession` arguments: `det_long` (detection long-side cap, default 1600), `upscale` (enlarge small images up to the cap, default `False`), `min_confidence` (drop weaker results, default 0.5), `threads` (line recognition threads, 0 = CPU count up to 8). Both methods take `auto_rotate` (default `False`). The session releases the GIL during inference, so several Python threads can share one session. A dictionary that does not match the recognition model raises `RuntimeError` at construction.

### Building (developers and publishers)

The root `pyproject.toml` (maturin backend) provides the build metadata. Thanks to `[tool.maturin] features = ["python"]`, you can omit `--features python`.

```bash
pip install maturin
maturin develop --release          # install into the current venv
maturin build --release            # build a wheel into target/wheels/
```

---

## 11. Model Preparation (ONNX Models and Dictionaries)

This framework does not bundle models. Inference needs an ONNX model file and (for recognition) a character dictionary. Model weights are not committed to the repo (`.gitignore` excludes `*.onnx` and `models/`).

### PaddleOCR ONNX models (source used for verification)

You can download pre-converted PP-OCR ONNX models and dictionaries directly (PaddlePaddle, Apache-2.0).

```bash
mkdir -p models
base="https://github.com/GreatV/oar-ocr/releases/download/v0.3.0"
# detection (language-agnostic)
curl -sL -o models/det.onnx       "$base/pp-ocrv5_mobile_det.onnx"
# recognition (per-language), e.g. Korean PP-OCRv5
curl -sL -o models/rec.onnx       "$base/korean_pp-ocrv5_mobile_rec.onnx"
# character dictionary: must match the recognition model
curl -sL -o models/dict.txt       "$base/ppocrv5_korean_dict.txt"
```

Recognition models for other languages (English, Latin, Japanese, and so on) and their matching dictionaries are in the same release.

### HuggingFace source (used for screen-photo verification)

A source where you can get per-language recognition models and dictionaries along with the orientation model for rotation correction (PP-LCNet doc-orientation), all in one place (PaddlePaddle conversion, Apache-2.0). This set was used for the real Korean screen-photo verification.

```bash
mkdir -p models
base="https://huggingface.co/monkt/paddleocr-onnx/resolve/main"
# detection (server, high accuracy)
curl -sL -o models/det.onnx   "$base/detection/v5/det.onnx"
# recognition (Korean) + dictionary
curl -sL -o models/rec.onnx   "$base/languages/korean/rec.onnx"
curl -sL -o models/dict.txt   "$base/languages/korean/dict.txt"
# (optional) lightweight mobile detection, for large batches / orientation search
curl -sL -o models/det_mobile.onnx "$base/detection/v3/det.onnx"
```

> The Korean dictionary starts with decomposed jamo (the U+1100 block), but the recognition model outputs precomposed syllables directly, so no separate NFC normalization is needed (verified). For detection, server (v5, about 88MB) is accurate but slow to load, while mobile (v3, about 2.4MB) is fast but has somewhat weaker word splitting and accuracy.

### Multilingual recognition (per-language models and dictionaries)

The detection (det) and orientation (doc-ori) models are language-agnostic and shared; only the recognition (rec) and dictionary (dict) change per language. You can download the major-language models and dictionaries in one go from the same source.

```bash
base="https://huggingface.co/monkt/paddleocr-onnx/resolve/main"
for L in arabic chinese english eslav greek hindi korean latin tamil telugu thai; do
  mkdir -p models/langs/$L
  curl -sL -o models/langs/$L/rec.onnx  "$base/languages/$L/rec.onnx"
  curl -sL -o models/langs/$L/dict.txt  "$base/languages/$L/dict.txt"
done
```

| Language | Folder | Notes |
|---|---|---|
| Chinese/Japanese (CJK) | `chinese` | includes Han characters (about 15,500) and kana (hiragana/katakana). Japanese is recognized by this model too (verified: こんにちは世界, 東京タワー, 日本語認識テスト accurate). Server-class (about 80MB). |
| English | `english` | Latin alphanumerics and symbols |
| Korean | `korean` | outputs precomposed Hangul |
| Latin (European) | `latin` | Latin-script languages such as French, German, Spanish |
| Others | `arabic`, `eslav` (Cyrillic), `greek`, `hindi`, `tamil`, `telugu`, `thai` | each script |

To switch languages, change only the recognition model and dictionary paths (the detection model stays the same):

```bash
# Japanese (CJK model: Han + kana)
roct image jp.png --det-model models/det.onnx \
  --rec-model models/langs/chinese/rec.onnx --dict models/langs/chinese/dict.txt --auto-rotate

# English
roct image en.png --det-model models/det.onnx \
  --rec-model models/langs/english/rec.onnx --dict models/langs/english/dict.txt
```

> In PP-OCRv5, Japanese is not a separate model; the general CJK (`chinese`) model handles Han characters and kana together.

> **The dictionary must match the model exactly.** The recognition model's number of output classes and the dictionary's length and character order must correspond 1:1 for correct recognition. Even for the same language, the dictionary differs by model version (v3/v4/v5), so use the dedicated dictionary distributed with the model. A mismatched dictionary maps every character incorrectly.

### Input shapes

Specify the input shape when constructing a backend (PP-OCRv5 recommended values): detection `(736, 1280)`, recognition `(48, 320)`, classification `(224, 224)`. Even if the model has dynamic inputs, the backend fixes it to this shape at load time. For recognition, `(48, 320)` is the base shape; wider buckets are loaded from the same file on demand (see [section 7](#7-per-task-behavior-and-maturity)). `OcrSession` chooses the detection shape from each image's size.

---

## 12. Embedding into a Service Pipeline

This library is not a standalone app; it is a core dependency you embed at the vision input stage. The extracted structured results (text, boxes, segments) are useful on their own, or you can feed them into the vision entry point of a retrieval-augmented-generation (RAG) ingest.

### 12.1 Embed into a Rust service

Inference is CPU-bound, so wrap it in `spawn_blocking` inside an async server (axum/actix). Create one `OcrSession` at startup and share it via `Arc` (it is `Send + Sync`; its model caches are internally locked).

```rust
use std::sync::Arc;
use rust_ocr_transformer::{OcrConfig, OcrSession};

// load once at startup, then share
let session = Arc::new(OcrSession::with_config(
    "models/det.onnx", "models/rec.onnx", "models/dict.txt",
    OcrConfig { det_long: 1600, ..OcrConfig::default() },
)?);

// handler
let s = session.clone();
let out = tokio::task::spawn_blocking(move || s.recognize_path("upload.png", true)).await??;
// out.rotation, out.width, out.height, out.regions (boxes in upload.png coordinates)
```

The detector cache holds up to `OcrConfig::det_cache_size` shapes (default 8, least recently used is dropped). A service that receives images of many different sizes can resize uploads to a few standard sizes to keep detector loads rare; `session.detector_loads()` shows how often it happens.

### 12.2 Video to subtitles (SRT) pipeline

The SSIM gate thins frames, only passing frames are OCR'd, and temporal merging forms subtitle segments.

```rust
use rust_ocr_transformer::{emit, Roi, SamplingGate, TemporalMerger};

let mut gate = SamplingGate::new(0.98)
    .with_roi(Roi { x: 0.0, y: 0.75, width: 1.0, height: 0.25 })  // subtitle band
    .with_max_interval(2_000);
let mut merger = TemporalMerger::new(0.85);
let mut segments = Vec::new();

for frame in frames {                       // video decode is on the caller side (until Phase 2)
    if !gate.admit(&frame) { continue; }    // skip unchanged frames
    let out = session.recognize(&frame, false)?;
    let text = out.regions.iter().map(|r| r.text.as_str()).collect::<Vec<_>>().join(" ");
    let conf = out.regions.iter().map(|r| r.confidence).fold(1.0f32, f32::min);
    if let Some(seg) = merger.push_scored(frame.timestamp, &text, conf) { segments.push(seg); }
}
if let Some(seg) = merger.finish_at(video_end) { segments.push(seg); }
std::fs::write("out.srt", emit::to_srt(&segments))?;
```

### 12.3 Other languages / batch: wrap the CLI

From non-Python, non-Rust stacks or from batch jobs, call the `roct` binary as a subprocess. It is a single static binary, so you only need to drop `roct` into your container (no runtime dependency).

```bash
roct image /data/page.png --det-model det.onnx --rec-model rec.onnx --dict dict.txt
```

---

## 13. Adding a New Task or Backend

You can plug in a new model or a new task without touching the core.

### 13.1 New backend: implement an existing task trait

For example, wire your own classification model as a `Classifier`. Using the shared [`TractModel`](#133-the-tract-backend-reference) runner plus the reusable pre/post-processing keeps it short.

```rust
use rust_ocr_transformer::{Classifier, Classification, Frame, Result, TractModel};
use rust_ocr_transformer::{preprocess, postprocess};

struct MyClassifier { model: TractModel, labels: Vec<String> }

impl Classifier for MyClassifier {
    fn classify(&self, frame: &Frame) -> Result<Vec<Classification>> {
        let (h, w) = self.model.dims();
        let (data, _) = preprocess::letterbox_chw(&frame.image, h, w,
            preprocess::IMAGENET_MEAN, preprocess::IMAGENET_STD);
        let (logits, _) = self.model.run(data)?;
        let probs = postprocess::softmax(&logits);
        let (i, score) = postprocess::argmax(&probs);
        Ok(vec![Classification { label: self.labels[i].clone(), score }])
    }
}
```

### 13.2 New task: a new trait

For a task the existing six do not express (for example keypoints or depth estimation), define a new `Send + Sync` trait following the `tasks` pattern and have it take a `Frame` as input. For pre/post-processing, reuse the functions in `preprocess`/`postprocess`.

### 13.3 The tract Backend (reference)

What `backends::tract` provides:

```rust
TractModel::load(path, in_h, in_w) -> Result<TractModel>   // loads even dynamic inputs after fixing them statically
fn dims(&self) -> (usize, usize)
fn run(&self, data: Vec<f32>) -> Result<(Vec<f32>, Vec<usize>)>  // (output slice, shape); rejects a wrong-sized input
fn probe_output_shape(&self) -> Result<Vec<usize>>              // one zero-input run, used for contract checks

TractTextDetector::new(model, (h, w))            // .with_threshold(bin) .with_box_threshold(score) .with_unclip(ratio)
                                                 // .with_xycut_gap(px) .with_channel_order(order)
TractTextRecognizer::new(model, dict, (h, w))    // validates dict vs. classes; .with_width_buckets(widths)
                                                 // .with_threads(n) .with_channel_order(order)
TractClassifier::new(model, labels, (h, w))      // .with_top_k(usize)
TractObjectDetector::new(model, labels, (h, w))  // .with_thresholds(score, iou)
TractDocOrientation::new(model, (h, w))          // orientation classification 0/90/180/270 -> .predict_conf / .correct(frame, min_conf)
```

What `backends::session` provides:

```rust
OcrSession::new(det, rec, dict) -> Result<OcrSession>
OcrSession::with_config(det, rec, dict, OcrConfig { .. }) -> Result<OcrSession>
fn recognize(&self, frame: &Frame, auto_rotate: bool) -> Result<OcrOutput>
fn recognize_path(&self, path, auto_rotate: bool) -> Result<OcrOutput>
fn detector_loads(&self) -> usize

// OcrConfig fields and defaults
det_long: 1600, upscale: false, min_text_confidence: 0.5, box_threshold: 0.6, unclip_ratio: 1.5,
xycut_gap: 8, rec_height: 48, rec_widths: [320, 640, 960, 1280, 1920, 2560, 3200], threads: 0,
channel_order: ChannelOrder::Bgr, det_cache_size: 8

// kept for compatibility: builds a session per call and returns the regions
recognize_image_auto(frame, det, rec, dict, auto_rotate, det_long) -> Result<Vec<Recognized>>
```

---

## 14. Build, Feature Combinations, and Testing

If you clone this repository, you need to build it once with a **Rust toolchain (stable, 1.82 or newer)** before using it.

| Use case | Build command | Result |
|---|---|---|
| CLI tool | `cargo build --release --features cli` | the single `target/release/roct` binary |
| Python module | `pip install maturin && maturin develop --release` | `import rust_ocr_transformer` in the current venv |
| Rust library | a `path`/`git` dependency in `Cargo.toml` | links into another Rust project |

```bash
# Default: includes the pure-Rust (tract) backend, zero FFI
cargo build --release

# Core IP only (inject the backend yourself)
cargo build --release --no-default-features

# CLI / Python
cargo build --release --features cli
maturin develop --release

# Test / lint
cargo test                  # pure logic + pipeline integration (no model files needed)
cargo clippy --all-targets --features cli

# Real-model regression tests (skipped by default; needs the PP-OCRv5 Korean models)
ROCT_MODEL_DIR=path/to/models cargo test --release --test real_models -- --ignored
```

The default tests verify what works without external models: the SSIM gate (global, block, ROI, forced interval), temporal merging rules (medoid text, end times, empty and out-of-order observations, maximum gap), SRT output, trait-composition engine wiring, CTC decoding including short tensors, dictionary alignment, channel order, and rotation back-mapping of boxes. The real-model tests in `tests/real_models.rs` read the synthetic fixtures in `tests/fixtures` with the PP-OCRv5 detection and Korean recognition models and check spaces between words, a long line, exact digits, original-frame coordinates after auto-rotation, rejection of a wrong dictionary, and detector reuse. `ROCT_MODEL_DIR` must contain `det_v5.onnx`, `rec_ko_v5.onnx`, and `ppocrv5_korean_dict.txt`.

---

## 15. Directory Layout

```text
rust_ocr_transformer/
  Cargo.toml
  README.md              # this document
  LICENSE                # Apache-2.0
  src/
    lib.rs               # crate root, re-exports
    types.rs             # common types (Frame/BBox/result types/OcrOutput/FrameAnalysis/Segment)
    tasks.rs             # task traits (TextDetector/Recognizer/ObjectDetector/Classifier/...)
    engine.rs            # OcrEngine (detection + recognition composition), crop_regions
    preprocess.rs        # letterbox, normalization, channel order, CHW tensorization
    postprocess.rs       # NMS, softmax, argmax, IoU, CTC, DB connected-component boxes (+ unit tests)
    sampler.rs           # SSIM sampling gate with ROI, blocks, forced interval (video)
    temporal.rs          # temporal merging with medoid text and timing rules (video)
    emit.rs              # SRT / JSON / plaintext serialization
    error.rs             # VisionError / Result
    python.rs            # PyO3 bindings (feature = "python")
    bin/
      roct.rs            # CLI binary (feature = "cli")
    backends/
      mod.rs             # feature gates
      tract.rs           # pure-Rust inference backend (feature = "tract")
      session.rs         # OcrSession: resident models, filtering, auto-rotation (feature = "tract")
  tests/
    pipeline.rs          # synthetic-fixture integration tests
    real_models.rs       # real-model regression tests (ignored unless ROCT_MODEL_DIR is set)
    fixtures/            # synthetic images with known text
```

---

## 16. License

Apache-2.0

---

## 17. Changelog

### 0.3.0

Accuracy and correctness:

- Spaces between words are kept. The recognizer now validates the dictionary against the model's class count and appends PaddleOCR's trailing space class; a mismatched dictionary is a load error instead of silently wrong text.
- Long lines are read correctly. The recognizer chooses an input width per crop instead of squeezing every line into width 320.
- Dot-sized detection boxes are dropped (box score threshold 0.6 and a minimum side of 3 px), and `OcrSession` drops empty and low-confidence results.
- With `auto_rotate`, boxes are returned in the original image's coordinates and the applied rotation is reported (`OcrOutput::rotation`). Upright images with only a few lines no longer trigger the four-direction search.
- CTC decoding and model outputs are length-checked: a short or mis-shaped tensor is an error (or, in `ctc_greedy_decode`, a truncated read) instead of a panic.
- Temporal merging: segment ends are the time the change was observed, empty observations close a segment, out-of-order timestamps are ignored and counted, `with_max_gap` and `finish_at` were added, and the segment text is the weighted medoid of the observations instead of the longest string.
- The PaddleOCR backends feed BGR, the channel order those models are trained with.

Performance and API:

- `OcrSession` (Rust and Python) loads the models once and caches detectors by input shape; the CLI accepts several images in one call and has `--json`, `--upscale`, and `--min-confidence`.
- Line recognition runs on several threads, and the Python calls release the GIL.
- `det_long` is now an upper bound: small images are no longer enlarged (opt in with `upscale`).
- `SamplingGate` gained `with_roi`, `with_blocks`, and `with_max_interval`.

Measured on 11 synthetic Korean and English images with known text (`det_v5.onnx` + `rec_ko_v5.onnx`, same models and machine for both versions):

| | 0.2.2 | 0.3.0 |
| --- | --- | --- |
| Character error rate, spaces included | 0.508 | 0.020 |
| Character error rate, spaces ignored | 0.395 | 0.000 |
| Long lines read (2 images) | 0 of 2 (empty output) | 2 of 2 |
| 11 images, total wall time | 15.8 s (one process per image) | 10.9 s (one process for all) |

The remaining errors are missing spaces in small text and in one line of digits. The set is synthetic and small; it is a regression check, not a benchmark of real-world accuracy.

Behavior changes to check when upgrading:

- `recognize_image` / `recognize_image_auto` drop empty and low-confidence (below 0.5) results, and with `auto_rotate` the boxes are in original coordinates.
- `det_long` no longer enlarges small images.
- `TemporalMerger` segment `end` values are later (the time the change was seen), and the representative text may differ from the longest observation.
- A dictionary that does not match the recognition model fails at load time.
- Minimum supported Rust version is 1.82.

