Metadata-Version: 2.5
Name: captcha-onnx
Version: 1.0.0
Summary: Lightweight CRNN-CTC captcha OCR library powered by ONNX Runtime with a bundled pre-trained model.
Project-URL: Homepage, https://github.com/hotroso/captcha-onnx
Project-URL: Repository, https://github.com/hotroso/captcha-onnx
Project-URL: Issues, https://github.com/hotroso/captcha-onnx/issues
Author: hotroso
License: MIT License
        
        Copyright (c) 2023 hotroso
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
License-File: LICENSE
Keywords: captcha,computer-vision,crnn,ctc,ocr,onnx,onnxruntime
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: License :: OSI Approved :: MIT License
Classifier: Operating System :: OS Independent
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Classifier: Typing :: Typed
Requires-Python: >=3.10
Requires-Dist: numpy>=1.24.0
Requires-Dist: onnxruntime>=1.16.0
Requires-Dist: pillow>=10.0.0
Provides-Extra: convert
Requires-Dist: h5py>=3.8.0; extra == 'convert'
Requires-Dist: onnx>=1.14.0; extra == 'convert'
Provides-Extra: dev
Requires-Dist: build>=1.0.0; extra == 'dev'
Requires-Dist: pytest>=8.0.0; extra == 'dev'
Requires-Dist: ruff>=0.6.0; extra == 'dev'
Provides-Extra: tensorflow
Requires-Dist: tensorflow>=2.11.0; extra == 'tensorflow'
Description-Content-Type: text/markdown

# captcha-onnx

[![CI](https://github.com/hotroso/captcha-onnx/actions/workflows/ci.yml/badge.svg)](https://github.com/hotroso/captcha-onnx/actions/workflows/ci.yml)
[![Python 3.10+](https://img.shields.io/badge/python-3.10%2B-blue.svg)](https://www.python.org/downloads/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)

Lightweight, fast Python OCR library for reading fixed-alphabet alphanumeric captcha images using a bundled CRNN-CTC model powered by **ONNX Runtime** — **no TensorFlow or OpenCV required**.

## Features

- **Zero-config, bundled model**: Ships with a pre-trained 1.7 MB ONNX model (`default.onnx`) ready to use immediately after `pip install`.
- **Lightweight & fast**: Only depends on `onnxruntime`, `numpy`, and `pillow` (works on Python 3.10–3.13 across Linux, macOS, and Windows).
- **Flexible inputs**: Accepts file paths (`str` / `Path`), raw `bytes` / `bytearray`, binary file streams (`BytesIO`), `PIL.Image.Image`, and `numpy.ndarray` directly in memory (no temporary files on disk).
- **Batch inference & confidence scores**: Run multiple images in a single forward pass and inspect per-character confidence scores.
- **Extensible**: Bring your own custom `.onnx` model and character set, or load legacy Keras `.h5` / `.keras` models via the optional `[tensorflow]` extra.

## Installation

```bash
pip install captcha-onnx
```

Install from GitHub:

```bash
pip install git+https://github.com/hotroso/captcha-onnx.git
```

Optional extras:

```bash
# Support loading legacy Keras .h5 / .keras models directly
pip install "captcha-onnx[tensorflow]"

# Tools for converting Keras CRNN .h5 models to .onnx
pip install "captcha-onnx[convert]"
```

## Quick Start

### One-line prediction

```python
import captcha_onnx

# From a file path
text = captcha_onnx.predict("assets/2ABJNN.png")
print(text)  # '2ABJNN'

# From raw bytes (e.g. downloaded image or HTTP upload)
with open("assets/2C7WKD.png", "rb") as f:
    text = captcha_onnx.predict(f.read())
print(text)  # '2C7WKD'

# Batch prediction
texts = captcha_onnx.predict_batch(["assets/2ABJNN.png", "assets/2BENRW.png"])
print(texts)  # ['2ABJNN', '2BENRW']
```

### Confidence scores & reusable recognizer

```python
from PIL import Image
from captcha_onnx import CaptchaOCR

ocr = CaptchaOCR()

img = Image.open("assets/2C7WKD.png")
result = ocr.predict_result(img)

print(result.text)              # '2C7WKD'
print(result.confidence)        # ~0.996
print(result.char_confidences)  # per-character probabilities
```

### Custom ONNX or Keras model

```python
from captcha_onnx import CaptchaOCR, OCRConfig

config = OCRConfig(
    characters=tuple("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"),
    image_width=200,
    image_height=40,
    trim_end=0,
)

# Custom ONNX model (also supports GPU providers such as CUDAExecutionProvider)
ocr = CaptchaOCR(
    model_path="path/to/my_model.onnx",
    config=config,
    providers=["CPUExecutionProvider"],
)

# Or load a Keras .h5 / .keras model (requires `pip install captcha-onnx[tensorflow]`)
tf_ocr = CaptchaOCR(model_path="path/to/my_model.h5", config=config)
```

## Default Model Specifications

| Property | Value |
| --- | --- |
| Architecture | 2-layer CNN + 2-layer Bidirectional LSTM + CTC |
| Format | ONNX (`opset 17`, dynamic batch size, ~1.7 MB) |
| Input size | `200 × 40` grayscale (`float32` normalized to `[0, 1]`) |
| Character set (29 chars) | `2356789ABCDEFGHJKMNPQRSTVWXYZ` |

## Converting a Keras `.h5` Model to ONNX

If you train a new CRNN-CTC model with the same architecture and want to export it to lightweight ONNX without TensorFlow:

```bash
pip install "captcha-onnx[convert]"
python scripts/convert_h5_to_onnx.py --input my_model.h5 --output my_model.onnx
```

## Development

```bash
git clone https://github.com/hotroso/captcha-onnx.git
cd captcha-onnx
pip install -e ".[dev]"

# Run unit tests
pytest

# Lint code
ruff check src tests scripts

# Build sdist & wheel
python -m build
```

## Publishing to PyPI

This repository includes a Trusted Publishing workflow at `.github/workflows/publish.yml`.
1. Configure a Trusted Publisher on PyPI for `hotroso/captcha-onnx` (`publish.yml`, environment `pypi`).
2. Bump `version` in `pyproject.toml` and `src/captcha_onnx/__init__.py`.
3. Create and publish a GitHub Release — the workflow builds and uploads the wheel & sdist automatically.

## License

MIT License — see [LICENSE](LICENSE) for details.
