npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

captcha-ocr

v1.0.0

Published

TypeScript captcha OCR recognizer with configurable profiles and rules

Readme

captcha-ocr

English | 中文

captcha-ocr 是一个用于图形算术验证码识别的 TypeScript OCR 包。它支持图片数据和 Base64 输入,可以对复杂图片进行预处理,使用 Tesseract OCR 识别文本,并通过可配置的 Profile 和 Rule 系统解析、计算识别结果。

环境要求

  • Node.js 20 或更高版本
  • sharp 支持的原生运行环境

首次调用 OCR 时,Tesseract 可能会下载英文训练数据(eng.traineddata)。请确保运行环境在首次初始化时可以访问网络,或者通过 Tesseract 配置提供训练数据。

安装

pnpm add captcha-ocr

包内同时提供 ESM、CommonJS 和 TypeScript 类型声明。

快速开始

import {
  closeDefaultRecognizer,
  recognizeCaptcha
} from 'captcha-ocr';

const result = await recognizeCaptcha(imageData);

if (result.ok) {
  console.log(result.expression); // 7*9
  console.log(result.answer);     // 63
} else {
  console.error(result.error?.code, result.error?.message);
}

await closeDefaultRecognizer();

imageData 支持以下类型:

  • Buffer
  • Uint8Array
  • 纯 Base64 字符串
  • 图片 Data URL,例如 data:image/png;base64,...

复用识别器

服务端连续识别多张图片时,建议创建一个识别器并复用,避免为每个请求重复初始化 OCR Worker。

import {
  arithmeticProfile,
  createRecognizer
} from 'captcha-ocr';

const recognizer = createRecognizer({
  profile: arithmeticProfile
});

const first = await recognizer.recognize(firstImage);
const second = await recognizer.recognize(secondImage);

await recognizer.close();

识别器不再使用时,请调用 close() 释放 Worker 资源。

识别结果

interface RecognitionResult<TAnswer> {
  ok: boolean;
  profileId: string;
  ocrText: string;
  normalizedText: string;
  expression: string | null;
  answer: TAnswer | null;
  error: {
    code: string;
    message: string;
  } | null;
  ocrVariant: 'original' | 'threshold';
  durationMs: number;
  source: {
    width: number | null;
    height: number | null;
    format: string | null;
  };
  preprocess: {
    mode: 'original' | 'threshold';
    scale: number;
    threshold: number | null;
  };
  processedImage?: Buffer;
}

默认不会返回处理后的图片。调试预处理结果时,可以显式开启:

const result = await recognizer.recognize(imageData, {
  includeProcessedImage: true
});

console.log(result.processedImage);

内置算术规则

默认的 arithmeticProfile 支持:

  • +
  • -
  • *
  • /

常见 OCR 变体会自动归一化:xX×· 会转换为 *÷ 会转换为 /。表达式使用固定解析器计算,不会调用 eval

也可以单独导入算术规则:

import {
  arithmeticProfile,
  createArithmeticRule
} from 'captcha-ocr/rules/arithmetic';

自定义 Profile 和 Rule

识别器不限于算术验证码。Profile 定义 OCR 参数和预处理方式,Rule 负责对识别文本进行归一化、解析和计算。

import {
  createRecognizer,
  type CaptchaProfile,
  type CaptchaRule
} from 'captcha-ocr';

interface ParsedCode {
  value: string;
}

const rule: CaptchaRule<ParsedCode, string> = {
  id: 'fixed-code-v1',

  normalize(text) {
    return text.trim().toUpperCase();
  },

  parse(text) {
    const normalized = this.normalize(text);

    if (!/^[A-F0-9]{4}$/.test(normalized)) {
      return {
        ok: false,
        normalized,
        error: {
          code: 'CODE_NOT_MATCHED',
          message: '无法识别为四位十六进制编码。'
        }
      };
    }

    return {
      ok: true,
      normalized,
      expression: normalized,
      parsed: {
        value: normalized
      }
    };
  },

  evaluate(parsed) {
    return parsed.value;
  }
};

const profile: CaptchaProfile<ParsedCode, string> = {
  id: 'fixed-code-v1',
  ocr: {
    language: 'eng',
    whitelist: '0123456789ABCDEF',
    pageSegMode: 7
  },
  rule
};

const recognizer = createRecognizer({ profile });
const result = await recognizer.recognize(imageData);
await recognizer.close();

这样可以复用统一的 OCR 流程,同时为不同验证码格式定义独立的解析和计算行为。

CommonJS

const {
  arithmeticProfile,
  createRecognizer
} = require('captcha-ocr');

错误处理

  • OCR 成功但规则无法解析文本时,结果会返回 ok: false 和结构化的 error
  • 输入不是有效图片数据时,会抛出 ImageInputError
  • OCR Worker 初始化、图片解码或原生依赖异常会抛出错误,调用方应根据业务需要处理。

本地 Demo

仓库还提供用于人工测试的 Web UI 和 CLI,它们属于开发工具,不会包含在发布包中。

pnpm install
pnpm start

服务启动后打开 http://127.0.0.1:3000