SPB Git

Repository Public

CaptureGuidanceTests.swift 11.9 KB 229 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Tests/MacLustrIdentityCoreTests/CaptureGuidanceTests.swift10// Module           : MacLustrIdentityCoreTests11// Repository       : https://git.spboucher.ai/maclustr-identity12// Project Website  : https://identity.spboucher.ai13// Created          : 2026-12-0114// Last Modified    : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author           : Simon-Pierre Boucher21// Position         : Professor of Finance22// Institution      : Université du Québec en Outaouais (UQO)23// Department       : Département des sciences administratives24// Organization     : SP Boucher25//26// Website          : https://spboucher.ai27// Git              : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General          : info@spboucher.ai34// Professional     : contact@spboucher.ai35// Direct           : simon@spboucher.ai36// Research         : research@spboucher.ai37// Development      : dev@spboucher.ai38// Support          : support@spboucher.ai39// Security/Admin   : admin@spboucher.ai40// Notifications    : notifications@spboucher.ai41//42// Preferred Contact: admin@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification   : Public67// Distribution     : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License          : None specified (no license file in this repository)81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import XCTest89@testable import MacLustrIdentityCore9091final class CaptureGuidanceTests: XCTestCase {92    func testLumaQuality() {93        let flat = [UInt8](repeating: 120, count: 64 * 48)94        let q = LumaQuality.measure(luma: flat, width: 64, height: 48)95        XCTAssertEqual(q.brightness, 120, accuracy: 0.001)96        XCTAssertEqual(q.contrast, 0, accuracy: 0.001)97        XCTAssertEqual(q.sharpness, 0, accuracy: 0.001)98        var checker = [UInt8](repeating: 0, count: 64 * 48)99        for y in 0..<48 { for x in 0..<64 where (x / 2 + y / 2) % 2 == 0 { checker[y * 64 + x] = 255 } }100        let c = LumaQuality.measure(luma: checker, width: 64, height: 48)101        XCTAssertEqual(c.brightness, 127.5, accuracy: 1)102        XCTAssertGreaterThan(c.contrast, 100)103        XCTAssertGreaterThan(c.sharpness, 10_000)104        // A smooth ramp is bright enough but has no edges.105        var ramp = [UInt8](repeating: 0, count: 64 * 48)106        for y in 0..<48 { for x in 0..<64 { ramp[y * 64 + x] = UInt8(60 + x * 2) } }107        XCTAssertLessThan(LumaQuality.measure(luma: ramp, width: 64, height: 48).sharpness, 1)108        XCTAssertEqual(LumaQuality.measure(luma: checker, width: 64, height: 48, step: 4).brightness, 255, accuracy: 0.001)   // stride lands on white cells109        XCTAssertEqual(LumaQuality.measure(luma: [1, 2], width: 2, height: 1), LumaQuality(brightness: 0, contrast: 0, sharpness: 0))110    }111112    private let good = LumaQuality(brightness: 130, contrast: 50, sharpness: 200)113    private func quad(_ inset: Double, shift: Double = 0) -> [(x: Double, y: Double)] {114        [(inset + shift, inset), (1 - inset + shift, inset), (1 - inset + shift, 1 - inset), (inset + shift, 1 - inset)]115    }116117    func testDocumentGuideSequence() {118        var g = DocumentGuide()119        XCTAssertEqual(g.update(.init(corners: nil, quality: LumaQuality(brightness: 20, contrast: 5, sharpness: 300), time: 0)), .tooDark)120        XCTAssertEqual(g.update(.init(corners: nil, quality: LumaQuality(brightness: 250, contrast: 5, sharpness: 300), time: 0.1)), .tooBright)121        XCTAssertEqual(g.update(.init(corners: nil, quality: good, time: 0.2)), .searching)122        XCTAssertEqual(g.update(.init(corners: quad(0.35), quality: good, time: 0.3)), .moveCloser)          // 9 % of the frame123        XCTAssertEqual(g.update(.init(corners: quad(0.15), quality: good, time: 0.4)), .holdSteady)          // moved since the last frame124        XCTAssertEqual(g.update(.init(corners: quad(0.15), quality: LumaQuality(brightness: 130, contrast: 50, sharpness: 20), time: 0.5)), .blurry)125        XCTAssertEqual(g.update(.init(corners: quad(0.15), quality: good, time: 0.6)), .holdSteady)126        XCTAssertEqual(g.update(.init(corners: quad(0.15), quality: good, time: 1.0)), .holdSteady)127        XCTAssertEqual(g.update(.init(corners: quad(0.15), quality: good, time: 1.55)), .ready)128        XCTAssertEqual(g.update(.init(corners: quad(0.15, shift: 0.05), quality: good, time: 1.6)), .holdSteady)   // movement resets the timer129        XCTAssertEqual(g.update(.init(corners: quad(0.15, shift: 0.05), quality: good, time: 1.7)), .holdSteady)130        g.reset()131        XCTAssertEqual(g.update(.init(corners: quad(0.15), quality: good, time: 5)), .holdSteady)132    }133134    func testQuadArea() {135        XCTAssertEqual(DocumentGuide.area(quad(0)), 1, accuracy: 1e-9)136        XCTAssertEqual(DocumentGuide.area(quad(0.25)), 0.25, accuracy: 1e-9)137    }138139    func testYawSignMatchesTheServerConvention() {140        // Unmirrored image, x to the right. Turning to one's own left moves the nose towards the image right.141        XCTAssertEqual(HeadPose.yaw(eyeA: (100, 100), eyeB: (200, 100), nose: (150, 150)), 0, accuracy: 1e-6)142        XCTAssertEqual(HeadPose.yaw(eyeA: (100, 100), eyeB: (200, 100), nose: (175, 150)), 0.25, accuracy: 1e-6)143        XCTAssertEqual(HeadPose.yaw(eyeA: (200, 100), eyeB: (100, 100), nose: (120, 150)), -0.3, accuracy: 1e-6)    // eye order is irrelevant144    }145146    /// Reference implementation of the server check (services/mlid/engines/liveness.py, `_challenge_ok`).147    private func serverAccepts(_ yaws: [Double], _ steps: [ChallengeStep]) -> Bool {148        var i = 0149        var wanted: [ChallengeStep?] = [nil]150        for s in steps { wanted.append(s); wanted.append(nil) }151        for step in wanted {152            var hit = false153            while i < yaws.count {154                let y = yaws[i]155                i += 1156                let ok: Bool157                switch step {158                case nil: ok = abs(y) < 0.07159                case .turnLeft?: ok = y > 0.16160                default: ok = y < -0.16161                }162                if ok { hit = true; break }163            }164            if !hit { return false }165        }166        return true167    }168169    func testLivenessGuideFollowsTheChallenge() {170        let steps: [ChallengeStep] = [.turnLeft, .turnRight]171        var g = LivenessGuide(steps: steps)172        XCTAssertEqual(g.instruction, .lookStraight)173        XCTAssertEqual(g.update(nil, frameIndex: 0), .noFace)174        XCTAssertEqual(g.update(.init(yaw: 0, faceWidth: 80), frameIndex: 1), .moveCloser)175        let yaws: [Double] = [0.12, 0.01, 0.1, 0.2, 0.3, 0.15, 0.06, 0.02, -0.1, -0.2, -0.28, -0.1, 0.0, 0.0]176        var shown: [LivenessInstruction] = []177        var movements: [Int] = []178        var doneAt: Int?179        for (i, y) in yaws.enumerated() {180            shown.append(g.update(.init(yaw: y, faceWidth: 300), frameIndex: i + 2))181            movements.append(g.currentMovement)182            if g.isDone, doneAt == nil { doneAt = i }183        }184        XCTAssertEqual(shown, [.lookStraight, .turnLeft, .turnLeft, .turnLeft, .backToCenter, .backToCenter, .backToCenter, .turnRight, .turnRight, .turnRight, .backToCenter, .backToCenter, .done, .done])185        XCTAssertEqual(movements, [0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2])186        XCTAssertEqual(doneAt, 12)187        XCTAssertEqual(g.keyFrames, [3, 6, 9, 12, 14])188        // What the device accepted, the server accepts too (its thresholds are looser).189        XCTAssertTrue(serverAccepts(Array(yaws.prefix(13)), steps))190        // A frame analysed but not recorded shows guidance without advancing.191        var h = LivenessGuide(steps: [.turnRight])192        XCTAssertEqual(h.update(.init(yaw: 0, faceWidth: 300), frameIndex: nil), .lookStraight)193        XCTAssertEqual(h.phaseIndex, 0)194    }195196    func testLivenessGuideRejectsWrongDirectionAndShallowTurns() {197        var g = LivenessGuide(steps: [.turnLeft])198        _ = g.update(.init(yaw: 0, faceWidth: 300), frameIndex: 0)199        XCTAssertEqual(g.update(.init(yaw: -0.4, faceWidth: 300), frameIndex: 1), .turnLeft)     // turned right instead200        XCTAssertEqual(g.update(.init(yaw: 0.18, faceWidth: 300), frameIndex: 2), .turnLeft)     // enough for the server, not for the margin201        XCTAssertEqual(g.update(.init(yaw: 0.25, faceWidth: 300), frameIndex: 3), .backToCenter)202        XCTAssertFalse(g.isDone)203    }204205    func testAccessibleGuideNeedsCentredFramesOnly() {206        var g = LivenessGuide(steps: [], accessibleFrames: 3)207        XCTAssertEqual(g.stepCount, 0)208        XCTAssertEqual(g.update(.init(yaw: 0.3, faceWidth: 300), frameIndex: 0), .lookStraight)209        XCTAssertEqual(g.update(.init(yaw: 0.0, faceWidth: 300), frameIndex: 1), .lookStraight)210        XCTAssertEqual(g.update(.init(yaw: 0.01, faceWidth: 300), frameIndex: 2), .lookStraight)211        XCTAssertEqual(g.update(.init(yaw: -0.02, faceWidth: 300), frameIndex: 3), .done)212        XCTAssertEqual(g.keyFrames, [1, 2, 3])213    }214215    func testFrameSelection() {216        XCTAssertEqual(FrameSelector.select(count: 10, keyFrames: [2, 5], max: 24), Array(0..<10))217        let sel = FrameSelector.select(count: 100, keyFrames: [3, 40, 41, 77, 99], max: 24)218        XCTAssertEqual(sel.count, 24)219        XCTAssertEqual(sel, sel.sorted())220        XCTAssertEqual(Set(sel).count, 24)221        XCTAssertTrue(Set([3, 40, 41, 77, 99]).isSubset(of: Set(sel)))222        XCTAssertLessThanOrEqual(zip(sel, sel.dropFirst()).map { $1 - $0 }.max()!, 8)       // evenly spread223        XCTAssertEqual(FrameSelector.select(count: 50, keyFrames: [10, 20, 30], max: 3), [10, 20, 30])224        XCTAssertEqual(FrameSelector.select(count: 30, keyFrames: [-1, 99], max: 8).count, 8)225        XCTAssertEqual(FrameSelector.select(count: 0, keyFrames: [], max: 8), [])226        for n in 25...130 { XCTAssertEqual(FrameSelector.select(count: n, keyFrames: [0, n / 2, n - 1], max: 24).count, 24, "\(n)") }227    }228}229
Files main
Menu

Theme