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/Recognizer.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 worker — image loading, Vision text recognition, banding, orientation detection.42import CoreGraphics43import Foundation44import ImageIO45import Vision4647struct OcrError: Error {48 let code: String49 let message: String50}5152struct Params {53 var languages: [String] = ["fr-CA", "en-US"]54 var fast = false55 var alternatives = 356 var languageCorrection = true57 var autoLanguage = false58 var minTextHeight = 0.059 var region: CGRect?60 var detectOrientation = false61 var maxPixels = 40_000_00062 var bandOverlap = 20063 var maxBandAspect = 4.064}6566struct Line {67 var text: String68 var confidence: Double69 var alternatives: [(String, Double)]70 var box: CGRect // base pixels, top-left origin71 var quad: [CGPoint] // top-left, top-right, bottom-right, bottom-left of the text, base pixels72 var band = 073}7475struct PageResult {76 var width = 077 var height = 078 var exif = 179 var rotation = 080 var rotationScores: [(Int, Double)] = []81 var rotationMethod = "none"82 var banded = false83 var bands = 184 var lines: [Line] = []85 var warnings: [String] = []86 var languages: [String] = []87}8889enum Engine {90 static let revision: Int = VNRecognizeTextRequest().revision91 static let os: String = ProcessInfo.processInfo.operatingSystemVersionString9293 private static let lock = NSLock()94 private static var cache: [Bool: [String]] = [:]9596 static func supportedLanguages(fast: Bool) -> [String] {97 lock.lock()98 defer { lock.unlock() }99 if let hit = cache[fast] { return hit }100 let request = VNRecognizeTextRequest()101 request.recognitionLevel = fast ? .fast : .accurate102 let found = (try? request.supportedRecognitionLanguages()) ?? []103 cache[fast] = found104 return found105 }106107 /// Keeps the supported languages (canonical spelling); reports the others as warnings.108 static func resolveLanguages(_ wanted: [String], fast: Bool) -> (kept: [String], warnings: [String]) {109 let supported = supportedLanguages(fast: fast)110 if supported.isEmpty { return (wanted, ["supported_languages_unavailable"]) }111 var kept: [String] = []112 var warnings: [String] = []113 for lang in wanted {114 if let exact = supported.first(where: { $0.lowercased() == lang.lowercased() }) {115 if !kept.contains(exact) { kept.append(exact) }116 continue117 }118 let primary = lang.split(separator: "-").first.map { $0.lowercased() } ?? lang.lowercased()119 if let near = supported.first(where: { $0.lowercased().split(separator: "-").first.map(String.init) == primary }) {120 warnings.append("language_substituted:\(lang)->\(near)")121 if !kept.contains(near) { kept.append(near) }122 } else {123 warnings.append("unsupported_language:\(lang)")124 }125 }126 if kept.isEmpty && !wanted.isEmpty { warnings.append("no_supported_language:using_vision_default") }127 return (kept, warnings)128 }129}130131func loadImage(_ path: String) throws -> (image: CGImage, exif: Int) {132 var isDir: ObjCBool = false133 guard FileManager.default.fileExists(atPath: path, isDirectory: &isDir) else {134 throw OcrError(code: "not_found", message: "no such file: \(path)")135 }136 if isDir.boolValue { throw OcrError(code: "not_a_file", message: "path is a directory: \(path)") }137 let size = (try? FileManager.default.attributesOfItem(atPath: path)[.size] as? NSNumber)?.int64Value ?? -1138 if size == 0 { throw OcrError(code: "empty_file", message: "file is empty: \(path)") }139 let options = [kCGImageSourceShouldCache: false] as CFDictionary140 guard let source = CGImageSourceCreateWithURL(URL(fileURLWithPath: path) as CFURL, options),141 CGImageSourceGetCount(source) > 0 else {142 throw OcrError(code: "unreadable_image", message: "not a decodable image: \(path)")143 }144 guard CGImageSourceGetStatusAtIndex(source, 0) == .statusComplete,145 let lazy = CGImageSourceCreateImageAtIndex(source, 0, nil), lazy.width > 0, lazy.height > 0 else {146 throw OcrError(code: "corrupt_image", message: "image header is incomplete or corrupt: \(path)")147 }148 // ImageIO decodes lazily and hands back a blank image when the data is truncated. Decode once149 // here: a failed or partial decode is an error, and the bands then share one decoded buffer.150 guard let pixels = lazy.dataProvider?.data, CFDataGetLength(pixels) >= lazy.bytesPerRow * (lazy.height - 1),151 CGImageSourceGetStatusAtIndex(source, 0) == .statusComplete else {152 throw OcrError(code: "corrupt_image", message: "image data is truncated or corrupt: \(path)")153 }154 var image = lazy155 if let space = lazy.colorSpace, let provider = CGDataProvider(data: pixels),156 let decoded = CGImage(width: lazy.width, height: lazy.height, bitsPerComponent: lazy.bitsPerComponent,157 bitsPerPixel: lazy.bitsPerPixel, bytesPerRow: lazy.bytesPerRow, space: space,158 bitmapInfo: lazy.bitmapInfo, provider: provider, decode: nil, shouldInterpolate: false,159 intent: lazy.renderingIntent) {160 image = decoded161 }162 var exif = 1163 if let props = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any],164 let value = props[kCGImagePropertyOrientation] as? NSNumber, (1...8).contains(value.intValue) {165 exif = value.intValue166 }167 return (image, exif)168}169170struct Page {171 let raw: CGImage172 let exifMap: UnitMap173 let baseSize: CGSize174175 init(raw: CGImage, exif: Int) {176 self.raw = raw177 self.exifMap = UnitMap.exif(exif)178 let w = CGFloat(raw.width), h = CGFloat(raw.height)179 self.baseSize = exifMap.swapsAxes ? CGSize(width: h, height: w) : CGSize(width: w, height: h)180 }181182 /// The raw-space crop that corresponds to a base-space pixel rectangle.183 func rawCrop(_ tile: CGRect) throws -> CGImage {184 let full = CGRect(origin: .zero, size: baseSize)185 if tile == full { return raw }186 let inv = exifMap.inverse187 let pts = corners(tile).map { p -> CGPoint in188 let q = inv.apply(CGPoint(x: p.x / baseSize.width, y: p.y / baseSize.height))189 return CGPoint(x: q.x * CGFloat(raw.width), y: q.y * CGFloat(raw.height))190 }191 let rect = boundingRect(pts).integral192 guard let crop = raw.cropping(to: rect) else {193 throw OcrError(code: "crop_failed", message: "cannot crop \(rect) from a \(raw.width)x\(raw.height) image")194 }195 return crop196 }197198 func makeRequest(_ params: Params, languages: [String], minTextHeight: Double) -> VNRecognizeTextRequest {199 let request = VNRecognizeTextRequest()200 request.recognitionLevel = params.fast ? .fast : .accurate201 request.usesLanguageCorrection = params.languageCorrection202 if !languages.isEmpty { request.recognitionLanguages = languages }203 request.automaticallyDetectsLanguage = params.autoLanguage204 if minTextHeight > 0 { request.minimumTextHeight = Float(min(minTextHeight, 1)) }205 return request206 }207208 /// Recognises one base-space tile seen under `rotation`; lines come back in base pixels.209 func recognize(tile: CGRect, rotation: Int, request: VNRecognizeTextRequest, alternatives: Int) throws -> [Line] {210 let crop = try rawCrop(tile)211 let rot = UnitMap.rotation(rotation)212 let code = exifMap.then(rot).exifCode213 let orientation = CGImagePropertyOrientation(rawValue: UInt32(code)) ?? .up214 let handler = VNImageRequestHandler(cgImage: crop, orientation: orientation, options: [:])215 do {216 try handler.perform([request])217 } catch {218 throw OcrError(code: "vision_failed", message: "\(error.localizedDescription)")219 }220 let back = rot.inverse221 func toBase(_ p: CGPoint) -> CGPoint {222 // Vision: normalised, bottom-left origin, in the rotated tile.223 let q = back.apply(CGPoint(x: p.x, y: 1 - p.y))224 return CGPoint(x: tile.minX + min(max(q.x, 0), 1) * tile.width,225 y: tile.minY + min(max(q.y, 0), 1) * tile.height)226 }227 var lines: [Line] = []228 for obs in request.results ?? [] {229 let candidates = obs.topCandidates(max(1, alternatives + 1))230 guard let top = candidates.first, !top.string.isEmpty else { continue }231 let b = obs.boundingBox232 let box = boundingRect([CGPoint(x: b.minX, y: b.minY), CGPoint(x: b.maxX, y: b.minY),233 CGPoint(x: b.maxX, y: b.maxY), CGPoint(x: b.minX, y: b.maxY)].map(toBase))234 let quad = [obs.topLeft, obs.topRight, obs.bottomRight, obs.bottomLeft].map(toBase)235 lines.append(Line(text: top.string, confidence: Double(top.confidence),236 alternatives: candidates.dropFirst().map { ($0.string, Double($0.confidence)) },237 box: box, quad: quad))238 }239 return lines240 }241}242243/// A downscaled copy used only to pick the rotation: a centred window when the page is very large,244/// so that the text stays legible after scaling.245func orientationProbe(_ page: Page, region: CGRect, maxDim: CGFloat = 1600) throws -> (image: CGImage, scale: CGFloat) {246 var window = region247 let limit = maxDim * 1.5248 if window.width > limit { window = window.insetBy(dx: (window.width - limit) / 2, dy: 0) }249 if window.height > limit { window = window.insetBy(dx: 0, dy: (window.height - limit) / 2) }250 let crop = try page.rawCrop(window.integral)251 let scale = min(1, maxDim / CGFloat(max(crop.width, crop.height)))252 if scale >= 1 { return (crop, 1) }253 let w = max(1, Int(CGFloat(crop.width) * scale)), h = max(1, Int(CGFloat(crop.height) * scale))254 guard let space = CGColorSpace(name: CGColorSpace.sRGB),255 let ctx = CGContext(data: nil, width: w, height: h, bitsPerComponent: 8, bytesPerRow: 0, space: space,256 bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue) else {257 return (crop, 1)258 }259 ctx.interpolationQuality = .high260 ctx.draw(crop, in: CGRect(x: 0, y: 0, width: w, height: h))261 guard let scaled = ctx.makeImage() else { return (crop, 1) }262 return (scaled, scale)263}264265/// Picks the clockwise rotation (0/90/180/270) that makes the text upright, on a downscaled probe.266///267/// 1. "quad": one accurate pass. Vision's accurate recogniser (revision 3) reads text at any right268/// angle and its quadrilaterals give the direction of each line; the directions vote, weighted269/// by character count. Used when one direction gets at least 60 % of the votes.270/// 2. "trial": otherwise the four rotations are tried with the fast recogniser and the best271/// mean confidence x character count wins (upright wins ties).272/// Measured on revision 3: trial scores alone do not separate the rotations (the accurate level273/// scores all four almost equally, the fast level scores 0 and 180 almost equally), which is why274/// the quadrilateral vote comes first.275func detectRotation(_ page: Page, region: CGRect, params: Params, languages: [String]) throws276 -> (rotation: Int, scores: [(Int, Double)], method: String) {277 var scores: [(Int, Double)] = []278 var method = "none"279 var chosen = 0280 try autoreleasepool {281 let probe = try orientationProbe(page, region: region)282 func run(_ rotation: Int, fast: Bool) throws -> [VNRecognizedTextObservation] {283 var trial = params284 trial.languageCorrection = false285 trial.fast = fast286 let wanted = Engine.resolveLanguages(params.languages, fast: fast).kept287 let request = page.makeRequest(trial, languages: wanted, minTextHeight: 0)288 let code = page.exifMap.then(UnitMap.rotation(rotation)).exifCode289 let handler = VNImageRequestHandler(cgImage: probe.image,290 orientation: CGImagePropertyOrientation(rawValue: UInt32(code)) ?? .up,291 options: [:])292 do {293 try handler.perform([request])294 } catch {295 throw OcrError(code: "vision_failed", message: "\(error.localizedDescription)")296 }297 return request.results ?? []298 }299 var votes: [Int: Double] = [0: 0, 90: 0, 180: 0, 270: 0]300 try autoreleasepool {301 // Displayed size of the probe: Vision's normalised coordinates refer to it.302 let pw = Double(page.exifMap.swapsAxes ? probe.image.height : probe.image.width)303 let ph = Double(page.exifMap.swapsAxes ? probe.image.width : probe.image.height)304 for obs in try run(0, fast: false) {305 guard let top = obs.topCandidates(1).first else { continue }306 let dx = Double(obs.topRight.x - obs.topLeft.x) * pw307 let dy = -Double(obs.topRight.y - obs.topLeft.y) * ph // Vision's y axis points up308 let rotation: Int309 if abs(dx) >= abs(dy) { rotation = dx >= 0 ? 0 : 180 } else { rotation = dy < 0 ? 90 : 270 }310 votes[rotation, default: 0] += Double(top.string.filter { !$0.isWhitespace }.count)311 }312 }313 let total = votes.values.reduce(0, +)314 scores = [0, 90, 180, 270].map { ($0, votes[$0] ?? 0) }315 if total > 0, let best = scores.max(by: { $0.1 < $1.1 }), best.1 >= total * 0.6 {316 chosen = best.0317 method = "quad"318 return319 }320 scores = []321 for rotation in [0, 90, 180, 270] {322 try autoreleasepool {323 var chars = 0324 var confSum = 0.0325 var count = 0326 for obs in try run(rotation, fast: true) {327 guard let top = obs.topCandidates(1).first else { continue }328 chars += top.string.filter { !$0.isWhitespace }.count329 confSum += Double(top.confidence)330 count += 1331 }332 scores.append((rotation, count > 0 ? confSum / Double(count) * Double(chars) : 0))333 }334 }335 var best = scores[0]336 for candidate in scores.dropFirst() where candidate.1 > best.1 { best = candidate }337 if best.1 > 0 {338 chosen = best.0339 method = "trial"340 }341 }342 return (chosen, scores, method)343}344345struct Band {346 let rect: CGRect347 let lo: CGFloat // owned interval along the banding axis348 let hi: CGFloat349}350351/// Splits `region` into overlapping bands along `vertical` (y) or x. A band holds at most352/// `maxPixels` pixels and is at most `maxAspect` times longer than it is wide: Vision scales its353/// input to a fixed working size and returns nothing at all for very elongated images (measured on354/// revision 3: a 529 x 6320 page yields 0 lines in one piece, all 216 lines in bands).355func makeBands(region: CGRect, maxPixels: Int, maxAspect: Double, overlap: Int, vertical: Bool) -> [Band] {356 let total = vertical ? region.height : region.width357 let cross = vertical ? region.width : region.height358 let origin = vertical ? region.minY : region.minX359 var length = (CGFloat(maxPixels) / max(cross, 1)).rounded(.down)360 if maxAspect > 0 { length = min(length, (cross * CGFloat(maxAspect)).rounded(.down)) }361 length = max(64, length)362 if length >= total { return [Band(rect: region, lo: -.infinity, hi: .infinity)] }363 let lap = min(CGFloat(max(overlap, 0)), (length / 3).rounded(.down))364 length = max(length, lap + 1)365 var spans: [(CGFloat, CGFloat)] = []366 var start: CGFloat = 0367 while true {368 let end = min(start + length, total)369 spans.append((start, end))370 if end >= total { break }371 start = end - lap372 }373 var bands: [Band] = []374 for (k, span) in spans.enumerated() {375 let lo = k == 0 ? -CGFloat.infinity : origin + (span.0 + spans[k - 1].1) / 2376 let hi = k == spans.count - 1 ? CGFloat.infinity : origin + (spans[k + 1].0 + span.1) / 2377 let rect = vertical378 ? CGRect(x: region.minX, y: origin + span.0, width: region.width, height: span.1 - span.0)379 : CGRect(x: origin + span.0, y: region.minY, width: span.1 - span.0, height: region.height)380 bands.append(Band(rect: rect, lo: lo, hi: hi))381 }382 return bands383}384385/// Keeps each line in the band that owns its centre, then removes the copies that survive on both386/// sides of a seam (same place, same text): the more confident reading wins.387func mergeBands(_ perBand: [[Line]], bands: [Band], vertical: Bool) -> [Line] {388 let margin: CGFloat = 4389 var kept: [Line] = []390 for (k, lines) in perBand.enumerated() {391 for var line in lines {392 let centre = vertical ? line.box.midY : line.box.midX393 if centre >= bands[k].lo - margin && centre < bands[k].hi + margin {394 line.band = k395 kept.append(line)396 }397 }398 }399 var dropped = Set<Int>()400 for i in kept.indices where !dropped.contains(i) {401 for j in kept.indices where j > i && !dropped.contains(j) && abs(kept[j].band - kept[i].band) == 1 {402 if iou(kept[i].box, kept[j].box) > 0.5 && textSimilarity(kept[i].text, kept[j].text) >= 0.8 {403 if kept[j].confidence > kept[i].confidence {404 dropped.insert(i)405 break406 }407 dropped.insert(j)408 }409 }410 }411 return kept.indices.filter { !dropped.contains($0) }.map { kept[$0] }412}413414/// Reading order: rows from top to bottom (lines whose centres are within half a line height415/// share a row), then left to right inside a row. For text rotated by 90/270 the roles of the416/// axes are swapped so that the order still follows the text.417func readingOrder(_ lines: [Line], rotation: Int) -> [Line] {418 func row(_ l: Line) -> CGFloat {419 switch rotation {420 case 90: return l.box.midX // page turned counter-clockwise: its top is on the left421 case 180: return -l.box.midY422 case 270: return -l.box.midX // page turned clockwise: its top is on the right423 default: return l.box.midY424 }425 }426 func col(_ l: Line) -> CGFloat {427 switch rotation {428 case 90: return -l.box.maxY // text runs from bottom to top429 case 180: return -l.box.maxX430 case 270: return l.box.minY // text runs from top to bottom431 default: return l.box.minX432 }433 }434 func thickness(_ l: Line) -> CGFloat { rotation == 90 || rotation == 270 ? l.box.width : l.box.height }435 let sorted = lines.sorted { a, b in436 if row(a) != row(b) { return row(a) < row(b) }437 if col(a) != col(b) { return col(a) < col(b) }438 return a.text < b.text439 }440 var rows: [[Line]] = []441 var anchor: CGFloat = 0442 var tolerance: CGFloat = 0443 for line in sorted {444 if !rows.isEmpty && row(line) - anchor <= tolerance {445 rows[rows.count - 1].append(line)446 } else {447 rows.append([line])448 anchor = row(line)449 tolerance = thickness(line) * 0.5450 }451 }452 return rows.flatMap { r in453 r.sorted { a, b in454 if col(a) != col(b) { return col(a) < col(b) }455 if row(a) != row(b) { return row(a) < row(b) }456 return a.text < b.text457 }458 }459}460461func recognizePage(path: String, params: Params) throws -> PageResult {462 var result = PageResult()463 try autoreleasepool {464 let loaded = try loadImage(path)465 let page = Page(raw: loaded.image, exif: loaded.exif)466 result.exif = loaded.exif467 result.width = Int(page.baseSize.width)468 result.height = Int(page.baseSize.height)469470 let full = CGRect(origin: .zero, size: page.baseSize)471 var region = full472 if let wanted = params.region {473 region = wanted.integral.intersection(full)474 if region.isNull || region.width < 1 || region.height < 1 {475 throw OcrError(code: "invalid_region", message: "region \(wanted) is outside the \(result.width)x\(result.height) image")476 }477 }478479 let resolved = Engine.resolveLanguages(params.languages, fast: params.fast)480 result.warnings += resolved.warnings481 result.languages = resolved.kept482483 if params.detectOrientation {484 let detected = try detectRotation(page, region: region, params: params, languages: resolved.kept)485 result.rotation = detected.rotation486 result.rotationScores = detected.scores487 result.rotationMethod = detected.method488 }489 let sideways = result.rotation == 90 || result.rotation == 270490 // Bands are cut across the text's vertical axis, so a seam never slices along a line.491 let bands = makeBands(region: region, maxPixels: max(params.maxPixels, 4096),492 maxAspect: params.maxBandAspect, overlap: params.bandOverlap, vertical: !sideways)493 let across = sideways ? region.height : region.width494 let along = sideways ? region.width : region.height495 if along > 0 && Double(across / along) > 8 { result.warnings.append("extreme_aspect_ratio:text_may_be_missed") }496 result.bands = bands.count497 result.banded = bands.count > 1498499 var perBand: [[Line]] = []500 for band in bands {501 try autoreleasepool {502 // minimumTextHeight is relative to the height Vision sees: rescale it per band.503 let whole = sideways ? page.baseSize.width : page.baseSize.height504 let seen = sideways ? band.rect.width : band.rect.height505 let request = page.makeRequest(params, languages: resolved.kept,506 minTextHeight: params.minTextHeight * Double(whole / max(seen, 1)))507 perBand.append(try page.recognize(tile: band.rect, rotation: result.rotation, request: request,508 alternatives: params.alternatives))509 }510 }511 let merged = bands.count > 1 ? mergeBands(perBand, bands: bands, vertical: !sideways) : perBand[0]512 result.lines = readingOrder(merged, rotation: result.rotation)513 }514 return result515}516