Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SPIDER — Universal Web Intelligence Engine7// File : services/ocr-worker/Sources/spider-ocr/main.swift8// Module : Services9// Repository : https://git.spboucher.ai/spider10// Project Website : Not specified11// Created : 2026-12-0412// Last Modified : 2026-12-0413//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : ISC33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041// spider-ocr — native macOS OCR worker for SPIDER (Apple Vision).42//43// spider-ocr [options] file... one JSON line per file on stdout44// spider-ocr --serve [options] JSON-lines requests on stdin, one JSON line per response45// spider-ocr --list-languages supported recognition languages as JSON46//47// Coordinates are pixels, origin top-left, in the image as displayed (EXIF orientation applied).48// Exit codes: 0 ok, 1 every file failed, 2 usage.49import Foundation5051let workerVersion = "1.0.0"5253let usage = """54usage: spider-ocr [options] file...55 spider-ocr --serve [options]56 spider-ocr --list-languages [--level accurate|fast]5758options:59 --languages a,b recognition languages, in priority order (default fr-CA,en-US)60 --level accurate|fast recognition level (default accurate); --fast is a shortcut61 --alternatives N other candidate readings per line (default 3, max 9)62 --no-language-correction disable Vision's language model correction63 --auto-language let Vision detect the language automatically64 --min-text-height F ignore text smaller than this fraction of the image height (default 0)65 --region x,y,w,h recognise only this pixel rectangle66 --detect-orientation find the rotation (0/90/180/270) that makes the text upright67 --max-pixels N larger images are processed in overlapping bands (default 40000000)68 --max-band-aspect F a band is at most F times longer than wide (default 4, 0 = no limit)69 --band-overlap N band overlap in pixels (default 200)70 --concurrency N images processed at once in --serve mode (default 2)71 --version, --help72"""7374func fail(_ message: String) -> Never {75 FileHandle.standardError.write(("spider-ocr: " + message + "\n" + usage + "\n").data(using: .utf8) ?? Data())76 exit(2)77}7879func engineJSON() -> J {80 .o([("name", .s("apple-vision")), ("revision", .i(Engine.revision)), ("os", .s(Engine.os)),81 ("worker", .s(workerVersion))])82}8384func parseRegion(_ values: [Double]) -> CGRect? {85 guard values.count == 4, values[2] > 0, values[3] > 0, values.allSatisfy({ $0.isFinite }) else { return nil }86 return CGRect(x: values[0], y: values[1], width: values[2], height: values[3])87}8889// ---------------------------------------------------------------------------- command line90var defaults = Params()91var files: [String] = []92var serve = false93var listLanguages = false94var concurrency = 29596var args = Array(CommandLine.arguments.dropFirst())97var index = 098func value(_ name: String) -> String {99 index += 1100 guard index < args.count else { fail("missing value for \(name)") }101 return args[index]102}103while index < args.count {104 let arg = args[index]105 switch arg {106 case "--serve": serve = true107 case "--list-languages": listLanguages = true108 case "--languages", "--langs":109 defaults.languages = value(arg).split(separator: ",").map { $0.trimmingCharacters(in: .whitespaces) }.filter { !$0.isEmpty }110 case "--level":111 let level = value(arg)112 guard level == "accurate" || level == "fast" else { fail("--level must be accurate or fast") }113 defaults.fast = level == "fast"114 case "--fast": defaults.fast = true115 case "--alternatives":116 guard let n = Int(value(arg)), n >= 0 else { fail("--alternatives must be a non-negative integer") }117 defaults.alternatives = min(n, 9)118 case "--no-language-correction": defaults.languageCorrection = false119 case "--auto-language": defaults.autoLanguage = true120 case "--min-text-height":121 guard let f = Double(value(arg)), f >= 0, f <= 1 else { fail("--min-text-height must be in [0, 1]") }122 defaults.minTextHeight = f123 case "--region":124 guard let rect = parseRegion(value(arg).split(separator: ",").compactMap { Double($0) }) else {125 fail("--region must be x,y,w,h with positive w and h")126 }127 defaults.region = rect128 case "--detect-orientation": defaults.detectOrientation = true129 case "--max-pixels":130 guard let n = Int(value(arg)), n >= 4096 else { fail("--max-pixels must be an integer >= 4096") }131 defaults.maxPixels = n132 case "--max-band-aspect":133 guard let f = Double(value(arg)), f >= 0 else { fail("--max-band-aspect must be >= 0") }134 defaults.maxBandAspect = f135 case "--band-overlap":136 guard let n = Int(value(arg)), n >= 0 else { fail("--band-overlap must be a non-negative integer") }137 defaults.bandOverlap = n138 case "--concurrency":139 guard let n = Int(value(arg)), n >= 1 else { fail("--concurrency must be a positive integer") }140 concurrency = min(n, 16)141 case "--version":142 print("spider-ocr \(workerVersion)")143 exit(0)144 case "--help", "-h":145 print(usage)146 exit(0)147 case "--":148 files += args[(index + 1)...]149 index = args.count150 default:151 if arg.hasPrefix("--") { fail("unknown option \(arg)") }152 files.append(arg)153 }154 index += 1155}156157signal(SIGPIPE, SIG_IGN)158159// ---------------------------------------------------------------------------- responses160func response(id: J, path: String, params: Params, started: Date) -> (J, Bool) {161 var head: [(String, J)] = [("id", id), ("path", .s(path))]162 func ms() -> J { .i(Int((Date().timeIntervalSince(started) * 1000).rounded())) }163 do {164 let page = try recognizePage(path: path, params: params)165 let lines: [J] = page.lines.map { line in166 .o([("text", .s(line.text)),167 ("confidence", .n((line.confidence * 10000).rounded() / 10000)),168 ("x", px(line.box.minX)), ("y", px(line.box.minY)),169 ("w", px(line.box.width)), ("h", px(line.box.height)),170 ("quad", .a(line.quad.map { .a([px($0.x), px($0.y)]) })),171 ("alternatives", .a(line.alternatives.map {172 .o([("text", .s($0.0)), ("confidence", .n(($0.1 * 10000).rounded() / 10000))])173 }))])174 }175 head += [("ok", .b(true)), ("width", .i(page.width)), ("height", .i(page.height)),176 ("orientation", .i(page.exif)), ("rotation", .i(page.rotation)),177 ("rotation_detected", .b(params.detectOrientation))]178 if params.detectOrientation {179 head.append(("rotation_method", .s(page.rotationMethod)))180 head.append(("rotation_scores", .o(page.rotationScores.map { ("\($0.0)", .n(($0.1 * 100).rounded() / 100)) })))181 }182 head += [("banded", .b(page.banded)), ("bands", .i(page.bands)),183 ("level", .s(params.fast ? "fast" : "accurate")),184 ("languages", .a(page.languages.map { .s($0) })),185 ("lines", .a(lines)), ("warnings", .a(page.warnings.map { .s($0) })),186 ("ms", ms()), ("engine", engineJSON()), ("error", .null)]187 return (.o(head), true)188 } catch let error as OcrError {189 head += [("ok", .b(false)), ("lines", .a([])), ("ms", ms()), ("engine", engineJSON()),190 ("error", .o([("code", .s(error.code)), ("message", .s(error.message))]))]191 return (.o(head), false)192 } catch {193 head += [("ok", .b(false)), ("lines", .a([])), ("ms", ms()), ("engine", engineJSON()),194 ("error", .o([("code", .s("internal")), ("message", .s("\(error)"))]))]195 return (.o(head), false)196 }197}198199func errorLine(id: J, code: String, message: String) -> J {200 .o([("id", id), ("ok", .b(false)), ("error", .o([("code", .s(code)), ("message", .s(message))]))])201}202203// ---------------------------------------------------------------------------- modes204if listLanguages {205 emit(.o([("level", .s(defaults.fast ? "fast" : "accurate")),206 ("languages", .a(Engine.supportedLanguages(fast: defaults.fast).map { .s($0) })),207 ("engine", engineJSON())]))208 exit(0)209}210211if !serve {212 if files.isEmpty { fail("no input file") }213 var failures = 0214 for path in files {215 let (line, ok) = response(id: .s(path), path: path, params: defaults, started: Date())216 emit(line)217 if !ok { failures += 1 }218 }219 exit(failures == files.count ? 1 : 0)220}221222if !files.isEmpty { fail("--serve takes its files from stdin requests, not from the command line") }223224/// Per-request parameters: the command-line values are the defaults.225func requestParams(_ req: [String: Any]) throws -> Params {226 var p = defaults227 func bad(_ message: String) -> OcrError { OcrError(code: "bad_request", message: message) }228 if let v = req["languages"], !(v is NSNull) {229 guard let langs = v as? [String] else { throw bad("languages must be an array of strings") }230 p.languages = langs231 }232 if let v = req["level"], !(v is NSNull) {233 guard let level = v as? String, level == "accurate" || level == "fast" else { throw bad("level must be accurate or fast") }234 p.fast = level == "fast"235 }236 if let v = req["alternatives"], !(v is NSNull) {237 guard let n = (v as? NSNumber)?.intValue, n >= 0 else { throw bad("alternatives must be a non-negative integer") }238 p.alternatives = min(n, 9)239 }240 if let v = req["language_correction"] as? Bool { p.languageCorrection = v }241 if let v = req["auto_language"] as? Bool { p.autoLanguage = v }242 if let v = req["detect_orientation"] as? Bool { p.detectOrientation = v }243 if let v = req["min_text_height"], !(v is NSNull) {244 guard let f = (v as? NSNumber)?.doubleValue, f >= 0, f <= 1 else { throw bad("min_text_height must be in [0, 1]") }245 p.minTextHeight = f246 }247 if let v = req["max_pixels"], !(v is NSNull) {248 guard let n = (v as? NSNumber)?.intValue, n >= 4096 else { throw bad("max_pixels must be an integer >= 4096") }249 p.maxPixels = n250 }251 if let v = req["max_band_aspect"], !(v is NSNull) {252 guard let f = (v as? NSNumber)?.doubleValue, f >= 0 else { throw bad("max_band_aspect must be >= 0") }253 p.maxBandAspect = f254 }255 if let v = req["band_overlap"], !(v is NSNull) {256 guard let n = (v as? NSNumber)?.intValue, n >= 0 else { throw bad("band_overlap must be a non-negative integer") }257 p.bandOverlap = n258 }259 if let v = req["region"], !(v is NSNull) {260 guard let nums = v as? [NSNumber], let rect = parseRegion(nums.map { $0.doubleValue }) else {261 throw bad("region must be [x, y, w, h] with positive w and h")262 }263 p.region = rect264 }265 return p266}267268func jsonID(_ raw: Any?) -> J {269 if let s = raw as? String { return .s(s) }270 if let n = raw as? NSNumber { return .n(n.doubleValue) }271 return .null272}273274// At most `concurrency` requests run (and therefore hold a decoded image) at any time; the others275// wait in the queue as plain request dictionaries.276let queue = OperationQueue()277queue.maxConcurrentOperationCount = concurrency278queue.qualityOfService = .userInitiated279280while let raw = readLine(strippingNewline: true) {281 let trimmed = raw.trimmingCharacters(in: .whitespacesAndNewlines)282 if trimmed.isEmpty { continue }283 guard let data = trimmed.data(using: .utf8),284 let req = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any] else {285 emit(errorLine(id: .null, code: "bad_json", message: "request is not a JSON object"))286 continue287 }288 let id = jsonID(req["id"])289 let op = (req["op"] as? String) ?? "recognize"290 switch op {291 case "ping":292 emit(.o([("id", id), ("ok", .b(true)), ("op", .s("pong")), ("pid", .i(Int(getpid()))),293 ("concurrency", .i(concurrency)), ("pending", .i(queue.operationCount)), ("engine", engineJSON())]))294 case "shutdown":295 queue.waitUntilAllOperationsAreFinished()296 emit(.o([("id", id), ("ok", .b(true)), ("op", .s("shutdown"))]))297 exit(0)298 case "languages":299 let fast = (req["level"] as? String) == "fast"300 emit(.o([("id", id), ("ok", .b(true)), ("op", .s("languages")), ("level", .s(fast ? "fast" : "accurate")),301 ("languages", .a(Engine.supportedLanguages(fast: fast).map { .s($0) }))]))302 case "recognize":303 guard let path = req["path"] as? String, !path.isEmpty else {304 emit(errorLine(id: id, code: "bad_request", message: "path is required"))305 continue306 }307 let params: Params308 do {309 params = try requestParams(req)310 } catch let error as OcrError {311 emit(errorLine(id: id, code: error.code, message: error.message))312 continue313 } catch {314 emit(errorLine(id: id, code: "bad_request", message: "\(error)"))315 continue316 }317 queue.addOperation {318 emit(response(id: id, path: path, params: params, started: Date()).0)319 }320 default:321 emit(errorLine(id: id, code: "bad_request", message: "unknown op \(op)"))322 }323}324queue.waitUntilAllOperationsAreFinished()325exit(0)326