SPB Git

Repository Public

VisionAndImageTests.swift 14.5 KB 267 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : MacLustr Identity9// File             : sdk/swift/Tests/MacLustrIdentityUITests/VisionAndImageTests.swift10// Module           : MacLustrIdentityUITests11// 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 CoreImage89import ImageIO90import SwiftUI91import XCTest92@testable import MacLustrIdentityUI9394/// Runs the on-device analysis on the repository's fictional documents and public-domain portraits95/// (tests/fixtures). Skipped when the package is used outside the repository.96final class VisionAndImageTests: XCTestCase {97    private func fixture(_ name: String, file: StaticString = #filePath) throws -> Data {98        var url = URL(fileURLWithPath: "\(file)")99        for _ in 0..<5 { url.deleteLastPathComponent() }        // …/sdk/swift/Tests/Target/File → repository root100        url.appendPathComponent("tests/fixtures/\(name)")101        guard let data = try? Data(contentsOf: url) else { throw XCTSkip("fixture \(name) not found at \(url.path)") }102        return data103    }104105    private func image(_ name: String) throws -> CGImage {106        let src = CGImageSourceCreateWithData(try fixture(name) as CFData, nil)!107        return CGImageSourceCreateImageAtIndex(src, 0, nil)!108    }109110    private func pixelBuffer(_ image: CGImage) -> CVPixelBuffer {111        var pb: CVPixelBuffer?112        CVPixelBufferCreate(nil, image.width, image.height, kCVPixelFormatType_32BGRA, [kCVPixelBufferCGImageCompatibilityKey: true, kCVPixelBufferCGBitmapContextCompatibilityKey: true] as CFDictionary, &pb)113        CVPixelBufferLockBaseAddress(pb!, [])114        let ctx = CGContext(data: CVPixelBufferGetBaseAddress(pb!), width: image.width, height: image.height, bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(pb!),115                            space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)!116        ctx.draw(image, in: CGRect(x: 0, y: 0, width: image.width, height: image.height))117        CVPixelBufferUnlockBaseAddress(pb!, [])118        return pb!119    }120121    /// Yaw index measured by the server engine (YuNet landmarks) on the same portraits.122    private let serverYaw: [String: Double] = ["a1.jpg": -0.016, "a2.jpg": 0.033, "b1.jpg": 0.124, "b2.jpg": 0.070]123124    func testYawIndexOnFrontalPortraitsIsCloseToTheServerIndex() throws {125        for (name, expected) in serverYaw.sorted(by: { $0.key < $1.key }) {126            let img = try image(name)127            let sample = try XCTUnwrap(VisionAnalysis.faceSample(in: img), name)128            print("yaw \(name): device \(String(format: "%.3f", sample.yaw)) server \(expected) faceWidth \(Int(sample.faceWidth))")129            XCTAssertEqual(sample.yaw, expected, accuracy: 0.06, name)130            XCTAssertGreaterThan(sample.faceWidth, 100, name)131        }132    }133134    func testYawSignFlipsWithTheImage() throws {135        // Mirroring a portrait must flip the sign of the yaw index: the SDK measures unmirrored frames.136        let img = try image("b1.jpg")137        let ci = CIImage(cgImage: img)138        let flipped = ci.transformed(by: CGAffineTransform(scaleX: -1, y: 1).translatedBy(x: -ci.extent.width, y: 0))139        let mirrored = try XCTUnwrap(CIContext().createCGImage(flipped, from: flipped.extent))140        let a = try XCTUnwrap(VisionAnalysis.faceSample(in: img)).yaw, b = try XCTUnwrap(VisionAnalysis.faceSample(in: mirrored)).yaw141        XCTAssertEqual(a, -b, accuracy: 0.06)142    }143144    func testFaceSampleFromPixelBufferAppliesTheUploadScale() throws {145        let img = try image("a2.jpg")146        let full = try XCTUnwrap(VisionAnalysis.faceSample(in: img))147        let half = try XCTUnwrap(VisionAnalysis.faceSample(in: pixelBuffer(img), uploadScale: 0.5))148        XCTAssertEqual(half.faceWidth, full.faceWidth / 2, accuracy: full.faceWidth * 0.1)149        XCTAssertEqual(half.yaw, full.yaw, accuracy: 0.05)150    }151152    func testDocumentIsFoundInTheScenes() throws {153        for name in ["licence_front_scene.jpg", "passport_scene.jpg"] {154            let corners = try XCTUnwrap(VisionAnalysis.documentCorners(in: try image(name)), name)155            XCTAssertEqual(corners.count, 4)156            var guide = DocumentGuide()157            let q = LumaQuality(brightness: 150, contrast: 60, sharpness: 400)158            _ = guide.update(.init(corners: corners, quality: q, time: 0))159            XCTAssertEqual(guide.update(.init(corners: corners, quality: q, time: 0.1)), .holdSteady, name)160            XCTAssertEqual(guide.update(.init(corners: corners, quality: q, time: 1.2)), .ready, name)161        }162        XCTAssertNil(VisionAnalysis.documentCorners(in: try image("a1.jpg")))163    }164165    func testLumaQualityOfAFrameIsCloseToTheServerMeasure() throws {166        // Server (OpenCV) on licence_front_scene.jpg: brightness 152.1, contrast 68.8, sharpness 426.4.167        let q = try XCTUnwrap(ImageUtilities.lumaQuality(of: pixelBuffer(try image("licence_front_scene.jpg"))))168        print("luma licence_front_scene: \(q)")169        XCTAssertEqual(q.brightness, 152.1, accuracy: 6)170        XCTAssertEqual(q.contrast, 68.8, accuracy: 6)171        XCTAssertGreaterThan(q.sharpness, 70)172    }173174    func testTextQualitySignal() throws {175        XCTAssertGreaterThan(VisionAnalysis.readableCharacterCount(in: try image("passport_scene.jpg")), 40)176        // A heavily blurred document has little readable text.177        let ci = CIImage(cgImage: try image("passport_scene.jpg"))178        let blurred = ci.clampedToExtent().applyingGaussianBlur(sigma: 28).cropped(to: ci.extent)179        let img = try XCTUnwrap(CIContext().createCGImage(blurred, from: ci.extent))180        XCTAssertLessThan(VisionAnalysis.readableCharacterCount(in: img), 12)181    }182183    func testNormalizedJPEGIsBoundedAndStripped() throws {184        let data = try fixture("passport_scene.jpg")185        let out = try XCTUnwrap(ImageUtilities.normalizedJPEG(from: data, maxSide: 1000))186        XCTAssertEqual(Array(out.jpeg.prefix(3)), [0xFF, 0xD8, 0xFF])187        XCTAssertEqual(max(out.image.width, out.image.height), 1000)188        let src = CGImageSourceCreateWithData(out.jpeg as CFData, nil)!189        let props = CGImageSourceCopyPropertiesAtIndex(src, 0, nil) as! [CFString: Any]190        XCTAssertNil(props[kCGImagePropertyGPSDictionary])191        XCTAssertNil(props[kCGImagePropertyExifDictionary].flatMap { ($0 as? [CFString: Any])?[kCGImagePropertyExifDateTimeOriginal] })192        XCTAssertNil(ImageUtilities.normalizedJPEG(from: Data("<html>".utf8)))193    }194195    /// A synthetic photo of the given size, detailed enough for the JPEG not to be tiny.196    private func syntheticPhoto(width: Int, height: Int) -> Data {197        let ctx = CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)!198        ctx.setFillColor(CGColor(red: 0.9, green: 0.9, blue: 0.85, alpha: 1))199        ctx.fill(CGRect(x: 0, y: 0, width: width, height: height))200        ctx.setFillColor(CGColor(red: 0.1, green: 0.1, blue: 0.2, alpha: 1))201        for i in stride(from: 0, to: width, by: 16) { ctx.fill(CGRect(x: i, y: (i * 7) % max(1, height - 40), width: 6, height: 40)) }202        return ImageUtilities.jpegData(ctx.makeImage()!, quality: 0.9)!203    }204205    func testDocumentKeepsFullResolutionUpTo3600() throws {206        XCTAssertEqual(ImageUtilities.documentMaxSide, 3600)207        XCTAssertEqual(ImageUtilities.documentQuality, 0.92)208        // A 12 MP still (4032 × 3024) is reduced to 3600 on its long side, no further.209        let big = try XCTUnwrap(ImageUtilities.normalizedJPEG(from: syntheticPhoto(width: 4032, height: 3024)))210        XCTAssertEqual(big.image.width, 3600)211        XCTAssertEqual(big.image.height, 2700)212        XCTAssertLessThanOrEqual(big.jpeg.count, ImageUtilities.documentMaxBytes)213        XCTAssertFalse(ImageUtilities.isLowResolutionDocument(width: big.image.width, height: big.image.height))214        // An image under the limit keeps its size: it is neither reduced nor enlarged.215        let mid = try XCTUnwrap(ImageUtilities.normalizedJPEG(from: syntheticPhoto(width: 3000, height: 2000)))216        XCTAssertEqual(mid.image.width, 3000)217        XCTAssertEqual(mid.image.height, 2000)218        // A 1080p video frame would be warned about: its short side is under 1000 px… as would anything smaller.219        let frame = try XCTUnwrap(ImageUtilities.normalizedJPEG(from: syntheticPhoto(width: 1920, height: 1080)))220        XCTAssertEqual(frame.image.width, 1920)221        XCTAssertFalse(ImageUtilities.isLowResolutionDocument(width: 1920, height: 1080))222        XCTAssertTrue(ImageUtilities.isLowResolutionDocument(width: 1280, height: 720))223        XCTAssertTrue(ImageUtilities.isLowResolutionDocument(width: 999, height: 3000))224        XCTAssertFalse(ImageUtilities.isLowResolutionDocument(width: 1000, height: 1500))225        // Over the byte limit: the quality is lowered, never the resolution.226        let squeezed = try XCTUnwrap(ImageUtilities.normalizedJPEG(from: syntheticPhoto(width: 2000, height: 1500), maxBytes: 60_000))227        XCTAssertEqual(squeezed.image.width, 2000)228        XCTAssertLessThan(squeezed.jpeg.count, mid.jpeg.count)229    }230231    func testStillPhotoSizeSelection() {232        // iPhone main camera in the photo preset: 12 MP and 48 MP → 12 MP is enough for 3600 px.233        let chosen = CameraController.photoDimensions(for: [(8064, 6048), (4032, 3024)])234        XCTAssertEqual(chosen?.0, 4032)235        XCTAssertEqual(chosen?.1, 3024)236        // Nothing reaches 3600 px: the largest available, never a video-sized frame when a bigger still exists.237        let small = CameraController.photoDimensions(for: [(1920, 1080), (3264, 2448), (1280, 720)])238        XCTAssertEqual(small?.0, 3264)239        let exact = CameraController.photoDimensions(for: [(3600, 2700), (4032, 3024)])240        XCTAssertEqual(exact?.0, 3600)241        XCTAssertNil(CameraController.photoDimensions(for: []))242    }243244    func testFrameEncoding() throws {245        let pb = pixelBuffer(try image("a2.jpg"))                       // 960 × 1280246        let jpeg = try XCTUnwrap(ImageUtilities.jpegData(from: pb, maxShortSide: 720, quality: 0.85, context: ImageUtilities.makeContext()))247        let src = CGImageSourceCreateWithData(jpeg as CFData, nil)!248        let img = CGImageSourceCreateImageAtIndex(src, 0, nil)!249        XCTAssertEqual(img.width, 720)250        XCTAssertEqual(img.height, 960)251        XCTAssertLessThan(jpeg.count, 3 * 1024 * 1024)252        // Encoding does not mirror: the face keeps the same yaw sign and magnitude.253        let before = try XCTUnwrap(VisionAnalysis.faceSample(in: try image("b1.jpg"))).yaw254        let b1 = try XCTUnwrap(ImageUtilities.jpegData(from: pixelBuffer(try image("b1.jpg")), maxShortSide: 720, quality: 0.85, context: ImageUtilities.makeContext()))255        let after = try XCTUnwrap(VisionAnalysis.faceSample(in: CGImageSourceCreateImageAtIndex(CGImageSourceCreateWithData(b1 as CFData, nil)!, 0, nil)!)).yaw256        XCTAssertEqual(before, after, accuracy: 0.05)257    }258259    func testHexColours() {260        XCTAssertNotNil(Color(identityHex: "#0A5FFF"))261        XCTAssertNotNil(Color(identityHex: "#abc"))262        XCTAssertNil(Color(identityHex: "blue"))263        XCTAssertNil(Color(identityHex: "#12345"))264        XCTAssertNil(Color(identityHex: nil))265    }266}267
Files main
Menu

Theme