SPB Git

Repository Public

SmartScanTests.swift 30.6 KB 516 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : SP ID & Card Vault7// File             : SPVaultTests/SmartScanTests.swift8// Module           : Tests9// 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 CoreImage43import Foundation44import Testing45@testable import SPVault4647/// Fictitious cards only: everything here is drawn by `DemoCardFactory`.48enum ScanFixtures {49    static let demos = DemoCardFactory.all(now: Date(timeIntervalSince1970: 1_796_000_000))50    static var credit: DemoCardFactory.Demo { demos[0] }51    static var licence: DemoCardFactory.Demo { demos[1] }52    static var passport: DemoCardFactory.Demo { demos[2] }5354    static func line(_ text: String, x: CGFloat = 0.1, y: CGFloat, width: CGFloat = 0.5, height: CGFloat = 0.06, confidence: Float = 1) -> RecognizedLine {55        RecognizedLine(text: text, confidence: confidence, box: CGRect(x: x, y: y, width: width, height: height))56    }5758    /// Ground-truth corners of `photographed` (Core Image pixels) as a normalised top-left quad.59    static func truth(_ corners: [CGPoint], canvas: CGSize) -> CardQuad {60        let p = corners.map { CGPoint(x: $0.x / canvas.width, y: 1 - $0.y / canvas.height) }61        return CardQuad(topLeft: p[0], topRight: p[1], bottomRight: p[2], bottomLeft: p[3])62    }6364    /// Mean absolute luminance difference (0…255) between two images compared at 96×60.65    static func difference(_ a: CGImage, _ b: CGImage) -> Double {66        func sample(_ image: CGImage) -> [Float] {67            let ci = CIImage(cgImage: image)68            // Low-pass before sampling, so fine print does not alias into noise.69            let soft = ci.clampedToExtent().applyingGaussianBlur(sigma: Double(ci.extent.width) / 96).cropped(to: ci.extent)70            let scaled = soft.transformed(by: CGAffineTransform(scaleX: 96 / ci.extent.width, y: 60 / ci.extent.height))71            return SampledBitmap(scaled, targetWidth: 96)!.luminance72        }73        let x = sample(a), y = sample(b)74        return Double(zip(x, y).map { abs($0 - $1) }.reduce(0, +)) / Double(x.count)75    }7677    static func render(_ image: CIImage, size: CGSize) -> CGImage {78        ImagePipeline.context.createCGImage(image, from: CGRect(origin: .zero, size: size))!79    }8081    static func calendarUTC() -> Calendar {82        var calendar = Calendar(identifier: .gregorian)83        calendar.timeZone = TimeZone(identifier: "UTC")!84        return calendar85    }8687    static func ymd(_ date: Date?) -> [Int] {88        guard let date else { return [] }89        let c = calendarUTC().dateComponents([.year, .month, .day], from: date)90        return [c.year!, c.month!, c.day!]91    }92}9394@Suite("SmartScan — detection and perspective")95struct SmartScanGeometryTests {96    @Test func quadOrderingAndGeometry() {97        let quad = CardQuad(unordered: [CGPoint(x: 0.8, y: 0.7), CGPoint(x: 0.2, y: 0.3), CGPoint(x: 0.82, y: 0.28), CGPoint(x: 0.18, y: 0.72)])98        #expect(quad.topLeft == CGPoint(x: 0.2, y: 0.3))99        #expect(quad.topRight == CGPoint(x: 0.82, y: 0.28))100        #expect(quad.bottomRight == CGPoint(x: 0.8, y: 0.7))101        #expect(quad.bottomLeft == CGPoint(x: 0.18, y: 0.72))102        #expect(quad.isConvex)103        #expect(abs(CardQuad.full.area - 1) < 1e-9)104        let bowtie = CardQuad(topLeft: .zero, topRight: CGPoint(x: 1, y: 1), bottomRight: CGPoint(x: 1, y: 0), bottomLeft: CGPoint(x: 0, y: 1))105        #expect(!bowtie.isConvex)106        let centred = CardQuad.centred(aspect: CardFormat.id1.aspectRatio, imageSize: CGSize(width: 3024, height: 4032))107        #expect(abs(centred.apparentAspect(imageSize: CGSize(width: 3024, height: 4032)) - CardFormat.id1.aspectRatio) < 0.01)108    }109110    @Test func stabilityNeedsSeveralSteadyFrames() {111        var tracker = StabilityTracker(tolerance: 0.01, requiredFrames: 3)112        let quad = CardQuad.centred(aspect: 1.586, imageSize: CGSize(width: 3, height: 4))113        var moved = quad114        moved.topLeft.x += 0.05115        let results = [quad, quad, quad, quad].map { tracker.feed($0) }116        #expect(results == [false, false, false, true])117        let afterMove = tracker.feed(moved)      // movement resets118        #expect(!afterMove)119        let afterLoss = tracker.feed(nil)        // losing the card resets120        #expect(!afterLoss)121        #expect(!tracker.isStable)122    }123124    /// The parent fixture (`DemoCardFactory.photographed`), lightly skewed.125    @Test(arguments: [0, 1, 2])126    func detectsAndFlattensAPhotographedCard(index: Int) throws {127        let demo = ScanFixtures.demos[index]128        let canvas = CGSize(width: 3024, height: 4032)129        let photo = DemoCardFactory.photographed(demo.front, canvas: canvas, skew: 0.015)130        let detected = try #require(CardDetector.detectRefined(in: photo.image))131        let truth = ScanFixtures.truth(photo.corners, canvas: canvas)132        #expect(detected.quad.maxCornerDistance(to: truth) < 0.006, "corner error \(detected.quad.maxCornerDistance(to: truth))")133134        // The owner chose the kind of card, so its format is announced to the corrector.135        let corrected = try #require(PerspectiveCorrector.correct(photo.image, quad: detected.quad, expectedFormat: demo.card.format))136        #expect(corrected.format == demo.card.format, "measured \(corrected.measuredAspect)")137        let aspect = Double(corrected.image.width) / Double(corrected.image.height)138        #expect(abs(aspect - demo.card.format.aspectRatio) / demo.card.format.aspectRatio < 0.005)139        #expect(max(corrected.image.width, corrected.image.height) <= PerspectiveCorrector.maximumLongEdge)140        // The flattened card is the artwork again: no distortion, no mirror, no rotation.141        let difference = ScanFixtures.difference(corrected.image, demo.front)142        #expect(difference < 6, "mean luminance difference \(difference)")143    }144145    /// A card seen by a pinhole camera, tilted in every direction: the true146    /// proportions are recovered from the geometry alone, with no hint.147    @Test(arguments: [[18.0, 12.0, 0.0], [-25.0, 8.0, 4.0], [10.0, -22.0, -6.0], [0.0, 0.0, 0.0], [0.0, 20.0, 0.0], [13.0, 9.0, -3.0]])148    func recoversTrueProportionsOfATiltedCard(angles: [Double]) throws {149        let canvas = CGSize(width: 3024, height: 4032)150        let art = ScanFixtures.licence.front151        let shot = SimulatedCamera.photograph(art, yaw: angles[0], pitch: angles[1], roll: angles[2], canvas: canvas)152        let id1 = CardFormat.id1.aspectRatio153154        // Exact corners: the estimate is exact, where averaging edge lengths is biased.155        let exact = PerspectiveCorrector.estimatedAspect(of: shot.quad, imageSize: canvas)156        // With a single vanishing point the focal length is assumed, not measured: 1 % there.157        let tolerance = angles[0] == 0 && angles[1] != 0 ? 0.01 : 0.003158        #expect(abs(exact - id1) / id1 < tolerance, "exact \(exact) naive \(shot.quad.apparentAspect(imageSize: canvas))")159160        // Detected corners: inside the 4 % window, with no announced format.161        let detected = try #require(CardDetector.detectRefined(in: shot.image))162        #expect(detected.quad.maxCornerDistance(to: shot.quad) < 0.006, "corner error \(detected.quad.maxCornerDistance(to: shot.quad))")163        let corrected = try #require(PerspectiveCorrector.correct(shot.image, quad: detected.quad))164        #expect(corrected.format == .id1, "measured \(corrected.measuredAspect), naive \(detected.quad.apparentAspect(imageSize: canvas))")165        let difference = ScanFixtures.difference(corrected.image, art)166        #expect(difference < 6, "difference \(difference)")167    }168169    @Test func formatDecisionRule() {170        let id1 = CardFormat.id1.aspectRatio171        #expect(PerspectiveCorrector.format(forMeasuredAspect: id1 * 1.03, expected: nil) == .id1)172        #expect(PerspectiveCorrector.format(forMeasuredAspect: id1 * 0.94, expected: .id1) == .id1)173        #expect(PerspectiveCorrector.format(forMeasuredAspect: id1 * 0.94, expected: nil) == .custom(aspect: id1 * 0.94))174        #expect(PerspectiveCorrector.format(forMeasuredAspect: 1.2, expected: .id1) == .custom(aspect: 1.2))175        // A passport page scanned while "credit card" was announced is still a passport page.176        #expect(PerspectiveCorrector.format(forMeasuredAspect: CardFormat.id3.aspectRatio, expected: .id1) == .id3)177    }178179    @Test func unusualProportionsAreKeptNotSnapped() throws {180        // A 1.25:1 badge is neither ID-1 nor ID-3: its measured ratio must survive.181        let badge = ScanFixtures.render(CIImage(color: CIColor(red: 0.9, green: 0.85, blue: 0.3)).cropped(to: CGRect(x: 0, y: 0, width: 1000, height: 800)),182                                        size: CGSize(width: 1000, height: 800))183        let photo = DemoCardFactory.photographed(badge, skew: 0)184        let detected = try #require(CardDetector.detectRefined(in: photo.image))185        let corrected = try #require(PerspectiveCorrector.correct(photo.image, quad: detected.quad))186        guard case .custom(let kept) = corrected.format else { Issue.record("expected a custom format, got \(corrected.format)"); return }187        #expect(abs(kept - 1.25) < 0.04)188        #expect(abs(Double(corrected.image.width) / Double(corrected.image.height) - corrected.measuredAspect) < 0.005)189    }190191    @Test func degenerateQuadsAreRefusedAndMissingCardFallsBack() {192        let image = ScanFixtures.credit.front193        let flat = CardQuad(topLeft: CGPoint(x: 0.1, y: 0.5), topRight: CGPoint(x: 0.9, y: 0.5), bottomRight: CGPoint(x: 0.9, y: 0.5), bottomLeft: CGPoint(x: 0.1, y: 0.5))194        #expect(PerspectiveCorrector.correct(image, quad: flat) == nil)195        #expect(throws: SmartScanError.correctionFailed) { try SmartScanEngine.process(still: image, quad: flat) }196        let blank = ScanFixtures.render(CIImage(color: CIColor(red: 0.3, green: 0.3, blue: 0.3)).cropped(to: CGRect(x: 0, y: 0, width: 900, height: 1200)),197                                        size: CGSize(width: 900, height: 1200))198        let located = SmartScanEngine.locateCard(in: blank)199        #expect(!located.wasDetected)200        #expect(located.quad.isConvex)201    }202203    @Test func rotationAndOrientationHelpers() {204        let image = ScanFixtures.credit.front205        let turned = ImageAdjustments.rotated(image, quarterTurnsClockwise: 1)206        #expect(turned.width == image.height && turned.height == image.width)207        let back = ImageAdjustments.rotated(turned, quarterTurnsClockwise: 3)208        #expect(back.width == image.width)209        #expect(ScanFixtures.difference(back, image) < 1.5)210        let enhanced = ImageAdjustments.enhanced(image)211        #expect(enhanced.width == image.width && enhanced.height == image.height)212        // Restrained: the enhanced card is still very close to the original.213        #expect(ScanFixtures.difference(enhanced, image) < 25)214    }215}216217@Suite("SmartScan — quality gates")218struct SmartScanQualityTests {219    let canvas = CGSize(width: 1512, height: 2016)220    var photo: (image: CGImage, corners: [CGPoint]) { DemoCardFactory.photographed(ScanFixtures.licence.front, canvas: canvas) }221222    @Test func aGoodFramePassesEveryGate() {223        let photo = photo224        let quad = ScanFixtures.truth(photo.corners, canvas: canvas)225        let report = QualityAnalyzer.analyze(photo.image, quad: quad)226        #expect(report.isAcceptable, "issues \(report.issues) sharpness \(report.sharpness) glare \(report.glareFraction) light \(report.luminance)")227        #expect(report.hint == "Ready")228    }229230    @Test func blurIsFlagged() {231        let photo = photo232        let quad = ScanFixtures.truth(photo.corners, canvas: canvas)233        let blurred = ScanFixtures.render(CIImage(cgImage: photo.image).clampedToExtent().applyingGaussianBlur(sigma: 9), size: canvas)234        let sharp = QualityAnalyzer.analyze(photo.image, quad: quad), soft = QualityAnalyzer.analyze(blurred, quad: quad)235        #expect(soft.issues.contains(.blurry), "sharp \(sharp.sharpness) blurred \(soft.sharpness)")236        #expect(soft.sharpness < sharp.sharpness / 4)237        #expect(soft.hint == QualityIssue.blurry.hint)238    }239240    @Test func glareIsFlagged() {241        let photo = photo242        let quad = ScanFixtures.truth(photo.corners, canvas: canvas)243        let spot = CIFilter(name: "CIRadialGradient", parameters: [244            "inputCenter": CIVector(x: canvas.width / 2, y: canvas.height / 2), "inputRadius0": 200, "inputRadius1": 330,245            "inputColor0": CIColor.white, "inputColor1": CIColor(red: 1, green: 1, blue: 1, alpha: 0)])!.outputImage!246        let glared = ScanFixtures.render(spot.composited(over: CIImage(cgImage: photo.image)), size: canvas)247        let report = QualityAnalyzer.analyze(glared, quad: quad)248        #expect(report.issues.contains(.glare), "glare \(report.glareFraction)")249        #expect(report.hint.contains("glare"))250    }251252    @Test func darknessIsFlagged() {253        let photo = photo254        let quad = ScanFixtures.truth(photo.corners, canvas: canvas)255        let dark = ScanFixtures.render(CIImage(cgImage: photo.image).applyingFilter("CIExposureAdjust", parameters: [kCIInputEVKey: -4.5]), size: canvas)256        let report = QualityAnalyzer.analyze(dark, quad: quad)257        #expect(report.issues.first == .tooDark, "light \(report.luminance)")258        #expect(report.hint == "More light needed")259    }260261    @Test func missingOrDistantCardIsFlagged() {262        let photo = photo263        #expect(QualityAnalyzer.analyze(photo.image, quad: nil).issues == [.noCard])264        var small = CardQuad.centred(aspect: 1.586, imageSize: canvas, widthFraction: 0.3)265        small = small.clamped()266        #expect(QualityAnalyzer.analyze(photo.image, quad: small).issues.contains(.tooFar))267        #expect(QualityIssue.tooFar.hint == "Move closer")268        #expect(QualityIssue.unstable.hint == "Hold steady")269    }270}271272@Suite("SmartScan — text parser")273struct CardTextParserTests {274    typealias F = ScanFixtures275    let now = F.calendarUTC().date(from: DateComponents(year: 2026, month: 12, day: 2))!276277    @Test func bankCardFromRawLines() {278        let lines = [F.line("AURORA BANK", y: 0.09, height: 0.07), F.line("WORLD ELITE", y: 0.18, height: 0.03),279                     F.line("4242 4242 4242 4242", y: 0.6, height: 0.09), F.line("VALID THRU", x: 0.44, y: 0.74, width: 0.12, height: 0.03),280                     F.line("05/28", x: 0.44, y: 0.78, width: 0.12, height: 0.05), F.line("ALEX SPECIMEN", y: 0.85, height: 0.05),281                     F.line("VISA", x: 0.75, y: 0.82, width: 0.2, height: 0.08)]282        let s = CardTextParser.suggestion(front: lines, kind: .creditCard, now: now)283        #expect(s.number == "4242424242424242")284        #expect(F.ymd(s.expiry) == [2028, 5, 31])285        #expect(s.holderName == "Alex Specimen")286        #expect(s.issuer == "Aurora Bank")287        #expect(s.name == "Aurora Bank Visa")288    }289290    @Test func neverInventsOrRepairsCharacters() {291        // One digit misread: the number fails Luhn and is not proposed, not "fixed".292        let misread = [F.line("4242 4242 4242 4243", y: 0.6), F.line("O5/28", y: 0.78)]293        let s = CardTextParser.suggestion(front: misread, kind: .creditCard, now: now)294        #expect(s.number == nil)295        #expect(s.expiry == nil)296        // A partly hidden number stays unknown.297        #expect(CardTextParser.bankNumber(in: [F.line("4242 4242 42", y: 0.6)]) == nil)298        // Groups read separately on one row are one number; a Luhn-valid fragment of a longer row is not.299        let groups = [F.line("4242", x: 0.06, y: 0.6, width: 0.2, height: 0.09), F.line("4242 4242 4242", x: 0.3, y: 0.6, width: 0.6, height: 0.09)]300        #expect(CardTextParser.bankNumber(in: groups) == "4242424242424242")301        let broken = [F.line("4243", x: 0.06, y: 0.6, width: 0.2, height: 0.09), F.line("4242 4242 4242", x: 0.3, y: 0.6, width: 0.6, height: 0.09)]302        #expect(CardTextParser.bankNumber(in: broken) == nil)303        // Low-confidence readings are ignored altogether.304        let doubtful = [F.line("4242 4242 4242 4242", y: 0.6, confidence: 0.3), F.line("ALEX SPECIMEN", y: 0.85, confidence: 0.3)]305        #expect(CardTextParser.suggestion(front: doubtful, kind: .creditCard, now: now) == CardSuggestion())306        #expect(CardTextParser.suggestion(front: [], kind: .driverLicense, now: now) == CardSuggestion())307    }308309    @Test func neverEmitsASecurityCode() {310        let front = [F.line("AURORA BANK", y: 0.09, height: 0.07), F.line("4242 4242 4242 4242", y: 0.6), F.line("05/28", y: 0.78), F.line("ALEX SPECIMEN", y: 0.85)]311        let back = [F.line("737", x: 0.72, y: 0.4, width: 0.1), F.line("CVV 737", x: 0.72, y: 0.52, width: 0.2), F.line("CVC: 9184", y: 0.6),312                    F.line("Customer service 1 800 555 0199", y: 0.7)]313        for kind in [CardKind.creditCard, .debitCard, .loyaltyCard, .driverLicense] {314            let s = CardTextParser.suggestion(front: kind.isBanking ? front : back, back: back, kind: kind, now: now)315            let values = [s.name, s.issuer, s.holderName, s.number].compactMap { $0 }316            for value in values {317                #expect(!value.contains("737"), "\(kind): \(value)")318                #expect(!value.contains("9184"), "\(kind): \(value)")319            }320        }321        // A back-only number (modern cards) is still found, without the code.322        let modernBack = [F.line("5555 5555 5555 4444", y: 0.3), F.line("02/27", y: 0.4), F.line("418", x: 0.7, y: 0.4, width: 0.08)]323        let s = CardTextParser.suggestion(front: [F.line("MERIDIAN", y: 0.1, height: 0.08)], back: modernBack, kind: .debitCard, now: now)324        #expect(s.number == "5555555555554444")325        #expect(F.ymd(s.expiry) == [2027, 2, 28])326    }327328    @Test func dateFormats() {329        func first(_ text: String) -> [Int] { F.ymd(CardTextParser.dates(in: text).first?.date) }330        #expect(first("05/28") == [2028, 5, 31])331        #expect(first("02 / 2027") == [2027, 2, 28])332        #expect(first("2027-01-13") == [2027, 1, 13])333        #expect(first("2026-11") == [2026, 11, 30])334        #expect(first("09 AUG 2031") == [2031, 8, 9])335        #expect(first("9 août 2031") == [2031, 8, 9])336        #expect(first("14 FÉV 1988") == [1988, 2, 14])337        #expect(CardTextParser.dates(in: "13/28").isEmpty)338        #expect(CardTextParser.dates(in: "2027-02-31").isEmpty)339        #expect(CardTextParser.dates(in: "14/02/1988").isEmpty)        // day/month/year is ambiguous: not guessed340        #expect(CardTextParser.dates(in: "4242 4242 4242 4242").isEmpty)341    }342343    @Test func expiryIsNeverABirthOrIssueDate() {344        let labelled = [F.line("Date of birth", y: 0.2, height: 0.03), F.line("1988-02-14", y: 0.24),345                        F.line("Expires", y: 0.4, height: 0.03), F.line("2027-01-13", y: 0.44), F.line("Issued 2023-01-13", y: 0.6)]346        #expect(F.ymd(CardTextParser.expiry(in: labelled, banking: false, now: now)) == [2027, 1, 13])347        // No label and nothing in the future: no proposal.348        let pastOnly = [F.line("1988-02-14", y: 0.24), F.line("2023-01-13", y: 0.6)]349        #expect(CardTextParser.expiry(in: pastOnly, banking: false, now: now) == nil)350        // An already expired document still reports its labelled expiry.351        let expired = [F.line("EXP 2024-06-30", y: 0.4)]352        #expect(F.ymd(CardTextParser.expiry(in: expired, banking: false, now: now)) == [2024, 6, 30])353        // Bank card with "valid from" and "valid thru": the later month wins.354        let both = [F.line("03/24", x: 0.2, y: 0.7, width: 0.1), F.line("05/28", x: 0.5, y: 0.7, width: 0.1)]355        #expect(F.ymd(CardTextParser.expiry(in: both, banking: true, now: now)) == [2028, 5, 31])356    }357358    @Test func identityDocuments() {359        let licence = [F.line("PROVINCE OF NORTHWIND", y: 0.03, height: 0.05), F.line("Driver's Licence · Permis de conduire", y: 0.09, height: 0.03),360                       F.line("NAME", x: 0.35, y: 0.2, height: 0.025), F.line("SPECIMEN, Alex", x: 0.35, y: 0.23, height: 0.05),361                       F.line("DATE OF BIRTH", x: 0.35, y: 0.31, height: 0.025), F.line("1988-02-14", x: 0.35, y: 0.34, height: 0.05),362                       F.line("EXPIRES", x: 0.35, y: 0.53, height: 0.025), F.line("2027-01-13", x: 0.35, y: 0.56, height: 0.05),363                       F.line("S1234-140288-07", x: 0.04, y: 0.82, height: 0.07)]364        let s = CardTextParser.suggestion(front: licence, kind: .driverLicense, now: now)365        #expect(s.number == "S1234-140288-07")366        #expect(s.holderName == "Alex Specimen")367        #expect(s.issuer == "Province Of Northwind")368        #expect(F.ymd(s.expiry) == [2027, 1, 13])369        #expect(s.name == nil)   // identity documents keep the name of their kind370371        let passport = [F.line("PASSPORT · PASSEPORT", y: 0.04, height: 0.05), F.line("REPUBLIC OF NORTHWIND", y: 0.1, height: 0.035),372                        F.line("Surname / Nom", x: 0.35, y: 0.18, height: 0.025), F.line("SPECIMEN", x: 0.35, y: 0.21, width: 0.2, height: 0.045),373                        F.line("Passport No.", x: 0.71, y: 0.18, width: 0.15, height: 0.025), F.line("NW4821973", x: 0.71, y: 0.21, width: 0.2, height: 0.045),374                        F.line("Given names / Prénoms", x: 0.35, y: 0.28, height: 0.025), F.line("ALEX JORDAN", x: 0.35, y: 0.31, width: 0.25, height: 0.045),375                        F.line("Date of birth / Date de naissance", x: 0.35, y: 0.47, height: 0.025), F.line("14 FEB 1988", x: 0.35, y: 0.5, width: 0.25, height: 0.045),376                        F.line("Date of expiry / Date d'expiration", x: 0.35, y: 0.57, height: 0.025), F.line("09 AUG 2031", x: 0.35, y: 0.6, width: 0.25, height: 0.045),377                        F.line("P<NWDSPECIMEN<<ALEX<JORDAN<<<<<<<<<<<<<<<<<<<", x: 0.04, y: 0.8, width: 0.9), F.line("NW4821973<4NWD8802145M3108097<<<<<<<<<<<<<<06", x: 0.04, y: 0.87, width: 0.9)]378        let p = CardTextParser.suggestion(front: passport, kind: .passport, now: now)379        #expect(p.number == "NW4821973")380        #expect(p.holderName == "Alex Jordan Specimen")381        #expect(p.issuer == "Republic Of Northwind")382        #expect(F.ymd(p.expiry) == [2031, 8, 9])383    }384385    @Test func documentNumbersAreNotPhoneNumbersOrDates() {386        let lines = [F.line("Harbor Mutual", y: 0.1, height: 0.1), F.line("Claims 1 800 555 0177", y: 0.5, height: 0.2), F.line("2027-05-11", y: 0.6, height: 0.2),387                     F.line("HM-AUTO-0048213", y: 0.84, height: 0.055)]388        let s = CardTextParser.suggestion(front: lines, kind: .autoInsurance, now: now)389        #expect(s.number == "HM-AUTO-0048213")390        #expect(s.name == "Harbor Mutual")391        #expect(CardTextParser.documentNumber(in: [F.line("Call 1 800 555 0199 for help", y: 0.5)], kind: .loyaltyCard) == nil)392    }393}394395@Suite("SmartScan — security code masking")396struct SecurityCodeTests {397    typealias F = ScanFixtures398399    @Test func candidatesFromRawLines() {400        // Alone on its line.401        #expect(SecurityCodeDetector.candidates(in: [F.line("737", x: 0.72, y: 0.4, width: 0.1)]).count == 1)402        // Labelled on the same line: only the code is masked, not the label.403        let labelled = RecognizedLine(text: "CVV 737", confidence: 1, box: CGRect(x: 0.6, y: 0.4, width: 0.3, height: 0.06))404        let rects = SecurityCodeDetector.candidates(in: [labelled])405        #expect(rects.count == 1)406        #expect(rects[0].midX > 0.75)407        // Four digits (American Express style) next to a label line.408        let nearLabel = [F.line("Security code", x: 0.6, y: 0.3, width: 0.3, height: 0.03), F.line("ref 9184", x: 0.62, y: 0.36, width: 0.25)]409        #expect(SecurityCodeDetector.candidates(in: nearLabel).count == 1)410        // Card numbers, phone numbers and sentences are left alone.411        let other = [F.line("4242 4242 4242 4242", y: 0.3), F.line("Customer service 1 800 555 0199", y: 0.6), F.line("Issued in 2023 by the bank", y: 0.7)]412        #expect(SecurityCodeDetector.candidates(in: other).isEmpty)413        // Doubtful readings still count for masking.414        #expect(SecurityCodeDetector.candidates(in: [F.line("418", x: 0.7, y: 0.4, width: 0.1, confidence: 0.3)]).count == 1)415    }416417    @Test func redactionIsOpaqueAndLeavesTheRestUntouched() throws {418        let image = F.credit.back!419        let rect = DemoCardFactory.bankBackCVVRect420        let redacted = Redactor.redact(image, rects: [rect])421        #expect(redacted.width == image.width && redacted.height == image.height)422        let ci = CIImage(cgImage: redacted)423        let region = CGRect(x: rect.minX * ci.extent.width, y: (1 - rect.maxY) * ci.extent.height, width: rect.width * ci.extent.width, height: rect.height * ci.extent.height)424        let inside = try #require(SampledBitmap(ci, region: region.insetBy(dx: 2, dy: 2), targetWidth: 120))425        #expect(inside.rgba.enumerated().allSatisfy { $0.offset % 4 == 3 || $0.element == 0 })426        // Outside the mask the photograph is unchanged.427        let stripe = CGRect(x: 0, y: ci.extent.height * 0.75, width: ci.extent.width, height: ci.extent.height * 0.15)428        let before = try #require(SampledBitmap(CIImage(cgImage: image), region: stripe, targetWidth: 200))429        let after = try #require(SampledBitmap(ci, region: stripe, targetWidth: 200))430        #expect(before.rgba == after.rgba)431        #expect(Redactor.redact(image, rects: []) === image)432    }433434    @Test func detectsAndRemovesTheCodeOfAPhotographedBack() throws {435        let photo = SimulatedCamera.photograph(F.credit.back!)436        let located = SmartScanEngine.locateCard(in: photo.image)437        #expect(located.wasDetected)438        let side = try SmartScanEngine.process(still: photo.image, quad: located.quad, expectedFormat: .id1)439        #expect(side.lines.contains { $0.text.contains("737") }, "OCR lines: \(side.lines.map(\.text))")440441        let rects = SmartScanEngine.securityCodeRects(in: side, cardSide: .back)442        #expect(!rects.isEmpty)443        let truth = DemoCardFactory.bankBackCVVRect444        let hit = try #require(rects.first { $0.intersects(truth) }, "candidates \(rects)")445        // The proposal covers the printed digits (they sit in the middle of the white box).446        #expect(hit.contains(CGPoint(x: truth.midX - 0.01, y: truth.midY - 0.01)))447        // It does not swallow the signature panel or the service number.448        #expect(rects.allSatisfy { $0.width < 0.3 && $0.height < 0.25 })449450        let redacted = Redactor.redact(side.image, rects: rects)451        let reread = CardOCR.recognize(redacted)452        #expect(!reread.contains { $0.text.contains("737") }, "after masking: \(reread.map(\.text))")453        // Text elsewhere on the card is still readable.454        #expect(reread.contains { $0.text.localizedCaseInsensitiveContains("signature") })455    }456457    @Test func frontOfAnOrdinaryCardNeedsNoMask() throws {458        let side = try SmartScanEngine.process(still: F.credit.front, quad: .full)459        #expect(SmartScanEngine.securityCodeRects(in: side, cardSide: .front).isEmpty)460    }461}462463@Suite("SmartScan — OCR on fictitious cards")464struct SmartScanOCRTests {465    typealias F = ScanFixtures466    let now = F.calendarUTC().date(from: DateComponents(year: 2026, month: 12, day: 2))!467468    func scan(_ image: CGImage, expected: CardFormat = .id1) throws -> ProcessedSide {469        let photo = SimulatedCamera.photograph(image)470        let located = SmartScanEngine.locateCard(in: photo.image)471        #expect(located.wasDetected)472        return try SmartScanEngine.process(still: photo.image, quad: located.quad, expectedFormat: expected)473    }474475    @Test func creditCardEndToEnd() throws {476        let front = try scan(F.credit.front), back = try scan(F.credit.back!)477        var maskedBack = back478        maskedBack.image = Redactor.redact(back.image, rects: SmartScanEngine.securityCodeRects(in: back, cardSide: .back))479        let draft = SmartScanEngine.makeDraft(kind: .creditCard, front: front, back: maskedBack, now: now)480        #expect(draft.suggestion.number == "4242424242424242", "lines \(front.lines.map(\.text))")481        #expect(F.ymd(draft.suggestion.expiry) == [2028, 5, 31])482        #expect(draft.suggestion.holderName == "Alex Specimen", "lines \(front.lines.map { "\($0.text)@\($0.box.midY)/\($0.confidence)" })")483        #expect(draft.suggestion.issuer?.localizedCaseInsensitiveContains("Aurora") == true)484        #expect(draft.format == .id1)485        #expect(draft.back != nil)486        for value in [draft.suggestion.name, draft.suggestion.issuer, draft.suggestion.holderName, draft.suggestion.number].compactMap({ $0 }) {487            #expect(!value.contains("737"))488        }489        let card = draft.makeCard(reminderOffsets: [30])490        #expect(card.last4 == "4242")491        #expect(card.hasBack)492        #expect(card.fields.isEmpty)493        try SensitiveDataPolicy.validate(card)494        // Dominant colour comes from the photograph (a dark card).495        #expect(draft.dominantColor.luminance < 0.35)496    }497498    @Test func passportEndToEnd() throws {499        let front = try scan(F.passport.front, expected: .id3)500        let draft = SmartScanEngine.makeDraft(kind: .passport, front: front, back: nil, now: now)501        #expect(draft.format == .id3)502        #expect(draft.suggestion.number == "NW4821973", "lines \(front.lines.map(\.text))")503        #expect(F.ymd(draft.suggestion.expiry) == [2031, 8, 9])504        #expect(draft.suggestion.holderName == "Alex Jordan Specimen")505        #expect(draft.back == nil)506    }507508    @Test func driverLicenceEndToEnd() throws {509        let front = try scan(F.licence.front)510        let draft = SmartScanEngine.makeDraft(kind: .driverLicense, front: front, back: nil, now: now)511        #expect(draft.suggestion.number == "S1234-140288-07", "lines \(front.lines.map(\.text))")512        #expect(F.ymd(draft.suggestion.expiry) == [2027, 1, 13])513        #expect(draft.suggestion.holderName == "Alex Specimen")514    }515}516
Files main
Menu

Theme