Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SP ID & Card Vault7// File : SPVault/Engines/SmartScan/CardTextParser.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 Foundation4344/// Turns recognised text into proposals for the card editor. Pure and45/// deterministic.46///47/// Rules it never breaks:48/// - only text that was actually read is proposed — nothing is completed,49/// corrected or guessed; a bank number is proposed only if it passes the50/// Luhn check as read;51/// - observations below `minimumConfidence` are ignored;52/// - a card security code (CVV/CVC/CID) is never placed in any field.53enum CardTextParser {54 static let minimumConfidence: Float = 0.55556 static func suggestion(front: [RecognizedLine], back: [RecognizedLine] = [], kind: CardKind, now: Date = Date()) -> CardSuggestion {57 let frontLines = usable(front), backLines = usable(back)58 var suggestion = CardSuggestion()59 if kind.isBanking {60 suggestion.number = bankNumber(in: frontLines) ?? bankNumber(in: backLines)61 suggestion.expiry = expiry(in: frontLines, banking: true, now: now) ?? expiry(in: backLines, banking: true, now: now)62 suggestion.holderName = bankHolder(in: frontLines) ?? bankHolder(in: backLines)63 suggestion.issuer = issuer(in: frontLines)64 if let issuer = suggestion.issuer {65 let network = suggestion.number.flatMap(PaymentCard.network(for:))66 suggestion.name = network.map { issuer.localizedCaseInsensitiveContains($0) ? issuer : "\(issuer) \($0)" } ?? issuer67 }68 } else {69 suggestion.number = documentNumber(in: frontLines, kind: kind)70 suggestion.expiry = expiry(in: frontLines, banking: false, now: now) ?? expiry(in: backLines, banking: false, now: now)71 suggestion.holderName = documentHolder(in: frontLines)72 suggestion.issuer = issuer(in: frontLines)73 if kind.categoryID != CardCategory.identity.id { suggestion.name = suggestion.issuer }74 }75 return suggestion76 }7778 static func usable(_ lines: [RecognizedLine]) -> [RecognizedLine] {79 lines.filter { $0.confidence >= minimumConfidence && !$0.text.trimmingCharacters(in: .whitespaces).isEmpty }80 }8182 static func folded(_ text: String) -> String {83 text.folding(options: [.diacriticInsensitive, .caseInsensitive], locale: nil).lowercased()84 }8586 static func words(_ text: String) -> [String] {87 folded(text).split { !($0.isLetter || $0.isNumber) }.map(String.init)88 }8990 private static func matches(_ pattern: String, in text: String, options: NSRegularExpression.Options = [.caseInsensitive]) -> [[String]] {91 guard let regex = try? NSRegularExpression(pattern: pattern, options: options) else { return [] }92 let ns = text as NSString93 return regex.matches(in: text, range: NSRange(location: 0, length: ns.length)).map { match in94 (0..<match.numberOfRanges).map { match.range(at: $0).location == NSNotFound ? "" : ns.substring(with: match.range(at: $0)) }95 }96 }9798 // MARK: Bank card number99100 /// A run of 12–19 digits (spaces or dashes allowed between groups) that101 /// passes the Luhn check exactly as read.102 static func bankNumber(in lines: [RecognizedLine]) -> String? {103 // Embossed numbers are often read as separate groups, so each row of the104 // card is taken as one line (what was read, in reading order, unchanged).105 // Working on whole rows also means a fragment of a longer number can106 // never be proposed as if it were the number.107 var best: String?108 for row in rows(of: lines) {109 for match in matches(#"(?<!\d)(?:\d[ \-]?){11,18}\d(?!\d)"#, in: row.text) {110 let digits = match[0].filter(\.isNumber)111 if PaymentCard.isValidNumber(digits), digits.count > (best?.count ?? 0) { best = digits }112 }113 }114 return best115 }116117 /// The card read row by row: lines on the same baseline with a similar height118 /// are joined left to right; a line alone on its baseline is its own row.119 static func rows(of lines: [RecognizedLine]) -> [RecognizedLine] {120 var remaining = lines.sorted { $0.box.minX < $1.box.minX }121 var rows: [RecognizedLine] = []122 while !remaining.isEmpty {123 let seed = remaining.removeFirst()124 var members = [seed]125 remaining.removeAll { other in126 let sameRow = abs(other.box.midY - seed.box.midY) < min(other.box.height, seed.box.height) * 0.5127 let similarHeight = max(other.box.height, seed.box.height) < min(other.box.height, seed.box.height) * 1.6128 if sameRow && similarHeight { members.append(other) }129 return sameRow && similarHeight130 }131 guard members.count > 1 else { rows.append(seed); continue }132 let box = members.dropFirst().reduce(seed.box) { $0.union($1.box) }133 rows.append(RecognizedLine(text: members.map(\.text).joined(separator: " "), confidence: members.map(\.confidence).min() ?? 0,134 box: box, tokens: members.flatMap(\.tokens)))135 }136 return rows137 }138139 // MARK: Dates140141 private static let months: [String: Int] = [142 "jan": 1, "janv": 1, "january": 1, "janvier": 1, "feb": 2, "fev": 2, "fevr": 2, "february": 2, "fevrier": 2,143 "mar": 3, "mars": 3, "march": 3, "apr": 4, "avr": 4, "april": 4, "avril": 4, "may": 5, "mai": 5,144 "jun": 6, "june": 6, "juin": 6, "jul": 7, "juil": 7, "july": 7, "juillet": 7, "aug": 8, "aou": 8, "aout": 8, "august": 8,145 "sep": 9, "sept": 9, "september": 9, "septembre": 9, "oct": 10, "october": 10, "octobre": 10,146 "nov": 11, "november": 11, "novembre": 11, "dec": 12, "december": 12, "decembre": 12,147 ]148149 private static let calendar: Calendar = {150 var calendar = Calendar(identifier: .gregorian)151 calendar.timeZone = TimeZone(identifier: "UTC")!152 return calendar153 }()154155 private static func date(year: Int, month: Int, day: Int?) -> Date? {156 guard (1...12).contains(month), (1900...2199).contains(year) else { return nil }157 var components = DateComponents(year: year, month: month, day: 1, hour: 12)158 guard let first = calendar.date(from: components), let days = calendar.range(of: .day, in: .month, for: first) else { return nil }159 if let day {160 guard days.contains(day) else { return nil } // "02-31" is a misreading, not a date161 components.day = day162 } else {163 // Month-only expiry: valid through the last day of that month.164 components.day = days.count165 }166 return calendar.date(from: components)167 }168169 struct FoundDate: Equatable {170 var date: Date171 var isMonthYear: Bool172 }173174 /// Every date written on one line, in the formats cards use.175 static func dates(in text: String, now: Date = Date()) -> [FoundDate] {176 var found: [FoundDate] = []177 let plain = folded(text)178 for m in matches(#"(?<!\d)((?:19|20)\d{2})[-/.](0[1-9]|1[0-2])[-/.](0[1-9]|[12]\d|3[01])(?!\d)"#, in: plain) {179 if let d = date(year: Int(m[1])!, month: Int(m[2])!, day: Int(m[3])!) { found.append(FoundDate(date: d, isMonthYear: false)) }180 }181 for m in matches(#"(?<![\d\-/.])(20\d{2})[-/](0[1-9]|1[0-2])(?![\d\-/.])"#, in: plain) {182 if let d = date(year: Int(m[1])!, month: Int(m[2])!, day: nil) { found.append(FoundDate(date: d, isMonthYear: true)) }183 }184 for m in matches(#"(?<![\d/\-.])(0[1-9]|1[0-2])\s?/\s?(\d{4}|\d{2})(?![\d/\-.])"#, in: plain) {185 let year = m[2].count == 2 ? 2000 + Int(m[2])! : Int(m[2])!186 if let d = date(year: year, month: Int(m[1])!, day: nil) { found.append(FoundDate(date: d, isMonthYear: true)) }187 }188 for m in matches(#"(?<!\d)(\d{1,2})\s+([a-z]{3,9})\.?\s+((?:19|20)\d{2})(?!\d)"#, in: plain) {189 if let month = months[m[2]], let d = date(year: Int(m[3])!, month: month, day: Int(m[1])!) {190 found.append(FoundDate(date: d, isMonthYear: false))191 }192 }193 return found194 }195196 private static let expiryWords: Set<String> = ["exp", "expiry", "expires", "expire", "expiration", "thru", "through", "until",197 "valable", "validite", "echeance", "fin"]198199 private static func isExpiryLabel(_ text: String) -> Bool {200 let w = words(text)201 if w.contains(where: expiryWords.contains) { return true }202 return w.contains("valid") && !w.contains("from")203 }204205 /// Nearest line directly above `line` (overlapping horizontally).206 static func lineAbove(_ line: RecognizedLine, in lines: [RecognizedLine], within distance: CGFloat = 0.14) -> RecognizedLine? {207 lines.filter { other in208 other != line && other.box.midY < line.box.minY + line.box.height * 0.25 && line.box.minY - other.box.maxY < distance209 && other.box.minX < line.box.maxX && other.box.maxX > line.box.minX210 }.max { $0.box.midY < $1.box.midY }211 }212213 /// Nearest line directly below `line` (overlapping horizontally).214 static func lineBelow(_ line: RecognizedLine, in lines: [RecognizedLine], within distance: CGFloat = 0.14) -> RecognizedLine? {215 lines.filter { other in216 other != line && other.box.midY > line.box.maxY - line.box.height * 0.25 && other.box.minY - line.box.maxY < distance217 && other.box.minX < line.box.maxX && other.box.maxX > line.box.minX218 }.min { $0.box.midY < $1.box.midY }219 }220221 /// Expiry date. A date is proposed when it is labelled as an expiry (on its222 /// line or the line above), or — unlabelled — when it is a bank card MM/YY223 /// or a date still in the future. A date of birth or of issue is never224 /// proposed as an expiry.225 static func expiry(in lines: [RecognizedLine], banking: Bool, now: Date = Date()) -> Date? {226 var labelled: [Date] = [], unlabelled: [FoundDate] = []227 for line in lines {228 let found = dates(in: line.text, now: now)229 guard !found.isEmpty else { continue }230 let above = lineAbove(line, in: lines)231 if isExpiryLabel(line.text) || (above.map { isExpiryLabel($0.text) && dates(in: $0.text).isEmpty } ?? false) {232 labelled.append(contentsOf: found.map(\.date))233 } else {234 unlabelled.append(contentsOf: found)235 }236 }237 if let best = labelled.max() { return best }238 let candidates = unlabelled.filter { banking ? $0.isMonthYear : $0.date > now }239 return candidates.map(\.date).max()240 }241242 // MARK: Names243244 private static let nonNameWords: Set<String> = [245 "visa", "mastercard", "debit", "credit", "valid", "thru", "world", "elite", "bank", "banque", "card", "carte", "member", "since",246 "platinum", "gold", "infinite", "business", "rewards", "good", "month", "year", "authorized", "signature", "void",247 "electronic", "use", "only", "union", "express", "american", "discover", "interac", "prepaid", "international",248 ]249250 static func titleCased(_ text: String) -> String {251 let trimmed = text.trimmingCharacters(in: .whitespacesAndNewlines)252 guard trimmed == trimmed.uppercased() else { return trimmed }253 return trimmed.lowercased().split(separator: " ").map { word in254 word.split(separator: "-").map { $0.prefix(1).uppercased() + $0.dropFirst() }.joined(separator: "-")255 }.joined(separator: " ")256 }257258 private static func looksLikePersonName(_ text: String) -> Bool {259 let parts = text.split(separator: " ")260 guard (2...4).contains(parts.count) else { return false }261 guard text.allSatisfy({ $0.isLetter || $0 == " " || $0 == "-" || $0 == "'" || $0 == "." }) else { return false }262 guard parts.allSatisfy({ $0.filter(\.isLetter).count >= 2 || $0.count <= 2 }) else { return false }263 return !words(text).contains(where: nonNameWords.contains)264 }265266 /// Cardholder name embossed or printed in the lower half of a bank card.267 static func bankHolder(in lines: [RecognizedLine]) -> String? {268 lines.filter { $0.box.midY > 0.5 && $0.box.height < 0.2 && looksLikePersonName($0.text) }269 .max { $0.box.midY < $1.box.midY }270 .map { titleCased($0.text) }271 }272273 private static func hasWord(_ text: String, _ candidates: Set<String>) -> Bool {274 words(text).contains(where: candidates.contains)275 }276277 /// Holder of an identity document: the value under a "Name" label, or278 /// surname + given names when they are separate fields.279 static func documentHolder(in lines: [RecognizedLine]) -> String? {280 func value(under labels: Set<String>, excluding: Set<String> = []) -> String? {281 for line in lines where hasWord(line.text, labels) && !hasWord(line.text, excluding) {282 // "Name: SPECIMEN, Alex" on one line.283 if let colon = line.text.firstIndex(of: ":") {284 let rest = line.text[line.text.index(after: colon)...].trimmingCharacters(in: .whitespaces)285 if rest.count >= 3 { return rest }286 }287 if let below = lineBelow(line, in: lines), below.text.contains(where: \.isLetter), !below.text.contains(where: \.isNumber) {288 return below.text289 }290 }291 return nil292 }293 let surname = value(under: ["surname", "nom"], excluding: ["given", "prenoms", "prenom"])294 let given = value(under: ["given", "prenoms", "prenom"], excluding: [])295 if let surname, let given { return titleCased("\(given) \(surname)") }296 guard let name = value(under: ["name", "nom", "holder", "titulaire"]) ?? surname else { return nil }297 if let comma = name.firstIndex(of: ",") { // "SPECIMEN, Alex" → "Alex Specimen"298 let last = name[..<comma].trimmingCharacters(in: .whitespaces), first = name[name.index(after: comma)...].trimmingCharacters(in: .whitespaces)299 guard !last.isEmpty, !first.isEmpty else { return titleCased(name) }300 return "\(titleCased(first)) \(titleCased(last))"301 }302 return titleCased(name)303 }304305 // MARK: Issuer306307 private static let genericDocumentWords: Set<String> = [308 "passport", "passeport", "driver", "drivers", "driving", "licence", "license", "permis", "de", "conduire", "card", "carte", "health",309 "insurance", "assurance", "maladie", "identity", "identite", "id", "specimen", "void", "s", "d", "the", "of",310 ]311312 /// The most prominent line of text in the top part of the card.313 static func issuer(in lines: [RecognizedLine]) -> String? {314 func candidates(above limit: CGFloat) -> [RecognizedLine] {315 lines.filter { line in316 guard line.box.midY < limit, line.box.height < 0.3 else { return false }317 guard line.text.filter(\.isLetter).count >= 3, line.text.filter(\.isNumber).count <= 1 else { return false }318 return !words(line.text).allSatisfy(genericDocumentWords.contains)319 }320 }321 // The header band first; a logo lower down only if the header has no text.322 let band = candidates(above: 0.2)323 return (band.isEmpty ? candidates(above: 0.42) : band).max { $0.box.height < $1.box.height }.map { titleCased($0.text) }324 }325326 // MARK: Document numbers327328 private static let numberLabels: Set<String> = ["no", "number", "numero", "num", "licence", "license", "permis", "policy", "police",329 "member", "membre", "certificate", "dossier"]330331 private static func looksLikeDocumentNumber(_ text: String) -> Bool {332 let compact = text.filter { !$0.isWhitespace }333 guard (5...24).contains(compact.count), compact.filter(\.isNumber).count >= 4 else { return false }334 guard compact.allSatisfy({ $0.isNumber || $0.isLetter || $0 == "-" }) else { return false }335 guard !text.contains("<"), dates(in: text).isEmpty else { return false }336 // Telephone numbers ("1 800 555 0199") are not document numbers.337 if !matches(#"(?<!\d)1?[ \-.]?\(?8(?:00|33|44|55|66|77|88)\)?[ \-.]\d{3}[ \-.]\d{4}(?!\d)"#, in: text).isEmpty { return false }338 // Mostly words with a stray figure is a sentence, not a number.339 return compact.filter(\.isLetter).count <= compact.filter(\.isNumber).count * 2 + 4340 }341342 static func documentNumber(in lines: [RecognizedLine], kind: CardKind) -> String? {343 let normal = lines.filter { !$0.text.contains("<") }344 if kind == .passport {345 for line in normal {346 if let m = matches(#"(?<![A-Z0-9])([A-Z]{1,2}\d{6,8})(?![A-Z0-9])"#, in: line.text, options: []).first { return m[1] }347 }348 }349 // A value on the same line as, or under, a number label.350 for line in normal where hasWord(line.text, numberLabels) {351 if let colon = line.text.lastIndex(where: { $0 == ":" || $0 == "#" }) {352 let rest = line.text[line.text.index(after: colon)...].trimmingCharacters(in: .whitespaces)353 if looksLikeDocumentNumber(rest) { return rest }354 }355 if let below = lineBelow(line, in: normal), looksLikeDocumentNumber(below.text) { return below.text.trimmingCharacters(in: .whitespaces) }356 }357 // Otherwise the most prominent number-like line.358 return normal.filter { looksLikeDocumentNumber($0.text) && $0.box.height < 0.3 }359 .max { $0.box.height < $1.box.height }360 .map { $0.text.trimmingCharacters(in: .whitespaces) }361 }362}363