Metadata-Version: 2.4
Name: digit-recognizer-py
Version: 0.1.0
Summary: A lightweight handwritten digit recognition Python library with pre-trained PyTorch CNN.
Author: Shivam Gupta
License-Expression: MIT
Keywords: digit-recognition,mnist,handwriting,cnn,pytorch,computer-vision
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Intended Audience :: Science/Research
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.8
Classifier: Programming Language :: Python :: 3.9
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: Operating System :: OS Independent
Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
Classifier: Topic :: Scientific/Engineering :: Image Recognition
Requires-Python: >=3.8
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: torch>=2.0.0
Requires-Dist: torchvision>=0.15.0
Requires-Dist: pillow>=9.0.0
Requires-Dist: numpy>=1.20.0
Provides-Extra: web
Requires-Dist: Flask>=3.0.0; extra == "web"
Provides-Extra: dev
Requires-Dist: pytest>=7.0.0; extra == "dev"
Requires-Dist: build>=1.0.0; extra == "dev"
Requires-Dist: twine>=4.0.0; extra == "dev"
Dynamic: license-file

# digit-recognizer-py

[![Python Version](https://img.shields.io/badge/python-3.8+-blue.svg)](https://pypi.org/project/digit-recognizer-py/)
[![License: MIT](https://img.shields.io/badge/License-MIT-green.svg)](https://opensource.org/licenses/MIT)

A lightweight, production-ready Python library for handwritten digit recognition powered by a pre-trained PyTorch Convolutional Neural Network (CNN).

Anyone can install it with `pip` and recognize handwritten digits from any image in just two lines of code—**no model training or weight downloading required**.

---

## ✨ Features

- **Batteries-Included**: Pre-trained PyTorch weights (`~1.5 MB`) bundled directly inside the library.
- **2-Line API**: Call `predict("image.png")` and get the predicted digit (`0-9`).
- **Flexible Inputs**: Accepts image file paths (`str`, `Path`), PIL Images, NumPy arrays (OpenCV), raw bytes, or file streams.
- **Smart Auto-Inversion**: Automatically detects light backgrounds (e.g., black pen on white paper) and inverts them to match standard MNIST format (white strokes on dark background).
- **Detailed Probability Scores**: Get confidence scores and the full probability distribution across all 10 digits (`0-9`).
- **Built-in CLI**: Run predictions directly from your terminal using `digit-recognizer path/to/image.png`.
- **GPU & Apple Silicon (MPS) Acceleration**: Automatically detects and uses CUDA or Apple Silicon GPU if available, with smooth CPU fallback.

---

## 📦 Installation

### From PyPI (once published)
```bash
pip install digit-recognizer-py
```

### From Local Source (Development / Editable mode)
```bash
git clone https://github.com/shivam-gupta90/handwriting-recognition.git
cd "handwriting recognition"
pip install -e .
```

---

## 🚀 Quickstart

### 1. Simplest One-Liner (Returns `int`)

```python
import digit_recognizer

# Pass the image path directly
digit = digit_recognizer.predict("sample_digit.png")
print("Predicted digit:", digit)  # e.g., 7
```

### 2. Get Confidence & Probabilities

```python
import digit_recognizer

result = digit_recognizer.predict("sample_digit.png", detailed=True)

print(f"Digit:      {result.digit}")         # 7
print(f"Confidence: {result.confidence:.2%}")  # 98.45%
print("Top 3 Predictions:", result.top_3)    # [(7, 0.9845), (1, 0.012), (2, 0.001)]
```

### 3. Using PIL, OpenCV, or Web Uploads

The library seamlessly accepts multiple input types:

```python
import cv2
from PIL import Image
import digit_recognizer

# Input as PIL Image
pil_img = Image.open("sample.png")
digit = digit_recognizer.predict(pil_img)

# Input as NumPy array (OpenCV)
cv_img = cv2.imread("sample.png")
digit = digit_recognizer.predict(cv_img)

# Input as raw bytes (FastAPI / Flask upload)
with open("sample.png", "rb") as f:
    byte_data = f.read()
digit = digit_recognizer.predict(byte_data)
```

### 4. Object-Oriented Interface

For high-throughput applications or custom models:

```python
from digit_recognizer import DigitRecognizer

# Initialize recognizer (model loads once into memory)
recognizer = DigitRecognizer(device="cpu")

# Predict repeatedly
for image_path in ["img1.png", "img2.png", "img3.png"]:
    print(recognizer.predict(image_path))
```

---

## 🖥️ Command Line Interface (CLI)

After installation, you can use the command-line tool `digit-recognizer`:

```bash
# Print just the predicted digit:
digit-recognizer sample.png

# Print detailed confidence and top predictions:
digit-recognizer sample.png --detailed
```

Output:
```text
===================================
  Predicted Digit: 7
  Confidence:      99.12%
===================================
  Top Predictions:
    1. Digit '7': 99.12%
    2. Digit '1': 0.72%
    3. Digit '2': 0.08%
===================================
```

---

## 🛠️ API Reference

### `digit_recognizer.predict(image_input, detailed=False, invert='auto', device=None)`
- **`image_input`**: Filepath (`str`, `Path`), `PIL.Image`, `numpy.ndarray`, `bytes`, or file-like object.
- **`detailed`** *(bool, default=False)*: If `False`, returns `int` (0-9). If `True`, returns a `PredictionResult` object.
- **`invert`** *(str or bool, default='auto')*:
  - `'auto'`: Automatically detects if the background is light (e.g. paper) and inverts it to dark background with white strokes.
  - `True`: Forces color inversion.
  - `False`: Keeps original colors.
- **`device`** *(str or torch.device, optional)*: Override inference device (`'cpu'`, `'cuda'`, `'mps'`).

### `digit_recognizer.predict_proba(image_input, invert='auto', device=None)`
- Returns a `list[float]` of length 10 containing predicted probabilities for digits `0` through `9`.

---

## 🚢 Publishing to PyPI

To publish this library to PyPI so anyone can install it with `pip install digit-recognizer-py`:

1. **Install build and twine**:
   ```bash
   pip install build twine
   ```

2. **Build the wheel and source distribution**:
   ```bash
   python -m build
   ```

3. **Upload to TestPyPI (recommended first)**:
   ```bash
   twine upload --repository testpypi dist/*
   ```

4. **Upload to PyPI (production)**:
   ```bash
   twine upload dist/*
   ```

---

## 📄 License

This project is licensed under the [MIT License](LICENSE).
