### Install Tesseract.js with npm or yarn Source: https://github.com/naptha/tesseract.js/blob/master/README.md These commands demonstrate how to install the latest version of Tesseract.js using either npm or yarn. Instructions for installing older versions are also provided. ```shell # For latest version npm install tesseract.js yarn add tesseract.js # For old versions npm install tesseract.js@3.0.3 yarn add tesseract.js@3.0.3 ``` -------------------------------- ### Basic Efficient Tesseract.js Example Source: https://github.com/naptha/tesseract.js/blob/master/docs/performance.md This example demonstrates setting up a Tesseract.js worker ahead of time for efficient recognition. It includes basic usage of recognizing text from an image. ```javascript import Tesseract from 'tesseract.js'; (async () => { const worker = await Tesseract.createWorker('eng', { logger: m => console.log(m), }); const { data: { text } } = await worker.recognize('https://tesseract.github.io/tesseract.js/img/eng_bw.png'); console.log(text); await worker.terminate(); })(); ``` -------------------------------- ### Install Tesseract.js Dependencies Source: https://github.com/naptha/tesseract.js/blob/master/README.md After cloning the repository, install the necessary Node.js dependencies using npm. This command reads the package.json file and downloads all required packages. ```shell npm install ``` -------------------------------- ### Start Tesseract.js Development Server Source: https://github.com/naptha/tesseract.js/blob/master/README.md Initiate the development server to automatically rebuild Tesseract.js files upon changes in the src folder. The server will be accessible at a specified local address. ```shell npm start ``` -------------------------------- ### Tesseract.js Scheduler Setup Source: https://github.com/naptha/tesseract.js/blob/master/examples/browser/basic-scheduler.html Initializes a Tesseract.js scheduler and a generator function to create and add workers to the scheduler. This setup is beneficial for parallel processing of multiple files. ```javascript // This example builds on "basic-efficient.html". // Rather than using a single worker, a scheduler manages a pool of multiple workers. // While performance is similar for a single file, this parallel processing results in significantly // faster speeds when used with multiple files. const scheduler = Tesseract.createScheduler(); // Creates worker and adds to scheduler const workerGen = async () => { const worker = await Tesseract.createWorker("eng", 1, { corePath: '../../node_modules/tesseract.js-core', workerPath: "/dist/worker.min.js", logger: function(m){console.log(m);} }); scheduler.addWorker(worker); } const workerN = 4; (async () => { const resArr = Array(workerN); for (let i=0; i { const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png'); console.log(text); await worker.terminate(); })(); ``` -------------------------------- ### Parallel Recognition with Schedulers and Workers Source: https://github.com/naptha/tesseract.js/blob/master/docs/workers_vs_schedulers.md This example demonstrates how to use Tesseract.js schedulers to run multiple recognition jobs in parallel. It sets up 4 workers and adds 10 recognition jobs to the scheduler. Workers added to the same scheduler should be configured identically to ensure consistent results. Remember to terminate the scheduler when all jobs are complete. ```javascript const scheduler = Tesseract.createScheduler(); // Creates worker and adds to scheduler const workerGen = async () => { const worker = await Tesseract.createWorker('eng'); scheduler.addWorker(worker); } const workerN = 4; (async () => { const resArr = Array(workerN); for (let i=0; i ( scheduler.addJob('recognize', 'https://tesseract.projectnaptha.com/img/eng_bw.png').then((x) => console.log(x.data.text)) ))) await scheduler.terminate(); // It also terminates all workers. })(); ``` -------------------------------- ### Benchmark Tesseract.js OCR Performance Source: https://github.com/naptha/tesseract.js/blob/master/benchmarks/browser/speed-benchmark.html This script initializes a Tesseract worker, measures its memory usage before and after recognition, and benchmarks the time taken to recognize text in multiple image files. Ensure the environment is cross-origin isolated for memory measurement. Launching a server via `npm start` and accessing via localhost should meet these conditions. ```javascript const { createWorker } = Tesseract; (async () => { const worker = await createWorker("eng", 1, { corePath: '../../node_modules/tesseract.js-core', workerPath: "/dist/worker.min.js", }); // The performance.measureUserAgentSpecificMemory function only runs under specific circumstances for security reasons. // See: https://developer.mozilla.org/en-US/docs/Web/API/Performance/measureUserAgentSpecificMemory#security_requirements // Launching a server using `npm start` and accessing via localhost on the same system should meet these conditions. const debugMemory = true; if (debugMemory && crossOriginIsolated) { const memObj = await performance.measureUserAgentSpecificMemory(); const memMb = memObj.breakdown.map((x) => { if(x.attribution?.[0]?.scope == "DedicatedWorkerGlobalScope") return x.bytes }).reduce((a, b) => (a || 0) + (b || 0), 0) / 1e6; console.log(`Worker memory utilization after initialization: ${memMb} MB`); } else { console.log("Unable to run `performance.measureUserAgentSpecificMemory`: not crossOriginIsolated.") } const fileArr = ["../data/meditations.jpg", "../data/tyger.jpg", "../data/testocr.png"]; let timeTotal = 0; for (let file of fileArr) { let time1 = Date.now(); for (let i=0; i < 10; i++) { await worker.recognize(file); } let time2 = Date.now(); const timeDif = (time2 - time1) / 1e3; timeTotal += timeDif; document.getElementById('message').innerHTML += "\n" + file + " [x10] runtime: " + timeDif + "s"; } if (debugMemory && crossOriginIsolated) { const memObj = await performance.measureUserAgentSpecificMemory(); const memMb = memObj.breakdown.map((x) => { if(x.attribution?.[0]?.scope == "DedicatedWorkerGlobalScope") return x.bytes }).reduce((a, b) => (a || 0) + (b || 0), 0) / 1e6; console.log(`Worker memory utilization after recognition: ${memMb} MB`); } document.getElementById('message').innerHTML += "\nTotal runtime: " + timeTotal + "s"; })(); ``` -------------------------------- ### Configure Tesseract.js Worker with Language Path Source: https://github.com/naptha/tesseract.js/blob/master/docs/performance.md Configure Tesseract.js worker with a specific language path for potentially faster language data. This example shows setting 'langPath' to a custom directory. ```javascript const worker = await Tesseract.createWorker({ logger: m => console.log(m), langPath: 'https://tessdata.projectnaptha.com/4.0.0_fast', cachePath: './cache/', cacheMethod: 'none', }); ``` -------------------------------- ### Create Tesseract Worker with Custom Paths Source: https://github.com/naptha/tesseract.js/blob/master/docs/local-installation.md Use this code to create a Tesseract worker instance when you need to specify custom paths for the worker script, language data, and core files. This is useful for local installations or when not using CDNs. ```javascript const worker = await createWorker('eng', 1, { workerPath: 'https://cdn.jsdelivr.net/npm/tesseract.js@v5.0.0/dist/worker.min.js', langPath: 'https://tessdata.projectnaptha.com/4.0.0', corePath: 'https://cdn.jsdelivr.net/npm/tesseract.js-core@v5.0.0', }); ``` -------------------------------- ### Accelerated OCR with Multiple Workers and Scheduler Source: https://github.com/naptha/tesseract.js/blob/master/docs/examples.md Speeds up OCR processing by using multiple workers managed by a scheduler. This example demonstrates adding 10 recognition jobs to be processed concurrently. ```javascript const { createWorker, createScheduler } = require('tesseract.js'); const scheduler = createScheduler(); const worker1 = await createWorker('eng'); const worker2 = await createWorker('eng'); (async () => { scheduler.addWorker(worker1); scheduler.addWorker(worker2); /** Add 10 recognition jobs */ const results = await Promise.all(Array(10).fill(0).map(() => ( scheduler.addJob('recognize', 'https://tesseract.projectnaptha.com/img/eng_bw.png') ))) console.log(results); await scheduler.terminate(); // It also terminates all workers. })(); ``` -------------------------------- ### Clone Tesseract.js Repository Source: https://github.com/naptha/tesseract.js/blob/master/README.md To set up a development environment, first clone the Tesseract.js repository using Git. This command fetches the entire project history and files. ```shell git clone https://github.com/naptha/tesseract.js.git ``` -------------------------------- ### Build Static Tesseract.js Files Source: https://github.com/naptha/tesseract.js/blob/master/README.md Execute this command to compile the Tesseract.js source code into static files, which will be placed in the 'dist' directory. This is typically used for production builds. ```shell npm run build ``` -------------------------------- ### Create Tesseract.js Worker and Recognize Text Source: https://github.com/naptha/tesseract.js/blob/master/examples/browser/basic-efficient.html Initializes a Tesseract.js worker with specified language and configuration, then sets up an event listener to recognize text from uploaded files. ```javascript const worker = await Tesseract.createWorker("eng", 1, { corePath: '../../node_modules/tesseract.js-core', workerPath: "/dist/worker.min.js", logger: function(m){console.log(m);} }); const recognize = async function(evt){ const files = evt.target.files; for (let i=0; i console.log(m), }); ``` -------------------------------- ### Initialize Tesseract Worker and Handle Image Upload for PDF Generation Source: https://github.com/naptha/tesseract.js/blob/master/examples/browser/download-pdf.html Initializes the Tesseract worker with English language support and specific core/worker paths. It sets up an event listener for an image uploader to recognize text and generate a PDF, then displays the recognized text and enables the download button. ```javascript const { createWorker } = Tesseract; const worker = await createWorker("eng", 1, { corePath: '/node_modules/tesseract.js-core', workerPath: "/dist/worker.min.js", logger: m => console.log(m), }); const uploader = document.getElementById('uploader'); const dlBtn = document.getElementById('download-pdf'); let pdf; const recognize = async ({ target: { files } }) => { const res = await worker.recognize(files[0],{pdfTitle: "Example PDF"},{pdf: true}); pdf = res.data.pdf; const text = res.data.text; const board = document.getElementById('board'); board.value = text; dlBtn.disabled = false; }; uploader.addEventListener('change', recognize); ``` -------------------------------- ### Create and Use Tesseract.js Worker Source: https://github.com/naptha/tesseract.js/blob/master/README.md This snippet demonstrates how to create a Tesseract.js worker for a specific language, recognize text from an image, and then terminate the worker. For recognizing multiple images, it's recommended to reuse the worker. ```javascript import { createWorker } from 'tesseract.js'; (async () => { const worker = await createWorker('eng'); const ret = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png'); console.log(ret.data.text); await worker.terminate(); })(); ``` -------------------------------- ### Create Tesseract.js Scheduler Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Creates a scheduler instance to manage multiple Tesseract.js workers for parallel processing and improved performance. ```javascript const { createScheduler } = Tesseract; const scheduler = createScheduler(); ``` -------------------------------- ### Tesseract.js File Recognition with Scheduler Source: https://github.com/naptha/tesseract.js/blob/master/examples/browser/basic-scheduler.html Handles file input changes and adds recognition jobs to the Tesseract.js scheduler. Each file is processed in parallel by the available workers. ```javascript const recognize = async function(evt){ const files = evt.target.files; for (let i=0; i console.log(x.data.text)) } } const elm = document.getElementById('uploader'); elm.addEventListener('change', recognize); ``` -------------------------------- ### Run Tesseract.js Linting Source: https://github.com/naptha/tesseract.js/blob/master/README.md Before submitting a pull request, run the linting process to check for code style issues and potential errors. This command enforces code quality standards. ```shell npm run lint ``` -------------------------------- ### Run Tesseract.js Automated Tests Source: https://github.com/naptha/tesseract.js/blob/master/README.md Execute the automated test suite to ensure all functionalities are working as expected. Passing these tests is a prerequisite for submitting pull requests. ```shell npm run test ``` -------------------------------- ### JavaScript Image Recognition with Tesseract.js Source: https://github.com/naptha/tesseract.js/blob/master/examples/browser/image-processing.html This JavaScript code snippet handles image uploads, initializes a Tesseract.js worker, and performs OCR. It then displays the original image, its greyscale version, and its binary version. Ensure Tesseract.js is correctly imported and worker paths are configured. ```javascript const recognize = async ({ target: { files } }) => { document.getElementById("imgInput").src = URL.createObjectURL(files[0]); const worker = await Tesseract.createWorker("eng", 1, { // corePath: '/tesseract-core-simd.wasm.js', workerPath: "/dist/worker.min.js" }); const ret = await worker.recognize(files[0], { rotateAuto: true }, { imageColor: true, imageGrey: true, imageBinary: true }); document.getElementById("imgOriginal").src = ret.data.imageColor; document.getElementById("imgGrey").src = ret.data.imageGrey; document.getElementById("imgBinary").src = ret.data.imageBinary; } const elm = document.getElementById('uploader'); elm.addEventListener('change', recognize); ``` -------------------------------- ### Download Recognized Text as PDF Source: https://github.com/naptha/tesseract.js/blob/master/examples/browser/download-pdf.html Handles the download of the generated PDF. It creates a Blob from the PDF data and uses browser-specific methods to initiate the download, either via navigator.msSaveBlob for IE or by creating a temporary link for other browsers. ```javascript const downloadPDF = async () => { const filename = 'tesseract-ocr-result.pdf'; const blob = new Blob([new Uint8Array(pdf)], { type: 'application/pdf' }); if (navigator.msSaveBlob) { // IE 10+ navigator.msSaveBlob(blob, filename); } else { const link = document.createElement('a'); if (link.download !== undefined) { const url = URL.createObjectURL(blob); link.setAttribute('href', url); link.setAttribute('download', filename); link.style.visibility = 'hidden'; document.body.appendChild(link); link.click(); document.body.removeChild(link); } } }; dlBtn.addEventListener('click', downloadPDF); ``` -------------------------------- ### Enable Detailed Logging Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Sets the logging flag to enable detailed information output, which is helpful for debugging. Accepts a boolean value. ```javascript const { setLogging } = Tesseract; setLogging(true); ``` -------------------------------- ### Include Tesseract.js via CDN Source: https://github.com/naptha/tesseract.js/blob/master/README.md This HTML snippet shows how to include the Tesseract.js library using a script tag from a CDN. After inclusion, the Tesseract variable becomes globally available for creating workers. ```html ``` -------------------------------- ### worker.reinitialize Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Re-initializes an existing Tesseract.js worker with different language and OCR engine mode arguments. ```APIDOC ## POST /worker/reinitialize ### Description Re-initializes an existing Tesseract.js worker with different `langs` and `oem` arguments. This allows changing the language models or OCR engine mode without creating a new worker. ### Method POST ### Endpoint /worker/reinitialize ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **langs** (string or array) - Required - A string or array of strings indicating the languages traineddata to download (e.g., 'eng', ['eng', 'chi_sim']). - **oem** (number) - Optional - An enum to indicate the OCR Engine Mode to use (e.g., 1 for LSTM, 0 for Legacy). - **config** (object) - Optional - An object of customized options to be set prior to initialization. - **jobId** (string) - Optional - An identifier for the job. ### Request Example ```json { "langs": "eng", "oem": 1, "jobId": "job-123" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "reinitialized" } ``` ``` -------------------------------- ### Set Tesseract Parameters Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Configure Tesseract's behavior by setting parameters using `worker.setParameters`. This is useful for options like `tessedit_char_whitelist` to restrict recognized characters. Note that `oem` cannot be changed after initialization. ```javascript (async () => { await worker.setParameters({ tessedit_char_whitelist: '0123456789', }); }) ``` -------------------------------- ### setLogging Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Configures the logging level for Tesseract.js. Setting to true enables detailed logs for debugging. ```APIDOC ## POST /logging/set ### Description Enables or disables detailed logging for Tesseract.js. ### Method POST ### Endpoint /logging/set ### Parameters #### Query Parameters - **logging** (boolean) - Required - Set to `true` to enable detailed logs, `false` to disable. Defaults to `false`. ### Response #### Success Response (200) - **message** (string) - Confirmation message. #### Response Example ```json { "message": "Logging set to true" } ``` ``` -------------------------------- ### OCR with Detailed Progress Logging Source: https://github.com/naptha/tesseract.js/blob/master/docs/examples.md Recognizes text from an image while logging detailed progress updates. The logger function is passed during worker creation. ```javascript const { createWorker } = require('tesseract.js'); const worker = await createWorker('eng', 1, { logger: m => console.log(m), // Add logger here }); (async () => { const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png'); console.log(text); await worker.terminate(); })(); ``` -------------------------------- ### detect (Deprecated) Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Deprecated function. Use `worker.detect` instead. Creates a new worker, loads it, and detects language information in an image. ```APIDOC ## POST /detect (Deprecated) ### Description Detects language information within an image. This function is deprecated and should be replaced by `worker.detect`. ### Method POST ### Endpoint /detect ### Parameters #### Request Body - **image** (any) - Required - The image to process. - **options** (object) - Optional - Additional options for detection. ### Response #### Success Response (200) - **data** (object) - The detection results. #### Response Example ```json { "data": { "blocks": [...] } } ``` ``` -------------------------------- ### Reinitialize Tesseract.js Worker Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Re-initializes an existing Tesseract.js worker with new language and OCR engine mode settings. Ensure legacy support is enabled if switching to Tesseract Legacy. ```javascript await worker.reinitialize('eng', 1); ``` -------------------------------- ### Generic File System Operation Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Performs a generic file system operation within the Tesseract.js worker's MEMFS using a specified method and arguments. This is equivalent to using specific FS methods like writeText. ```javascript (async () => { await worker.FS('writeFile', ['tmp.txt', 'Hi\nTesseract.js\n']); // equal to: // await worker.writeText('tmp.txt', 'Hi\nTesseract.js\n'); })(); ``` -------------------------------- ### createWorker() Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Creates a Tesseract.js worker instance for performing OCR tasks. ```APIDOC ## createWorker() ### Description Creates a Tesseract.js worker. A worker manages an instance of Tesseract running in a web worker or worker thread, allowing OCR jobs to be sent to it. ### Method `createWorker` ### Parameters #### Arguments - **langs** (string or array) - Required - The language(s) to be used for OCR. Specify multiple languages using an array (e.g., `['eng', 'chi_sim']`). - **oem** (enum) - Optional - The OCR Engine Mode to use. - **options** (object) - Optional - An object for customized options: - **corePath** (string) - Path to the Tesseract.js-core package directory. Strongly discouraged to point to a specific file. - **langPath** (string) - Path for downloading traineddata. Do not include a trailing slash. - **workerPath** (string) - Path for downloading the worker script. - **dataPath** (string) - Path for saving traineddata in the WebAssembly file system (not commonly modified). - **cachePath** (string) - Path for cached traineddata. For browsers, this changes the IndexDB key. - **cacheMethod** (string) - Method for cache management. Options: `write` (default), `readOnly`, `refresh`, `none`. - **legacyCore** (boolean) - Set to `true` to ensure support for the Legacy model in addition to LSTM. - **legacyLang** (boolean) - Set to `true` to ensure language data supports the Legacy model in addition to LSTM. - **workerBlobURL** (boolean) - Define whether to use Blob URL for the worker script. Default: `true`. - **gzip** (boolean) - Define whether traineddata from the remote is gzipped. Default: `true`. - **logger** (function) - A function to log progress (e.g., `m => console.log(m)`). - **errorHandler** (function) - A function to handle worker errors (e.g., `err => console.error(err)`). - **config** (object) - Optional - An object for customized options set prior to initialization. This allows setting "init only" Tesseract parameters like `load_system_dawg`, `load_number_dawg`, and `load_punc_dawg`. ### Request Example ```javascript const { createWorker } = Tesseract; const worker = await createWorker('eng', 1, { langPath: '...', logger: m => console.log(m), }); ``` ### Response - **Worker** (object) - A Tesseract.js worker instance. ``` -------------------------------- ### Image Recognition and Rotation with Tesseract.js Source: https://github.com/naptha/tesseract.js/blob/master/benchmarks/browser/auto-rotate-benchmark.html This JavaScript code snippet initializes a Tesseract.js worker, iterates through a list of images, applies different rotations, and then attempts to auto-correct the rotation while generating color, grey, and binary versions of the processed image. It appends the results to the DOM. ```javascript const recognize = async () => { const element = document.getElementById("imgRow"); const worker = await Tesseract.createWorker('eng', 0, { // corePath: '/tesseract-core-simd.wasm.js', workerPath: "/dist/worker.min.js" }); const fileArr = ["../data/meditations.jpg", "../data/tyger.jpg", "../data/testocr.png"]; let timeTotal = 0; let lastElement = element; for (let file of fileArr) { for (let rad of [-0.2, -0.1, 0.1, 0.2]) { const newElement = element.cloneNode(true); // Create the rotated images const ret1 = await worker.recognize(file, { rotateRadians: rad }, { text: false, blocks: false, hocr: false, tsv: false, imageColor: true }); newElement.children[0].children[1].src = ret1.data.imageColor; // Attempt to remove the rotation using the auto-rotate feature const ret2 = await worker.recognize(ret1.data.imageColor, { rotateAuto: true }, { text: false, blocks: false, hocr: false, tsv: false, imageColor: true, imageGrey: true, imageBinary: true, debug: true }); newElement.children[1].children[1].src = ret2.data.imageColor; newElement.children[2].children[1].src = ret2.data.imageGrey; newElement.children[3].children[1].src = ret2.data.imageBinary; lastElement.after(newElement); lastElement = newElement; } } } recognize(); ``` -------------------------------- ### recognize (Deprecated) Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Deprecated function. Use `worker.recognize` instead. Creates a new worker, loads it, and performs recognition on an image. ```APIDOC ## POST /recognize (Deprecated) ### Description Performs OCR recognition on an image. This function is deprecated and should be replaced by `worker.recognize`. ### Method POST ### Endpoint /recognize ### Parameters #### Request Body - **image** (any) - Required - The image to process. - **langs** (string) - Optional - Language(s) to use for recognition. - **options** (object) - Optional - Additional options for recognition. ### Response #### Success Response (200) - **data** (object) - The recognition results. #### Response Example ```json { "data": { "text": "Recognized text" } } ``` ``` -------------------------------- ### OEM Constants Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Provides access to Orientation and OCR Engine Mode (OEM) constants. ```APIDOC ## GET /constants/oem ### Description Retrieves the Orientation and OCR Engine Mode (OEM) constants used by Tesseract. ### Method GET ### Endpoint /constants/oem ### Parameters None ### Response #### Success Response (200) - **OEM** (object) - An object containing OEM constants. #### Response Example ```json { "OEM": { "OSD_ONLY": 0, "AUTO_OSD": 1, "AUTO_ONLY": 2, "AUTO": 3 } } ``` ``` -------------------------------- ### worker.FS Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md A generic file system function to perform various operations within the worker's virtual file system (MEMFS). ```APIDOC ## POST /worker/FS ### Description Provides a generic interface to interact with the worker's file system (MEMFS), allowing for a wide range of operations beyond basic read/write/remove. ### Method POST ### Endpoint /worker/FS ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **method** (string) - Required - The name of the file system method to execute (e.g., 'writeFile', 'readFile', 'removeFile', 'mkdir', 'readdir'). Refer to the Emscripten Filesystem API for available methods. - **args** (array) - Required - An array of arguments to pass to the specified file system method. - **jobId** (string) - Optional - An identifier for the job. ### Request Example ```json { "method": "writeFile", "args": ["tmp.txt", "Hi\nTesseract.js\n"], "jobId": "fs-job-141" } ``` ### Response #### Success Response (200) - **data** (any) - The result of the file system operation. The type depends on the method called. #### Response Example ```json { "data": "success" } ``` ``` -------------------------------- ### createScheduler Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Factory function to create a scheduler instance for managing a job queue and multiple workers. ```APIDOC ## POST /createScheduler ### Description Creates a scheduler instance. A scheduler manages a job queue and workers, enabling parallel processing and improving performance by distributing tasks among available workers. ### Method POST ### Endpoint /createScheduler ### Parameters None ### Request Example ```json { "jobId": "scheduler-create-151" } ``` ### Response #### Success Response (200) - **scheduler** (object) - An object representing the created scheduler instance. #### Response Example ```json { "scheduler": { "id": "scheduler-123" } } ``` ``` -------------------------------- ### Detect Image Orientation and Script Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Performs Orientation and Script Detection (OSD) on an image using a Tesseract.js worker. Requires a worker configured with legacyCore and legacyLang set to true. ```javascript const { createWorker } = Tesseract; (async () => { const worker = await createWorker('eng', 1, {legacyCore: true, legacyLang: true}); const { data } = await worker.detect(image); console.log(data); })(); ``` -------------------------------- ### PSM Constants Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Provides access to Page Segmentation Mode (PSM) constants. ```APIDOC ## GET /constants/psm ### Description Retrieves the Page Segmentation Mode (PSM) constants used by Tesseract. ### Method GET ### Endpoint /constants/psm ### Parameters None ### Response #### Success Response (200) - **PSM** (object) - An object containing PSM constants. #### Response Example ```json { "PSM": { "OSD_ONLY": 0, "AUTO_OSD": 1, "AUTO_ONLY": 2, "AUTO": 3 } } ``` ``` -------------------------------- ### worker.detect Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Performs Orientation and Script Detection (OSD) on an image instead of OCR. ```APIDOC ## POST /worker/detect ### Description Performs Orientation and Script Detection (OSD) on an image. This method requires a worker configured with Tesseract Legacy support (`legacyCore: true`, `legacyLang: true`). ### Method POST ### Endpoint /worker/detect ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **image** (object or string) - Required - The image to process. See [Image Format](./image-format.md) for details. - **jobId** (string) - Optional - An identifier for the job. ### Request Example ```json { "image": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA...", "jobId": "detect-job-456" } ``` ### Response #### Success Response (200) - **data** (object) - Contains the OSD results. #### Response Example ```json { "data": { "lines": [], "script": "Latin", "orientation": 0, "direction": "undefined", "angle": 0, "clockwiseOrientation": 0 } } ``` ``` -------------------------------- ### Specify Worker Path in Node.js Source: https://github.com/naptha/tesseract.js/blob/master/docs/faq.md When running Tesseract.js in a Node.js environment, you may need to manually set the `workerPath` to ensure the worker code is found by the build system. This is particularly useful when framework build processes alter file locations. ```javascript const worker = await createWorker("eng", 1, {workerPath: "./node_modules/tesseract.js/src/worker-script/node/index.js"}); ``` -------------------------------- ### scheduler.getQueueLen Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Returns the current length of the job queue. ```APIDOC ## GET /scheduler/queue-len ### Description Retrieves the number of jobs currently in the job queue. ### Method GET ### Endpoint /scheduler/queue-len ### Parameters None ### Response #### Success Response (200) - **length** (number) - The number of jobs in the queue. #### Response Example ```json { "length": 5 } ``` ``` -------------------------------- ### OCR on Multiple Image Rectangles in Parallel with Scheduler Source: https://github.com/naptha/tesseract.js/blob/master/docs/examples.md Processes multiple specified rectangular regions of an image in parallel using a scheduler. This can significantly speed up processing for multiple regions. ```javascript const { createWorker, createScheduler } = require('tesseract.js'); const scheduler = createScheduler(); const worker1 = await createWorker('eng'); const worker2 = await createWorker('eng'); const rectangles = [ { left: 0, top: 0, width: 500, height: 250, }, { left: 500, top: 0, width: 500, height: 250, }, ]; (async () => { scheduler.addWorker(worker1); scheduler.addWorker(worker2); const results = await Promise.all(rectangles.map((rectangle) => ( scheduler.addJob('recognize', 'https://tesseract.projectnaptha.com/img/eng_bw.png', { rectangle }) ))); console.log(results.map(r => r.data.text)); await scheduler.terminate(); })(); ``` -------------------------------- ### worker.readText Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Reads the content of a text file from the worker's virtual file system (MEMFS). ```APIDOC ## POST /worker/readText ### Description Reads a text file from a specified path in the worker's MEMFS. This is useful for verifying file content or using it in subsequent operations. ### Method POST ### Endpoint /worker/readText ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **path** (string) - Required - The path of the text file to read from MEMFS. - **jobId** (string) - Optional - An identifier for the job. ### Request Example ```json { "path": "tmp.txt", "jobId": "read-job-112" } ``` ### Response #### Success Response (200) - **data** (string) - The content of the text file. #### Response Example ```json { "data": "Hi\nTesseract.js\n" } ``` ``` -------------------------------- ### Read Text from MEMFS Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Reads the content of a text file from the Tesseract.js worker's in-memory file system (MEMFS). ```javascript (async () => { const { data } = await worker.readText('tmp.txt'); console.log(data); })(); ``` -------------------------------- ### OCR with Specific Page Segmentation Mode (PSM) Source: https://github.com/naptha/tesseract.js/blob/master/docs/examples.md Performs OCR using a specified page segmentation mode (PSM). The PSM.SINGLE_BLOCK mode is used here, which treats the image as a single text block. Refer to the Tesseract documentation for other modes. ```javascript const { createWorker, PSM } = require('tesseract.js'); const worker = await createWorker('eng'); (async () => { await worker.setParameters({ tessedit_pageseg_mode: PSM.SINGLE_BLOCK, }); const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png'); console.log(text); await worker.terminate(); })(); ``` -------------------------------- ### worker.writeText Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Writes text content to a specified file path within the worker's virtual file system (MEMFS). ```APIDOC ## POST /worker/writeText ### Description Writes a text file to a specified path in the worker's MEMFS. This is useful for features that require Tesseract.js to read from a file system. ### Method POST ### Endpoint /worker/writeText ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **path** (string) - Required - The path where the text file will be written within MEMFS. - **text** (string) - Required - The content of the text file. - **jobId** (string) - Optional - An identifier for the job. ### Request Example ```json { "path": "tmp.txt", "text": "Hi\nTesseract.js\n", "jobId": "write-job-101" } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the file write operation. #### Response Example ```json { "status": "written" } ``` ``` -------------------------------- ### Recognize Text with a Single Worker Source: https://github.com/naptha/tesseract.js/blob/master/docs/workers_vs_schedulers.md Use this snippet to recognize text from an image using a single Tesseract.js worker. Ensure to call `worker.terminate()` when done to free up resources. It's recommended to create the worker ahead of time and reuse it for multiple recognition tasks. ```javascript (async () => { const worker = await Tesseract.createWorker('eng'); const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png'); console.log(text); await worker.terminate(); })(); ``` -------------------------------- ### Write Text to MEMFS Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Writes specified text content to a file path within the Tesseract.js worker's in-memory file system (MEMFS). ```javascript (async () => { await worker.writeText('tmp.txt', 'Hi\nTesseract.js\n'); })(); ``` -------------------------------- ### Add Worker to Scheduler Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Adds a Tesseract.js worker to a scheduler's pool. It is recommended to add each worker to only one scheduler. ```javascript const { createWorker, createScheduler } = Tesseract; const scheduler = createScheduler(); const worker = await createWorker(); scheduler.addWorker(worker); ``` -------------------------------- ### OCR with Multiple Languages Source: https://github.com/naptha/tesseract.js/blob/master/docs/examples.md Performs OCR using multiple languages simultaneously. Languages are provided as an array or a string separated by '+'. ```javascript const { createWorker } = require('tesseract.js'); const worker = await createWorker(['eng', 'chi_tra']); (async () => { const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png'); console.log(text); await worker.terminate(); })(); ``` -------------------------------- ### OCR on Multiple Image Rectangles Sequentially Source: https://github.com/naptha/tesseract.js/blob/master/docs/examples.md Processes multiple specified rectangular regions of an image sequentially. Each rectangle's recognized text is collected into an array. ```javascript const { createWorker } = require('tesseract.js'); const worker = await createWorker('eng'); const rectangles = [ { left: 0, top: 0, width: 500, height: 250, }, { left: 500, top: 0, width: 500, height: 250, }, ]; (async () => { const values = []; for (let i = 0; i < rectangles.length; i++) { const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png', { rectangle: rectangles[i] }); values.push(text); } console.log(values); await worker.terminate(); })(); ``` -------------------------------- ### Add Job to Scheduler Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Adds a job to the queue and waits for an idle worker to process it. Supports 'recognize' and 'detect' actions. ```javascript (async () => { const { data: { text } } = await scheduler.addJob('recognize', image, options); const { data } = await scheduler.addJob('detect', image); })(); ``` -------------------------------- ### OCR with Whitelisted Characters Source: https://github.com/naptha/tesseract.js/blob/master/docs/examples.md Recognizes text from an image, but only includes characters specified in 'tessedit_char_whitelist'. This is useful for extracting specific types of data like numbers. ```javascript const { createWorker } = require('tesseract.js'); const worker = await createWorker('eng'); (async () => { await worker.setParameters({ tessedit_char_whitelist: '0123456789', }); const { data: { text } } = await worker.recognize('https://tesseract.projectnaptha.com/img/eng_bw.png'); console.log(text); await worker.terminate(); })(); ``` -------------------------------- ### worker.setParameters Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Sets Tesseract API parameters to modify OCR behavior. Useful for fine-tuning recognition, such as whitelisting characters or preserving spaces. ```APIDOC ## POST /worker/setParameters ### Description Sets parameters for the Tesseract API using `SetVariable()`, which can alter Tesseract's behavior. Some parameters, like `tessedit_char_whitelist`, are very useful for controlling recognition output. ### Method POST ### Endpoint /worker/setParameters ### Parameters #### Request Body - **params** (object) - Required - An object with key-value pairs of parameters to set. - **jobId** (string) - Optional - Identifier for the job. ### Request Example ```json { "params": { "tessedit_char_whitelist": "0123456789", "preserve_interword_spaces": "1" } } ``` ### Response #### Success Response (200) - **status** (string) - Indicates the success of the operation. #### Response Example ```json { "status": "Parameters set successfully." } ``` ### Useful Parameters | name | type | default value | description | | --------------------------- | ------ | ----------------- | ------------------------------------------------------------------------------------------------------------------------------- | | tessedit_pageseg_mode | enum | PSM.SINGLE_BLOCK | Check [HERE](https://github.com/tesseract-ocr/tesseract/blob/4.0.0/src/ccstruct/publictypes.h#L163) for definition of each mode | | tessedit_char_whitelist | string | '' | setting white list characters makes the result only contains these characters, useful if content in image is limited | | preserve_interword_spaces | string | '0' | '0' or '1', keeps the space between words | | user_defined_dpi | string | '' | Define custom dpi, use to fix **Warning: Invalid resolution 0 dpi. Using 70 instead.** | Note: `worker.setParameters` cannot be used to change the `oem`, as this value is set at initialization. `oem` requires running `worker.reinitialize` to change. ``` -------------------------------- ### Perform OCR on an Image Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Use `worker.recognize` to extract text from an image. Ensure the image is of sufficient resolution for better results. The default output is plain text. ```javascript const { createWorker } = Tesseract; (async () => { const worker = await createWorker('eng'); const { data: { text } } = await worker.recognize(image); console.log(text); })(); ``` -------------------------------- ### worker.recognize Source: https://github.com/naptha/tesseract.js/blob/master/docs/api.md Executes the core OCR function to recognize text within an image. It can process various image formats and return results in different output formats. ```APIDOC ## POST /worker/recognize ### Description Provides the core function of Tesseract.js by executing OCR on an image to identify words and their locations. ### Method POST ### Endpoint /worker/recognize ### Parameters #### Request Body - **image** (Image) - Required - The image to process. See [Image Format](./image-format.md) for details. - **options** (object) - Optional - An object of customized options. - **rectangle** (object) - Optional - An object to specify regions for recognition, containing `top`, `left`, `width`, and `height`. - **output** (object) - Optional - An object specifying which output formats to return. Defaults to `{ text: true }`. Other options include `blocks`, `hocr`, and `tsv`. - **jobId** (string) - Optional - Identifier for the job. ### Request Example ```json { "image": "path/to/your/image.png", "options": { "rectangle": { "top": 0, "left": 0, "width": 100, "height": 100 } }, "output": { "text": true, "hocr": true } } ``` ### Response #### Success Response (200) - **jobId** (string) - The ID of the job. - **data** (object) - Contains the OCR results in the specified output formats. - **text** (string) - The recognized text. - **blocks** (json) - Recognized blocks of text. - **hocr** (string) - HOCR formatted output. - **tsv** (string) - TSV formatted output. #### Response Example ```json { "jobId": "some-job-id", "data": { "text": "Recognized text content.", "blocks": [...], "hocr": "