SPB Git

Repository Public

README.md 7.7 KB 148 lines markdown

1# spider-ocr23Native macOS OCR worker for SPIDER. It reads images with ImageIO, recognises text with Apple4Vision (`VNRecognizeTextRequest`) and prints JSON. macOS 13 or later; no third-party dependency.56## Build78```sh9./build.sh              # swift build -c release -> .build/release/spider-ocr10./build.sh --install    # also copies the binary to ~/.spider/bin/spider-ocr11```1213The Python wrapper (`spider.ocr`) looks for the binary in `$SPIDER_OCR_BIN`, then in14`services/ocr-worker/.build/release/spider-ocr`, then in `~/.spider/bin/spider-ocr`.15`spider.ocr.build()` runs the same SwiftPM build.1617## Modes1819```sh20spider-ocr [options] file...     # one JSON line per file, in order21spider-ocr --serve [options]     # JSON-lines requests on stdin, one JSON line per response22spider-ocr --list-languages [--level fast]23```2425Exit codes: `0` ok (at least one file succeeded, or serve mode ended normally), `1` every file26failed, `2` usage error. A missing, empty, truncated or non-image file gives a JSON error, never a27crash.2829| Option | Default | Meaning |30|---|---|---|31| `--languages a,b` | `fr-CA,en-US` | recognition languages, in priority order |32| `--level accurate\|fast` (`--fast`) | `accurate` | Vision recognition level |33| `--alternatives N` | 3 | other candidate readings per line (max 9) |34| `--no-language-correction` | correction on | disable Vision's language-model correction |35| `--auto-language` | off | let Vision detect the language |36| `--min-text-height F` | 0 | ignore text smaller than this fraction of the image height |37| `--region x,y,w,h` | whole image | recognise only this pixel rectangle |38| `--detect-orientation` | off | find the rotation (0/90/180/270) that makes the text upright |39| `--max-pixels N` | 40000000 | images with more pixels are processed in overlapping bands |40| `--max-band-aspect F` | 4 | a band is at most F times longer than wide (0 = no limit) |41| `--band-overlap N` | 200 | overlap between two bands, in pixels |42| `--concurrency N` | 2 | images processed at once in serve mode (max 16) |4344In serve mode the command-line options are the defaults of every request.4546## Serve protocol4748One JSON object per line in, one per line out, flushed after every line. Responses may arrive in49a different order than the requests: match them by `id`.5051Request (only `path` is required):5253```json54{"id": "r1", "path": "/abs/capture.png", "languages": ["fr-CA", "en-US"], "level": "accurate",55 "alternatives": 3, "language_correction": true, "min_text_height": 0.0,56 "region": [0, 0, 800, 600], "detect_orientation": false, "auto_language": false,57 "max_pixels": 40000000, "max_band_aspect": 4, "band_overlap": 200}58```5960Response:6162```json63{"id": "r1", "path": "/abs/capture.png", "ok": true, "width": 451, "height": 264,64 "orientation": 1, "rotation": 0, "rotation_detected": false,65 "banded": false, "bands": 1, "level": "accurate", "languages": ["fr-FR", "en-US"],66 "lines": [{"text": "Total à payer : 2 847,35 $", "confidence": 1,67            "x": 31.9, "y": 190, "w": 190.2, "h": 18,68            "quad": [[31.9, 190], [222.1, 190], [222.1, 208], [31.9, 208]],69            "alternatives": [{"text": "Total à payer: 2 847,35 $", "confidence": 1}]}],70 "warnings": ["language_substituted:fr-CA->fr-FR"], "ms": 41,71 "engine": {"name": "apple-vision", "revision": 3, "os": "Version 27.3 (Build ...)", "worker": "1.0.0"},72 "error": null}73```7475Failure: `{"id", "path", "ok": false, "lines": [], "ms", "engine", "error": {"code", "message"}}`.76Error codes: `not_found`, `not_a_file`, `empty_file`, `unreadable_image`, `corrupt_image`,77`invalid_region`, `crop_failed`, `vision_failed`, `bad_request`, `bad_json`, `internal`.7879Other operations:8081```json82{"op": "ping", "id": 1}        -> {"id": 1, "ok": true, "op": "pong", "pid", "concurrency", "pending", "engine"}83{"op": "languages", "level": "fast"} -> {"ok": true, "op": "languages", "level", "languages": [...]}84{"op": "shutdown"}             -> waits for the running requests, answers {"ok": true, "op": "shutdown"}, exits 085```8687End of input (stdin closed) also ends the worker after the running requests.8889## Fields9091- `width`, `height`: size of the image as displayed, that is after the EXIF orientation is applied.92- `x`, `y`, `w`, `h`: bounding box in pixels of that displayed image, origin top-left (Vision's93  normalised bottom-left coordinates are converted). `quad`: the four corners of the text line,94  in reading order of the text (top-left, top-right, bottom-right, bottom-left), same space.95  With `--detect-orientation` the coordinates still refer to the original image, not to a rotated96  copy.97- `orientation`: EXIF orientation of the file (1 to 8). `rotation`: clockwise rotation in degrees98  that makes the text upright (always 0 without `--detect-orientation`); `rotation_method` and99  `rotation_scores` say how it was chosen.100- `confidence`: Vision's confidence of the top candidate. `alternatives`: the next candidates.101- Line order: rows from top to bottom (two lines share a row when their centres are within half a102  line height), then left to right. With a detected rotation the order follows the rotated text.103- `languages`: the languages actually given to Vision. A requested language that Vision does not104  support is replaced by a supported one with the same primary subtag (`fr-CA` -> `fr-FR`) or105  dropped; each case is listed in `warnings`.106- `banded`, `bands`: whether the image was cut in bands and how many.107108## Orientation detection109110Measured on Vision revision 3: the accurate recogniser reads text at 0, 90, 180 and 270 degrees111with nearly the same confidence, and the fast recogniser scores 0 and 180 nearly the same, so112"best mean confidence x character count" over four trials does not separate the rotations.113The worker therefore runs one accurate pass on a downscaled copy (at most 1600 px, a centred114window for very large pages) and lets the direction of each line's quadrilateral vote, weighted115by character count (`rotation_method: "quad"`, used when one direction gets 60 % of the votes).116Only if that is inconclusive are the four rotations tried with the fast recogniser and scored by117mean confidence x character count (`"trial"`). `"none"` means no text was found; rotation is 0.118119The fast level only reads upright text: use `--detect-orientation` with it for rotated pages.120The mirrored EXIF orientations (2, 4, 5, 7) are applied like the others; a bitmap that is mirrored121without saying so in EXIF is not detected.122123## Bands124125Vision scales its input to a fixed working size. Measured on revision 3: a 529 x 6320 page126recognised in one piece returns 0 lines; the same page in bands returns its 216 lines. The worker127never downscales: an image is cut into bands across the text's vertical axis when it has more than128`--max-pixels` pixels or when it is more than `--max-band-aspect` times longer than wide. Bands129overlap by `--band-overlap` pixels; a line is kept from the band that owns its centre, and a line130still present on both sides of a seam (IoU > 0.5 and text similarity >= 0.8) is kept once, with the131higher confidence. A very wide and short image (more than 8:1) is not cut, because a vertical cut132would slice through the lines; the response then carries the warning `extreme_aspect_ratio`.133134## Memory and concurrency135136At most `--concurrency` images are decoded at any time in serve mode; waiting requests are only137small dictionaries. Each image and each band runs in its own autorelease pool. An image is decoded138once in full (width x height x 4 bytes); bands share that buffer.139140## Examples141142```sh143spider-ocr --languages fr-CA,en-US capture.png | jq -r '.lines[].text'144spider-ocr --detect-orientation scan.jpg | jq '{rotation, n: (.lines | length)}'145printf '%s\n' '{"id":"a","path":"/tmp/a.png"}' '{"id":"b","path":"/tmp/b.png","level":"fast"}' \146  | spider-ocr --serve --concurrency 4147```148
Files main
Menu

Theme