Skip to main content

rusto (Python SDK)

Official Python bindings for RustO! — a high-performance, pure-Rust OCR engine powered by Indra OCR, PaddleOCR, and the pure-Rust MNN (rusto-nn) inference runtime via UniFFI.

Features

  • Zero-Config Indra OCR: RustO.initialize() automatically downloads and caches the default indraocr models on first run from Hugging Face Hub.
  • Context Manager Support: Deterministic native resource cleanup with with RustO.initialize() as engine: or engine.close().
  • Full Document Pipeline: Neural document unwarping (with_auto_unwarp()), page orientation detection (with_orientation_detection()), semantic layout analysis, and reading-order recovery (with_layout_reading()).
  • Fluent Builder API: Chain .as_lines(), .as_words(), .as_spatial(), .as_tsv(), or .with_output(...) into a single .run() terminal method.
  • Zero-Copy Raw RGB Support: Feed NumPy / OpenCV / Pillow RGB8 buffers directly via .rgb(pixels, width, height, stride).

Installation

pip install rusto

Quick Start

from rusto import RustO

# Zero-config initialization (auto-downloads Indra OCR models from Hugging Face Hub if not cached)
with RustO.initialize() as engine:
    result = (
        engine.detect_text("invoice.png")
        .with_auto_unwarp()
        .with_layout_reading()
        .as_lines()
        .run()
    )

    if result.is_STRUCTURED():
        for item in result.results:
            print(
                f"[{item.score:.2f}] ({item.layout_type or 'line'} #{item.region_id}) {item.text}"
            )

    # Reconstructed 2D spatial text layout
    spatial = engine.detect_text("invoice.png").as_spatial().run()
    if spatial.is_SPATIAL():
        print(spatial.text)

You can also manage the engine lifecycle explicitly without a with block:

from rusto import InitializeConfig, RustO

engine = RustO.initialize(InitializeConfig.indra())
try:
    result = engine.detect_text("invoice.png").as_words().run()
    if result.is_STRUCTURED():
        for word in result.results:
            print(word.text, word.frame)
finally:
    engine.close()

Custom Configuration & Offline Models (.mnn / .rten)

Select canonical model tiers ("indraocr", "ppocrv6-tiny", "ppocrv6-small", "ppocrv5-mobile", "ppocrv4-mobile"), languages, or local model paths:

from rusto import (
    DetectionConfig,
    InitializeConfig,
    LayoutConfig,
    RecognitionConfig,
    RustO,
    UnwarpConfig,
)

# Preset by canonical model + language (auto-downloaded to cache)
cfg = InitializeConfig.for_model("ppocrv6-tiny", lang="latin")
engine = RustO.initialize(cfg)
engine.close()

# Explicit local assets for offline environments
offline_cfg = InitializeConfig(
    template="indra",
    enable_reading_order=True,
    detection=DetectionConfig(enabled=True, model_path="./models/indra_det.mnn"),
    recognition=RecognitionConfig(
        enabled=True,
        model_path="./models/indra_rec.mnn",
        dict_path="./models/indra_meta.json",
    ),
    unwarp=UnwarpConfig(enabled=True, model_path="./models/uvdoc.mnn"),
    layout=LayoutConfig(enabled=True, model_path="./models/layout_cdla.mnn"),
)
with RustO.initialize(offline_cfg) as offline_engine:
    res = offline_engine.detect_text("scan.png").with_auto_unwarp().as_lines().run()

Pre-download models into a target cache directory ahead of time (e.g., during Docker image build):

from rusto import download_model

paths = download_model(model="indraocr", lang="latin", cache_dir="./models-cache")

Input Sources & Raw RGB Buffers

Pass a file path (str or Path), encoded image bytes, ImageSource, or raw interleaved 24-bit RGB pixels:

from pathlib import Path
import numpy as np
from rusto import RustO

with RustO.initialize() as engine:
    # 1. Encoded PNG/JPEG bytes
    png_bytes = Path("invoice.png").read_bytes()
    res_bytes = engine.detect_text(png_bytes).as_lines().run()

    # 2. Raw HxWx3 uint8 RGB array (e.g. from Pillow / imageio)
    rgb_array = np.zeros((720, 1280, 3), dtype=np.uint8)
    height, width, _ = rgb_array.shape
    stride = width * 3

    res_rgb = (
        engine.detect_text()
        .rgb(rgb_array.tobytes(), width, height, stride)
        .as_lines()
        .run()
    )

6-Phase Pipeline Options

Customize every phase of OCR execution per request:

from rusto import (
    DetectionRunOptions,
    OutputGranularity,
    PostDetectionOptions,
    PostRecognitionOptions,
    PreDetectionOptions,
    PreRecognitionOptions,
    RecognitionRunOptions,
)

result = (
    engine.detect_text("document.jpg")
    .with_orientation_detection()
    .with_auto_unwarp()
    .with_layout_reading()
    .with_pre_detection(PreDetectionOptions(descreen_strength=0.3, target_max_side=1280))
    .with_detection(DetectionRunOptions(limit_side_len=960, limit_type="max"))
    .with_post_detection(PostDetectionOptions(threshold=0.3, box_threshold=0.6, unclip_ratio=1.6))
    .with_pre_recognition(PreRecognitionOptions(line_y_threshold=0.5, word_x_threshold=0.4))
    .with_recognition(RecognitionRunOptions(batch_size=8))
    .with_post_recognition(PostRecognitionOptions(score_threshold=0.5))
    .with_output(OutputGranularity.LINES)
    .run()
)

Result Reference

DetectTextResult is a tagged union returned by .run():

  • result.is_STRUCTURED() -> True for .as_lines() and .as_words(). Access result.results (list[TextResult]):
    • item.text (str): Recognized text string.
    • item.score (float): Confidence score (0.0 – 1.0).
    • item.box_points (list[Point]): 4 polygon vertices (x, y).
    • item.frame (Frame): Axis-aligned bounding box (width, height, top, left).
    • item.region_id (int | None): Layout region index when with_layout_reading() is active.
    • item.layout_type (LayoutType | None): Semantic region category (TEXT, TITLE, TABLE, HEADER, FOOTER, FIGURE, etc.).
  • result.is_SPATIAL() -> True for .as_spatial(). Access result.text (str).

License

Apache-2.0 OR MIT

Metadata

Release files for rusto 0.4.0

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for rusto 0.4.0
File Size Uploaded Provenance Actions
rusto-0.4.0.tar.gz 1.0 MB Without provenance Details for rusto-0.4.0.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for rusto 0.4.0
File Interpreter ABI Platform Actions
rusto-0.4.0-py3-none-any.whl Python 3 none any Details for rusto-0.4.0-py3-none-any.whl

Total release size: 2.1 MB

Release files / rusto-0.4.0.tar.gz

Download URL rusto-0.4.0.tar.gz
Size 1.0 MB
Tags Source
SHA-256 checksum
How to use checksums
15298b156285a1276aec814b11e08a254577bc5dda4b53ac661d0b3d69c6d074
BLAKE2b-256 checksum
How to use checksums
c6666f1422c0d565337dadbdf9d1ca40bef7ba038e0e680347e1026c792f50f0
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / rusto-0.4.0-py3-none-any.whl

Download URL rusto-0.4.0-py3-none-any.whl
Size 1.0 MB
Tags Python 3
SHA-256 checksum
How to use checksums
ea0b20fbb81105cdd90b511495028fa3af4f09368be40792cae58b496832f7c5
BLAKE2b-256 checksum
How to use checksums
24d8164bd5d5d0d721e77a743ad2c2863a1bc1d2c7fc77f2d17aab808deac005
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for rusto 0.4.0

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page