Skip to main content

🔍 CapSnap

A pure-Python CAPTCHA solver & OCR engine — built from scratch, zero dependencies

PyPI version Python License: MIT CI Downloads

No Tesseract. No OpenCV. No NumPy. No Pillow. Just Python.


🤔 What is CapSnap?

CapSnap is a production-quality CAPTCHA solver and OCR engine written entirely in the Python standard library with zero external dependencies. It implements every component from scratch:

  • 📦 Custom PNG decoder
  • 🖼️ Grayscale conversion & Otsu's binarization
  • 🔗 Connected-component labeling for character isolation
  • 🧠 Multi-Layer Perceptron (MLP) neural network — trained on real CAPTCHA images
  • ✂️ 5-way forced vertical slicing for noisy CAPTCHAs

It ships with a pre-trained model specifically tuned for noisy, handwritten-style CAPTCHA characters used by real-world websites — and it can be retrained on any new CAPTCHA style in minutes.


✨ Key Features

Feature Details
🚫 Zero dependencies Pure Python standard library only — nothing to pip install
🔓 CAPTCHA solver Built-in mode for 4–5 character noisy CAPTCHAs
🧠 Neural network OCR Custom MLP with ReLU hidden layer and softmax output
📸 Universal input File path, pathlib.Path, raw bytes, or base64 data-URL
🏋️ Self-trainable Retrain on any CAPTCHA dataset — answers extracted from API tokens automatically
🖥️ CLI included capsnap captcha.png works out of the box
Lightweight < 2 MB installed, starts instantly, no warmup
🔒 Privacy-first Runs 100% locally — no API calls, no cloud, no data leaks

📦 Installation

pip install capsnap

No extra dependencies. No system libraries. Works on Python 3.11+.


🚀 Quick Start — CAPTCHA Solving

from capsnap import OCR

# Initialize in CAPTCHA mode
ocr = OCR(mode="captcha")

# Solve from a file path
result = ocr.read("captcha.png")
print(result.text)        # e.g. "RF3rH"
print(result.confidence)  # e.g. 0.923

Feed it anything

# From a URL / API response (base64 data-URL)
result = ocr.read("data:image/png;base64,iVBORw0KGgo...")

# From raw bytes (e.g. requests response)
import urllib.request
with urllib.request.urlopen("https://example.com/captcha") as r:
    result = ocr.read(r.read())

# From a pathlib.Path
from pathlib import Path
result = ocr.read(Path("captcha.png"))

Full example — solve a live CAPTCHA from an API

import json
import urllib.request
import base64
from capsnap import OCR

url = "https://example.com/api/captcha"
req = urllib.request.Request(url, headers={"accept": "application/json"})
with urllib.request.urlopen(req) as response:
    data = json.loads(response.read().decode())

# Pass the base64 image directly to CapSnap
ocr = OCR(mode="captcha")
result = ocr.read(data["image"])  # data:image/png;base64,...
print(result.text)

🖥️ CLI Usage

# Solve a CAPTCHA image
capsnap --mode captcha captcha.png

# Standard document OCR
capsnap document.png

🔄 All Input Methods

from capsnap import OCR
ocr = OCR(mode="captcha")

ocr.read("captcha.png")                    # file path string
ocr.read(Path("captcha.png"))              # pathlib.Path
ocr.read(open("captcha.png", "rb").read()) # raw bytes
ocr.read("data:image/png;base64,...")      # base64 data-URL

# Explicit methods still available
ocr.read_path("captcha.png")
ocr.read_bytes(raw_bytes)
ocr.read_base64(b64_string)

🏗️ Architecture

Input (path / bytes / base64)
          │
          ▼
   ┌─────────────┐
   │ PNG Decoder │ ← pure Python, no Pillow
   └──────┬──────┘
          │
          ▼
   ┌─────────────┐
   │  Grayscale  │ ← luminance-weighted conversion
   └──────┬──────┘
          │
          ▼
   ┌─────────────┐
   │    Otsu     │ ← auto threshold binarization
   └──────┬──────┘
          │
     ┌────┴─────────────────────┐
     │ CAPTCHA mode             │ Document mode
     │ 5-way vertical slicing   │ Connected-component labeling
     └────────────┬─────────────┘
                  │
                  ▼
         ┌──────────────┐
         │ Feature Ext. │ ← normalized 20×20 patch
         └──────┬───────┘
                │
                ▼
         ┌──────────────┐
         │  MLP Network │ ← ReLU hidden → Softmax output
         └──────┬───────┘
                │
                ▼
          OCRResult
       (text, confidence)

🎯 Retraining on Any CAPTCHA

CapSnap can retrain its neural network on any CAPTCHA style automatically if the API exposes the answer in the response token. No manual labeling needed:

# Fetch 1000 real CAPTCHAs and retrain the model
PYTHONPATH=. python tools/train_from_tokens.py

The training script:

  1. Fetches live CAPTCHAs from the target API
  2. Decodes the correct answer from the API's JWT/token
  3. Extracts and normalizes character patches
  4. Trains the MLP for 100 epochs
  5. Saves the updated capsnap/model.capsnap automatically

📁 Project Structure

capsnap/
├── capsnap/               ← installable package
│   ├── api.py             ← OCR class (universal entry point)
│   ├── model.py           ← MLP neural network (pure Python)
│   ├── model.capsnap      ← pre-trained weights (bundled)
│   ├── recognize.py       ← character recognition
│   ├── decoder/           ← pure-Python PNG decoder
│   ├── components.py      ← connected-component labeling
│   ├── features.py        ← patch extraction + resize
│   ├── grayscale.py       ← RGB → grayscale
│   ├── threshold.py       ← Otsu's binarization
│   ├── morphology.py      ← noise removal
│   ├── segmentation.py    ← line/word grouping
│   └── cli.py             ← CLI entry point
├── tests/                 ← offline unit tests
├── examples/              ← usage examples
├── assets/                ← images & donation QR codes
└── .github/workflows/     ← CI + auto-publish to PyPI

🧪 Testing

pip install -e ".[dev]"
pytest tests/ -v

All 8 tests run offline — no network, no API calls required.


💖 Support & Donations

CapSnap is free and open-source. If it saved you time, helped bypass a pesky CAPTCHA, or powered your project, consider buying me a coffee! ☕

🇧🇩 bKash / Nagad / Rocket (Bangladesh)

Bangladesh Mobile Payment QR

💎 Telegram Stars / TON (Gram)

Telegram TON QR

🪙 Litecoin (LTC)

Litecoin QR

💵 USDT (BEP20)

USDT QR

Every contribution — big or small — keeps this project alive. Thank you! 🙏


📄 License

MIT License — see LICENSE for details.


Made with ❤️ by @anbuinfosec · Pure Python · Zero Dependencies

Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

capsnap-1.0.1.tar.gz (534.6 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

capsnap-1.0.1-py3-none-any.whl (534.0 kB view details)

Uploaded Python 3

File details

Details for the file capsnap-1.0.1.tar.gz.

File metadata

  • Download URL: capsnap-1.0.1.tar.gz
  • Upload date:
  • Size: 534.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.11.16

File hashes

Hashes for capsnap-1.0.1.tar.gz
Algorithm Hash digest
SHA256 22fc57e08f3bfdcb6ff413c49830dec4f43792aed255831fa99149a32d7c83ba
MD5 661df4e7d5a9e4f85028e8e433a7851b
BLAKE2b-256 64e60531ce1b4685f7d30c24da3a6c8161ff3635a12776fb16208ff65939d96a

See more details on using hashes here.

File details

Details for the file capsnap-1.0.1-py3-none-any.whl.

File metadata

  • Download URL: capsnap-1.0.1-py3-none-any.whl
  • Upload date:
  • Size: 534.0 kB
  • Tags: Python 3
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/7.0.0 CPython/3.11.16

File hashes

Hashes for capsnap-1.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 96d151e51376d3138fbc34b1dd3d500c19c22f46b75eff60ed809f59d115045e
MD5 e70fcb7f9b90f1d66cbfbe156943febc
BLAKE2b-256 1fd4417aa4b477e5e275f99da304be3ece570e347e3fc0aeba2354b33357b681

See more details on using hashes here.

Release history Release notifications | RSS feed

1.0.2

2 files

This release

1.0.1 This release

2 files

1.0.0

2 files

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page