### Install mac-ocr Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Install the mac-ocr package using npm. ```sh npm install mac-ocr ``` -------------------------------- ### OCR Default Action Examples Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Demonstrates various ways to use the default OCR action, including file inputs, piped stdin, and URL inputs. ```sh mac-ocr receipt.jpg ``` ```sh mac-ocr scan.pdf --format jsonl ``` ```sh mac-ocr a.png b.png c.png ``` ```sh cat shot.png | mac-ocr ``` ```sh mac-ocr https://example.com/sign.png ``` -------------------------------- ### Install mac-ocr globally Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Install the mac-ocr command-line tool globally using npm. This makes the 'mac-ocr' command available in your terminal. ```sh npm install -g mac-ocr ``` -------------------------------- ### Run mac-ocr without installation Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Execute mac-ocr directly using npx without a global installation. This is useful for trying out the tool or for one-off commands. ```sh npx mac-ocr receipt.jpg ``` -------------------------------- ### Run Swift and Node.js Tests Source: https://github.com/privatenumber/mac-ocr/blob/develop/CONTRIBUTING.md Commands for running Swift tests using `--no-parallel` to avoid ANE contention and Node.js tests after installing dependencies. Includes type checking and linting. ```sh swift test --no-parallel # Swift suites (spawn .build/debug/mac-ocr) pnpm install pnpm test:node # Node API suites (manten) — builds and copies the debug binary to bin/mac-ocr first pnpm typecheck pnpm lint # lintroll (TS) + swift format lint ``` -------------------------------- ### HTTP GET with Auth and POST Data Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Fetch an image from an HTTP API using curl with authentication headers and pipe the content to mac-ocr for processing. Note that mac-ocr itself only supports simple GET requests. ```sh curl -H "Authorization: Bearer $TOKEN" https://api.example.com/img | mac-ocr - ``` -------------------------------- ### Region of Interest Examples Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Demonstrates the different formats accepted for specifying a region of interest for OCR, including object, tuple, and string representations. Object and tuple forms are validated before subprocess execution. ```typescript { x: 0, y: 0, width: 1, height: 0.5 } // object ``` ```typescript [0, 0, 1, 0.5] // tuple: [x, y, width, height] ``` ```typescript '0,0,1,0.5' // string ``` -------------------------------- ### Semantic Release Commit Message Example Source: https://github.com/privatenumber/mac-ocr/blob/develop/CONTRIBUTING.md Use this format for commit messages to trigger releases. Breaking changes require a 'BREAKING CHANGE:' footer. ```git commit feat(ocr): restructure result schema BREAKING CHANGE: the flat `file` field is replaced by a tagged `source` union. ``` -------------------------------- ### Get Supported Languages Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Retrieve a list of languages supported for OCR and searchable PDF creation on the current macOS version using 'supportedLanguages'. ```ts // Recognition languages supported on this macOS version (for ocr and createSearchablePdf) const languages = await supportedLanguages() ``` -------------------------------- ### Output recognized text in JSON format Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Use the --format option to get detailed JSON output, including bounding boxes and confidence scores, or JSON Lines for streamed page data. ```sh mac-ocr receipt.jpg --format json ``` ```sh mac-ocr document.pdf --format jsonl # one JSON object per page, streamed ``` -------------------------------- ### mac-ocr JSON Error Format Example Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Configure the environment variable `MAC_OCR_ERROR_FORMAT` to `json` and use file descriptor 3 to receive structured JSON error messages. This format is intended for programmatic consumption. ```jsonc { "schema": "mac-ocr.error", "schemaVersion": 1, // consumers should require this exact version "kind": "runtime", // usage | unavailable | runtime | internal "code": "batch_failed", // machine-readable code "message": "one or more inputs failed", "exitCode": 1, "command": "ocr", // optional "requires": "macOS 26+" // optional; set when kind is "unavailable" } ``` -------------------------------- ### Get OCR result from bytes Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Extract text, observations, and dimensions from image or PDF bytes using the ocr function. This is for single-page inputs. ```ts const { text, observations, width, height } = await ocr(bytes) ``` -------------------------------- ### ocr.pages(input, options?) Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md OCRs every page of a (possibly multi-page) PDF. It returns an AsyncIterable that streams OcrResult objects for each page as they are processed. This is suitable for large PDFs to manage memory and get early results. ```APIDOC ## ocr.pages(input, options?) ### Description OCRs every page of a (possibly multi-page) PDF. The return value is a plain `AsyncIterable`. ### Method POST ### Endpoint /ocr/pages ### Parameters #### Request Body - **input** (Buffer | Uint8Array | ArrayBuffer) - Required - PDF bytes. - **options** (object) - Optional - Configuration options for OCR. ### Response #### Success Response (AsyncIterable) - **page** (number) - The current page number. - **pageCount** (number) - The total number of pages in the PDF. - **text** (string) - The recognized text for the current page. - **observations** (array) - Detected text observations for the current page. - **width** (number) - The width of the current page. - **height** (number) - The height of the current page. ### Request Example ```json { "input": "" } ``` ### Response Example (for each page) ```json { "page": 1, "pageCount": 5, "text": "Recognized text from page 1.", "observations": [ { "text": "some text on page 1", "boundingBox": [x1, y1, x2, y2] } ], "width": 1700, "height": 2200 } ``` ``` -------------------------------- ### Build and Run mac-ocr Source: https://github.com/privatenumber/mac-ocr/blob/develop/CONTRIBUTING.md Commands to build the project and run the mac-ocr executable with different arguments for image processing, PDF conversion, and help display. ```sh swift build swift run mac-ocr receipt.jpg swift run mac-ocr scan.pdf --format jsonl swift run mac-ocr searchable-pdf scan.pdf -o out.pdf swift run mac-ocr --help ``` -------------------------------- ### Basic CLI Usage Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Shows the basic structure for invoking mac-ocr with inputs and optional OCR settings. ```bash mac-ocr [ocr options] # recognize text (default) mac-ocr ocr [ocr options] # explicit form (optional) mac-ocr searchable-pdf [-o ] [ocr options] ``` -------------------------------- ### Build Universal Release Binary Source: https://github.com/privatenumber/mac-ocr/blob/develop/CONTRIBUTING.md Command to build a universal release binary for the mac-ocr project, optimized for size. ```sh pnpm build ``` -------------------------------- ### Basic Searchable PDF Creation Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Use this command to create a searchable PDF from a single scan or image file. The output file will be named based on the input file with an .ocr.pdf extension. ```sh mac-ocr searchable-pdf scan.pdf # writes scan.ocr.pdf mac-ocr searchable-pdf photo.jpg # image → one-page photo.ocr.pdf ``` -------------------------------- ### Searchable PDF with Custom Output Filename Pattern Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Creates a searchable PDF with a custom filename pattern, allowing dynamic naming based on the input. ```sh mac-ocr searchable-pdf scan.pdf -o '[name]-ocr.pdf' # scan-ocr.pdf ``` -------------------------------- ### Searchable PDF with Custom Output Directory Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Generates a searchable PDF and places it in a specified output directory. The filename is derived from the input. ```sh mac-ocr searchable-pdf scan.pdf -o out/ # out/scan.ocr.pdf ``` -------------------------------- ### Basic Searchable PDF Creation Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Generates a searchable PDF from a single input file. The output file is named by appending '.ocr' to the input filename. ```sh mac-ocr searchable-pdf scan.pdf # writes scan.ocr.pdf ``` -------------------------------- ### Enabling Debugging Output Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Use the `MAC_OCR_DEBUG=1` environment variable to enable advanced diagnostics. This will draw OCR boxes on the output PDF and generate a JSONL sidecar file for detailed analysis. ```sh MAC_OCR_DEBUG=1 mac-ocr searchable-pdf file.pdf ``` -------------------------------- ### Searchable PDF Output to Stdout Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Generates a searchable PDF and outputs the binary content to standard output. Requires an explicit '-o -' to specify stdout. ```sh mac-ocr searchable-pdf scan.pdf -o - # PDF to stdout ``` -------------------------------- ### Configuring OCR Strategy Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Control the OCR process using the `--ocr-strategy` option. Choose between 'auto', 'standard' (full-page OCR), or 'partitioned' (recursive splitting for large pages). ```sh mac-ocr searchable-pdf --ocr-strategy auto file.pdf mac-ocr searchable-pdf --ocr-strategy standard file.pdf mac-ocr searchable-pdf --ocr-strategy partitioned file.pdf ``` -------------------------------- ### Batch Searchable PDF Creation Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Creates searchable PDFs for multiple input files. Each output file is named by appending '.ocr' to its respective input filename. ```sh mac-ocr searchable-pdf *.pdf # writes .ocr.pdf for each ``` -------------------------------- ### Save recognized text to files Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Use the -o option to specify output file paths, directories, or filename templates. Supports plain text and markdown output. ```sh mac-ocr ~/Screenshots/*.png -o '[dir]/[name].txt' # a .txt next to each image ``` ```sh mac-ocr scan.pdf -o notes.md # recognized text to a chosen .txt/.md file ``` ```sh mac-ocr receipts/*.pdf -o out/ # one file per input in out/ ``` -------------------------------- ### createSearchablePdf Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Produces a searchable PDF with an invisible, selectable OCR text layer. It returns the PDF bytes as a Promise. ```APIDOC ## `createSearchablePdf(input, options?)` Produces a searchable PDF — the same content with an invisible, selectable OCR text layer — and returns its bytes as a `Promise`. ### Parameters #### Options - `ocrAllPages` (boolean) - Optional - OCR every page, including pages that already have selectable text (skipped by default). For hybrid scan-plus-stamp pages; existing digital text may appear twice in copy/search. - `ocrStrategy` (string) - Optional - Searchable PDF OCR strategy. Default `auto`; use `standard` to force full-page OCR only, or `partitioned` to force the recursive partitioned pass for eligible pages. - `imageQuality` (number) - Optional - Visible image layer quality for image inputs (`0`–`1`). OCR still uses the original full-resolution image; PDF inputs are not recompressed. - `imagePageDpi` (number) - Optional - DPI to use for image input page sizing. OCR still uses the original full-resolution image; PDF inputs are not affected. - `imageDownsampleDpi` (number) - Optional - Maximum DPI for the visible image layer of image inputs. OCR and page size are not affected; PDF inputs are not downsampled. - `fast` (boolean) - Optional - Use the faster character-by-character recognizer instead of the default neural net — lower accuracy; see [Recognition levels](CLI.md#recognition-levels). - `languages` (string[]) - Optional - Recognition languages (BCP-47), e.g. `['en-US', 'ja-JP']`. Validated by the CLI against `supportedLanguages()` — unsupported codes reject with a `usage`-kind error. - `confidence` (number) - Optional - Drop observations below this confidence (`0`–`1`). - `customWords` (string[]) - Optional - Custom vocabulary to bias recognition toward. - `languageCorrection` (boolean) - Optional - Language correction (default `true`). - `minTextHeight` (number) - Optional - Ignore text shorter than this fraction of image height (`0`–`1`). - `regionOfInterest` (object | tuple | string) - Optional - Restrict recognition to a sub-rectangle (see below). - `pdfDpi` (number | string) - Optional - PDF rasterization DPI (`'auto'` default, or `72`–`600`). - `password` (string) - Optional - Password for an encrypted PDF (falls back to `MAC_OCR_PDF_PASSWORD`). Forwarded to the CLI via the env var, never `argv`, so it stays out of the process list. - `signal` (AbortSignal) - Optional - Abort the underlying subprocess. ### `regionOfInterest` Normalized, top-left origin. Three accepted forms: ```ts { x: 0, y: 0, width: 1, height: 0.5 } // object [0, 0, 1, 0.5] // tuple: [x, y, width, height] '0,0,1,0.5' // string ``` Object/tuple forms are validated before the subprocess spawns (throws `RangeError`/`TypeError` on out-of-range or malformed values). ### Response - `Promise` - A promise that resolves with the bytes of the searchable PDF. ``` -------------------------------- ### Batch Processing and Output Options Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Process multiple files at once or specify custom output paths and naming conventions. The `-o` flag supports file paths, name templates, and directories. ```sh mac-ocr searchable-pdf *.pdf # writes .ocr.pdf for each mac-ocr searchable-pdf scan.pdf -o out/ # out/scan.ocr.pdf mac-ocr searchable-pdf scan.pdf -o '[name]-ocr.pdf' # scan-ocr.pdf ``` -------------------------------- ### Output to Standard Output Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Redirect the generated searchable PDF to standard output. This is useful for piping the output to other commands or processes. Note that this option is refused on a TTY. ```sh mac-ocr searchable-pdf scan.pdf -o - # PDF to stdout (refused on a TTY) ``` -------------------------------- ### Control Output Destination for Searchable PDFs Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Specify the output path for the searchable PDF using the `-o` flag. This can be a directory, a name template, a fixed file path, or stdout. ```sh mac-ocr searchable-pdf scan.pdf -o out/ # out/scan.ocr.pdf mac-ocr searchable-pdf scan.pdf -o '[name]-ocr.pdf' # scan-ocr.pdf mac-ocr searchable-pdf scan.pdf -o searchable.pdf # fixed path mac-ocr searchable-pdf scan.pdf -o - > scan.pdf # stdout ``` -------------------------------- ### Create Searchable PDF Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Generate a searchable PDF from an existing PDF file using 'createSearchablePdf'. The function returns the bytes of the new PDF, which can then be written to a file. ```ts // Build a searchable PDF (returns the PDF bytes) const pdf = await createSearchablePdf(await fs.readFile('scan.pdf'), { fast: true }) await fs.writeFile('scan.ocr.pdf', pdf) ``` -------------------------------- ### Batch OCR to JSONL Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Process a large number of PDF documents in batch and output results as JSON Lines to a file. This method is memory-bounded, processing one page at a time. ```sh mac-ocr --format jsonl large-docs/*.pdf > results.jsonl # memory-bounded, one line per page ``` -------------------------------- ### Force Partitioned OCR Strategy Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Use `--ocr-strategy partitioned` to force the partitioned OCR pass for eligible pages, which can improve accuracy for small text on high-resolution images. This strategy cannot be combined with `--roi`. ```sh mac-ocr searchable-pdf --ocr-strategy partitioned scan.pdf ``` -------------------------------- ### Opt-out of Partitioned OCR Strategy Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Use `--ocr-strategy standard` to disable the partitioned OCR pass and use the default full-page OCR strategy. ```sh mac-ocr searchable-pdf --ocr-strategy standard scan.pdf ``` -------------------------------- ### Create Searchable PDF Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Generates a searchable PDF with an invisible OCR text layer from input bytes. Preserves existing text in born-digital pages and adds OCR to scanned pages. For hybrid pages, existing digital text may appear twice. ```typescript const pdf = await createSearchablePdf(scanBytes) await fs.writeFile('scan.ocr.pdf', pdf) ``` -------------------------------- ### Import mac-ocr API functions Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Import necessary functions from the mac-ocr library for use in your Node.js project. ```ts import { ocr, createSearchablePdf, supportedLanguages } from 'mac-ocr' ``` -------------------------------- ### Enabling Debug Mode for Searchable PDFs Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Activates debug mode by setting the MAC_OCR_DEBUG environment variable. This generates visible OCR boxes and a JSONL sidecar file for diagnostics. Debug mode requires file output and is incompatible with stdout output. ```sh MAC_OCR_DEBUG=1 mac-ocr searchable-pdf lease.pdf ``` -------------------------------- ### Basic OCR Usage Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Run OCR on various input types including images, PDFs, multiple files, stdin, and URLs. Output can be directed to stdout or a file using a template. ```sh mac-ocr photo.png # text → stdout mac-ocr scan.pdf # multi-page PDF, streamed mac-ocr a.png b.png c.png # multiple images cat screenshot.png | mac-ocr # stdin (auto-detected) mac-ocr https://example.com/img.png # URL (simple GET only) mac-ocr shots/*.png -o '[dir]/[name].txt' # a .txt next to each image mac-ocr --format jsonl scans/*.pdf # streaming JSONL for big jobs ``` -------------------------------- ### Node.js OCR and PDF API Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Demonstrates the Node.js API for performing OCR on images or single-page PDFs, streaming multi-page PDFs, creating searchable PDFs, and retrieving supported languages. Inputs are expected as bytes. ```ts const { text, observations } = await ocr(bytes) // single image or single-page PDF for await (const page of ocr.pages(pdfBytes)) { /* … */ } // stream multi-page PDF const pages = await Array.fromAsync(ocr.pages(pdfBytes)) // …or collect → OcrResult[] const pdf = await createSearchablePdf(bytes) // → Uint8Array (PDF bytes) const langs = await supportedLanguages() // → string[] (ocr + createSearchablePdf) ``` -------------------------------- ### mac-ocr Node.js API Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Provides a typed, promise-based Node.js API for performing OCR and creating searchable PDFs. It mirrors the CLI options and accepts byte inputs. ```APIDOC ## Node.js API The package also exposes a typed, promise-based API (`import { ocr, createSearchablePdf, supportedLanguages } from 'mac-ocr'`) that spawns the binary. Inputs are **bytes** (Buffer/Uint8Array/ArrayBuffer) — read files or fetch URLs in your own code. ```ts const { text, observations } = await ocr(bytes) // single image or single-page PDF for await (const page of ocr.pages(pdfBytes)) { /* … */ } // stream multi-page PDF const pages = await Array.fromAsync(ocr.pages(pdfBytes)) // …or collect → OcrResult[] const pdf = await createSearchablePdf(bytes) // → Uint8Array (PDF bytes) const langs = await supportedLanguages() // → string[] (ocr + createSearchablePdf) ``` - `ocr()` throws if given a multi-page PDF — use `ocr.pages()`. - Options mirror the CLI: `fast`, `languages`, `confidence`, `customWords`, `languageCorrection` (default true), `minTextHeight`, `maxCandidates` (ocr only), `regionOfInterest` (`{x,y,width,height}` | `[x,y,width,height]` | `"x,y,w,h"`), `pdfDpi`, `ocrStrategy`, `imageQuality`, `imagePageDpi`, and `imageDownsampleDpi` (searchable PDF only), `password`, `signal` (AbortSignal). - Failures throw `MacOcrError` with `.kind` (`'usage'`, `'runtime'`, `'unavailable'`, …) and `.stderr`. ``` -------------------------------- ### mac-ocr CLI Languages Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Lists the recognition languages supported by the mac-ocr CLI for the current macOS version. This applies to both standard OCR and searchable PDF creation. ```APIDOC ## languages List the recognition languages supported on this macOS version (one BCP-47 code per line). They apply to both OCR and `searchable-pdf`. ```sh mac-ocr languages # accurate recognizer mac-ocr languages --fast # fast recognizer's set ``` ``` -------------------------------- ### Handling MacOcrError in Node.js Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Demonstrates how to catch and inspect MacOcrError instances thrown by the OCR process. This includes accessing error kind, code, exit code, and captured stderr. ```typescript import { MacOcrError } from 'mac-ocr' try { await ocr(bytes) } catch (error) { if (error instanceof MacOcrError) { error.kind // category — see below error.code // machine-readable code from the CLI, when available error.exitCode // process exit code, or null (signal/never-started) error.stderr // captured CLI stderr } } ``` -------------------------------- ### mac-ocr scans/*.pdf -o '[name].md' Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Processes multiple PDF files in the 'scans/' directory and saves the recognized text for each input into a separate Markdown file named after the input file. This uses a template to specify the output filename. ```sh mac-ocr scans/*.pdf -o '[name].md' # one .md per input ``` -------------------------------- ### Create Searchable PDF Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Generate a searchable PDF from an existing PDF file. This function embeds the recognized text invisibly, allowing for text selection and searching. ```APIDOC ## createSearchablePdf ### Description Creates a new PDF file with an invisible layer of text, making it searchable. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **bytes** (Buffer | Uint8Array) - Required - The input PDF file content as bytes. - **options** (object) - Optional - Configuration options for PDF creation. - **fast** (boolean) - Optional - If true, uses a faster but potentially less accurate method. ### Response #### Success Response (200) - **pdfBytes** (Buffer | Uint8Array) - The bytes of the generated searchable PDF. ### Request Example ```javascript import fs from 'node:fs/promises' import { createSearchablePdf } from 'mac-ocr' const pdf = await createSearchablePdf(await fs.readFile('scan.pdf'), { fast: true }) await fs.writeFile('scan.ocr.pdf', pdf) ``` ``` -------------------------------- ### Forcing Standard OCR Strategy Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Uses only full-page OCR, disabling the partitioned OCR pass. This is useful when the partitioned strategy is not desired or might introduce errors. ```sh mac-ocr searchable-pdf --ocr-strategy standard input.pdf ``` -------------------------------- ### Supported Languages Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Retrieve a list of languages that are currently supported by the `mac-ocr` library on the current macOS version for both text recognition and searchable PDF creation. ```APIDOC ## supportedLanguages ### Description Returns a list of languages supported by the `mac-ocr` library on the current system. ### Parameters None ### Response #### Success Response (200) - **languages** (Array) - An array of strings, where each string is a supported language code (e.g., 'en-US', 'fr-FR'). ### Request Example ```javascript import { supportedLanguages } from 'mac-ocr' const languages = await supportedLanguages() console.log(languages) ``` ``` -------------------------------- ### Cancel OCR Operation with AbortController Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Demonstrates how to cancel an ongoing OCR operation using `AbortController`. The operation will reject with a `MacOcrError` of kind 'abort' if cancelled. ```typescript const controller = new AbortController() setTimeout(() => controller.abort(), 5_000) await ocr(bytes, { signal: controller.signal }) // rejects with MacOcrError, kind 'abort' ``` -------------------------------- ### ocr(input, options?) Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Recognizes text in a single image or single-page PDF. It takes image or PDF bytes as input and returns a Promise resolving to an OcrResult object containing the recognized text, observations, width, and height. ```APIDOC ## ocr(input, options?) ### Description Recognizes text in a single image or single-page PDF. Returns `Promise`. ### Method POST ### Endpoint /ocr ### Parameters #### Request Body - **input** (Buffer | Uint8Array | ArrayBuffer) - Required - Image or PDF bytes. - **options** (object) - Optional - Configuration options for OCR. ### Response #### Success Response (200) - **text** (string) - The recognized text. - **observations** (array) - Detected text observations. - **width** (number) - The width of the input image/page. - **height** (number) - The height of the input image/page. ### Request Example ```json { "input": "" } ``` ### Response Example ```json { "text": "Recognized text from the image/PDF.", "observations": [ { "text": "some text", "boundingBox": [x1, y1, x2, y2] } ], "width": 1920, "height": 1080 } ``` ``` -------------------------------- ### Merging Multiple Inputs into One PDF Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Combine multiple image or PDF files into a single searchable PDF document. The `--merge` option requires a specific output file path or stdout. ```sh mac-ocr searchable-pdf --merge -o lease.pdf page1.jpg page2.jpg ``` -------------------------------- ### JSON Output Structure Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Illustrates the structure of JSON output for OCR results, including source information, page details, recognized text, and bounding box data for observations. Bounding boxes are normalized and can be converted to pixel coordinates. ```jsonc { "source": { "type": "file", "path": "scan.pdf" }, "page": 1, "pageCount": 3, "width": 1224, "height": 1584, "text": "Full recognized text\nwith newlines", "observations": [ { "text": "Full recognized text", "confidence": 1.0, "boundingBox": { "x": 0.05, "y": 0.42, "width": 0.37, "height": 0.06 }, "requestRevision": 3 } ] } ``` -------------------------------- ### supportedLanguages Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Lists the recognition languages Vision supports on this macOS version (BCP-47 codes). These languages apply to both `ocr` and `createSearchablePdf`. ```APIDOC ## `supportedLanguages(options?)` Lists the recognition languages Vision supports on this macOS version (BCP-47 codes). They apply to both `ocr` and `createSearchablePdf`. Returns `Promise`. ### Parameters #### Options - `fast` (boolean) - Optional - Use the faster character-by-character recognizer instead of the default neural net — lower accuracy; see [Recognition levels](CLI.md#recognition-levels). ### Response - `Promise` - A promise that resolves with an array of supported language codes (BCP-47). ``` -------------------------------- ### OCR All Pages Option Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Force OCR processing on every page, including those that already contain selectable text. This is useful for hybrid pages but may result in duplicated text. ```sh mac-ocr searchable-pdf --ocr-all-pages input.pdf ``` -------------------------------- ### Perform OCR on an image file Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Read an image file into bytes and then perform OCR using the ocr function. Ensure the input is a valid image format supported by macOS. ```ts import fs from 'node:fs/promises' const result = await ocr(await fs.readFile('receipt.jpg')) ``` -------------------------------- ### OCR All Pages Regardless of Existing Text Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Use `--ocr-all-pages` to ensure that OCR is performed on every page, even if the page already contains selectable text. This overrides the default behavior of skipping pages that do not need OCR. ```sh mac-ocr searchable-pdf --ocr-all-pages scan.pdf ``` -------------------------------- ### Collect all OCR results from PDF into an array Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Read all pages of a PDF and collect the OCR results into an array. This is suitable when all results are needed at once. ```ts // …or collect all pages into an array: const pages = await Array.fromAsync(ocr.pages(pdfBytes)) // OcrResult[] ``` -------------------------------- ### Stream OCR results from multi-page PDF Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Process each page of a PDF asynchronously as it becomes available. This method is memory-efficient for large PDFs. ```ts // Stream pages as each finishes — bounded memory, early results: for await (const page of ocr.pages(pdfBytes)) { console.log(page.page, '/', page.pageCount, page.text) } ``` -------------------------------- ### mac-ocr scan.pdf -o notes.md Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Writes recognized text from a PDF file to a Markdown file named 'notes.md'. This demonstrates saving plain text output to a file with a .md extension. ```sh mac-ocr scan.pdf -o notes.md # recognized text → notes.md ``` -------------------------------- ### Multi-page PDF Text Recognition Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Process multi-page PDFs by streaming pages as they are recognized using `ocr.pages`. You can iterate through the pages as they become available or collect them all into an array. ```APIDOC ## ocr.pages ### Description Processes a multi-page PDF, yielding each page's recognized text as it becomes available. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **bytes** (Buffer | Uint8Array) - Required - The PDF file content as bytes. ### Response #### Success Response (200) - **page** (AsyncIterableIterator) - An async iterator yielding page objects. - **page** (number) - The current page number. - **pageCount** (number) - The total number of pages in the PDF. - **text** (string) - The recognized text for the current page. ### Request Example ```javascript import fs from 'node:fs/promises' import { ocr } from 'mac-ocr' // Stream pages as they finish for await (const page of ocr.pages(await fs.readFile('book.pdf'))) { console.log(page.page, '/', page.pageCount, page.text) } // Collect all pages into an array const pages = await Array.fromAsync(ocr.pages(await fs.readFile('book.pdf'))) ``` ``` -------------------------------- ### mac-ocr JSON Output Schema Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md This is the output schema when using the --format json option. It wraps all results in a single array. ```json { "source": { "type": "file", "path": "scan.pdf" }, "page": 1, "pageCount": 3, "width": 1224, "height": 1584, "text": "Line one\nLine two", "observations": [ { "text": "Line one", "confidence": 1.0, "boundingBox": { "x": 0.05, "y": 0.42, "width": 0.37, "height": 0.06 }, "candidates": [ { "text": "Line one", "confidence": 1.0 }, { "text": "Line orie", "confidence": 0.3 } ], "requestRevision": 3 } ] } ``` -------------------------------- ### Recognize text from images and PDFs Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Basic usage of mac-ocr to recognize text from various input sources. Supports single images, multiple images, PDFs, stdin, and URLs. ```sh mac-ocr receipt.jpg # text → stdout ``` ```sh mac-ocr page1.png page2.png # multiple images ``` ```sh mac-ocr scan.pdf # multi-page PDF ``` ```sh cat screenshot.png | mac-ocr # stdin ``` ```sh mac-ocr https://example.com/a.png # URL (simple GET) ``` -------------------------------- ### Image Downsampling Control Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Limit the resolution of the visible image layer for image inputs with `--image-downsample-dpi`. OCR and page size remain unaffected. ```sh mac-ocr searchable-pdf --image-downsample-dpi 600 input.jpg ``` -------------------------------- ### Convert Normalized Bounding Box to Pixels Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/CLI.md Convert normalized bounding box coordinates to pixel values using the result's width and height. This is useful for displaying bounding boxes on the original image. ```javascript const px = obs.boundingBox.x * result.width const py = obs.boundingBox.y * result.height const pw = obs.boundingBox.width * result.width const ph = obs.boundingBox.height * result.height ``` -------------------------------- ### List Supported OCR Languages Source: https://github.com/privatenumber/mac-ocr/blob/develop/docs/NODE.md Retrieves a list of BCP-47 language codes supported by the Vision OCR engine on the current macOS version. This applies to both `ocr` and `createSearchablePdf` functions. An optional `fast: true` parameter uses a faster, less accurate recognizer. ```typescript const languages = await supportedLanguages() // accurate recognizer const fastLanguages = await supportedLanguages({ fast: true }) ``` -------------------------------- ### List Supported OCR Languages Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Lists the recognition languages supported by the accurate and fast recognizers on the current macOS version. Each language is represented by a BCP-47 code. ```sh mac-ocr languages # accurate recognizer mac-ocr languages --fast # fast recognizer's set ``` -------------------------------- ### Image Page DPI Override Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Specify the DPI for sizing image inputs using `--image-page-dpi`. This affects page size but not the resolution used for OCR. ```sh mac-ocr searchable-pdf --image-page-dpi 300 input.jpg ``` -------------------------------- ### Process Multi-page PDF Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Iterate through pages of a multi-page PDF as they are processed using 'ocr.pages'. Alternatively, collect all pages into an array. ```ts // Multi-page PDF: stream pages as they finish… for await (const page of ocr.pages(await fs.readFile('book.pdf'))) { console.log(page.page, '/', page.pageCount, page.text) } // …or collect the whole thing into an array const pages = await Array.fromAsync(ocr.pages(await fs.readFile('book.pdf'))) ``` -------------------------------- ### Text Recognition Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Recognize text in an image or a single-page PDF by passing the file bytes to the `ocr` function. The result includes the recognized text and a list of observations with confidence scores and bounding boxes. ```APIDOC ## ocr ### Description Recognizes text within an image or a single-page PDF. ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **bytes** (Buffer | Uint8Array) - Required - The image or PDF file content as bytes. ### Response #### Success Response (200) - **text** (string) - The full recognized text from the input. - **observations** (Array) - A list of recognized text observations. - **text** (string) - The recognized text for this observation. - **confidence** (number) - The confidence score for the recognition. - **boundingBox** (object) - The bounding box coordinates of the recognized text. - **x** (number) - **y** (number) - **width** (number) - **height** (number) ### Request Example ```javascript import fs from 'node:fs/promises' import { ocr } from 'mac-ocr' const result = await ocr(await fs.readFile('receipt.jpg')) console.log(result.text) for (const { text, confidence, boundingBox } of result.observations) { /* ... */ } ``` ``` -------------------------------- ### Recognize Text in Image or PDF Source: https://github.com/privatenumber/mac-ocr/blob/develop/README.md Use the 'ocr' function to recognize text from an image file or a single-page PDF. The result includes the extracted text and observations with confidence scores and bounding boxes. ```ts import fs from 'node:fs/promises' import { ocr, createSearchablePdf, supportedLanguages } from 'mac-ocr' // Recognize text in an image or single-page PDF const result = await ocr(await fs.readFile('receipt.jpg')) console.log(result.text) for (const { text, confidence, boundingBox } of result.observations) { /* … */ } ``` -------------------------------- ### Image Quality Control Source: https://github.com/privatenumber/mac-ocr/blob/develop/skills/mac-ocr/SKILL.md Adjust the quality of the visible image layer for image inputs using `--image-quality`. The OCR process still uses the full-resolution image. ```sh mac-ocr searchable-pdf --image-quality 0.8 input.jpg ```