Metadata-Version: 2.4
Name: akaocr
Version: 2.1.8
Summary: OCR Package Tools
Author: LauNT
License-Expression: Apache-2.0
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
License-File: NOTICE
Requires-Dist: numpy
Requires-Dist: opencv-python
Requires-Dist: onnxruntime
Requires-Dist: pyclipper
Requires-Dist: Pillow
Provides-Extra: gpu
Requires-Dist: onnxruntime-gpu; extra == "gpu"
Dynamic: license-file

# OCR Package Tools

[![PyPI](https://img.shields.io/pypi/v/akaocr)](https://pypi.org/project/akaocr/)
[![License](https://img.shields.io/badge/License-Apache%202.0-blue)](https://www.apache.org/licenses/LICENSE-2.0)
[![Python](https://img.shields.io/badge/python-3.7+-blue)](https://www.python.org/)
[![ONNX](https://img.shields.io/badge/ONNX-Compatible-brightgreen)](https://onnx.ai/)

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

```bash
pip install akaocr
```

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

## Quick start

```python
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

```python
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:

```python
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.
