Metadata-Version: 2.5
Name: captcha-onnx
Version: 1.0.1
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

**Lightweight, fast Python Captcha OCR library powered by ONNX Runtime — bundled CRNN-CTC model, no TensorFlow or OpenCV required.**

[![PyPI version](https://img.shields.io/pypi/v/captcha-onnx.svg)](https://pypi.org/project/captcha-onnx/)
[![PyPI downloads](https://img.shields.io/pypi/dm/captcha-onnx.svg)](https://pypi.org/project/captcha-onnx/)
[![Python versions](https://img.shields.io/pypi/pyversions/captcha-onnx.svg)](https://pypi.org/project/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)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://github.com/hotroso/captcha-onnx/blob/main/LICENSE)

`captcha-onnx` is an open-source, offline Python OCR library for recognizing fixed-alphabet alphanumeric captcha images using a pre-trained **CRNN + CTC** deep learning model exported to **ONNX**. It ships with a 1.7 MB model bundled directly inside the package and runs in milliseconds on CPU with only `onnxruntime`, `numpy`, and `pillow`.

---

## Sample Predictions

| Captcha Image | Predicted Text | Confidence |
| --- | :---: | :---: |
| ![2ABJNN](https://raw.githubusercontent.com/hotroso/captcha-onnx/main/assets/2ABJNN.png) | `2ABJNN` | `98.4%` |
| ![2B87DN](https://raw.githubusercontent.com/hotroso/captcha-onnx/main/assets/2B87DN.png) | `2B87DN` | `90.6%` |
| ![2BENRW](https://raw.githubusercontent.com/hotroso/captcha-onnx/main/assets/2BENRW.png) | `2BENRW` | `98.9%` |
| ![2BFZBG](https://raw.githubusercontent.com/hotroso/captcha-onnx/main/assets/2BFZBG.png) | `2BFZBG` | `97.9%` |
| ![2C7WKD](https://raw.githubusercontent.com/hotroso/captcha-onnx/main/assets/2C7WKD.png) | `2C7WKD` | `99.6%` |

---

## Why `captcha-onnx`?

| Feature | `captcha-onnx` (ONNX Runtime) | Traditional TensorFlow + OpenCV |
| --- | --- | --- |
| **Core dependencies** | `onnxruntime`, `numpy`, `pillow` | `tensorflow` (~1 GB), `opencv-python` |
| **Bundled model** | Ready out of the box (`default.onnx`, 1.7 MB) | Manual model download & path setup |
| **Disk I/O** | 100% in-memory (`bytes`, `BytesIO`, `PIL`, `ndarray`) | Often writes temp files to disk |
| **Batch inference** | Native single forward pass (`predict_batch`) | Usually loops image-by-image |
| **Offline & free** | Runs locally on CPU/GPU, zero external API calls | Local or cloud |
| **Python support** | Python 3.10 – 3.13 (Linux, macOS, Windows) | Often pinned to older Python/TF versions |

---

## Installation

Install from [PyPI](https://pypi.org/project/captcha-onnx/):

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

Or with [`uv`](https://docs.astral.sh/uv/):

```bash
uv add captcha-onnx
```

### Optional Extras

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

# Convert custom Keras CRNN .h5 models to lightweight .onnx
pip install "captcha-onnx[convert]"
```

---

## Quick Start

### 1. One-line OCR prediction

```python
import captcha_onnx

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

### 2. In-memory bytes, `BytesIO`, `PIL.Image`, or `numpy.ndarray`

No temporary files needed — pass image bytes directly from HTTP requests, web apps, or memory buffers:

```python
import io
from PIL import Image
import captcha_onnx

raw_bytes = open("assets/2C7WKD.png", "rb").read()

# All of these produce '2C7WKD'
captcha_onnx.predict(raw_bytes)
captcha_onnx.predict(io.BytesIO(raw_bytes))
captcha_onnx.predict(Image.open("assets/2C7WKD.png"))
```

### 3. Confidence scores & reusable recognizer

```python
from captcha_onnx import CaptchaOCR

ocr = CaptchaOCR()
result = ocr.predict_result("assets/2C7WKD.png")

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

### 4. Batch inference

Process multiple images in a single ONNX forward pass:

```python
import captcha_onnx

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

---

## Using Custom Models & GPU Acceleration

`captcha-onnx` supports custom ONNX CRNN-CTC models, custom character alphabets, GPU execution providers (e.g. CUDA / CoreML), and legacy Keras `.h5`/`.keras` models:

```python
from captcha_onnx import CaptchaOCR, OCRConfig

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

# Custom ONNX model with optional GPU acceleration
ocr = CaptchaOCR(
    model_path="path/to/custom_model.onnx",
    config=config,
    providers=["CUDAExecutionProvider", "CPUExecutionProvider"],
)

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

### Convert a Keras CRNN `.h5` Model to ONNX

Export a Keras CRNN-CTC `.h5` checkpoint to `.onnx` without installing TensorFlow:

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

---

## API Reference

| Symbol | Description |
| --- | --- |
| `captcha_onnx.predict(image)` | Recognize text from a single image using the cached default recognizer. |
| `captcha_onnx.predict_result(image)` | Return a `PredictionResult(text, confidence, char_confidences)`. |
| `captcha_onnx.predict_batch(images)` | Recognize a sequence of images in a single batch forward pass. |
| `captcha_onnx.predict_batch_results(images)` | Batch variant returning `list[PredictionResult]`. |
| `CaptchaOCR(model_path=None, config=None, backend=None, providers=None)` | Configurable recognizer class (supports custom `.onnx`, `.h5`/`.keras`, or custom `InferenceBackend`). |
| `OCRConfig(characters, image_width, image_height, blank_index, trim_end, transpose_image)` | Immutable preprocessing and CTC decoding configuration. |
| `CaptchaOCRError` | Base exception (`ModelLoadError`, `ImageLoadError`, `BackendNotInstalledError`). |

---

## Default Model Specifications

| Property | Value |
| --- | --- |
| **Architecture** | 2× Conv2D + MaxPooling2D → Dense → 2× Bidirectional LSTM → Softmax + CTC |
| **Model format** | ONNX (`opset 17`, dynamic batch size, `1.71 MB`) |
| **Input tensor** | `[batch, 200, 40, 1]` (`float32`, grayscale normalized to `[0, 1]`) |
| **Character set (29 chars)** | `2356789ABCDEFGHJKMNPQRSTVWXYZ` |

---

## FAQ

**Does `captcha-onnx` require internet access or API keys?**
No. Inference runs 100% locally and offline using the bundled ONNX model.

**Can I run inference on GPU?**
Yes. Install `onnxruntime-gpu` and pass `providers=["CUDAExecutionProvider", "CPUExecutionProvider"]` to `CaptchaOCR(...)`.

**What image formats are supported?**
Any format readable by Pillow (`PNG`, `JPEG`, `BMP`, `WEBP`, `GIF`, etc.), as well as `PIL.Image.Image` and 2D/3D `numpy.ndarray` objects.

---

## Development

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

# Run tests
pytest

# Lint with Ruff
ruff check src tests scripts

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

## License

Released under the [MIT License](LICENSE). Copyright © [hotroso](https://github.com/hotroso).
