Skip to main content

OCR Package Tools

PyPI License Python ONNX

Lightweight OCR built on ONNX Runtime: text detection, text recognition, and orientation classification for English and Japanese. The models are included, and it runs on CPU or GPU.

Installation

pip install akaocr

For GPU inference, also install onnxruntime-gpu. Requires Python 3.8+.

Quick start

import cv2
import numpy as np
from akaocr import BoxEngine, ClsEngine, TextEngine


def crop_box(image, box):
    """Extract a text region and straighten it."""
    box = np.asarray(box, dtype=np.float32)
    w = int(max(np.linalg.norm(box[0] - box[1]), np.linalg.norm(box[2] - box[3])))
    h = int(max(np.linalg.norm(box[0] - box[3]), np.linalg.norm(box[1] - box[2])))
    m = cv2.getPerspectiveTransform(box, np.float32([[0, 0], [w, 0], [w, h], [0, h]]))
    crop = cv2.warpPerspective(image, m, (w, h), flags=cv2.INTER_CUBIC,
                               borderMode=cv2.BORDER_REPLICATE)
    return np.ascontiguousarray(np.rot90(crop) if h >= 1.5 * w else crop)


detector, classifier, recognizer = BoxEngine(), ClsEngine(), TextEngine()

image = cv2.imread("document.png")
boxes = detector(image)
crops = [crop_box(image, box) for box in boxes]

# Rotate upside-down text lines
for i, (label, score) in enumerate(classifier(crops)):
    if label == "180" and score >= classifier.conf_thres:
        crops[i] = cv2.rotate(crops[i], cv2.ROTATE_180)

for text, score in recognizer(crops):
    print(f"{score:.2f}  {text}")

Visualization

from akaocr import highlight

results = recognizer(crops)
cv2.imwrite("overlay.png", highlight(image, boxes, results))              # labels above boxes
cv2.imwrite("side.png", highlight(image, boxes, results, layout="side"))  # image | text panel

API

All engines accept BGR images as NumPy arrays, the format returned by cv2.imread. Grayscale and BGRA images are converted automatically. Every engine takes model_path (defaults to the bundled model) and device ("cpu" or "gpu").

BoxEngine: text detection

Returns a list of (4, 2) arrays (top-left, top-right, bottom-right, bottom-left), sorted in reading order.

Parameter Default Description
side_len 960 Target side length for resizing
limit_type "min" "min" enlarges small images; "max" shrinks large ones
conf_thres 0.5 Minimum box confidence
mask_thes 0.4 Pixel threshold for the probability map
unclip_ratio 2.0 Box expansion; larger values give looser boxes
max_candidates 1000 Maximum regions examined per image

TextEngine: text recognition

Accepts one crop or a list of crops. Returns [(text, confidence), ...] in input order.

Parameter Default Description
vocab_path None Custom vocabulary file, one character per line
use_space_char True Recognize spaces
batch_sizes 32 Crops per inference batch
model_shape (3, 48, 320) Model input shape (C, H, W)
max_wh_ratio None Fixed width/height ratio per batch (capped at 10)

Japanese output may contain the ideographic space " ".

ClsEngine: orientation classification

Accepts one crop or a list of crops. Returns [(label, confidence), ...], where label is "0" or "180".

Parameter Default Description
conf_thres 0.75 Suggested rotation threshold. Stored for your use; the engine does not apply it
batch_size 32 Crops per inference batch

highlight: visualization

highlight(image, boxes, results=None, *, layout="overlay", ...) returns a new BGR image. Options: layout ("overlay" or "side"), min_score, show_score, font_path, font_size, alpha, thickness. Pass font_path if Japanese labels show as empty squares.

Error handling

Calling an engine directly never raises. On failure it logs the error through Python's logging module and returns None. Use predict() to raise exceptions instead:

boxes = detector.predict(image)

Performance tips

  • Create engines once and reuse them. Loading a model costs far more than one inference.
  • Pass all crops in a single call. They are sorted by width and batched automatically.
  • On CPU, a smaller batch_sizes (e.g. 8) reduces padding and can be noticeably faster.

Metadata

Release files for akaocr 2.1.8

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

Source distribution (sdist)

Source distribution for akaocr 2.1.8
File Size Uploaded Provenance Actions
akaocr-2.1.8.tar.gz 16.8 MB Without provenance Details for akaocr-2.1.8.tar.gz

Built distribution (wheel)

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

Total release size: 33.7 MB

Release files / akaocr-2.1.8.tar.gz

Download URL akaocr-2.1.8.tar.gz
Size 16.8 MB
Tags Source
SHA-256 checksum
How to use checksums
8952c4944b831ccc5c33adeb2b285b97224618e6e4da11c19223f481a33b469b
BLAKE2b-256 checksum
How to use checksums
5a53d489cef425e0cdcc2b1ea373181c11c32c2428b1494ef5efde3b7b07a8a3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Release files / akaocr-2.1.8-py3-none-any.whl

Download URL akaocr-2.1.8-py3-none-any.whl
Size 16.8 MB
Tags Python 3
SHA-256 checksum
How to use checksums
426e9b2e9ed42a95270dd3cd24f459fdf3e3e2524828324f191d7140c620b7f2
BLAKE2b-256 checksum
How to use checksums
4b7e0d5f56a18559c1655c44232ecddd270b5e045a5759e173eac9d540dd0f05
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.12.3

Security for akaocr 2.1.8

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