SPB Git

Repository Public License

EngineTests.swift 9.2 KB 201 lines swift

1// ORIX Scan2// File: Packages/ORIXKit/Tests/ORIXKitTests/EngineTests.swift3// Description: Unit tests of the pure engines: geometry, metrics, reading order, table reconstruction, quality heuristics, rename tokens.4//5// Author: Simon-Pierre Boucher6// Contact: contact@spboucher.ai7import CoreGraphics8import Foundation9import Testing10@testable import ORIXKit1112@Suite struct GeometryTests {13    @Test func fullQuadIsValidAndFull() {14        #expect(Quad.full.isValid)15        #expect(Quad.full.isFull)16        #expect(abs(Quad.full.area - 1) < 1e-9)17        #expect(Quad.full.perspectiveDistortion() < 1e-9)18    }1920    @Test func crossedQuadIsInvalid() {21        let q = Quad(topLeft: CGPoint(x: 0.1, y: 0.1), topRight: CGPoint(x: 0.9, y: 0.9), bottomRight: CGPoint(x: 0.9, y: 0.1), bottomLeft: CGPoint(x: 0.1, y: 0.9))22        #expect(!q.isValid)23    }2425    @Test func trapezoidReportsPerspective() {26        let q = Quad(topLeft: CGPoint(x: 0.3, y: 0.1), topRight: CGPoint(x: 0.7, y: 0.1), bottomRight: CGPoint(x: 0.95, y: 0.9), bottomLeft: CGPoint(x: 0.05, y: 0.9))27        #expect(q.isValid)28        #expect(q.perspectiveDistortion() > 0.4)29    }3031    @Test func fourQuarterTurnsAreIdentity() {32        let q = Quad(rect: CGRect(x: 0.1, y: 0.2, width: 0.5, height: 0.3))33        #expect(q.rotated(quarterTurns: 4).isClose(to: q, tolerance: 1e-9))34        let once = q.rotated(quarterTurns: 1)35        #expect(abs(once.bounds.width - 0.3) < 1e-9 && abs(once.bounds.height - 0.5) < 1e-9)36        #expect(once.isValid)37    }3839    @Test func cacheKeyIsStableAndSensitive() {40        let a = PageEdit(), b = PageEdit()41        #expect(a.cacheKey == b.cacheKey)42        var c = a43        c.contrast = 0.244        #expect(c.cacheKey != a.cacheKey)45        #expect(c.geometryKey == a.geometryKey)46        c.quarterTurns = 147        #expect(c.geometryKey != a.geometryKey)48        var d = a49        d.quarterTurns = 450        #expect(d.geometryKey == a.geometryKey)51    }52}5354@Suite struct TextMetricsTests {55    @Test func identicalTextHasZeroError() {56        #expect(TextMetrics.characterErrorRate(reference: "Bonjour le monde", hypothesis: "Bonjour  le\nmonde") == 0)57        #expect(TextMetrics.wordErrorRate(reference: "a b c", hypothesis: "a b c") == 0)58    }5960    @Test func knownDistances() {61        #expect(TextMetrics.editDistance(Array("kitten"), Array("sitting")) == 3)62        #expect(abs(TextMetrics.characterErrorRate(reference: "abcd", hypothesis: "abxd") - 0.25) < 1e-9)63        #expect(abs(TextMetrics.wordErrorRate(reference: "one two three four", hypothesis: "one too three") - 0.5) < 1e-9)64        #expect(TextMetrics.characterErrorRate(reference: "", hypothesis: "x") == 1)65    }6667    @Test func composedAndDecomposedAccentsMatch() {68        #expect(TextMetrics.characterErrorRate(reference: "é", hypothesis: "e\u{301}") == 0)69    }70}7172@Suite struct ReadingOrderTests {73    private func line(_ text: String, _ x: CGFloat, _ y: CGFloat, w: CGFloat = 0.35, h: CGFloat = 0.02) -> OCRLine {74        OCRLine(text: text, confidence: 1, quad: Quad(rect: CGRect(x: x, y: y, width: w, height: h)))75    }7677    @Test func twoColumnsAreReadColumnByColumn() {78        let lines = [line("R1", 0.55, 0.10), line("L2", 0.08, 0.14), line("L1", 0.08, 0.10), line("R2", 0.55, 0.14), line("L3", 0.08, 0.18), line("R3", 0.55, 0.18)]79        #expect(ReadingOrder.sorted(lines).map(\.text) == ["L1", "L2", "L3", "R1", "R2", "R3"])80    }8182    @Test func fullWidthTitleComesBeforeColumns() {83        let lines = [line("L1", 0.08, 0.20), line("R1", 0.55, 0.20), line("Title", 0.08, 0.05, w: 0.84), line("L2", 0.08, 0.24), line("R2", 0.55, 0.24)]84        #expect(ReadingOrder.sorted(lines).map(\.text) == ["Title", "L1", "L2", "R1", "R2"])85    }8687    @Test func singleColumnKeepsTopToBottomAndSplitsParagraphs() {88        let lines = [line("c", 0.1, 0.30, w: 0.8), line("a", 0.1, 0.10, w: 0.8), line("b", 0.1, 0.13, w: 0.8)]89        #expect(ReadingOrder.sorted(lines).map(\.text) == ["a", "b", "c"])90        #expect(ReadingOrder.paragraphs(lines).count == 2)91    }92}9394@Suite struct TableExtractorTests {95    private func page(_ rows: [[String]], xs: [CGFloat]) -> OCRPage {96        var lines: [OCRLine] = []97        for (r, row) in rows.enumerated() {98            for (c, cell) in row.enumerated() where !cell.isEmpty {99                let width = CGFloat(cell.count) * 0.011100                let quad = Quad(rect: CGRect(x: xs[c], y: 0.1 + CGFloat(r) * 0.05, width: width, height: 0.02))101                lines.append(OCRLine(text: cell, confidence: 0.95, quad: quad, words: [OCRWord(text: cell, quad: quad)]))102            }103        }104        return OCRPage(imageWidth: 1000, imageHeight: 1000, lines: lines, mode: .accurate, languages: [])105    }106107    @Test func reconstructsRegularGrid() {108        let rows = [["Item", "Qty", "Price"], ["Paper", "2", "4.50"], ["Ink", "1", "19.99"], ["Stapler", "3", "7.25"]]109        let tables = TableExtractor.extract(from: page(rows, xs: [0.1, 0.45, 0.7]))110        #expect(tables.count == 1)111        #expect(tables.first?.rows == rows)112        #expect(tables.first?.uncertainCells.isEmpty == true)113        #expect((tables.first?.confidence ?? 0) > 0.9)114    }115116    @Test func emptyCellsStayInTheirColumn() {117        let rows = [["Name", "Mon", "Tue"], ["Ana", "", "x"], ["Bo", "x", ""], ["Cy", "x", "x"]]118        let table = TableExtractor.extract(from: page(rows, xs: [0.1, 0.45, 0.7])).first119        #expect(table?.rows == rows)120        #expect((table?.confidence ?? 1) < 0.9)121    }122123    @Test func plainParagraphIsNotATable() {124        let lines = (0..<5).map { OCRLine(text: "A full line of ordinary prose number \($0)", confidence: 1, quad: Quad(rect: CGRect(x: 0.1, y: 0.1 + CGFloat($0) * 0.04, width: 0.8, height: 0.02))) }125        let page = OCRPage(imageWidth: 1000, imageHeight: 1000, lines: lines, mode: .accurate, languages: [])126        #expect(TableExtractor.extract(from: page).isEmpty)127    }128129    @Test func csvEscapesSeparatorsAndQuotes() {130        let table = ExtractedTable(rows: [["a,b", "say \"hi\""], ["plain", "line\nbreak"]], confidence: 1, bounds: .zero)131        #expect(table.csv == "\"a,b\",\"say \"\"hi\"\"\"\r\nplain,\"line\nbreak\"\r\n")132    }133}134135@Suite struct QualityTests {136    @Test func sharpPageIsClean() {137        let report = QualityAnalyzer.analyze(Fixture.page(Fixture.english))138        #expect(report.issues.isEmpty, "\(report)")139    }140141    @Test func blurredPageIsFlagged() {142        let report = QualityAnalyzer.analyze(Fixture.blurred(Fixture.page(Fixture.english), radius: 7))143        #expect(report.issues.contains(.blur), "\(report)")144    }145146    @Test func faintPageIsLowContrast() {147        let report = QualityAnalyzer.analyze(Fixture.page(Fixture.english, background: 0.8, ink: 0.66))148        #expect(report.issues.contains(.lowContrast), "\(report)")149    }150151    @Test func darkPageIsFlagged() {152        let report = QualityAnalyzer.analyze(Fixture.page(Fixture.english, background: 0.22, ink: 0.0))153        #expect(report.issues.contains(.tooDark), "\(report)")154    }155156    @Test func smallImageIsLowResolution() {157        let report = QualityAnalyzer.analyze(Fixture.page("Tiny", width: 500, height: 700, fontSize: 20, margin: 30))158        #expect(report.issues.contains(.lowResolution))159    }160161    @Test func textTouchingEdgeIsCropped() {162        let line = OCRLine(text: "cut off", confidence: 0.9, quad: Quad(rect: CGRect(x: 0, y: 0.5, width: 0.3, height: 0.03)))163        let ocr = OCRPage(imageWidth: 1654, imageHeight: 2339, lines: [line], mode: .fast, languages: [])164        #expect(QualityAnalyzer.analyze(Fixture.page(Fixture.english), ocr: ocr).issues.contains(.croppedText))165    }166}167168@Suite struct WorkflowModelTests {169    @Test func renameTokens() {170        let date = Date(timeIntervalSince1970: 1_795_000_000) // 2026-11-18 11:06:40 UTC171        let title = WorkflowEngine.resolve(pattern: "Receipt {date} {time} ({pages}p) {title}", title: "Scan", pageCount: 3, now: date, timeZone: TimeZone(identifier: "UTC")!)172        #expect(title == "Receipt 2026-11-18 11.06 (3p) Scan")173    }174175    @Test func presetsAreValidAndStable() {176        #expect(Workflow.presets.count == 8)177        #expect(Set(Workflow.presets.map(\.id)).count == 8)178        for preset in Workflow.presets { #expect(preset.validationIssues.isEmpty, "\(preset.name)") }179        #expect(Workflow.presets.map(\.name) == ["Scan to PDF", "Scan to Searchable PDF", "Receipt Archive", "Document Cleanup", "Book Scanner", "Extract Text", "Extract Tables", "Compress PDF"])180    }181182    @Test func validationCatchesEmptyParameters() {183        #expect(Workflow(name: "Empty").validationIssues == [.noSteps])184        let step = ActionStep(.moveToFolder, folderName: " ")185        #expect(Workflow(name: "x", steps: [step]).validationIssues == [.missingFolder(step.id)])186    }187188    @Test func workflowsRoundTripThroughJSON() throws {189        for preset in Workflow.presets {190            let decoded = try JSONDecoder().decode(Workflow.self, from: JSONEncoder().encode(preset))191            #expect(decoded == preset)192        }193    }194195    @Test func safeFileNames() {196        #expect(DocumentProcessor.safeFileName("Reçu d'épicerie / été: 2026?") == "Reçu d'épicerie   été  2026")197        #expect(DocumentProcessor.safeFileName("...") == "Document")198        #expect(DocumentProcessor.safeFileName("日本語の書類") == "日本語の書類")199    }200}201
Files main
Menu

Theme