SPB Git

Repository Public

CardOCR.swift 5.0 KB 115 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVault/Engines/SmartScan/CardOCR.swift8// Module           : SPVault9// Repository       : https://git.spboucher.ai/sp-id-card-vault10// Project Website  : Not specified11// Created          : 2026-12-0212// Last Modified    : 2026-12-0213//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          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import CoreGraphics42import Foundation43import Vision4445/// One whitespace-separated word of a recognised line, with its own box.46struct RecognizedToken: Equatable, Sendable {47    var text: String48    /// Normalised to the image, origin top-left.49    var box: CGRect50}5152/// One line of text read on a card. Boxes are normalised, origin top-left.53struct RecognizedLine: Equatable, Sendable {54    var text: String55    /// Vision's confidence for the reading, 0…1.56    var confidence: Float57    var box: CGRect58    var tokens: [RecognizedToken]5960    init(text: String, confidence: Float, box: CGRect, tokens: [RecognizedToken]? = nil) {61        self.text = text62        self.confidence = confidence63        self.box = box64        self.tokens = tokens ?? RecognizedLine.evenTokens(text: text, box: box)65    }6667    /// Fallback token boxes: the line box split in proportion to character counts.68    static func evenTokens(text: String, box: CGRect) -> [RecognizedToken] {69        let total = max(text.count, 1)70        var tokens: [RecognizedToken] = []71        var index = 072        for word in text.split(separator: " ", omittingEmptySubsequences: false) {73            if !word.isEmpty {74                let x = box.minX + box.width * CGFloat(index) / CGFloat(total)75                tokens.append(RecognizedToken(text: String(word), box: CGRect(x: x, y: box.minY, width: box.width * CGFloat(word.count) / CGFloat(total), height: box.height)))76            }77            index += word.count + 178        }79        return tokens80    }81}8283/// On-device text recognition (Vision, accurate level). Language correction is84/// off on purpose: a card number or a name must be reported as read, never85/// "repaired" into something plausible.86enum CardOCR {87    static func recognize(_ image: CGImage) -> [RecognizedLine] {88        let request = VNRecognizeTextRequest()89        request.recognitionLevel = .accurate90        request.usesLanguageCorrection = false91        request.recognitionLanguages = ["en-US", "fr-FR"]92        request.minimumTextHeight = 0.01293        let handler = VNImageRequestHandler(cgImage: image, options: [:])94        guard (try? handler.perform([request])) != nil else { return [] }95        func flip(_ r: CGRect) -> CGRect { CGRect(x: r.minX, y: 1 - r.maxY, width: r.width, height: r.height) }96        return (request.results ?? []).compactMap { observation -> RecognizedLine? in97            guard let candidate = observation.topCandidates(1).first else { return nil }98            let text = candidate.string99            var tokens: [RecognizedToken] = []100            var cursor = text.startIndex101            while cursor < text.endIndex {102                guard let start = text[cursor...].firstIndex(where: { !$0.isWhitespace }) else { break }103                let end = text[start...].firstIndex(where: \.isWhitespace) ?? text.endIndex104                if let box = try? candidate.boundingBox(for: start..<end) {105                    tokens.append(RecognizedToken(text: String(text[start..<end]), box: flip(box.boundingBox)))106                }107                cursor = end108            }109            let lineBox = flip(observation.boundingBox)110            return RecognizedLine(text: text, confidence: candidate.confidence, box: lineBox, tokens: tokens.isEmpty ? nil : tokens)111        }112        .sorted { abs($0.box.midY - $1.box.midY) > 0.02 ? $0.box.midY < $1.box.midY : $0.box.minX < $1.box.minX }113    }114}115
Files main
Menu

Theme