SPB Git

Repository Public

CaptureGuidance.swift 15.1 KB 353 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Sources/MacLustrIdentityCore/CaptureGuidance.swift10// Module           : MacLustrIdentityCore11// 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// =============================================================================8788// Pure capture-guidance logic shared by the camera screens: image quality measures, document guidance,89// head-turn guidance and frame selection. No camera or Vision dependency, so it is unit-tested on any platform.90import Foundation9192// MARK: - Image quality9394/// Luminance statistics of a frame, on the same scales as the server-side quality check.95public struct LumaQuality: Equatable, Sendable {96    /// Mean luminance, 0–255.97    public var brightness: Double98    /// Standard deviation of the luminance.99    public var contrast: Double100    /// Variance of the 4-neighbour Laplacian. Higher is sharper.101    public var sharpness: Double102103    public init(brightness: Double, contrast: Double, sharpness: Double) {104        self.brightness = brightness; self.contrast = contrast; self.sharpness = sharpness105    }106107    /// Measures a row-major 8-bit luminance buffer.108    /// - Parameter step: sampling stride in pixels; choose it so that the sampled long side is about 900 pixels,109    ///   the scale at which the server measures sharpness.110    public static func measure(luma: UnsafeBufferPointer<UInt8>, width: Int, height: Int, bytesPerRow: Int, step: Int = 1) -> LumaQuality {111        let s = max(1, step)112        let w = width / s, h = height / s113        guard w >= 3, h >= 3, luma.count >= (height - 1) * bytesPerRow + width else { return LumaQuality(brightness: 0, contrast: 0, sharpness: 0) }114        @inline(__always) func px(_ x: Int, _ y: Int) -> Double { Double(luma[y * s * bytesPerRow + x * s]) }115        var sum = 0.0, sumSq = 0.0116        var lapSum = 0.0, lapSq = 0.0117        for y in 0..<h {118            for x in 0..<w {119                let v = px(x, y)120                sum += v; sumSq += v * v121                if x > 0, y > 0, x < w - 1, y < h - 1 {122                    let l = px(x - 1, y) + px(x + 1, y) + px(x, y - 1) + px(x, y + 1) - 4 * v123                    lapSum += l; lapSq += l * l124                }125            }126        }127        let n = Double(w * h), m = Double((w - 2) * (h - 2))128        let mean = sum / n, lapMean = lapSum / m129        return LumaQuality(brightness: mean, contrast: (max(0, sumSq / n - mean * mean)).squareRoot(), sharpness: max(0, lapSq / m - lapMean * lapMean))130    }131132    public static func measure(luma: [UInt8], width: Int, height: Int, step: Int = 1) -> LumaQuality {133        luma.withUnsafeBufferPointer { measure(luma: $0, width: width, height: height, bytesPerRow: width, step: step) }134    }135}136137// MARK: - Document guidance138139public enum DocumentHint: Equatable, Sendable {140    case searching, moveCloser, tooDark, tooBright, blurry, holdSteady, ready141142    public var string: IdentityString {143        switch self {144        case .searching: return .docGuideSearching145        case .moveCloser: return .docGuideCloser146        case .tooDark: return .docGuideDark147        case .tooBright: return .docGuideBright148        case .blurry: return .docGuideBlurry149        case .holdSteady: return .docGuideSteady150        case .ready: return .docGuideReady151        }152    }153}154155/// Turns per-frame observations into a hint and decides when to capture automatically.156/// The thresholds are deliberately a little stricter than the server's (brightness 55–235, sharpness 55).157public struct DocumentGuide: Sendable {158    public struct Observation: Sendable {159        /// Corners of the detected document in normalised image coordinates (0–1), or nil when none is found.160        public var corners: [(x: Double, y: Double)]?161        public var quality: LumaQuality162        public var time: TimeInterval163164        public init(corners: [(x: Double, y: Double)]?, quality: LumaQuality, time: TimeInterval) {165            self.corners = corners; self.quality = quality; self.time = time166        }167    }168169    public var minBrightness = 65.0170    public var maxBrightness = 225.0171    public var minSharpness = 70.0172    /// Minimum share of the frame the document must cover.173    public var minArea = 0.22174    /// Maximum corner movement between two frames (normalised units) to be considered steady.175    public var maxMotion = 0.02176    /// Time the document must stay steady and sharp before the automatic capture.177    public var steadyDuration: TimeInterval = 0.9178179    private var lastCorners: [(x: Double, y: Double)]?180    private var steadySince: TimeInterval?181182    public init() {}183184    public mutating func reset() { lastCorners = nil; steadySince = nil }185186    public mutating func update(_ o: Observation) -> DocumentHint {187        defer { lastCorners = o.corners }188        if o.quality.brightness < minBrightness { steadySince = nil; return .tooDark }189        if o.quality.brightness > maxBrightness { steadySince = nil; return .tooBright }190        guard let c = o.corners, c.count == 4 else { steadySince = nil; return .searching }191        if DocumentGuide.area(c) < minArea { steadySince = nil; return .moveCloser }192        let motion = lastCorners.map { prev in zip(prev, c).map { abs($0.x - $1.x) + abs($0.y - $1.y) }.max() ?? 1 } ?? 1193        if motion > maxMotion { steadySince = nil; return .holdSteady }194        if o.quality.sharpness < minSharpness { steadySince = nil; return .blurry }195        if steadySince == nil { steadySince = o.time }196        return o.time - (steadySince ?? o.time) >= steadyDuration ? .ready : .holdSteady197    }198199    /// Area of a quadrilateral (shoelace formula), corners in order around the shape.200    static func area(_ c: [(x: Double, y: Double)]) -> Double {201        var a = 0.0202        for i in 0..<c.count {203            let p = c[i], q = c[(i + 1) % c.count]204            a += p.x * q.y - q.x * p.y205        }206        return abs(a) / 2207    }208}209210// MARK: - Head pose211212public enum HeadPose {213    /// Yaw index used by the server: horizontal offset of the nose from the midpoint of the eyes, in interocular214    /// distances, measured in the unmirrored image with x growing to the right. Positive when the person turns215    /// to their own left.216    public static func yaw(eyeA: (x: Double, y: Double), eyeB: (x: Double, y: Double), nose: (x: Double, y: Double)) -> Double {217        let iod = ((eyeA.x - eyeB.x) * (eyeA.x - eyeB.x) + (eyeA.y - eyeB.y) * (eyeA.y - eyeB.y)).squareRoot() + 1e-6218        return (nose.x - (eyeA.x + eyeB.x) / 2) / iod219    }220}221222// MARK: - Liveness guidance223224public enum LivenessInstruction: Equatable, Sendable {225    case noFace, moveCloser, lookStraight, turnLeft, turnRight, backToCenter, done226227    public var string: IdentityString {228        switch self {229        case .noFace: return .selfieGuideNoFace230        case .moveCloser: return .selfieGuideCloser231        case .lookStraight: return .selfieGuideCenter232        case .turnLeft: return .selfieGuideTurnLeft233        case .turnRight: return .selfieGuideTurnRight234        case .backToCenter: return .selfieGuideBackToCenter235        case .done: return .selfieGuideDone236        }237    }238}239240/// Follows the challenge on the device exactly as the server will check it: centre, then each requested turn241/// followed by a return to the centre. The on-device thresholds are stricter than the server's (turn 0.16,242/// centre 0.07) so that a sequence accepted here leaves a margin there. This is guidance only: the server decides.243public struct LivenessGuide: Sendable {244    public struct FaceSample: Sendable {245        /// Yaw index (see `HeadPose.yaw`).246        public var yaw: Double247        /// Face width in pixels in the frame that will be uploaded.248        public var faceWidth: Double249        public init(yaw: Double, faceWidth: Double) { self.yaw = yaw; self.faceWidth = faceWidth }250    }251252    enum Phase: Equatable { case center, turn(ChallengeStep) }253254    public var turnThreshold = 0.22255    public var centerThreshold = 0.05256    /// Minimum face width in pixels (the server needs about 90).257    public var minFaceWidth = 140.0258    /// Centred frames required when the challenge has no movement (accessible alternative).259    public var accessibleFrames: Int260261    private let phases: [Phase]262    public private(set) var phaseIndex = 0263    private var centeredCount = 0264    /// Indices (in recorded-frame order) of the frames that satisfied each phase.265    public private(set) var keyFrames: [Int] = []266    public let stepCount: Int267268    public init(steps: [ChallengeStep], accessibleFrames: Int = 8) {269        var p: [Phase] = [.center]270        for s in steps { p.append(.turn(s)); p.append(.center) }271        phases = p272        stepCount = steps.count273        self.accessibleFrames = accessibleFrames274    }275276    public var isDone: Bool { phaseIndex >= phases.count }277278    /// 1-based index of the movement in progress, 0 before the first one.279    public var currentMovement: Int { min(stepCount, (phaseIndex + 1) / 2) }280281    /// Instruction to display given only the progress so far.282    public var instruction: LivenessInstruction {283        guard !isDone else { return .done }284        switch phases[phaseIndex] {285        case .center: return phaseIndex == 0 ? .lookStraight : .backToCenter286        case .turn(.turnLeft): return .turnLeft287        case .turn(.turnRight): return .turnRight288        case .turn(.unknown): return .lookStraight289        }290    }291292    /// Feeds the analysis of the frame that was just recorded.293    /// - Parameters:294    ///   - sample: nil when no face is visible.295    ///   - frameIndex: index of this frame among the recorded frames, or nil when the frame was analysed but not recorded.296    public mutating func update(_ sample: FaceSample?, frameIndex: Int?) -> LivenessInstruction {297        guard !isDone else { return .done }298        guard let s = sample else { return .noFace }299        if s.faceWidth < minFaceWidth { return .moveCloser }300        guard let frameIndex else { return instruction }301        switch phases[phaseIndex] {302        case .center:303            if abs(s.yaw) < centerThreshold {304                if stepCount == 0 {305                    centeredCount += 1306                    keyFrames.append(frameIndex)307                    if centeredCount >= accessibleFrames { phaseIndex += 1 }308                } else {309                    keyFrames.append(frameIndex)310                    phaseIndex += 1311                }312            }313        case .turn(let step):314            let ok: Bool315            switch step {316            case .turnLeft: ok = s.yaw > turnThreshold317            case .turnRight: ok = s.yaw < -turnThreshold318            case .unknown: ok = true319            }320            if ok { keyFrames.append(frameIndex); phaseIndex += 1 }321        }322        return instruction323    }324}325326// MARK: - Frame selection327328public enum FrameSelector {329    /// Chooses at most `max` of `count` recorded frames, in order: every key frame is kept and the remaining330    /// places are spread evenly over the other frames, so that the motion stays continuous.331    public static func select(count: Int, keyFrames: [Int], max: Int) -> [Int] {332        guard count > 0, max > 0 else { return [] }333        if count <= max { return Array(0..<count) }334        var chosen = Set(keyFrames.filter { $0 >= 0 && $0 < count }.prefix(max))335        let free = max - chosen.count336        if free > 0 {337            let others = (0..<count).filter { !chosen.contains($0) }338            if others.count <= free {339                chosen.formUnion(others)340            } else {341                for i in 0..<free {342                    let pos = free == 1 ? 0 : Int((Double(i) * Double(others.count - 1) / Double(free - 1)).rounded())343                    chosen.insert(others[pos])344                }345                // Rounding may pick the same frame twice; top up with the first unused frames.346                var it = others.makeIterator()347                while chosen.count < max, let next = it.next() { chosen.insert(next) }348            }349        }350        return chosen.sorted()351    }352}353
Files main
Menu

Theme