spider-ocr
Native macOS OCR worker for SPIDER. It reads images with ImageIO, recognises text with Apple
Vision (VNRecognizeTextRequest) and prints JSON. macOS 13 or later; no third-party dependency.
Build
./build.sh # swift build -c release -> .build/release/spider-ocr
./build.sh --install # also copies the binary to ~/.spider/bin/spider-ocrThe Python wrapper (spider.ocr) looks for the binary in $SPIDER_OCR_BIN, then in
services/ocr-worker/.build/release/spider-ocr, then in ~/.spider/bin/spider-ocr.
spider.ocr.build() runs the same SwiftPM build.
Modes
spider-ocr [options] file... # one JSON line per file, in order
spider-ocr --serve [options] # JSON-lines requests on stdin, one JSON line per response
spider-ocr --list-languages [--level fast]Exit codes: 0 ok (at least one file succeeded, or serve mode ended normally), 1 every file
failed, 2 usage error. A missing, empty, truncated or non-image file gives a JSON error, never a
crash.
| Option | Default | Meaning |
|---|---|---|
--languages a,b |
fr-CA,en-US |
recognition languages, in priority order |
--level accurate|fast (--fast) |
accurate |
Vision recognition level |
--alternatives N |
3 | other candidate readings per line (max 9) |
--no-language-correction |
correction on | disable Vision's language-model correction |
--auto-language |
off | let Vision detect the language |
--min-text-height F |
0 | ignore text smaller than this fraction of the image height |
--region x,y,w,h |
whole image | recognise only this pixel rectangle |
--detect-orientation |
off | find the rotation (0/90/180/270) that makes the text upright |
--max-pixels N |
40000000 | images with more pixels are processed in overlapping bands |
--max-band-aspect F |
4 | a band is at most F times longer than wide (0 = no limit) |
--band-overlap N |
200 | overlap between two bands, in pixels |
--concurrency N |
2 | images processed at once in serve mode (max 16) |
In serve mode the command-line options are the defaults of every request.
Serve protocol
One JSON object per line in, one per line out, flushed after every line. Responses may arrive in
a different order than the requests: match them by id.
Request (only path is required):
{"id": "r1", "path": "/abs/capture.png", "languages": ["fr-CA", "en-US"], "level": "accurate",
"alternatives": 3, "language_correction": true, "min_text_height": 0.0,
"region": [0, 0, 800, 600], "detect_orientation": false, "auto_language": false,
"max_pixels": 40000000, "max_band_aspect": 4, "band_overlap": 200}Response:
{"id": "r1", "path": "/abs/capture.png", "ok": true, "width": 451, "height": 264,
"orientation": 1, "rotation": 0, "rotation_detected": false,
"banded": false, "bands": 1, "level": "accurate", "languages": ["fr-FR", "en-US"],
"lines": [{"text": "Total à payer : 2 847,35 $", "confidence": 1,
"x": 31.9, "y": 190, "w": 190.2, "h": 18,
"quad": [[31.9, 190], [222.1, 190], [222.1, 208], [31.9, 208]],
"alternatives": [{"text": "Total à payer: 2 847,35 $", "confidence": 1}]}],
"warnings": ["language_substituted:fr-CA->fr-FR"], "ms": 41,
"engine": {"name": "apple-vision", "revision": 3, "os": "Version 27.3 (Build ...)", "worker": "1.0.0"},
"error": null}Failure: {"id", "path", "ok": false, "lines": [], "ms", "engine", "error": {"code", "message"}}.
Error codes: not_found, not_a_file, empty_file, unreadable_image, corrupt_image,
invalid_region, crop_failed, vision_failed, bad_request, bad_json, internal.
Other operations:
{"op": "ping", "id": 1} -> {"id": 1, "ok": true, "op": "pong", "pid", "concurrency", "pending", "engine"}
{"op": "languages", "level": "fast"} -> {"ok": true, "op": "languages", "level", "languages": [...]}
{"op": "shutdown"} -> waits for the running requests, answers {"ok": true, "op": "shutdown"}, exits 0End of input (stdin closed) also ends the worker after the running requests.
Fields
width,height: size of the image as displayed, that is after the EXIF orientation is applied.x,y,w,h: bounding box in pixels of that displayed image, origin top-left (Vision's normalised bottom-left coordinates are converted).quad: the four corners of the text line, in reading order of the text (top-left, top-right, bottom-right, bottom-left), same space. With--detect-orientationthe coordinates still refer to the original image, not to a rotated copy.orientation: EXIF orientation of the file (1 to 8).rotation: clockwise rotation in degrees that makes the text upright (always 0 without--detect-orientation);rotation_methodandrotation_scoressay how it was chosen.confidence: Vision's confidence of the top candidate.alternatives: the next candidates.- Line order: rows from top to bottom (two lines share a row when their centres are within half a line height), then left to right. With a detected rotation the order follows the rotated text.
languages: the languages actually given to Vision. A requested language that Vision does not support is replaced by a supported one with the same primary subtag (fr-CA->fr-FR) or dropped; each case is listed inwarnings.banded,bands: whether the image was cut in bands and how many.
Orientation detection
Measured on Vision revision 3: the accurate recogniser reads text at 0, 90, 180 and 270 degrees
with nearly the same confidence, and the fast recogniser scores 0 and 180 nearly the same, so
"best mean confidence x character count" over four trials does not separate the rotations.
The worker therefore runs one accurate pass on a downscaled copy (at most 1600 px, a centred
window for very large pages) and lets the direction of each line's quadrilateral vote, weighted
by character count (rotation_method: "quad", used when one direction gets 60 % of the votes).
Only if that is inconclusive are the four rotations tried with the fast recogniser and scored by
mean confidence x character count ("trial"). "none" means no text was found; rotation is 0.
The fast level only reads upright text: use --detect-orientation with it for rotated pages.
The mirrored EXIF orientations (2, 4, 5, 7) are applied like the others; a bitmap that is mirrored
without saying so in EXIF is not detected.
Bands
Vision scales its input to a fixed working size. Measured on revision 3: a 529 x 6320 page
recognised in one piece returns 0 lines; the same page in bands returns its 216 lines. The worker
never downscales: an image is cut into bands across the text's vertical axis when it has more than
--max-pixels pixels or when it is more than --max-band-aspect times longer than wide. Bands
overlap by --band-overlap pixels; a line is kept from the band that owns its centre, and a line
still present on both sides of a seam (IoU > 0.5 and text similarity >= 0.8) is kept once, with the
higher confidence. A very wide and short image (more than 8:1) is not cut, because a vertical cut
would slice through the lines; the response then carries the warning extreme_aspect_ratio.
Memory and concurrency
At most --concurrency images are decoded at any time in serve mode; waiting requests are only
small dictionaries. Each image and each band runs in its own autorelease pool. An image is decoded
once in full (width x height x 4 bytes); bands share that buffer.
Examples
spider-ocr --languages fr-CA,en-US capture.png | jq -r '.lines[].text'
spider-ocr --detect-orientation scan.jpg | jq '{rotation, n: (.lines | length)}'
printf '%s\n' '{"id":"a","path":"/tmp/a.png"}' '{"id":"b","path":"/tmp/b.png","level":"fast"}' \
| spider-ocr --serve --concurrency 4