mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-05 01:46:54 +00:00
Improved reading and writing large Office files without copying them into memory (#1243)
This commit is contained in:
1 parent
918572c158
commit
dbe609a9a7
37 files changed
+1161
-471
No files matched your search
@@ -63,7 +63,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
[Test]
|
||||
public async Task TheWordsGoToTheModelAndTheMarkupBecomesTags()
|
||||
{
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
@@ -192,7 +192,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
var page =$"<p>Intro text.</p>{Nested("div", 300, "Deep block")}<p>Before {Nested("span", 300, "deep words")} after.</p><p>Outro text.</p>";
|
||||
File.WriteAllText(this.source, page, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
|
||||
var written = await File.ReadAllTextAsync(this.target);
|
||||
|
||||
@@ -209,7 +209,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
// Thousands of elements without their end tags, as a broken generator may write them:
|
||||
File.WriteAllText(this.source, "<p>" + string.Concat(Enumerable.Repeat("<span>", 20_000)) + "Words</p>", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
|
||||
Assert.That(async () => await this.format.ReadAsync(this.source, CancellationToken.None), Throws.Exception);
|
||||
Assert.That(async () => await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None), Throws.Exception);
|
||||
}
|
||||
|
||||
[Test]
|
||||
@@ -218,7 +218,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
// A card, as many pages show them: a link around a heading and a paragraph:
|
||||
File.WriteAllText(this.source, "<a href=\"/mars\"><div><h3>Mars</h3><p>The red planet.</p></div></a>", new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
Assert.That(keys, Is.EqualTo(new[] { "Mars", "The red planet." }));
|
||||
}
|
||||
@@ -248,7 +248,7 @@ public sealed class HtmlSegmentFormatTests
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
|
||||
@@ -362,11 +362,11 @@ public sealed class LatexSegmentFormatTests
|
||||
|
||||
private void WriteSource(string text) => File.WriteAllText(this.source, text, new UTF8Encoding(encoderShouldEmitUTF8Identifier: false));
|
||||
|
||||
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
|
||||
@@ -199,7 +199,7 @@ public sealed class MarkdownSegmentFormatTests
|
||||
{
|
||||
var source = await this.WriteSourceAsync("Fish & Chips cost 5 \\* 3 \\| 2 © us.\n");
|
||||
|
||||
var keys = (await this.format.ReadAsync(source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
Assert.That(keys, Is.EqualTo(new[] { "Fish & Chips cost 5 * 3 | 2 © us." }));
|
||||
}
|
||||
@@ -277,7 +277,7 @@ public sealed class MarkdownSegmentFormatTests
|
||||
{
|
||||
var source = await this.WriteSourceAsync("Press <1> to continue.\n\nPress <1 /> as well.\n\nOther words.\n");
|
||||
|
||||
var keys = (await this.format.ReadAsync(source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
Assert.That(keys, Is.EqualTo(new[] { "Other words." }), "A model could not tell such words apart from tags, even when they come from two entities and the words between them.");
|
||||
}
|
||||
@@ -291,7 +291,7 @@ public sealed class MarkdownSegmentFormatTests
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(string path, Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(path, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(path, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
using System.IO.Compression;
|
||||
using System.IO.Packaging;
|
||||
|
||||
using AIStudio.Tests.Tools.OpenXml;
|
||||
using AIStudio.Tests.Tools.PowerPoint;
|
||||
using AIStudio.Tools.DocumentSegments;
|
||||
using AIStudio.Tools.DocumentSegments.PowerPoint;
|
||||
using AIStudio.Tools.OpenXml;
|
||||
using AIStudio.Tools.PowerPoint;
|
||||
|
||||
using DocumentFormat.OpenXml;
|
||||
@@ -90,7 +89,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
[Test]
|
||||
public async Task TheTextsOfSlidesAndNotesBecomeSegmentsWithTags()
|
||||
{
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
@@ -248,7 +247,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
this.AddVideo();
|
||||
|
||||
var results = await this.ResultsAsync(key => key.ToUpperInvariant());
|
||||
var stagedBefore = StagedFiles();
|
||||
var stagedBefore = StagingFolder.Files();
|
||||
var allocatedBefore = GC.GetTotalAllocatedBytes(true);
|
||||
var result = await this.format.WriteAsync(this.source, this.target, results, "de-DE", NullLogger.Instance, CancellationToken.None);
|
||||
var allocated = GC.GetTotalAllocatedBytes(true) - allocatedBefore;
|
||||
@@ -267,7 +266,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
Assert.That(targetVideo.CompressedLength, Is.EqualTo(targetVideo.Length), "The video stays uncompressed.");
|
||||
Assert.That(allocated, Is.LessThan(VIDEO_SIZE / 2), "The video goes through the stream, not through memory.");
|
||||
Assert.That(SlideOf(document).Descendants<A.Paragraph>().Select(paragraph => paragraph.InnerText), Has.Member("MISSION TO MARS"), "The new words reach the new document.");
|
||||
Assert.That(StagedFiles().Except(stagedBefore), Is.Empty, "The new document leaves nothing behind in the staging folder.");
|
||||
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The new document leaves nothing behind in the staging folder.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -283,6 +282,21 @@ public sealed class PowerPointSegmentFormatTests
|
||||
Assert.That(this.format.TextSizeOf(this.source), Is.EqualTo(xmlSize).And.LessThan(VIDEO_SIZE), "Only the XML comes into memory, unpacked, never the pictures and videos.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ReadingThroughTheSkeletonLeavesNothingBehind()
|
||||
{
|
||||
this.AddVideo();
|
||||
var stagedBefore = StagingFolder.Files();
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(keys, Does.Contain("Mission to Mars"), "The skeleton holds every text of the presentation.");
|
||||
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The skeleton is gone once the presentation is read.");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AChangedSourceWritesNothing()
|
||||
{
|
||||
@@ -297,7 +311,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
@@ -309,19 +323,7 @@ public sealed class PowerPointSegmentFormatTests
|
||||
/// <summary>
|
||||
/// Adds a video as PowerPoint stores it: uncompressed, behind the slides, which the update mode of ZipArchive would load into memory.
|
||||
/// </summary>
|
||||
private void AddVideo()
|
||||
{
|
||||
var video = new byte[VIDEO_SIZE];
|
||||
new Random(1179).NextBytes(video);
|
||||
|
||||
using var package = Package.Open(this.source, FileMode.Open, FileAccess.ReadWrite);
|
||||
var slidePart = package.GetParts().Single(part => part.Uri.OriginalString.StartsWith("/ppt/slides/slide", StringComparison.Ordinal));
|
||||
var videoPart = package.CreatePart(new Uri("/ppt/media/video1.mp4", UriKind.Relative), "video/mp4", CompressionOption.NotCompressed);
|
||||
using (var stream = videoPart.GetStream())
|
||||
stream.Write(video);
|
||||
|
||||
slidePart.CreateRelationship(videoPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
|
||||
}
|
||||
private void AddVideo() => TestTemplate.AddVideo(this.source, 1, TestTemplate.VideoOf(VIDEO_SIZE));
|
||||
|
||||
private static byte[] ContentOf(ZipArchiveEntry entry)
|
||||
{
|
||||
@@ -331,12 +333,6 @@ public sealed class PowerPointSegmentFormatTests
|
||||
return content.ToArray();
|
||||
}
|
||||
|
||||
private static HashSet<string> StagedFiles()
|
||||
{
|
||||
var directory = Path.Join(Path.GetTempPath(), StagedDocument.DIRECTORY);
|
||||
return Directory.Exists(directory) ? Directory.EnumerateFiles(directory).ToHashSet() : [];
|
||||
}
|
||||
|
||||
private static IEnumerable<OpenXmlElement> RootsOf(PresentationDocument document)
|
||||
{
|
||||
var slidePart = document.PresentationPart!.SlideParts.Single();
|
||||
|
||||
@@ -4,6 +4,8 @@ using AIStudio.Tools.DocumentSegments;
|
||||
using AIStudio.Tools.DocumentSegments.Html;
|
||||
using AIStudio.Tools.DocumentSegments.Latex;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AIStudio.Tests.Tools.DocumentSegments;
|
||||
|
||||
/// <summary>
|
||||
@@ -69,7 +71,7 @@ public sealed class TextDocumentFileTests
|
||||
{
|
||||
var source = await this.WriteAsync("page.html", Encoding.ASCII.GetBytes("<html><head><meta charset=\"iso-8859-1\"></head><body><p>Müller</p></body></html>"));
|
||||
|
||||
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None));
|
||||
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
|
||||
|
||||
Assert.That(exception!.DeclaredEncoding, Is.EqualTo("iso-8859-1"), "An ASCII page which says Latin-1 would show new words in UTF-8 garbled.");
|
||||
}
|
||||
@@ -80,7 +82,7 @@ public sealed class TextDocumentFileTests
|
||||
var page = "<html><head><meta charset=\"iso-8859-1\"></head><body><p>Grüße</p></body></html>";
|
||||
var source = await this.WriteAsync("page.html", new UTF8Encoding(true).GetPreamble().Concat(Encoding.UTF8.GetBytes(page)).ToArray());
|
||||
|
||||
var segments = await new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None);
|
||||
var segments = await new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
Assert.That(segments.Select(segment => segment.Key), Does.Contain("Grüße"), "Browsers follow the byte order mark, too.");
|
||||
}
|
||||
@@ -90,7 +92,7 @@ public sealed class TextDocumentFileTests
|
||||
{
|
||||
var source = await this.WriteAsync("paper.tex", Encoding.ASCII.GetBytes("\\documentclass{article}\n\\usepackage[latin1]{inputenc}\n\\begin{document}\nHello.\n\\end{document}"));
|
||||
|
||||
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new LatexSegmentFormat().ReadAsync(source, CancellationToken.None));
|
||||
var exception = await Assert.ThrowsAsync<UnsupportedTextEncodingException>(() => new LatexSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
|
||||
|
||||
Assert.That(exception!.DeclaredEncoding, Is.EqualTo("latin1"));
|
||||
}
|
||||
@@ -146,7 +148,7 @@ public sealed class TextDocumentFileTests
|
||||
await using (var stream = new FileStream(source, FileMode.CreateNew))
|
||||
stream.SetLength(new HtmlSegmentFormat().MaxTextSize + 1);
|
||||
|
||||
await Assert.ThrowsAsync<DocumentTooLargeException>(() => new HtmlSegmentFormat().ReadAsync(source, CancellationToken.None));
|
||||
await Assert.ThrowsAsync<DocumentTooLargeException>(() => new HtmlSegmentFormat().ReadAsync(source, NullLogger.Instance, CancellationToken.None));
|
||||
}
|
||||
|
||||
private async Task<string> WriteAsync(string name, byte[] bytes)
|
||||
|
||||
@@ -383,7 +383,7 @@ public sealed class WordInlineFormattingTests
|
||||
|
||||
private void CreateSentence() => Create(this.source, Paragraph(Run("This is "), Bold("very"), Run(" "), Italic("important"), Run(" and "), Link("linked"), Run(" text.")));
|
||||
|
||||
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
private async Task<List<string>> KeysAsync() => (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
private Task<SegmentWriteResult> WriteAsync(string key, string newText)
|
||||
{
|
||||
|
||||
@@ -44,7 +44,7 @@ public sealed class WordSegmentFormatTests
|
||||
[Test]
|
||||
public async Task TheParagraphsBecomeSegmentsWithTags()
|
||||
{
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
@@ -201,7 +201,7 @@ public sealed class WordSegmentFormatTests
|
||||
using (var sourceToExtend = WordprocessingDocument.Open(this.source, true))
|
||||
BodyOf(sourceToExtend).AppendChild(bound);
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
|
||||
@@ -224,7 +224,7 @@ public sealed class WordSegmentFormatTests
|
||||
new W.DeletedRun(new W.Run(new W.DeletedText("gone"))) { Id = "1", Author = "Tester" },
|
||||
new W.InsertedRun(Run("new")) { Id = "2", Author = "Tester" }));
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
|
||||
@@ -250,7 +250,7 @@ public sealed class WordSegmentFormatTests
|
||||
Run("Introduction")),
|
||||
Paragraph(Run("Methods"), new W.Run(new W.FieldChar { FieldCharType = W.FieldCharValues.End })));
|
||||
|
||||
var keys = (await this.format.ReadAsync(this.source, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
var keys = (await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None)).Select(segment => segment.Key).ToList();
|
||||
await this.format.WriteAsync(this.source, this.target, await this.ResultsAsync(key => key.ToUpperInvariant()), string.Empty, NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
using var sourceDocument = WordprocessingDocument.Open(this.source, false);
|
||||
@@ -324,7 +324,7 @@ public sealed class WordSegmentFormatTests
|
||||
|
||||
private async Task<SegmentResults> ResultsAsync(Func<string, string> transform)
|
||||
{
|
||||
var segments = await this.format.ReadAsync(this.source, CancellationToken.None);
|
||||
var segments = await this.format.ReadAsync(this.source, NullLogger.Instance, CancellationToken.None);
|
||||
return new SegmentResults(segments
|
||||
.Where(segment => segment.HasWords)
|
||||
.DistinctBy(segment => segment.Key)
|
||||
|
||||
@@ -0,0 +1,211 @@
|
||||
using System.IO.Compression;
|
||||
|
||||
using AIStudio.Tests.Tools.PowerPoint;
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
using A = DocumentFormat.OpenXml.Drawing;
|
||||
using P = DocumentFormat.OpenXml.Presentation;
|
||||
|
||||
namespace AIStudio.Tests.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// Checks that the skeleton of an Office document holds only its XML, and that a new document takes each entry from
|
||||
/// where it lies: the XML from the skeleton or from a DOM, the pictures and videos from the source, and new parts from
|
||||
/// their files.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Most tests build their documents as plain archives, since the skeleton works on entries and knows nothing of their
|
||||
/// meaning; a writer which edits the skeleton is played by the update mode of ZipArchive.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class PackageSkeletonTests
|
||||
{
|
||||
private const string CONTENT_TYPES = "[Content_Types].xml";
|
||||
private const string RELATIONSHIPS = "_rels/.rels";
|
||||
private const string SLIDE = "ppt/slides/slide1.xml";
|
||||
private const string PICTURE = "ppt/media/image1.png";
|
||||
private const string VIDEO = "ppt/media/video1.mp4";
|
||||
private const string THUMBNAIL = "docProps/thumbnail.jpeg";
|
||||
|
||||
private static readonly string[] ENTRY_NAMES = [CONTENT_TYPES, RELATIONSHIPS, SLIDE, PICTURE, VIDEO, THUMBNAIL];
|
||||
|
||||
private string testFolder = string.Empty;
|
||||
private string sourcePath = string.Empty;
|
||||
private string documentPath = string.Empty;
|
||||
|
||||
[SetUp]
|
||||
public void CreateSource()
|
||||
{
|
||||
this.testFolder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
|
||||
this.sourcePath = Path.Join(this.testFolder, "source.pptx");
|
||||
this.documentPath = Path.Join(this.testFolder, "document.pptx");
|
||||
WriteArchive(this.sourcePath, VideoOf(1));
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void RemoveFolder() => Directory.Delete(this.testFolder, true);
|
||||
|
||||
[Test]
|
||||
public void TheSkeletonKeepsOnlyTheXml()
|
||||
{
|
||||
var stagedBefore = StagingFolder.Files();
|
||||
using (var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
using var skeletonFile = skeleton.OpenRead();
|
||||
using var archive = new ZipArchive(skeletonFile, ZipArchiveMode.Read);
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(archive.Entries.Select(entry => entry.FullName), Is.EqualTo(ENTRY_NAMES), "Every entry keeps its place.");
|
||||
Assert.That(ContentOf(archive.GetEntry(SLIDE)!), Is.EqualTo(ContentOf(this.sourcePath, SLIDE)), "The XML keeps its content.");
|
||||
Assert.That(ContentOf(archive.GetEntry(RELATIONSHIPS)!), Is.EqualTo(ContentOf(this.sourcePath, RELATIONSHIPS)), "The relationships keep their content.");
|
||||
Assert.That(archive.Entries.Where(entry => !PackageSkeleton.HoldsXml(entry)).Select(entry => entry.Length), Has.Exactly(3).Items.And.All.Zero, "Pictures and videos stay empty.");
|
||||
}
|
||||
}
|
||||
|
||||
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "Disposing the skeleton removes it.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void TheDocumentTakesEachEntryFromWhereItLies()
|
||||
{
|
||||
var newPicture = Path.Join(this.testFolder, "new.png");
|
||||
File.WriteAllBytes(newPicture, [7, 8, 9]);
|
||||
|
||||
bool isWritten;
|
||||
using (var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
// The writer changes a slide, removes the thumbnail, and adds a picture and a slide:
|
||||
using (var skeletonFile = skeleton.OpenForEditing())
|
||||
using (var archive = new ZipArchive(skeletonFile, ZipArchiveMode.Update))
|
||||
{
|
||||
Overwrite(archive, SLIDE, "<slide>changed</slide>"u8.ToArray());
|
||||
archive.GetEntry(THUMBNAIL)!.Delete();
|
||||
archive.CreateEntry("ppt/media/image2.png");
|
||||
Add(archive, "ppt/slides/slide2.xml", "<slide>new</slide>"u8.ToArray(), CompressionLevel.Optimal);
|
||||
}
|
||||
|
||||
isWritten = skeleton.TryWriteDocument([], new Dictionary<string, string> { ["ppt/media/image2.png"] = newPicture }, this.documentPath, CancellationToken.None);
|
||||
}
|
||||
|
||||
using var document = ZipFile.OpenRead(this.documentPath);
|
||||
var video = document.GetEntry(VIDEO)!;
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(isWritten, Is.True);
|
||||
Assert.That(document.Entries.Select(entry => entry.FullName), Is.EqualTo(new[] { CONTENT_TYPES, RELATIONSHIPS, SLIDE, PICTURE, VIDEO, "ppt/media/image2.png", "ppt/slides/slide2.xml" }), "What the writer removed stays out, and what it added comes along.");
|
||||
Assert.That(ContentOf(document.GetEntry(SLIDE)!), Is.EqualTo("<slide>changed</slide>"u8.ToArray()), "The XML comes from the skeleton.");
|
||||
Assert.That(ContentOf(document.GetEntry(PICTURE)!), Is.EqualTo(ContentOf(this.sourcePath, PICTURE)), "A picture of the source comes from the source.");
|
||||
Assert.That(ContentOf(video), Is.EqualTo(VideoOf(1)), "A video of the source comes from the source.");
|
||||
Assert.That(video.CompressedLength, Is.EqualTo(video.Length), "A stored video stays stored.");
|
||||
Assert.That(ContentOf(document.GetEntry("ppt/media/image2.png")!), Is.EqualTo(new byte[] { 7, 8, 9 }), "A new picture comes from its file.");
|
||||
Assert.That(ContentOf(document.GetEntry("ppt/slides/slide2.xml")!), Is.EqualTo("<slide>new</slide>"u8.ToArray()));
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ANewPartUnderTheNameOfARemovedOneComesFromItsFile()
|
||||
{
|
||||
var newPicture = Path.Join(this.testFolder, "new.png");
|
||||
File.WriteAllBytes(newPicture, [7, 8, 9]);
|
||||
|
||||
using (var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
// The SDK may give a new part the name of a part it removed:
|
||||
using (var skeletonFile = skeleton.OpenForEditing())
|
||||
using (var archive = new ZipArchive(skeletonFile, ZipArchiveMode.Update))
|
||||
{
|
||||
archive.GetEntry(PICTURE)!.Delete();
|
||||
archive.CreateEntry(PICTURE);
|
||||
}
|
||||
|
||||
skeleton.TryWriteDocument([], new Dictionary<string, string> { [PICTURE] = newPicture }, this.documentPath, CancellationToken.None);
|
||||
}
|
||||
|
||||
using var document = ZipFile.OpenRead(this.documentPath);
|
||||
Assert.That(ContentOf(document.GetEntry(PICTURE)!), Is.EqualTo(new byte[] { 7, 8, 9 }));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AChangedPartComesFromItsDom()
|
||||
{
|
||||
using (var template = TestTemplate.Create(new TestTemplateOptions(Slides: [new TestSlide(0, (TestPlaceholder.Title(), "News"))]), new TestLayout("Title", TestPlaceholder.Title())))
|
||||
File.WriteAllBytes(this.sourcePath, template.ToArray());
|
||||
|
||||
using (var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
using var skeletonFile = skeleton.OpenRead();
|
||||
using var presentation = PresentationDocument.Open(skeletonFile, false);
|
||||
var slidePart = presentation.PresentationPart!.SlideParts.Single();
|
||||
slidePart.Slide!.Descendants<A.Text>().Single().Text = "Breaking news";
|
||||
|
||||
skeleton.TryWriteDocument([slidePart], new Dictionary<string, string>(), this.documentPath, CancellationToken.None);
|
||||
}
|
||||
|
||||
using var document = PresentationDocument.Open(this.documentPath, false);
|
||||
Assert.That(document.PresentationPart!.SlideParts.Single().Slide!.Descendants<P.Shape>().Single().InnerText, Is.EqualTo("Breaking news"));
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void AChangedSourceWritesNoDocument()
|
||||
{
|
||||
using var skeleton = PackageSkeleton.Create(this.sourcePath, ".pptx", NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
// PowerPoint saved the source with another video meanwhile:
|
||||
File.Delete(this.sourcePath);
|
||||
WriteArchive(this.sourcePath, VideoOf(2));
|
||||
|
||||
Assert.That(skeleton.TryWriteDocument([], new Dictionary<string, string>(), this.documentPath, CancellationToken.None), Is.False);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Writes a document as PowerPoint stores it: the XML deflated, the picture deflated, and the video stored.
|
||||
/// </summary>
|
||||
private static void WriteArchive(string path, byte[] video)
|
||||
{
|
||||
using var archive = ZipFile.Open(path, ZipArchiveMode.Create);
|
||||
Add(archive, CONTENT_TYPES, "<Types />"u8.ToArray(), CompressionLevel.Optimal);
|
||||
Add(archive, RELATIONSHIPS, "<Relationships />"u8.ToArray(), CompressionLevel.Optimal);
|
||||
Add(archive, SLIDE, "<slide>original</slide>"u8.ToArray(), CompressionLevel.Optimal);
|
||||
Add(archive, PICTURE, [.. Enumerable.Repeat((byte)1, 4096)], CompressionLevel.Optimal);
|
||||
Add(archive, VIDEO, video, CompressionLevel.NoCompression);
|
||||
Add(archive, THUMBNAIL, [4, 5, 6], CompressionLevel.Optimal);
|
||||
}
|
||||
|
||||
private static void Add(ZipArchive archive, string name, byte[] content, CompressionLevel compressionLevel)
|
||||
{
|
||||
using var stream = archive.CreateEntry(name, compressionLevel).Open();
|
||||
stream.Write(content);
|
||||
}
|
||||
|
||||
private static void Overwrite(ZipArchive archive, string name, byte[] content)
|
||||
{
|
||||
using var stream = archive.GetEntry(name)!.Open();
|
||||
stream.SetLength(0);
|
||||
stream.Write(content);
|
||||
}
|
||||
|
||||
private static byte[] VideoOf(int seed)
|
||||
{
|
||||
var video = new byte[64 * 1024];
|
||||
new Random(seed).NextBytes(video);
|
||||
return video;
|
||||
}
|
||||
|
||||
private static byte[] ContentOf(string path, string name)
|
||||
{
|
||||
using var archive = ZipFile.OpenRead(path);
|
||||
return ContentOf(archive.GetEntry(name)!);
|
||||
}
|
||||
|
||||
private static byte[] ContentOf(ZipArchiveEntry entry)
|
||||
{
|
||||
using var stream = entry.Open();
|
||||
using var content = new MemoryStream();
|
||||
stream.CopyTo(content);
|
||||
return content.ToArray();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
namespace AIStudio.Tests.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// The folder in which StagedDocument puts its files. Tests have no data directory, so it lies in the temporary folder.
|
||||
/// </summary>
|
||||
internal static class StagingFolder
|
||||
{
|
||||
/// <summary>
|
||||
/// The files in the staging folder; other tests may have left some there.
|
||||
/// </summary>
|
||||
public static HashSet<string> Files()
|
||||
{
|
||||
var directory = Path.Join(Path.GetTempPath(), StagedDocument.DIRECTORY);
|
||||
return Directory.Exists(directory) ? Directory.EnumerateFiles(directory).ToHashSet() : [];
|
||||
}
|
||||
}
|
||||
@@ -1,67 +0,0 @@
|
||||
using AIStudio.Tools.OpenXml;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AIStudio.Tests.Tools.OpenXml;
|
||||
|
||||
/// <summary>
|
||||
/// Checks that a copy of a template leaves nothing behind in the temporary folder.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Writing a document into the copy and the copy into the chosen file is checked by the tests of the
|
||||
/// documents themselves, e.g., PresentationFileTests.
|
||||
/// </remarks>
|
||||
[TestFixture]
|
||||
public sealed class TemplateCopyTests
|
||||
{
|
||||
private static readonly byte[] TEMPLATE_CONTENT = [1, 2, 3];
|
||||
|
||||
private string testFolder = string.Empty;
|
||||
private string temporaryDirectory = string.Empty;
|
||||
|
||||
[SetUp]
|
||||
public void CreateFolders()
|
||||
{
|
||||
this.testFolder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
|
||||
this.temporaryDirectory = $"mindwork-ai-studio-tests-{Guid.NewGuid():N}";
|
||||
}
|
||||
|
||||
[TearDown]
|
||||
public void RemoveFolders()
|
||||
{
|
||||
Directory.Delete(this.testFolder, true);
|
||||
var copies = Path.Join(Path.GetTempPath(), this.temporaryDirectory);
|
||||
if (Directory.Exists(copies))
|
||||
Directory.Delete(copies, true);
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task TheCopyHoldsTheTemplateUntilItIsDisposed()
|
||||
{
|
||||
var templatePath = Path.Join(this.testFolder, "template.docx");
|
||||
await File.WriteAllBytesAsync(templatePath, TEMPLATE_CONTENT);
|
||||
|
||||
string copyPath;
|
||||
using (var copy = await TemplateCopy.CreateAsync(templatePath, this.temporaryDirectory, ".docx", NullLogger.Instance, CancellationToken.None))
|
||||
{
|
||||
copyPath = copy.FilePath;
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(Path.GetDirectoryName(copyPath), Is.EqualTo(Path.Join(Path.GetTempPath(), this.temporaryDirectory)), "The copy comes about in the temporary folder, never next to the chosen file.");
|
||||
Assert.That(Path.GetExtension(copyPath), Is.EqualTo(".docx"));
|
||||
Assert.That(File.ReadAllBytes(copyPath), Is.EqualTo(TEMPLATE_CONTENT));
|
||||
}
|
||||
}
|
||||
|
||||
Assert.That(File.Exists(copyPath), Is.False, "Disposing the copy removes it.");
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task AMissingTemplateLeavesNoCopyBehind()
|
||||
{
|
||||
var templatePath = Path.Join(this.testFolder, "missing.docx");
|
||||
|
||||
await Assert.ThrowsAsync<FileNotFoundException>(() => TemplateCopy.CreateAsync(templatePath, this.temporaryDirectory, ".docx", NullLogger.Instance, CancellationToken.None));
|
||||
Assert.That(Directory.GetFiles(Path.Join(Path.GetTempPath(), this.temporaryDirectory)), Is.Empty);
|
||||
}
|
||||
}
|
||||
@@ -1,13 +1,19 @@
|
||||
using System.IO.Compression;
|
||||
|
||||
using AIStudio.Tests.Tools.OpenXml;
|
||||
using AIStudio.Tools.PowerPoint;
|
||||
|
||||
using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Validation;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
namespace AIStudio.Tests.Tools.PowerPoint;
|
||||
|
||||
/// <summary>
|
||||
/// Checks that a presentation file comes about without anything next to the file the user chose.
|
||||
/// Checks that a presentation file comes about without anything next to the file the user chose, and without its
|
||||
/// template or its pictures in memory.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Inside the Flatpak, the save dialog grants access to exactly the chosen file. A temporary file next
|
||||
@@ -27,6 +33,16 @@ public sealed class PresentationFileTests
|
||||
|
||||
private static readonly byte[] PREVIOUS_CONTENT = [1, 2, 3];
|
||||
|
||||
/// <summary>
|
||||
/// A video of a template, large enough that the update mode of ZipArchive would show in the allocations.
|
||||
/// </summary>
|
||||
private const int VIDEO_SIZE = 32 * 1024 * 1024;
|
||||
|
||||
private static readonly SlotBounds PICTURE_BOUNDS = new(6_200_000, 1_825_625, 5_150_000, 3_500_000);
|
||||
private static readonly byte[] TEMPLATE_PICTURE = [11, 12, 13];
|
||||
private static readonly byte[] SAMPLE_PICTURE = [21, 22, 23];
|
||||
private static readonly byte[] PHOTO = [31, 32, 33, 34];
|
||||
|
||||
private string templateFolder = string.Empty;
|
||||
private string targetFolder = string.Empty;
|
||||
|
||||
@@ -47,7 +63,7 @@ public sealed class PresentationFileTests
|
||||
var templatePath = await this.CreateTemplateAsync();
|
||||
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
|
||||
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
|
||||
var temporaryFiles = TemporaryFiles();
|
||||
var stagedFiles = StagingFolder.Files();
|
||||
|
||||
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, BasisOf(templatePath), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
|
||||
|
||||
@@ -57,7 +73,7 @@ public sealed class PresentationFileTests
|
||||
Assert.That(result.IsWritten, Is.True);
|
||||
Assert.That(Directory.GetFileSystemEntries(this.targetFolder), Is.EqualTo(new[] { targetPath }), "Nothing else came about next to the chosen file.");
|
||||
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The chosen file holds the presentation instead of what it held before.");
|
||||
Assert.That(TemporaryFiles(), Is.EquivalentTo(temporaryFiles), "The copy of the template is gone.");
|
||||
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -67,7 +83,7 @@ public sealed class PresentationFileTests
|
||||
var templatePath = await this.CreateTemplateAsync();
|
||||
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
|
||||
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
|
||||
var temporaryFiles = TemporaryFiles();
|
||||
var stagedFiles = StagingFolder.Files();
|
||||
|
||||
// Without a basis, nothing is known to fit, as after a change of the template:
|
||||
var result = await PresentationFile.CreateAsync(templatePath, targetPath, DECK, new Dictionary<string, string>(), OPTIONS, new NoPictures(), NullLogger.Instance, CancellationToken.None);
|
||||
@@ -77,7 +93,7 @@ public sealed class PresentationFileTests
|
||||
{
|
||||
Assert.That(result.IsWritten, Is.False);
|
||||
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT));
|
||||
Assert.That(TemporaryFiles(), Is.EquivalentTo(temporaryFiles), "The copy of the template is gone.");
|
||||
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template is gone.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -93,7 +109,91 @@ public sealed class PresentationFileTests
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(result.IsWritten, Is.True);
|
||||
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was copied before it was written over.");
|
||||
Assert.That(document.PresentationPart!.SlideParts.Count(), Is.EqualTo(2), "The template was read completely before it was written over.");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task APictureWhichFailsLeavesNothingBehind()
|
||||
{
|
||||
var templatePath = await this.CreateTemplateAsync();
|
||||
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
|
||||
await File.WriteAllBytesAsync(targetPath, PREVIOUS_CONTENT);
|
||||
var deck = new SlideDeckSpec("Mars", [new SlideSpec("L2", false, "Why Mars", string.Empty, [], [], [1, 2], null)]);
|
||||
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
|
||||
var stagedFiles = StagingFolder.Files();
|
||||
|
||||
// The first picture is staged already when the second one fails:
|
||||
await Assert.ThrowsAsync<IOException>(() => PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new FailingAtSecondPicture(), NullLogger.Instance, CancellationToken.None));
|
||||
|
||||
var targetContent = await File.ReadAllBytesAsync(targetPath);
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(targetContent, Is.EqualTo(PREVIOUS_CONTENT), "The chosen file stays as it was.");
|
||||
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton of the template and the staged picture are gone.");
|
||||
}
|
||||
}
|
||||
|
||||
[TestCase(false)]
|
||||
[TestCase(true)]
|
||||
public async Task TheMediaOfTheTemplateStreamThroughAsTheyAre(bool asTemplate)
|
||||
{
|
||||
// The deck keeps slide 1 with its picture and video, and leaves out slide 2, a sample with a picture and a video of its own:
|
||||
var templatePath = Path.Join(this.templateFolder, asTemplate ? "template.potx" : "template.pptx");
|
||||
var templateOptions = new TestTemplateOptions(AsTemplate: asTemplate, Slides:
|
||||
[
|
||||
new TestSlide(1, (TestPlaceholder.Title(), "Mars")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, TEMPLATE_PICTURE)] },
|
||||
new TestSlide(1, (TestPlaceholder.Title(), "Sample")) { Elements = [TestElement.Picture(PICTURE_BOUNDS, SAMPLE_PICTURE)] },
|
||||
]);
|
||||
|
||||
using (var template = TestTemplate.Create(templateOptions,
|
||||
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(new SlotBounds(1_524_000, 3_602_038, 9_144_000, 1_655_762))),
|
||||
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS)),
|
||||
new TestLayout("Picture", TestPlaceholder.Title(), TestPlaceholder.Picture(11, PICTURE_BOUNDS))))
|
||||
await File.WriteAllBytesAsync(templatePath, template.ToArray());
|
||||
|
||||
var video = TestTemplate.VideoOf(VIDEO_SIZE);
|
||||
TestTemplate.AddVideo(templatePath, 1, video);
|
||||
TestTemplate.AddVideo(templatePath, 2, TestTemplate.VideoOf(1024 * 1024, 2), "/ppt/media/video2.mp4");
|
||||
|
||||
var deck = new SlideDeckSpec("Mars",
|
||||
[
|
||||
new SlideSpec(string.Empty, false, string.Empty, string.Empty, [], [], [], null, 1),
|
||||
new SlideSpec("L3", false, "The rocket", string.Empty, [], [], [1], null),
|
||||
]);
|
||||
|
||||
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
|
||||
var targetPath = Path.Join(this.targetFolder, "Mars.pptx");
|
||||
var stagedFiles = StagingFolder.Files();
|
||||
|
||||
var allocatedBefore = GC.GetTotalAllocatedBytes(true);
|
||||
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, OPTIONS, new OnePhoto(), NullLogger.Instance, CancellationToken.None);
|
||||
var allocated = GC.GetTotalAllocatedBytes(true) - allocatedBefore;
|
||||
|
||||
List<string> templateErrors;
|
||||
using (var template = PresentationDocument.Open(templatePath, false))
|
||||
templateErrors = ValidationErrorsOf(template);
|
||||
|
||||
using var archive = ZipFile.OpenRead(targetPath);
|
||||
var targetVideo = archive.GetEntry("ppt/media/video1.mp4");
|
||||
var smallEntries = archive.Entries.Where(entry => entry.Length < 1024).Select(ContentOf).ToList();
|
||||
using var document = PresentationDocument.Open(targetPath, false);
|
||||
var slides = document.PresentationPart!.Presentation!.SlideIdList!.Elements<DocumentFormat.OpenXml.Presentation.SlideId>()
|
||||
.Select(slideId => (SlidePart)document.PresentationPart.GetPartById(slideId.RelationshipId!.Value!))
|
||||
.ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(result.IsWritten, Is.True);
|
||||
Assert.That(targetVideo, Is.Not.Null, "The video of the kept slide comes along.");
|
||||
Assert.That(targetVideo is null ? Array.Empty<byte>() : ContentOf(targetVideo), Is.EqualTo(video), "The video keeps its bytes.");
|
||||
Assert.That(targetVideo?.CompressedLength, Is.EqualTo(targetVideo?.Length), "The video stays stored.");
|
||||
Assert.That(archive.GetEntry("ppt/media/video2.mp4"), Is.Null, "The video of the sample slide stays out.");
|
||||
Assert.That(smallEntries, Has.None.EqualTo(SAMPLE_PICTURE), "The picture of the sample slide stays out.");
|
||||
Assert.That(slides.Select(slide => slide.ImageParts.Select(ContentOf).Single()), Is.EqualTo(new[] { TEMPLATE_PICTURE, PHOTO }), "The kept slide keeps its picture, and the new slide shows the photo.");
|
||||
Assert.That(allocated, Is.LessThan(VIDEO_SIZE / 4), $"The template goes through streams, not through memory; {allocated / 1024 / 1024} MB were allocated.");
|
||||
Assert.That(ValidationErrorsOf(document), Is.EquivalentTo(templateErrors), "The presentation is as valid as its template.");
|
||||
Assert.That(StagingFolder.Files(), Is.EquivalentTo(stagedFiles), "The skeleton, the photo, and the presentation leave nothing behind in the staging folder.");
|
||||
}
|
||||
}
|
||||
|
||||
@@ -108,19 +208,43 @@ public sealed class PresentationFileTests
|
||||
return templatePath;
|
||||
}
|
||||
|
||||
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath).DescribeBasisOf(DECK);
|
||||
private static IReadOnlyDictionary<string, string> BasisOf(string templatePath) => PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(DECK);
|
||||
|
||||
/// <summary>
|
||||
/// The files in the folder where the presentations come about; others may have left some there.
|
||||
/// </summary>
|
||||
private static string[] TemporaryFiles()
|
||||
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
|
||||
.Validate(document)
|
||||
.Select(error => $"{error.Path?.XPath}: {error.Description}")
|
||||
.ToList();
|
||||
|
||||
private static byte[] ContentOf(ZipArchiveEntry entry)
|
||||
{
|
||||
var folder = Path.Join(Path.GetTempPath(), "mindwork-ai-studio-presentations");
|
||||
return Directory.Exists(folder) ? Directory.GetFiles(folder) : [];
|
||||
using var stream = entry.Open();
|
||||
using var content = new MemoryStream();
|
||||
stream.CopyTo(content);
|
||||
return content.ToArray();
|
||||
}
|
||||
|
||||
private static byte[] ContentOf(ImagePart part)
|
||||
{
|
||||
using var stream = part.GetStream(FileMode.Open, FileAccess.Read);
|
||||
using var content = new MemoryStream();
|
||||
stream.CopyTo(content);
|
||||
return content.ToArray();
|
||||
}
|
||||
|
||||
private sealed class NoPictures : IPictureSource
|
||||
{
|
||||
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult<SlidePicture?>(null);
|
||||
}
|
||||
|
||||
private sealed class OnePhoto : IPictureSource
|
||||
{
|
||||
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => Task.FromResult(number == 1 ? new SlidePicture(PHOTO, "image/jpeg", 400, 300) : null);
|
||||
}
|
||||
|
||||
private sealed class FailingAtSecondPicture : IPictureSource
|
||||
{
|
||||
public Task<SlidePicture?> LoadAsync(int number, CancellationToken token) => number < 2
|
||||
? Task.FromResult<SlidePicture?>(new SlidePicture([1, 2, 3], "image/png", 400, 100))
|
||||
: throw new IOException("The picture cannot be read.");
|
||||
}
|
||||
}
|
||||
@@ -1,5 +1,8 @@
|
||||
using AIStudio.Tests.Tools.OpenXml;
|
||||
using AIStudio.Tools.PowerPoint;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
using P = DocumentFormat.OpenXml.Presentation;
|
||||
|
||||
namespace AIStudio.Tests.Tools.PowerPoint;
|
||||
@@ -37,6 +40,40 @@ public sealed class PresentationTemplateTests
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void ATemplateFileIsReadThroughItsSkeleton()
|
||||
{
|
||||
var folder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
|
||||
try
|
||||
{
|
||||
var path = Path.Join(folder, "template.pptx");
|
||||
using (var file = TestTemplate.Create(
|
||||
new TestTemplateOptions(Slides: [new TestSlide(1, (TestPlaceholder.Title(), "News"), (TestPlaceholder.Text(1, FULL_TEXT), "A point"))]),
|
||||
new TestLayout("Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(SUBTITLE)),
|
||||
new TestLayout("Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, FULL_TEXT))))
|
||||
File.WriteAllBytes(path, file.ToArray());
|
||||
|
||||
TestTemplate.AddVideo(path, 1, TestTemplate.VideoOf(1024 * 1024));
|
||||
var stagedBefore = StagingFolder.Files();
|
||||
|
||||
var fromFile = PresentationTemplate.ReadFile(path, NullLogger.Instance);
|
||||
PresentationTemplate fromStream;
|
||||
using (var stream = File.OpenRead(path))
|
||||
fromStream = PresentationTemplate.Read(stream);
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(fromFile.ToCatalogPrompt(), Is.EqualTo(fromStream.ToCatalogPrompt()), "The skeleton holds every layout.");
|
||||
Assert.That(fromFile.Slides.Select(slide => slide.Title), Is.EqualTo(new[] { "News" }), "The skeleton holds every slide.");
|
||||
Assert.That(StagingFolder.Files().Except(stagedBefore), Is.Empty, "The skeleton is gone once the template is read.");
|
||||
}
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(folder, true);
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public void LayoutsWhichOnlyLookAlikeAreNoVariants()
|
||||
{
|
||||
|
||||
@@ -4,6 +4,8 @@ using DocumentFormat.OpenXml;
|
||||
using DocumentFormat.OpenXml.Packaging;
|
||||
using DocumentFormat.OpenXml.Validation;
|
||||
|
||||
using Microsoft.Extensions.Logging.Abstractions;
|
||||
|
||||
using A = DocumentFormat.OpenXml.Drawing;
|
||||
using P = DocumentFormat.OpenXml.Presentation;
|
||||
using P14 = DocumentFormat.OpenXml.Office2010.PowerPoint;
|
||||
@@ -321,16 +323,8 @@ public sealed class PresentationWriterTests
|
||||
new TestLayout("A Content", TestPlaceholder.Title(), TestPlaceholder.Text(1, TestTemplate.MASTER_BODY_BOUNDS), TestPlaceholder.Footer(10, FOOTER)),
|
||||
new TestLayout("B Content", TestPlaceholder.Title(), TestPlaceholder.Text(2, TestTemplate.MASTER_BODY_BOUNDS), TestPlaceholder.Footer(12, FOOTER)));
|
||||
|
||||
var template = PresentationTemplate.Read(templateFile);
|
||||
templateFile.Position = 0;
|
||||
|
||||
using var output = new MemoryStream();
|
||||
await templateFile.CopyToAsync(output);
|
||||
output.Position = 0;
|
||||
await PresentationWriter.WriteAsync(output, template, new SlideDeckSpec("Weekly", [Keep(1)]), OPTIONS with { VariantLabel = "B" }, new FakePictureSource(), CancellationToken.None);
|
||||
output.Position = 0;
|
||||
|
||||
using var document = PresentationDocument.Open(output, false);
|
||||
var (file, _) = await WriteFromAsync(templateFile, new SlideDeckSpec("Weekly", [Keep(1)]), OPTIONS with { VariantLabel = "B" });
|
||||
using var document = PresentationDocument.Open(file, false);
|
||||
var slide = SlidesOf(document)[0];
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
@@ -570,6 +564,61 @@ public sealed class PresentationWriterTests
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ARemovedVideoLeavesTheFile()
|
||||
{
|
||||
var templateOptions = new TestTemplateOptions(Slides: [new TestSlide(2, (TestPlaceholder.Title(), "Launch")) { Elements = [TestElement.Video(RIGHT_PICTURE, 4, 5, 6)] }]);
|
||||
var deck = new SlideDeckSpec("Weekly", [Edit(1) with { Removals = ["element 1"] }]);
|
||||
|
||||
var (file, _) = await WriteAsync(deck, OPTIONS, templateOptions);
|
||||
using var document = PresentationDocument.Open(file, false);
|
||||
var slide = SlidesOf(document)[0];
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(ValidationErrorsOf(document), Is.Empty);
|
||||
Assert.That(slide.Slide!.Descendants<P.Picture>(), Is.Empty);
|
||||
Assert.That(slide.ImageParts, Is.Empty, "The poster frame leaves the file along with its shape.");
|
||||
Assert.That(slide.DataPartReferenceRelationships, Is.Empty, "The slide no longer refers to the video.");
|
||||
Assert.That(document.DataParts, Is.Empty, "The video leaves the file along with its shape.");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task ALinkOfAKeptSlideKeepsNoRemovedSlideInTheFile()
|
||||
{
|
||||
var templateOptions = new TestTemplateOptions(Slides:
|
||||
[
|
||||
new TestSlide(2, (TestPlaceholder.Title(), "Agenda")) { Elements = [TestElement.TextBox(HEADING, "Launch"), TestElement.TextBox(LEFT_TEXT, "Budget")] },
|
||||
new TestSlide(2, (TestPlaceholder.Title(), "Launch")) { Elements = [TestElement.Video(RIGHT_PICTURE, 4, 5, 6)] },
|
||||
new TestSlide(2, (TestPlaceholder.Title(), "Budget"))
|
||||
]);
|
||||
|
||||
using var templateFile = TestTemplate.Create(templateOptions, Layouts());
|
||||
using (var templateDocument = PresentationDocument.Open(templateFile, true))
|
||||
{
|
||||
// The agenda leads to both other slides, as a table of contents does:
|
||||
var templateSlides = SlidesOf(templateDocument);
|
||||
LinkText(templateSlides[0], "Launch", templateSlides[1]);
|
||||
LinkText(templateSlides[0], "Budget", templateSlides[2]);
|
||||
}
|
||||
|
||||
var (file, _) = await WriteFromAsync(templateFile, new SlideDeckSpec("Weekly", [Keep(1), Keep(3)]), OPTIONS);
|
||||
using var document = PresentationDocument.Open(file, false);
|
||||
var slides = SlidesOf(document);
|
||||
var links = slides[0].Slide!.Descendants<A.HyperlinkOnClick>().ToList();
|
||||
|
||||
using (Assert.EnterMultipleScope())
|
||||
{
|
||||
Assert.That(ValidationErrorsOf(document), Is.Empty);
|
||||
Assert.That(document.GetAllParts().OfType<SlidePart>().Count(), Is.EqualTo(2), "The removed slide leaves the file, although the agenda led to it.");
|
||||
Assert.That(document.DataParts, Is.Empty, "The video of the removed slide leaves the file along with it.");
|
||||
Assert.That(links, Has.Count.EqualTo(1), "Only the link to the slide which is gone is gone.");
|
||||
Assert.That(links.Select(link => slides[0].GetPartById(link.Id!.Value!)), Has.All.SameAs(slides[1]), "The link to the kept slide still leads to it.");
|
||||
Assert.That(slides[0].Slide!.InnerText, Does.Contain("Launch"), "The text of the link stays, as a plain text.");
|
||||
}
|
||||
}
|
||||
|
||||
[Test]
|
||||
public async Task RemovingAnAnimatedShapeDropsTheAnimationsOfItsSlide()
|
||||
{
|
||||
@@ -676,6 +725,15 @@ public sealed class PresentationWriterTests
|
||||
private static P.Shape ShapeWithIdOf(SlidePart slide, uint id) => slide.Slide!.Descendants<P.Shape>()
|
||||
.Single(shape => shape.NonVisualShapeProperties?.NonVisualDrawingProperties?.Id?.Value == id);
|
||||
|
||||
/// <summary>
|
||||
/// Turns a text of a slide into a link to another slide, as PowerPoint writes one.
|
||||
/// </summary>
|
||||
private static void LinkText(SlidePart slide, string text, SlidePart target)
|
||||
{
|
||||
var run = slide.Slide!.Descendants<A.Run>().Single(run => run.InnerText == text);
|
||||
run.RunProperties = new A.RunProperties(new A.HyperlinkOnClick { Id = slide.GetIdOfPart(slide.AddPart(target)), Action = "ppaction://hlinksldjump" });
|
||||
}
|
||||
|
||||
private static TestLayout[] Layouts() =>
|
||||
[
|
||||
new("A Title", TestPlaceholder.Title(), TestPlaceholder.Subtitle(SUBTITLE), TestPlaceholder.Footer(10, FOOTER), TestPlaceholder.SlideNumber(11, SLIDE_NUMBER)),
|
||||
@@ -696,19 +754,29 @@ public sealed class PresentationWriterTests
|
||||
/// <summary>
|
||||
/// Writes a presentation from a template file of the test's own, e.g., from a presentation written before.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// The presentation comes about as in the Slide Assistant: from a template file into the file the user chose.
|
||||
/// </remarks>
|
||||
private static async Task<WrittenPresentation> WriteFromAsync(Stream templateFile, SlideDeckSpec deck, PresentationWriteOptions options, IPictureSource? pictures = null)
|
||||
{
|
||||
templateFile.Position = 0;
|
||||
var template = PresentationTemplate.Read(templateFile);
|
||||
templateFile.Position = 0;
|
||||
var folder = Directory.CreateDirectory(Path.Join(Path.GetTempPath(), "mindwork-ai-studio-tests", Guid.NewGuid().ToString("N"))).FullName;
|
||||
try
|
||||
{
|
||||
var templatePath = Path.Join(folder, "template.pptx");
|
||||
var targetPath = Path.Join(folder, "presentation.pptx");
|
||||
templateFile.Position = 0;
|
||||
await using (var file = new FileStream(templatePath, FileMode.CreateNew, FileAccess.Write))
|
||||
await templateFile.CopyToAsync(file);
|
||||
|
||||
// The writer edits a copy of the template, as the Slide Assistant does with one on disk:
|
||||
var output = new MemoryStream();
|
||||
await templateFile.CopyToAsync(output);
|
||||
output.Position = 0;
|
||||
var result = await PresentationWriter.WriteAsync(output, template, deck, options, pictures ?? new FakePictureSource(), CancellationToken.None);
|
||||
output.Position = 0;
|
||||
return new WrittenPresentation(output, result);
|
||||
var basis = PresentationTemplate.ReadFile(templatePath, NullLogger.Instance).DescribeBasisOf(deck);
|
||||
var result = await PresentationFile.CreateAsync(templatePath, targetPath, deck, basis, options, pictures ?? new FakePictureSource(), NullLogger.Instance, CancellationToken.None);
|
||||
Assert.That(result.IsWritten, Is.True, "The template stays as it is, so the deck still fits.");
|
||||
return new WrittenPresentation(new MemoryStream(await File.ReadAllBytesAsync(targetPath)), result);
|
||||
}
|
||||
finally
|
||||
{
|
||||
Directory.Delete(folder, true);
|
||||
}
|
||||
}
|
||||
|
||||
private static List<string> ValidationErrorsOf(PresentationDocument document) => new OpenXmlValidator(FileFormatVersions.Office2019)
|
||||
@@ -765,5 +833,5 @@ public sealed class PresentationWriterTests
|
||||
/// </summary>
|
||||
/// <param name="File">The presentation, positioned at its start.</param>
|
||||
/// <param name="Result">What happened beyond writing.</param>
|
||||
private sealed record WrittenPresentation(MemoryStream File, PresentationWriteResult Result);
|
||||
private sealed record WrittenPresentation(MemoryStream File, PresentationFileResult Result);
|
||||
}
|
||||
@@ -1,3 +1,4 @@
|
||||
using System.IO.Packaging;
|
||||
using System.Text;
|
||||
|
||||
using AIStudio.Tools.PowerPoint;
|
||||
@@ -226,6 +227,44 @@ internal static class TestTemplate
|
||||
return PresentationTemplate.Read(stream);
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Adds a video to a slide of a presentation file as PowerPoint stores it: uncompressed, behind the slides, which
|
||||
/// the update mode of ZipArchive would load into memory.
|
||||
/// </summary>
|
||||
/// <param name="path">The presentation file.</param>
|
||||
/// <param name="slideNumber">The 1-based number of the slide in the order of the presentation.</param>
|
||||
/// <param name="video">The content of the video.</param>
|
||||
/// <param name="videoPartName">The name of the part of the video.</param>
|
||||
public static void AddVideo(string path, int slideNumber, byte[] video, string videoPartName = "/ppt/media/video1.mp4")
|
||||
{
|
||||
Uri slideUri;
|
||||
using (var document = PresentationDocument.Open(path, false))
|
||||
{
|
||||
var presentationPart = document.PresentationPart!;
|
||||
var slideId = presentationPart.Presentation!.SlideIdList!.Elements<P.SlideId>().ElementAt(slideNumber - 1);
|
||||
slideUri = presentationPart.GetPartById(slideId.RelationshipId!.Value!).Uri;
|
||||
}
|
||||
|
||||
using var package = Package.Open(path, FileMode.Open, FileAccess.ReadWrite);
|
||||
var videoPart = package.CreatePart(new Uri(videoPartName, UriKind.Relative), "video/mp4", CompressionOption.NotCompressed);
|
||||
using (var stream = videoPart.GetStream())
|
||||
stream.Write(video);
|
||||
|
||||
package.GetPart(slideUri).CreateRelationship(videoPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/video");
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The content of a video for a test, which no compression shrinks.
|
||||
/// </summary>
|
||||
/// <param name="size">The size in bytes.</param>
|
||||
/// <param name="seed">Tells videos of the same size apart.</param>
|
||||
public static byte[] VideoOf(int size, int seed = 1179)
|
||||
{
|
||||
var video = new byte[size];
|
||||
new Random(seed).NextBytes(video);
|
||||
return video;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// The shape tree of a layout, a master or a slide.
|
||||
/// </summary>
|
||||
@@ -423,6 +462,34 @@ internal sealed record TestElement(Func<uint, SlidePart, OpenXmlElement> Create)
|
||||
new P.ShapeProperties(TransformOf(bounds), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }));
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A video as PowerPoint embeds one: a picture with a poster frame, which refers to the video twice, once for older
|
||||
/// versions of PowerPoint and once for newer ones.
|
||||
/// </summary>
|
||||
public static TestElement Video(SlotBounds bounds, params byte[] data) => new((id, slidePart) =>
|
||||
{
|
||||
var mediaPart = ((PresentationDocument)slidePart.OpenXmlPackage).CreateMediaDataPart(MediaDataPartType.Mp4);
|
||||
using (var stream = new MemoryStream(data))
|
||||
mediaPart.FeedData(stream);
|
||||
|
||||
var posterPart = slidePart.AddImagePart("image/png");
|
||||
using (var stream = new MemoryStream([1, 2, 3]))
|
||||
posterPart.FeedData(stream);
|
||||
|
||||
var videoId = slidePart.AddVideoReferenceRelationship(mediaPart).Id;
|
||||
var mediaId = slidePart.AddMediaReferenceRelationship(mediaPart).Id;
|
||||
return new P.Picture(
|
||||
new P.NonVisualPictureProperties(
|
||||
new P.NonVisualDrawingProperties { Id = id, Name = $"Video {id}" },
|
||||
new P.NonVisualPictureDrawingProperties(new A.PictureLocks { NoChangeAspect = true }),
|
||||
new P.ApplicationNonVisualDrawingProperties(
|
||||
new A.VideoFromFile { Link = videoId },
|
||||
new P.ApplicationNonVisualDrawingPropertiesExtensionList(
|
||||
new P.ApplicationNonVisualDrawingPropertiesExtension(new P14.Media { Embed = mediaId }) { Uri = "{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}" }))),
|
||||
new P.BlipFill(new A.Blip { Embed = slidePart.GetIdOfPart(posterPart) }, new A.Stretch(new A.FillRectangle())),
|
||||
new P.ShapeProperties(TransformOf(bounds), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }));
|
||||
});
|
||||
|
||||
/// <summary>
|
||||
/// A bar chart without data, with a chart part of its own.
|
||||
/// </summary>
|
||||
|
||||
Reference in new issue
Block a user