# Process OCR Batches with Vision on a Hosted Mac

Canonical: https://figment.so/blog/mac-vision-ocr-batches

Save the Swift script, run it on a test folder, pick a confidence threshold from your own sample, then schedule it with launchd. Figment's Intel Mac VM ($25 a month) can run file-based OCR on CPU.

**Run `VNRecognizeTextRequest` from a Swift script over a folder of images, choose a confidence threshold from your own sample, and schedule the script with launchd.** Apple's Vision framework recognizes text on the Mac itself, so page images never go to a third-party API. Figment's Intel Mac VM ($25 a month) can run file-based OCR on CPU.

Vision's text recognition is documented in Apple's [Recognizing text in images](https://developer.apple.com/documentation/vision/recognizing-text-in-images). Figment does not publish an OCR throughput number, so benchmark on your own representative sample.

## What should I decide before I start?

| Factor | Implication |
|--------|-------------|
| Input format | PNG, JPEG, TIFF and HEIC load through ImageIO. PDF pages need a PDFKit render step first |
| Required languages | Vision biases toward English by default. Set `recognitionLanguages` explicitly for other scripts |
| Confidence threshold | Sets the accept and reject split. Tune it on a representative sample before committing |
| Schedule | Overnight batch: launchd `StartCalendarInterval`. Watch folder: `QueueDirectories` |

## What does the script need access to?

`VNRecognizeTextRequest` works from a `CGImage`. File-based OCR of images you own does not need Accessibility or Screen Recording consent, because the script reads image files directly through ImageIO. It needs:

- Read access to the input directory (SFTP in, cloud sync or a mounted share)
- Write access to an output directory for `.txt` results
- No outbound call to an OCR API, since processing is local

From Apple's documentation: to recognize traditional and simplified Chinese, specify `zh-Hant` and `zh-Hans` as the first elements in `recognitionLanguages`. English is the only other language you can pair with Chinese, and language correction is not available for Chinese. For other language sets, call `VNRecognizeTextRequest.supportedRecognitionLanguages(for:revision:)` to see what your macOS version supports.

## How do I run OCR on a folder of images?

Save this as `ocr_batch.swift`. It is an untested educational example to adapt to your project. It is not a benchmark result and not evidence of throughput.

```swift
#!/usr/bin/env swift
// ocr_batch.swift — batch image-to-text using Vision VNRecognizeTextRequest
// Usage: ./ocr_batch.swift <input-dir> <output-dir> [min-confidence 0.0-1.0]
import Foundation
import CoreGraphics
import ImageIO
import Vision

let args = CommandLine.arguments
guard args.count >= 3 else {
    FileHandle.standardError.write(Data("Usage: ocr_batch <input-dir> <output-dir> [min-confidence]\n".utf8))
    exit(2)
}

let inputDir  = URL(fileURLWithPath: args[1])
let outputDir = URL(fileURLWithPath: args[2])
let minConf   = Double(args.count > 3 ? args[3] : "0.0") ?? 0.0

let fm = FileManager.default
var accepted = 0, skipped = 0, errors = 0

do {
    try fm.createDirectory(at: outputDir, withIntermediateDirectories: true)
} catch {
    FileHandle.standardError.write(Data("OUTPUT_DIR_ERROR: \(error)\n".utf8))
    exit(3)
}

let exts: Set<String> = ["png","jpg","jpeg","tiff","tif","heic"]
let files: [URL]
do {
    files = try fm.contentsOfDirectory(at: inputDir, includingPropertiesForKeys: nil)
        .filter { exts.contains($0.pathExtension.lowercased()) }
        .sorted { $0.lastPathComponent < $1.lastPathComponent }
} catch {
    FileHandle.standardError.write(Data("INPUT_DIR_ERROR: \(error)\n".utf8))
    exit(4)
}

for file in files {
    guard let src = CGImageSourceCreateWithURL(file as CFURL, nil),
          let img = CGImageSourceCreateImageAtIndex(src, 0, nil) else {
        FileHandle.standardError.write(Data("LOAD_ERROR: \(file.lastPathComponent)\n".utf8))
        errors += 1
        continue
    }

    let request = VNRecognizeTextRequest()
    // The accurate path is the default; set it explicitly to document intent.
    request.recognitionLevel = .accurate
    request.usesLanguageCorrection = true
    // Set request.recognitionLanguages here if you need non-English input.

    do {
        try VNImageRequestHandler(cgImage: img).perform([request])
    } catch {
        FileHandle.standardError.write(Data("VISION_ERROR: \(file.lastPathComponent): \(error)\n".utf8))
        errors += 1
        continue
    }

    let observations = (request.results as? [VNRecognizedTextObservation]) ?? []
    let lines: [String] = observations.compactMap { obs in
        guard let top = obs.topCandidates(1).first,
              Double(top.confidence) >= minConf else { return nil }
        return top.string
    }

    if lines.isEmpty { skipped += 1; continue }

    let outURL = outputDir.appendingPathComponent(
        file.deletingPathExtension().lastPathComponent + ".txt")
    do {
        try lines.joined(separator: "\n").write(to: outURL, atomically: true, encoding: .utf8)
        accepted += 1
    } catch {
        FileHandle.standardError.write(Data("WRITE_ERROR: \(outURL.lastPathComponent): \(error)\n".utf8))
        errors += 1
    }
}

print("accepted=\(accepted) skipped=\(skipped) errors=\(errors)")
exit(errors > 0 ? 1 : 0)
```

Run a small manual test before scheduling, with your own paths:

```bash
chmod +x ~/scripts/ocr_batch.swift
~/scripts/ocr_batch.swift ~/test-images ~/test-output 0.80
```

The script exits non-zero when any file errored, so a scheduler, CI step or wrapper can detect partial failure instead of accepting broken output.

## Which confidence threshold should I use?

Run the first pass with `min-confidence 0.0` to collect the full spread of top-candidate confidence values, then apply this matrix to pick a production threshold.

| Confidence range | Typical source material | Recommended action |
|-----------------|------------------------|-------------------|
| 0.95 to 1.00 | Machine-printed text, modern scans | Accept automatically; spot-check a small random sample |
| 0.80 to 0.94 | Mixed print and light handwriting | Accept; route to a low-priority human review queue |
| 0.50 to 0.79 | Poor scan quality, faded ink | Route to the review queue; flag the original scan |
| 0.00 to 0.49 | Non-text images, damaged scans | Reject to a `rejected/` subfolder; alert the operator |

Build a histogram from a representative sample of your own pipeline, because clean office scans and archival scans behave very differently. Record the threshold, sample size and date in a short acceptance note so later changes are auditable.

## How do I schedule the batch with launchd?

Use `QueueDirectories` to process a spool folder whenever files arrive, or `StartCalendarInterval` for a nightly run. Both keys are documented in Apple's [Creating Launchd Jobs](https://developer.apple.com/library/archive/documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html). `QueueDirectories` starts your job while the listed directories are non-empty and keeps it running until they drain.

Save this plist to `~/Library/LaunchAgents/com.example.ocr-batch.plist`, replacing `agent` with your account name:

```xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN"
  "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key><string>com.example.ocr-batch</string>
    <key>ProgramArguments</key>
    <array>
        <string>/Users/agent/scripts/ocr_batch.swift</string>
        <string>/Users/agent/ocr-spool</string>
        <string>/Users/agent/ocr-output</string>
        <string>0.80</string>
    </array>
    <key>QueueDirectories</key>
    <array><string>/Users/agent/ocr-spool</string></array>
    <key>StandardOutPath</key><string>/Users/agent/Library/Logs/ocr_batch.out.log</string>
    <key>StandardErrorPath</key><string>/Users/agent/Library/Logs/ocr_batch.err.log</string>
</dict>
</plist>
```

Load it with `launchctl load ~/Library/LaunchAgents/com.example.ocr-batch.plist`. The paths are user-owned, so the job needs no root access and does not touch other users' files.

## What if a run fails or stalls?

- Append each written filename to `~/ocr-output/processed.txt` and skip listed names on restart, so a crash mid-batch does not reprocess finished work.
- Use the script's non-zero exit to notify yourself. Pull the webhook secret from your own secret manager. Do not put the webhook URL in the plist's environment keys or in shell history.
- Schedule a separate `StartCalendarInterval` job that alerts if `ocr-spool` keeps growing while `ocr-output` has not changed in 30 minutes. That catches a stuck launchd job that `launchctl load` alone will not show.
- Keep a dated acceptance log (sample size, histogram shape, chosen threshold). Tuning a threshold without a record is a frequent source of silent regressions.

## How large an OCR batch can the Intel Mac VM handle?

Vision's accurate path runs a neural network. On the Intel Mac VM it runs on CPU, with 4 shared vCPUs, 4GB of RAM and 80GB of SSD, so size the batch to that. If CPU is saturated on real input (watch `top` or Activity Monitor), move up. Rough example for a department scanning about 2,000 A4 pages a month at 150 dpi (your numbers depend on image size, language mix and whether language correction is on):

| Plan | Monthly | 12 months | When it fits |
|---|---|---|---|
| Intel Mac VM | $25 | 12 × $25 = $300 | Steady overnight batch that is the main job on the machine |
| Apple Silicon Mac VM (4 shared vCPUs, 4GB) | $39 | 12 × $39 = $468 | You want Apple silicon or Xcode 26.4 and later |
| Dedicated M4 Pro 48 GB | $349 | $3,228 paid up front | Parallel batches or mixed workloads on a whole Mac |

The Apple Silicon VM costs $168 a year more than the Intel VM (468 - 300). We have not measured whether Vision uses the Neural Engine inside a VM, so test that on your own sample before you pay for the upgrade on that basis. The Intel VM cannot run arm64-only binaries. Daily plans on the VMs ($2, $6, or $12 for the 8 GB size) suit one-off backlogs; the Dedicated M4 Pro is monthly only. See [Figment Mac Hosting](/mac-hosting).

Disk use depends on input resolution and retention. A 150 dpi grayscale A4 scan is often a few hundred KB as PNG, and a colour 300 dpi scan can be several megabytes. Estimate your per-page size, multiply by retention, and copy finished output off the Mac (S3, Backblaze B2 or your own store) before the disk fills. Storage includes the OS, and a persistent disk is not a backup.

## How do I set this up on a new Mac?

1. Connect over SSH or remote desktop, create `~/scripts/` and add `ocr_batch.swift`.
2. Create the working directories: `mkdir -p ~/ocr-spool ~/ocr-output ~/Library/Logs`.
3. Install the LaunchAgent plist above (with your real user name) and load it with `launchctl load`.
4. Drop a test image into `~/ocr-spool` and confirm a matching `.txt` appears in `~/ocr-output`.
5. Collect a representative sample, build a histogram and tune the threshold with the matrix above.

**Related guides:**
- [Run a Mac API agent runtime](/blog/mac-api-agent-runtime)
- [Self-hosted GitHub Actions runner on Mac](/blog/mac-github-actions-self-hosted-runner)
- [Migrate your Mac agent workload](/blog/mac-agent-exit-migration)
