How To

Use Python

Using the native UniFFI-powered RustO! OCR library in Python.

The rusto Python package provides high-performance bindings powered by Mozilla's UniFFI, allowing Python applications to run pure-Rust OCR with native C-speed and zero Python GIL contention during inference.

Installation

pip install rusto

1. Engine Initialization

Initialize the engine using template presets or custom JSON configurations:

from rusto import (
    RustO,
    InitializeConfig,
    OcrRunOptions,
    ImageSource,
    OutputGranularity,
)

# Initialize with PP-OCRv6 preset
config = InitializeConfig.ppv6(
    det="models/PPOCR_v6/det.rten",
    rec="models/PPOCR_v6/rec.rten",
    dict="models/PPOCR_v6/dict.txt"
)
engine = RustO.initialize(config)

Alternatively, initialize directly from a JSON string:

import json

config_json = json.dumps({
    "detection": {"model_path": "models/PPOCR_v6/det.rten"},
    "recognition": {
        "model_path": "models/PPOCR_v6/rec.rten",
        "dict_path": "models/PPOCR_v6/dict.txt"
    }
})
engine = RustO.initialize_from_json(config_json)

2. Text Recognition

Structured Output (lines or words)

# Configure OCR options
options = OcrRunOptions(
    output=OutputGranularity.LINES,
    text_score=0.5
)

# Run recognition on an image file
result = engine.detect_text(ImageSource.PATH("receipt.jpg"), options)

if result.is_STRUCTURED():
    for item in result.results:
        print(f"[{item.score:.2f}] {item.text}")
        print(f"  Frame: left={item.frame.left}, top={item.frame.top}, w={item.frame.width}, h={item.frame.height}")

From In-Memory Bytes

with open("invoice.png", "rb") as f:
    image_bytes = f.read()

result = engine.detect_text(ImageSource.BYTES(image_bytes), OcrRunOptions())

3. Spatial Layout Reconstruction

To preserve invoices, tabular layouts, or multi-column documents:

spatial_options = OcrRunOptions(
    output=OutputGranularity.SPATIAL,
    line_y_threshold=0.5,
    word_x_threshold=0.4
)

result = engine.detect_text(ImageSource.PATH("invoice.png"), spatial_options)

if result.is_SPATIAL():
    print("--- Reconstructed Spatial Document ---")
    print(result.text)