digit-recognizer-py
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)
pip install digit-recognizer-py
From Local Source (Development / Editable mode)
git clone https://github.com/shivam-gupta90/handwriting-recognition.git
cd "handwriting recognition"
pip install -e .
🚀 Quickstart
1. Simplest One-Liner (Returns int)
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
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:
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:
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:
# Print just the predicted digit:
digit-recognizer sample.png
# Print detailed confidence and top predictions:
digit-recognizer sample.png --detailed
Output:
===================================
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): IfFalse, returnsint(0-9). IfTrue, returns aPredictionResultobject.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 digits0through9.
🚢 Publishing to PyPI
To publish this library to PyPI so anyone can install it with pip install digit-recognizer-py:
-
Install build and twine:
pip install build twine
-
Build the wheel and source distribution:
python -m build
-
Upload to TestPyPI (recommended first):
twine upload --repository testpypi dist/*
-
Upload to PyPI (production):
twine upload dist/*
📄 License
This project is licensed under the MIT License.
Metadata
Release files for digit-recognizer-py 0.1.0
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | |
|---|---|---|---|
| digit_recognizer_py-0.1.0.tar.gz | 1.5 MB | Details |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Reset |
|---|---|---|---|---|
| digit_recognizer_py-0.1.0-py3-none-any.whl | Python 3 | none | any | Details |
Total release size: 2.9 MB
Release files / digit_recognizer_py-0.1.0.tar.gz
| Download URL | digit_recognizer_py-0.1.0.tar.gz |
|---|---|
| Size | 1.5 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
0f3a8325bb4a06c63c4f7f111d7c4a11429e5acacafa16d5faecca69edc61098
|
|
BLAKE2b-256 checksum How to use checksums |
cc88c51b564e344f19b28e4431ce7e46e9ad6891f58f347d712b9468f183dc04
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.1
|
Release files / digit_recognizer_py-0.1.0-py3-none-any.whl
| Download URL | digit_recognizer_py-0.1.0-py3-none-any.whl |
|---|---|
| Size | 1.5 MB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
58a3132a4c3ccf04175142e0c9464e5fe132421aa26d7130cbd6b1d2c03c7b12
|
|
BLAKE2b-256 checksum How to use checksums |
1730e862b4c4a8224695906ed4e4a09061ee5a210b9bbe22adf17cff345c5969
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.13.1
|