SPB Git

Repository Public

VisionAnalysis.swift 7.7 KB 152 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Sources/MacLustrIdentityUI/VisionAnalysis.swift10// Module           : MacLustrIdentityUI11// 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// On-device Vision analysis used only to guide the capture. Nothing computed here is uploaded, stored or logged.89import CoreVideo90import Foundation91import Vision92import MacLustrIdentityCore9394enum VisionAnalysis {95    /// Corners of the most likely document in the frame, in normalised coordinates, in order around the shape.96    static func documentCorners(in pixelBuffer: CVPixelBuffer) -> [(x: Double, y: Double)]? {97        documentCorners(VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .up, options: [:]))98    }99100    static func documentCorners(in image: CGImage) -> [(x: Double, y: Double)]? {101        documentCorners(VNImageRequestHandler(cgImage: image, orientation: .up, options: [:]))102    }103104    private static func documentCorners(_ handler: VNImageRequestHandler) -> [(x: Double, y: Double)]? {105        let request = VNDetectDocumentSegmentationRequest()106        guard (try? handler.perform([request])) != nil, let r = request.results?.first, r.confidence > 0.5 else { return nil }107        return [r.topLeft, r.topRight, r.bottomRight, r.bottomLeft].map { (Double($0.x), Double($0.y)) }108    }109110    /// Head pose of the largest face, with the same yaw index as the server (see `HeadPose.yaw`).111    /// - Parameter uploadScale: factor applied to the frame before upload, so that the face width is expressed in uploaded pixels.112    static func faceSample(in pixelBuffer: CVPixelBuffer, uploadScale: Double) -> LivenessGuide.FaceSample? {113        let size = CGSize(width: CVPixelBufferGetWidth(pixelBuffer), height: CVPixelBufferGetHeight(pixelBuffer))114        return faceSample(VNImageRequestHandler(cvPixelBuffer: pixelBuffer, orientation: .up, options: [:]), imageSize: size, uploadScale: uploadScale)115    }116117    static func faceSample(in image: CGImage, uploadScale: Double = 1) -> LivenessGuide.FaceSample? {118        faceSample(VNImageRequestHandler(cgImage: image, orientation: .up, options: [:]), imageSize: CGSize(width: image.width, height: image.height), uploadScale: uploadScale)119    }120121    private static func faceSample(_ handler: VNImageRequestHandler, imageSize: CGSize, uploadScale: Double) -> LivenessGuide.FaceSample? {122        let request = VNDetectFaceLandmarksRequest()123        guard (try? handler.perform([request])) != nil,124              let face = request.results?.max(by: { $0.boundingBox.width * $0.boundingBox.height < $1.boundingBox.width * $1.boundingBox.height }),125              let marks = face.landmarks else { return nil }126        // Vision image coordinates: origin at the bottom left, x growing to the right as in the image itself.127        func centre(_ region: VNFaceLandmarkRegion2D?) -> (x: Double, y: Double)? {128            guard let pts = region?.pointsInImage(imageSize: imageSize), !pts.isEmpty else { return nil }129            let n = Double(pts.count)130            return (pts.reduce(0) { $0 + Double($1.x) } / n, pts.reduce(0) { $0 + Double($1.y) } / n)131        }132        // Eye and nose-outline centres: on frontal portraits this combination is the closest to the index the133        // server derives from its own landmark model (see VisionAndImageTests).134        guard let eyeA = centre(marks.leftEye), let eyeB = centre(marks.rightEye), let nose = centre(marks.nose) else { return nil }135        let width = Double(face.boundingBox.width * imageSize.width) * uploadScale136        return LivenessGuide.FaceSample(yaw: HeadPose.yaw(eyeA: eyeA, eyeB: eyeB, nose: nose), faceWidth: width)137    }138139    /// Number of characters Vision can read on the captured document. Used only as a capture-quality signal:140    /// the recognised text never leaves this function.141    static func readableCharacterCount(in image: CGImage) -> Int {142        let request = VNRecognizeTextRequest()143        request.recognitionLevel = .fast144        request.usesLanguageCorrection = false145        guard (try? VNImageRequestHandler(cgImage: image, orientation: .up, options: [:]).perform([request])) != nil else { return 0 }146        return (request.results ?? []).reduce(0) { total, observation in147            guard let best = observation.topCandidates(1).first, best.confidence >= 0.3 else { return total }148            return total + best.string.count149        }150    }151}152
Files main
Menu

Theme