SPB Git

Repository Public

VisionPreprocessorTests.swift 11.7 KB 211 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Astra9// File             : Tests/AstraLocalTests/VisionPreprocessorTests.swift10// Module           : AstraLocalTests11// Repository       : https://git.spboucher.ai/orix-astra12// Created          : 2026-11-2213// Last Modified    : 2026-11-2214//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import AstraCore89import CoreGraphics90import Foundation91import ImageIO92import Testing93@testable import AstraLocal9495@Suite struct VisionPreprocessorTests {96    /// A w × h image whose left half is red and right half is blue, encoded with the given EXIF orientation.97    static func halves(_ width: Int, _ height: Int, type: String = "public.jpeg", orientation: Int? = nil) throws -> Data {98        let c = try #require(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, bytesPerRow: 0, space: CGColorSpaceCreateDeviceRGB(),99                                       bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))100        c.setFillColor(red: 1, green: 0, blue: 0, alpha: 1); c.fill(CGRect(x: 0, y: 0, width: width / 2, height: height))101        c.setFillColor(red: 0, green: 0, blue: 1, alpha: 1); c.fill(CGRect(x: width / 2, y: 0, width: width - width / 2, height: height))102        let image = try #require(c.makeImage())103        var properties: [CFString: Any] = [kCGImageDestinationLossyCompressionQuality: 0.95]104        if let orientation { properties[kCGImagePropertyOrientation] = orientation }105        return try #require(VisionTestImages.encode(image, type: type, properties: properties))106    }107108    /// RGB of one pixel, origin at the top left.109    static func pixel(_ image: CGImage, x: Int, y: Int) throws -> (r: Int, g: Int, b: Int) {110        var bytes = [UInt8](repeating: 0, count: 4)111        let c = try #require(CGContext(data: &bytes, width: 1, height: 1, bitsPerComponent: 8, bytesPerRow: 4, space: CGColorSpaceCreateDeviceRGB(),112                                       bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue))113        c.draw(image, in: CGRect(x: -x, y: -(image.height - 1 - y), width: image.width, height: image.height))114        return (Int(bytes[0]), Int(bytes[1]), Int(bytes[2]))115    }116117    let limits = VisionLimits(maxLongSide: 512, maxPixels: 512 * 512, maxImages: 2)118119    @Test func targetSizeKeepsTheAspectRatioAndNeverEnlarges() {120        let p = VisionPreprocessor(limits: limits)121        #expect(p.targetSize(width: 4000, height: 3000) == (512, 384))122        #expect(p.targetSize(width: 3000, height: 4000) == (384, 512))123        #expect(p.targetSize(width: 200, height: 100) == (200, 100))124        #expect(p.targetSize(width: 0, height: 10) == (0, 0))125        // The pixel budget binds before the long side for a near-square image.126        let tight = VisionPreprocessor(limits: VisionLimits(maxLongSide: 2000, maxPixels: 250_000, maxImages: 1))127        let s = tight.targetSize(width: 2000, height: 2000)128        #expect(s.width == 500 && s.height == 500)129        let wide = tight.targetSize(width: 4000, height: 1000)130        #expect(wide.width * wide.height <= 250_000 && abs(Double(wide.width) / Double(wide.height) - 4) < 0.05)131    }132133    @Test func aLargeImageIsDecodedAtTheBoundedSize() throws {134        let data = try Self.halves(2400, 1200)135        let out = try VisionPreprocessor(limits: limits).prepare(data)136        #expect(out.originalWidth == 2400 && out.originalHeight == 1200)137        #expect(out.width == 512 && out.height == 256 && out.wasDownscaled)138        let left = try Self.pixel(out.image, x: 40, y: 128), right = try Self.pixel(out.image, x: 470, y: 128)139        #expect(left.r > 200 && left.b < 60 && right.b > 200 && right.r < 60)140    }141142    @Test func aSmallImageIsLeftAtItsSize() throws {143        let out = try VisionPreprocessor(limits: limits).prepare(try Self.halves(96, 64, type: "public.png"))144        #expect(out.width == 96 && out.height == 64 && !out.wasDownscaled)145    }146147    @Test func exifOrientationIsApplied() throws {148        // Orientation 6: the stored pixels must be rotated 90° clockwise to be upright. Stored left (red) becomes the top.149        let data = try Self.halves(800, 400, orientation: 6)150        let out = try VisionPreprocessor(limits: limits).prepare(data)151        #expect(out.originalWidth == 400 && out.originalHeight == 800, "the reported size is the upright one")152        #expect(out.width == 256 && out.height == 512)153        let top = try Self.pixel(out.image, x: 128, y: 40), bottom = try Self.pixel(out.image, x: 128, y: 470)154        #expect(top.r > 200 && top.b < 60 && bottom.b > 200 && bottom.r < 60)155        // Orientation 3 (upside down): left and right swap, the size does not.156        let flipped = try VisionPreprocessor(limits: limits).prepare(try Self.halves(800, 400, orientation: 3))157        #expect(flipped.width == 512 && flipped.height == 256)158        let l = try Self.pixel(flipped.image, x: 40, y: 128)159        #expect(l.b > 200 && l.r < 60)160    }161162    @Test func undecodableAndEmptyDataAreTypedErrors() {163        let p = VisionPreprocessor(limits: limits)164        #expect(throws: VisionInputError.undecodable(index: 3)) { try p.prepare(Data("not an image".utf8), index: 3) }165        #expect(throws: VisionInputError.emptyImage(index: 1)) { try p.prepare(Data()) }166        #expect(VisionInputError.undecodable(index: 3).astraError == .invalidRequest("Image 3 could not be decoded."))167    }168169    @Test func imageCountIsCheckedAgainstTheModel() throws {170        try VisionPreprocessor.check(imageCount: 0, limits: nil, modelID: "text")171        try VisionPreprocessor.check(imageCount: 2, limits: limits, modelID: "vlm")172        #expect(throws: VisionInputError.modelCannotReadImages(modelID: "text")) { try VisionPreprocessor.check(imageCount: 1, limits: nil, modelID: "text") }173        #expect(throws: VisionInputError.tooManyImages(sent: 3, limit: 2, modelID: "vlm")) { try VisionPreprocessor.check(imageCount: 3, limits: limits, modelID: "vlm") }174        let textOnly = VisionInputError.modelCannotReadImages(modelID: "Qwen3-4B-4bit").astraError175        #expect(textOnly == .unsupported("This model cannot read images."), "the sentence build 2 shipped is kept")176        #expect(VisionInputError.modelCannotReadImages(modelID: "Qwen3-4B-4bit").errorDescription == "“Qwen3-4B-4bit” is a text-only model and cannot read images. Choose a vision model or remove the image.")177        let one = VisionInputError.tooManyImages(sent: 2, limit: 1, modelID: "SmolVLM2").astraError178        #expect(one == .unsupported("“SmolVLM2” reads one image per conversation, and 2 were sent. Keep one image."))179    }180181    @Test func severalImagesKeepTheirOrderAndIndexErrors() throws {182        let p = VisionPreprocessor(limits: limits)183        let a = ImageInput(data: try Self.halves(100, 50, type: "public.png"), mimeType: "image/png")184        let b = ImageInput(data: try Self.halves(60, 120, type: "public.png"), mimeType: "image/png")185        let out = try p.prepare([a, b])186        #expect(out.map(\.width) == [100, 60] && out.map(\.height) == [50, 120])187        #expect(throws: VisionInputError.undecodable(index: 5)) { try p.prepare([a, ImageInput(data: Data([1, 2, 3]))], startIndex: 4) }188    }189190    @Test func generatedTestImagesDecodeWithTheirKnownContent() throws {191        let p = VisionPreprocessor(limits: VisionLimits(maxLongSide: 2048, maxPixels: 4 << 20, maxImages: 1))192        let red = try p.prepare(try #require(VisionTestImages.solid(VisionTestImages.red)))193        #expect(red.width == 384 && red.height == 384)194        let centre = try Self.pixel(red.image, x: 192, y: 192)195        #expect(centre.r > 200 && centre.g < 40 && centre.b < 40)196        let chart = try p.prepare(try #require(VisionTestImages.chart()))197        #expect(chart.width == 768 && chart.height == 512)198        // Bar C (87 of 100) is drawn in blue where bar D (12) leaves the page white at the same height.199        let slot = (768.0 - 120) / 4200        let barC = try Self.pixel(chart.image, x: Int(70 + 2 * slot + slot * 0.3), y: 512 - 70 - 150)201        let aboveD = try Self.pixel(chart.image, x: Int(70 + 3 * slot + slot * 0.3), y: 512 - 70 - 150)202        #expect(barC.b > 150 && barC.r < 90 && aboveD.r > 240 && aboveD.g > 240)203        let page = try p.prepare(try #require(VisionTestImages.textPage()))204        // Text was really drawn: the page is not blank.205        var dark = 0206        for x in stride(from: 50, to: 700, by: 3) { for y in stride(from: 60, to: 140, by: 3) { if try Self.pixel(page.image, x: x, y: y).r < 80 { dark += 1 } } }207        #expect(dark > 50)208        #expect(VisionTestImages.chartBars.max { $0.value < $1.value }?.label == "C" && VisionTestImages.pageLines[0].contains("4812"))209    }210}211
Files main
Menu

Theme