SPB Git

Repository Public License

PresentationTests.swift 18.0 KB 245 lines swift

1// ORIX Convert — Packages/EngineDocuments/Tests/EngineDocumentsTests/PresentationTests.swift2// Description: Presentation paths: PDF, per-slide images, format conversion, text + notes extraction, media3//              extraction, slide subsets, hidden slides, inspection and preflight warnings.4// Author: Simon-Pierre Boucher — contact@spboucher.ai5import Testing6import Foundation7import PDFKit8@testable import EngineDocuments9import ConvertCore1011let presentationPathIDs: [String] = Engines.presentations.paths.map(\.id).sorted()12private let slideWords = ["Aardvark", "ocelot", "pangolin", "Quokka", "Wombat", "Saguenay", "9001"]1314@Suite("Presentation paths")15struct PresentationTests {16    @Test func catalog() {17        #expect(presentationPathIDs.count == 24)18        #expect(!Engines.presentations.paths.contains { $0.destination == .html }, "LibreOffice's slide HTML export was evaluated and dropped")19    }2021    @Test(arguments: presentationPathIDs)22    func declaredPath(_ id: String) async throws {23        let path = try #require(Engines.path(id))24        let fx = try await FixtureStore.shared.get()25        let s = path.source, d = path.destination26        let run = try await convert(try #require(fx.deck[s]), s, d, operation: path.operation)27        #expect(run.failedChecks.isEmpty, "validation: \(run.failedChecks)")28        #expect(!run.checks.isEmpty)29        if path.operation == Operations.mediaExtract {30            let files = try FileManager.default.contentsOfDirectory(at: run.file, includingPropertiesForKeys: nil)31            #expect(files.count >= 1)32            let firstFile = try #require(files.first)33            let size = try #require(Raster.imageSize(firstFile))34            #expect(size.width == 64 && size.height == 48, "the embedded picture keeps its pixels: \(size)")35            return36        }37        switch d {38        case .pdf:39            let pdf = try #require(PDFDocument(url: run.file))40            #expect(pdf.pageCount == 3)41            let text = normalized(pdf.string ?? "")42            for w in slideWords { #expect(text.contains(w.lowercased()), "\(w) on the slides") }43            // Slide order.44            #expect(normalized(pdf.page(at: 0)?.string ?? "").contains("aardvark") && normalized(pdf.page(at: 2)?.string ?? "").contains("wombat"))45            let bounds = try #require(pdf.page(at: 0)).bounds(for: .mediaBox)46            #expect(abs(bounds.width / bounds.height - 28.0 / 15.75) < 0.01, "slide aspect ratio: \(bounds)")47            let f = try facts(run.file, .pdf)48            #expect(f.imageCount >= 1)49            #expect(f.title == "Deck Title Capybara", "title carried: \(f.title ?? "nil")")50        case .png, .jpeg:51            #expect(run.output.files.count == 3)52            #expect(run.output.files.map(\.lastPathComponent) == ["deck-slide-01", "deck-slide-02", "deck-slide-03"].map { $0 + (d == .png ? ".png" : ".jpg") })53            for f in run.output.files {54                let size = try #require(Raster.imageSize(f))55                // LibreOffice's default 16:9 slide, 28 cm × 15.75 cm, at 150 dpi.56                #expect(size.width == 1654 && size.height == 930, "pixel size \(size)")57                let head = try Data(contentsOf: f).prefix(3)58                #expect(d == .png ? head == Data([0x89, 0x50, 0x4E]) : head == Data([0xFF, 0xD8, 0xFF]))59            }60        case .txt, .markdown:61            let text = try String(contentsOf: run.file, encoding: .utf8)62            for w in slideWords + ["narwhal", "axolotl"] { #expect(text.contains(w), "\(w) in the text export") }63            // Order: slide 1 title, its notes, slide 2 title, its notes, slide 3.64            let order = ["Aardvark", "narwhal", "Quokka", "axolotl", "Wombat", "Saguenay"].compactMap { text.range(of: $0)?.lowerBound }65            #expect(order.count == 6 && order == order.sorted(), "slide and note order is exact")66            if d == .markdown {67                #expect(text.contains("## Slide 1\n") && text.contains("| Saguenay | 9001 |") && text.contains("# Deck Title Capybara") && text.contains("> Speaker note one narwhal"))68            } else {69                #expect(text.contains("Slide 3\n") && text.contains("Saguenay\t9001") && text.contains("Notes:\nSpeaker note one narwhal"))70            }71            #expect(run.recorder.has("non-text-dropped") || s == .ppt)72        case .pptx, .odp, .ppt:73            var readable = run.file74            var format = d75            if d == .ppt {76                // Independent check of the binary file: LibreOffice converts it back to PPTX.77                readable = try Fixtures.newDirectory("ppt-roundtrip").appendingPathComponent("back.pptx")78                _ = try await LibreOffice.convert(run.file, filter: "pptx:Impress MS PowerPoint 2007 XML", to: readable, scratch: readable.deletingLastPathComponent())79                format = .pptx80            }81            let f = try PresentationFacts.extract(readable, format: format)82            #expect(f.slides.count == 3)83            #expect(f.slides.map { $0.paragraphs.first ?? "" } == ["Opening Slide Aardvark", "Picture Slide Quokka", "Table Slide Wombat"], "first text of each slide: \(f.slides.map(\.paragraphs))")84            #expect(f.slides[0].notes.joined().contains("narwhal") && f.slides[1].notes.joined().contains("axolotl"), "speaker notes kept")85            #expect(f.slides[2].tables.first?.last == ["Saguenay", "9001"], "table kept as a table: \(f.slides[2].tables)")86            #expect(f.slides[1].imageCount == 1 && f.mediaFiles.count >= 1, "picture kept")87            #expect(f.meta.title == "Deck Title Capybara")88            if let w = f.slideWidth, let h = f.slideHeight { #expect(abs(w / h - 28.0 / 15.75) < 0.01) } else { Issue.record("slide size is readable") }89        default: Issue.record("unexpected destination \(d)")90        }91    }9293    // Regression (2026-11-21): the text export was validated by counting lines starting with "Slide N", so a deck94    // whose body text says "Slide 1 of 3" failed with "slides 3, sections 6".95    @Test(arguments: [FormatID.pptx, .odp])96    func bodyTextThatLooksLikeASlideHeading(_ format: FormatID) async throws {97        let fx = try await FixtureStore.shared.get()98        let dir = try Fixtures.newDirectory("slide-lines")99        let deck = dir.appendingPathComponent("lines.\(format.rawValue)")100        let rule = String(repeating: "-", count: 40)101        func rewrite(_ xml: String) -> String {102            xml.replacingOccurrences(of: "First body line ocelot", with: "Slide 1 of 3")103                .replacingOccurrences(of: "Second body line pangolin", with: "Slide 2: the plan")104                .replacingOccurrences(of: "Speaker note one narwhal", with: "Slide 3")105                .replacingOccurrences(of: "Speaker note two axolotl", with: rule)106        }107        var transforms: [String: (String) -> String] = ["content.xml": rewrite]108        for n in 1...3 { transforms["ppt/slides/slide\(n).xml"] = rewrite; transforms["ppt/notesSlides/notesSlide\(n).xml"] = rewrite }109        try repackage(try #require(fx.deck[format]), to: deck, edits: [:], transform: transforms)110        let facts = try PresentationFacts.extract(deck, format: format)111        #expect(facts.slides.count == 3 && facts.slides[0].paragraphs.contains("Slide 1 of 3") && facts.slides[0].paragraphs.contains("Slide 2: the plan"))112        #expect(facts.slides[0].notes == ["Slide 3"] && facts.slides[1].notes == [rule], "notes: \(facts.slides.map(\.notes))")113114        let txt = try await convert(deck, format, .txt)115        #expect(txt.failedChecks.isEmpty, "txt: \(txt.failedChecks)")116        let text = try String(contentsOf: txt.file, encoding: .utf8)117        #expect(text.contains("\nSlide 1 of 3\n") && text.contains("\nSlide 2: the plan\n") && text.contains("Notes:\nSlide 3\n"))118        #expect(DocumentFacts.regexCount(#"^Slide \d+"#, text, options: [.anchorsMatchLines]) > 3, "the old count would have failed on this text")119        #expect(txt.checks.contains { $0.name == "One section per slide" && $0.detail.hasPrefix("slides 3, sections 3") })120        let md = try await convert(deck, format, .markdown)121        #expect(md.failedChecks.isEmpty, "markdown: \(md.failedChecks)")122        let crlf = try await convert(deck, format, .txt, options: ["text.lineending": .string("crlf"), "encoding.output": .string("utf-16")])123        #expect(crlf.failedChecks.isEmpty, "utf-16 + CRLF: \(crlf.failedChecks)")124        let subset = try await convert(deck, format, .txt, options: ["slides": .string("1,3")])125        #expect(subset.failedChecks.isEmpty, "subset: \(subset.failedChecks)")126127        // The check still catches a missing section: remove the rule under one heading, or a whole heading.128        for damage in ["Slide 2", "Slide 3"] {129            let broken = try Fixtures.newDirectory("broken").appendingPathComponent("lines.txt")130            var lines = text.components(separatedBy: "\n")131            let index = try #require(lines.indices.first { lines[$0].hasPrefix(damage) && $0 + 1 < lines.count && lines[$0 + 1] == rule })132            if damage == "Slide 2" { lines.remove(at: index + 1) } else { lines.removeSubrange(index...(index + 1)) }133            try Data(lines.joined(separator: "\n").utf8).write(to: broken)134            let checks = try await Engines.presentations.validate(ConversionOutput(file: broken, facts: txt.output.facts), request: txt.request, source: nil)135            #expect(checks.contains { $0.name == "One section per slide" && !$0.passed }, "damage \(damage): \(checks)")136        }137        // Markdown is immune by construction: body text cannot start a line with an unescaped "#".138        let titled = PresentationFacts.Slide(title: nil, paragraphs: ["## Slide 9", "Slide 7"], notes: ["## Slide 8"])139        let rendered = PresentationsEngine.renderText(slides: [(number: 1, slide: titled)], markdown: true, notes: true, title: nil)140        #expect(DocumentFacts.regexCount(#"^## Slide \d+"#, rendered, options: [.anchorsMatchLines]) == 1, "\(rendered)")141        #expect(PresentationsEngine.textSectionsFound("Slide 1 of 3\nSlide 1\n\(rule)\nSlide 2: x\nSlide 2: t\n\(rule)\n", expectedNumbers: [1, 2]) == 2)142        #expect(PresentationsEngine.textSectionsFound("Slide 1 of 3\nSlide 2\n\(rule)\n", expectedNumbers: [1, 2]) == 1)143    }144145    @Test func slideSubsetAndOptions() async throws {146        let fx = try await FixtureStore.shared.get()147        let pptx = try #require(fx.deck[.pptx])148        let pdf = try await convert(pptx, .pptx, .pdf, options: ["slides": .string("2-3")])149        #expect(pdf.failedChecks.isEmpty, "\(pdf.failedChecks)")150        let doc = try #require(PDFDocument(url: pdf.file))151        #expect(doc.pageCount == 2 && normalized(doc.page(at: 0)?.string ?? "").contains("quokka"))152        let png = try await convert(pptx, .pptx, .png, options: ["slides": .string("1,3"), "image.dpi": .int(72)])153        #expect(png.failedChecks.isEmpty, "\(png.failedChecks)")154        #expect(png.output.files.map(\.lastPathComponent) == ["deck-slide-01.png", "deck-slide-03.png"])155        #expect(Raster.imageSize(png.output.files[0])?.width == 794)156        let txt = try await convert(pptx, .pptx, .txt, options: ["slides": .string("2"), "notes.include": .bool(false), "text.lineending": .string("crlf")])157        let text = try String(contentsOf: txt.file, encoding: .utf8)158        #expect(text.contains("Quokka") && !text.contains("Aardvark") && !text.contains("axolotl") && text.contains("\r\n"))159        await #expect(throws: ConversionError.self) { _ = try await convert(pptx, .pptx, .png, options: ["slides": .string("7")]) }160        await #expect(throws: ConversionError.self) { _ = try await convert(pptx, .pptx, .png, options: ["image.dpi": .int(600), "slides": .string("abc")]) }161        // Progress while rasterising is measured, never invented.162        let fractions = png.recorder.progress.compactMap(\.fraction)163        #expect(fractions == [0.5, 1.0], "fractions: \(fractions)")164    }165166    @Test func titlePlaceholders() async throws {167        // The hand-written deck has plain text boxes. Mark the first shape of each slide as the title placeholder.168        let fx = try await FixtureStore.shared.get()169        let dir = try Fixtures.newDirectory("titles")170        let pptx = dir.appendingPathComponent("titled.pptx")171        var edits: [String: (String) -> String] = [:]172        for n in 1...3 {173            edits["ppt/slides/slide\(n).xml"] = { xml in174                guard let r = xml.range(of: "<p:cNvSpPr txBox=\"1\"/><p:nvPr/>") else { return xml }175                return xml.replacingCharacters(in: r, with: "<p:cNvSpPr/><p:nvPr><p:ph type=\"title\"/></p:nvPr>")176            }177        }178        try repackage(try #require(fx.deck[.pptx]), to: pptx, edits: [:], transform: edits)179        let f = try PresentationFacts.extract(pptx, format: .pptx)180        #expect(f.slides.map { $0.title ?? "" } == ["Opening Slide Aardvark", "Picture Slide Quokka", "Table Slide Wombat"])181        #expect(f.slides[0].paragraphs == ["First body line ocelot", "Second body line pangolin"])182        let md = try await convert(pptx, .pptx, .markdown)183        #expect(md.failedChecks.isEmpty, "\(md.failedChecks)")184        #expect(try String(contentsOf: md.file, encoding: .utf8).contains("## Slide 1: Opening Slide Aardvark"))185        let odp = dir.appendingPathComponent("titled.odp")186        try repackage(try #require(fx.deck[.odp]), to: odp, edits: [:], transform: ["content.xml": { xml in187            xml.replacingOccurrences(of: "<draw:frame draw:style-name=\"gr1\"", with: "<draw:frame presentation:class=\"title\" draw:style-name=\"gr1\"")188        }])189        let o = try PresentationFacts.extract(odp, format: .odp)190        #expect(o.slides.compactMap(\.title).contains("Picture Slide Quokka"), "titles: \(o.slides.map(\.title))")191    }192193    @Test func hiddenSlides() async throws {194        let fx = try await FixtureStore.shared.get()195        let hidden = try Fixtures.newDirectory("hidden").appendingPathComponent("hidden.pptx")196        try repackage(try #require(fx.deck[.pptx]), to: hidden, edits: [:], transform: ["ppt/slides/slide2.xml": { $0.replacingOccurrences(of: "<p:sld ", with: "<p:sld show=\"0\" ") }])197        let facts = try PresentationFacts.extract(hidden, format: .pptx)198        #expect(facts.slides.map(\.hidden) == [false, true, false])199        let pdf = try await convert(hidden, .pptx, .pdf)200        #expect(pdf.failedChecks.isEmpty, "\(pdf.failedChecks)")201        #expect(PDFDocument(url: pdf.file)?.pageCount == 2)202        #expect(pdf.recorder.has("hidden-slides-skipped"))203        let all = try await convert(hidden, .pptx, .pdf, options: ["slides.hidden": .bool(true)])204        #expect(all.failedChecks.isEmpty, "\(all.failedChecks)")205        #expect(PDFDocument(url: all.file)?.pageCount == 3)206        let png = try await convert(hidden, .pptx, .png, options: ["image.dpi": .int(36)])207        #expect(png.output.files.count == 2 && png.failedChecks.isEmpty)208    }209210    @Test func inspectAndPreflight() async throws {211        let fx = try await FixtureStore.shared.get()212        for format in [FormatID.pptx, .odp] {213            let url = try #require(fx.deck[format])214            let i = try await Engines.presentations.inspect(url, format: format)215            #expect(i.pageCount == 3)216            func field(_ key: String) -> String? { i.fields.first { $0.key == key }?.value }217            #expect(field("Title") == "Deck Title Capybara" && field("Slides with speaker notes") == "2" && field("Slides with transitions") == "1")218            #expect(field("Slide size")?.hasPrefix("794 × 446 pt") == true, "slide size: \(field("Slide size") ?? "nil")")219            #expect(field("Macros") == "None" && field("Tables") == "1" && field("Pictures") == "1")220            let request = ConversionRequest(source: url, sourceFormat: format, destinationFormat: .pdf)221            let codes = Engines.presentations.preflight(request, inspection: i).map(\.code)222            #expect(codes.contains("transitions-dropped") && codes.contains("notes-not-exported"), "codes: \(codes)")223            let textCodes = Engines.presentations.preflight(ConversionRequest(source: url, sourceFormat: format, destinationFormat: .txt), inspection: i).map(\.code)224            #expect(textCodes.contains("non-text-dropped") && !textCodes.contains("transitions-dropped"))225        }226        let ppt = try await Engines.presentations.inspect(try #require(fx.deck[.ppt]), format: .ppt)227        #expect(ppt.pageCount == nil && !ppt.notes.isEmpty, "nothing is guessed for a binary PPT")228        // A deck with a macro part, a video relationship and an unknown font.229        let rich = try Fixtures.newDirectory("rich").appendingPathComponent("rich.pptx")230        try repackage(try #require(fx.deck[.pptx]), to: rich, edits: ["ppt/vbaProject.bin": Data([0xD0, 0xCF, 0x11, 0xE0, 1, 2, 3, 4])], transform: [231            "ppt/slides/slide1.xml": { $0.replacingOccurrences(of: "<a:t>Opening Slide Aardvark</a:t>", with: "<a:t>Opening Slide Aardvark</a:t></a:r><a:r><a:rPr><a:latin typeface=\"Zyxxy Imaginary Sans\"/></a:rPr><a:t> extra</a:t>") },232            "ppt/slides/_rels/slide1.xml.rels": { $0.replacingOccurrences(of: "</Relationships>", with: "<Relationship Id=\"rIdVid\" Type=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships/video\" Target=\"file:///movie.mp4\" TargetMode=\"External\"/></Relationships>") },233        ])234        let i = try await Engines.presentations.inspect(rich, format: .pptx)235        #expect(i.fields.contains { $0.key == "Macros" && $0.value.hasPrefix("Present") } && i.fields.contains { $0.key == "Video" && $0.value == "1" })236        let warnings = Engines.presentations.preflight(ConversionRequest(source: rich, sourceFormat: .pptx, destinationFormat: .pdf), inspection: nil)237        #expect(warnings.contains { $0.code == "macros-dropped" } && warnings.contains { $0.code == "media-dropped" })238        #expect(warnings.contains { $0.code == "fonts-missing" && $0.message.contains("Zyxxy Imaginary Sans") }, "warnings: \(warnings.map(\.message))")239        // The macro part never reaches the converted file.240        let odp = try await convert(rich, .pptx, .odp)241        let zip = try ZipReader(url: odp.file)242        #expect(!zip.entries.contains { $0.name.lowercased().contains("vba") || $0.name.hasPrefix("Basic/") } && odp.recorder.has("macros-dropped"))243    }244}245
Files main
Menu

Theme