Skip to content

About

OCR captcha solver for Node.js — extract text from CAPTCHA images with Tesseract.js + Jimp. Auto-preprocessing (grayscale, binarize, invert, upscale, pad), multi-pass fallback, character whitelisting. Supports Buffer, URL, Base64 & Axios responses.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Latest commit

 

History

5 Commits

Folders and files

NameName
Last commit message
Last commit date
 
 
 
 
 
 

Repository files navigation

ocr-captcha-solver

OCR captcha solver for Node.js — extract text from CAPTCHA images with Tesseract.js + Jimp. Auto-preprocessing (grayscale, binarize, invert, upscale, pad), multi-pass fallback, character whitelisting. Supports Buffer, URL, Base64 & Axios responses.

It handles the messy parts for you: mixed image formats, dark/inverted backgrounds, noisy strokes, missing quiet zones, and edge-cut characters. Just pass in an image (Buffer, URL, Base64, or Axios response) and get clean text back.


✨ Features

  • 🔍 Automatic image format detection — PNG, JPEG, GIF, WEBP, BMP (and rejects HTML error pages).
  • 🧠 Smart preprocessing pipeline with Jimp:
    • Grayscale conversion
    • Contrast enhancement
    • Auto-inversion for dark backgrounds
    • Luminance binarization (thresholding)
    • Image upscaling (2.5× by default — Tesseract loves big letters)
    • Quiet-zone border padding
  • ♻️ Multi-pass OCR fallback — tries multiple Tesseract PSM modes and the raw image if preprocessing fails.
  • 🎯 Character whitelisting — restrict the alphabet for numeric-only or alphanumeric CAPTCHAs.
  • 🧾 Flexible input handling — Buffer, ArrayBuffer, Base64 data URL, raw binary string, HTTP(S) URL, or a full Axios response.
  • 🔧 Flexible function signatures — simple call or fine-grained options object.
  • 🐛 Debug logging built-in for troubleshooting low-confidence OCR results.

📦 Installation

npm install tesseract.js axios jimp

Note: tesseract.js downloads language data (~10 MB for eng) on first use. Ensure your environment has internet access, or configure a local langPath in Tesseract.


🚀 Quick Start

const { detectCaptcha } = require('./captcha-ocr');

// From an Axios response
const axios = require('axios');
const res = await axios.get('https://example.com/captcha.png', {
  responseType: 'arraybuffer'
});

const text = await detectCaptcha(res);
console.log('CAPTCHA text:', text);

That's it. The module handles normalization, preprocessing, OCR, and cleanup.


📖 API Reference

detectCaptcha(imageData, [expectedLengthOrOptions], [charWhitelist], [options])

Runs the full OCR pipeline and returns the extracted CAPTCHA text.

Parameters

Name Type Description
imageData Buffer | ArrayBuffer | string | Object The image. Accepts Buffer, URL, Base64 data URL, binary string, or Axios response.
expectedLengthOrOptions number | string | Object Optional. Either the expected character count, a whitelist string, or an options object.
charWhitelist string Optional. Characters Tesseract is allowed to return.
options Object Optional. Tuning options (see below).

Returns: Promise<string> — the cleaned, whitelisted text.


preprocessCaptcha(buffer, [options])

Runs the Jimp preprocessing pipeline independently. Useful if you want to inspect or cache preprocessed images.

Parameters

Name Type Default Description
buffer Buffer — Original image buffer.
options.scale number 2.5 Upscaling factor.
options.contrast number 0.4 Contrast boost (−1 to 1).
options.threshold number | null 140 Binarization cutoff (0–255). Set to null to disable.
options.autoInvert boolean true Invert dark backgrounds automatically.
options.padding number 16 Quiet-zone padding in pixels.
options.debug boolean false Enable log output.

Returns: Promise<Buffer> — preprocessed PNG buffer.


DEFAULT_WHITELIST

The default allowed-character set:

'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

🎛 Options Reference (detectCaptcha)

Option Type Default Description
expectedLength number null Expected number of characters (used for validation logging only).
charWhitelist string DEFAULT_WHITELIST Allowed characters.
preprocess boolean true Enable the Jimp preprocessing pipeline.
psm string '8' Tesseract page-segmentation mode. 8 = single word, 7 = single line, 6 = uniform block, 13 = raw line.
scale number 2.5 Image upscaling factor.
contrast number 0.4 Contrast boost.
threshold number 140 Binarization cutoff (0–255). null disables.
autoInvert boolean true Auto-invert dark backgrounds.
padding number 16 White quiet-zone padding (px).
debug boolean true Print pipeline logs.

💡 Usage Examples

1. Simplest call

const text = await detectCaptcha(imageBuffer);

2. Specify expected length

const text = await detectCaptcha(imageBuffer, 5);

3. Numeric-only CAPTCHA

const text = await detectCaptcha(imageBuffer, 5, '0123456789');

4. Full options object

const text = await detectCaptcha(imageBuffer, {
  expectedLength: 6,
  charWhitelist: '0123456789',
  psm: '7',
  scale: 3,
  contrast: 0.6,
  threshold: 150,
  autoInvert: true,
  padding: 20,
  debug: true
});

5. From a URL

const text = await detectCaptcha('https://example.com/api/captcha?id=123');

6. From a Base64 data URL

const text = await detectCaptcha('data:image/png;base64,iVBORw0KG...');

7. From an Axios response

const res = await axios.get('https://example.com/captcha.png', {
  responseType: 'arraybuffer'
});

const text = await detectCaptcha(res); // The whole response works

8. Only preprocess the image

const { preprocessCaptcha } = require('./captcha-ocr');

const cleanPng = await preprocessCaptcha(rawBuffer, {
  scale: 3,
  threshold: 128
});

require('fs').writeFileSync('debug.png', cleanPng);

9. Retry-on-failure loop (common in bot workflows)

async function solveWithRetry(maxAttempts = 5) {
  for (let i = 1; i <= maxAttempts; i++) {
    const res = await axios.get('https://example.com/captcha', {
      responseType: 'arraybuffer'
    });

    const text = await detectCaptcha(res, {
      expectedLength: 5,
      charWhitelist: '0123456789',
      debug: i === maxAttempts // only log on the last attempt
    });

    if (text.length === 5) return text;
    console.warn(`Attempt ${i} yielded "${text}", retrying...`);
  }
  throw new Error('Unable to solve CAPTCHA after retries');
}

🔬 How It Works

When you call detectCaptcha, the module runs this pipeline:

Input (Buffer | URL | Base64 | Axios response | ArrayBuffer)
        │
        ▼
┌───────────────────────────────────────┐
│ 1. normalizeInput()                   │ → converts everything to Buffer
├───────────────────────────────────────┤
│ 2. inspectImageBuffer()               │ → magic-byte format check
│                                       │   (rejects HTML error pages)
├───────────────────────────────────────┤
│ 3. Jimp preprocessing (optional)      │
│     • Greyscale                       │
│     • Contrast boost                  │
│     • Auto-invert dark backgrounds    │
│     • Binarize (threshold)            │
│     • Upscale (default 2.5×)          │
│     • Add white border padding        │
├───────────────────────────────────────┤
│ 4. Tesseract OCR — Pass 1             │ → whitelist + configured PSM
│    If empty → Pass 2 (PSM 7)          │
│    If empty → Pass 3 (raw buffer)     │
├───────────────────────────────────────┤
│ 5. Post-filter with whitelist regex   │ → strips invalid characters
└───────────────────────────────────────┘
        │
        ▼
   Clean text string

🧪 Tuning Tips

Different CAPTCHA providers behave differently. Try these tweaks if accuracy is low:

Symptom Suggested adjustment
Characters are cut off at edges Increase padding (e.g., 24).
Text is too small Increase scale (e.g., 3.5).
Background is noisy / patterned Lower threshold (e.g., 120) or disable with null.
Strokes are broken Raise contrast (e.g., 0.6).
Dark background not being inverted Enable debug: true and check luminance log.
Multi-line text misread Try psm: '6' (uniform block).
Numeric CAPTCHA misreads letters Set charWhitelist: '0123456789'.
OCR returns nothing on clean images Disable preprocessing with preprocess: false.

🐛 Troubleshooting

[OCR Error] Received HTML text instead of an image

Your HTTP request returned a webpage (e.g., a 403/404 error page) instead of image bytes.

Fix: Ensure Axios uses responseType: 'arraybuffer'.

axios.get(url, { responseType: 'arraybuffer' }); // ✅

[OCR Error] Received an empty 0-byte buffer

The server returned nothing. Common causes:

  • Missing/incorrect User-Agent header
  • Missing session cookie or referer
  • Server-side rate limiting or IP block

[OCR Error] Unsupported image input type

You passed something the module can't normalize (e.g., a plain object, undefined, a stream).

Fix: Convert to a Buffer first, or pass the URL / Axios response directly.

Low confidence scores in debug logs

  • Check whether preprocessing helped — try preprocess: false to compare.
  • Save the preprocessed image with preprocessCaptcha() and inspect it visually.
  • Adjust scale, threshold, or contrast as shown in the tuning table.

tesseract.js fails to download language data

If you're in an offline/restricted environment, configure Tesseract with a local langPath by patching the createWorker call in your fork, or copy eng.traineddata into the working directory.


📁 Module Exports

const {
  detectCaptcha,
  preprocessCaptcha,
  DEFAULT_WHITELIST
} = require('./captcha-ocr');
Export Type Purpose
detectCaptcha async function Main OCR entry point.
preprocessCaptcha async function Standalone Jimp preprocessing.
DEFAULT_WHITELIST string Default allowed character set.

✅ Requirements

  • Node.js ≥ 20
  • tesseract.js (installs its own WASM worker)
  • jimp (v1.x or v2.x — both supported)
  • axios (for URL input; not required if you only pass Buffers)

📜 License

MIT — use it, modify it, ship it. Attribution appreciated but not required.


🤝 Contributing

Found a CAPTCHA style that doesn't work well? Open an issue with:

  1. A sample (redacted/anonymized) image.
  2. The debug output from detectCaptcha.
  3. What you tried (psm, threshold, scale, etc.).

PRs that improve accuracy, add preprocessing options, or broaden input handling are welcome.

About

OCR captcha solver for Node.js — extract text from CAPTCHA images with Tesseract.js + Jimp. Auto-preprocessing (grayscale, binarize, invert, upscale, pad), multi-pass fallback, character whitelisting. Supports Buffer, URL, Base64 & Axios responses.

Topics

Resources

Stars

1 star

Watchers

0 watching

Forks

Contributors

Languages