Files
AI-Studio/app/MindWork AI Studio/Tools/DocumentSegments/OpenXmlSegmentFormat.cs
T

181 lines
8.5 KiB
C#

using System.Collections.ObjectModel;
using System.IO.Compression;
using AIStudio.Tools.OpenXml;
using AIStudio.Tools.Rust;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace AIStudio.Tools.DocumentSegments;
/// <summary>
/// A format of Office documents, e.g., Word documents, whose paragraphs a model works on.
/// </summary>
/// <remarks>
/// The source is read again, for reading only, and nothing is written when the results miss one of its paragraphs.
/// Reading and writing both go through a PackageSkeleton, which holds only the XML of the source: the writer changes the
/// DOM of the paragraphs in the skeleton, and the skeleton writes a new document with the parts whose paragraphs got new
/// words, streaming the pictures and videos through from the source. They never come into memory, nor into the
/// temporary folder, where the SDK copies whatever it opens for reading. The new document comes about in a
/// StagedDocument and goes into the file the user chose once it is complete, see TargetFile. A paragraph whose text
/// stays as it was keeps everything, its runs included.
/// </remarks>
/// <typeparam name="TDocument">The kind of Office document, e.g., WordprocessingDocument.</typeparam>
/// <typeparam name="TParagraph">A paragraph as the reader of the format returns it, with all its writer needs.</typeparam>
internal abstract class OpenXmlSegmentFormat<TDocument, TParagraph> : IDocumentSegmentFormat where TDocument : OpenXmlPackage
{
/// <summary>
/// How many times the size of its XML an Office document takes in memory while it is read and written, see
/// DocumentMemoryBudget.
/// </summary>
/// <remarks>
/// The DOM of the SDK, the segments, and the new words take up to about 30 times the unpacked size of the XML, as
/// measured with a Word document of many short paragraphs; a real presentation with videos took about 18 times.
/// </remarks>
private const int MEMORY_FACTOR = 30;
#region Implementation of IDocumentSegmentFormat
/// <inheritdoc />
public abstract FileTypeFilter FileType { get; }
/// <inheritdoc />
public abstract string LimitsNotice { get; }
/// <inheritdoc />
public long MaxTextSize => DocumentMemoryBudget.MaxTextSize(MEMORY_FACTOR);
/// <inheritdoc />
/// <remarks>
/// The entries of XML and of relationships, which a PackageSkeleton keeps, count with their unpacked size, which the
/// directory of the archive holds, so nothing is unpacked; pictures, videos, and other binary entries never come into
/// memory.
/// </remarks>
public long TextSizeOf(string path)
{
using var file = TemplateFile.OpenRead(path);
using var archive = new ZipArchive(file, ZipArchiveMode.Read);
return archive.Entries.Where(PackageSkeleton.HoldsXml).Sum(entry => entry.Length);
}
/// <inheritdoc />
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, ILogger logger, CancellationToken token) => Task.Run<IReadOnlyList<DocumentSegment>>(() =>
{
this.RefuseTooLargeText(path);
using var skeleton = PackageSkeleton.Create(path, this.FileExtension, logger, token);
using var file = skeleton.OpenRead();
using var document = this.Open(file, isEditable: false);
return this.ReadParagraphs(document).Select(this.SegmentOf).ToList();
}, token);
/// <inheritdoc />
public async Task<SegmentWriteResult> WriteAsync(string sourcePath, string targetPath, SegmentResults results, string languageTag, ILogger logger, CancellationToken token)
{
using var stagedDocument = StagedDocument.Create(this.FileExtension, logger);
var result = await Task.Run(() => this.WriteInto(sourcePath, stagedDocument.FilePath, results, languageTag, logger, token), token);
if (result.Outcome is SegmentWriteOutcome.WRITTEN)
await stagedDocument.WriteIntoAsync(targetPath, token);
return result;
}
#endregion
/// <summary>
/// The extension of the documents, with its dot, e.g., ".docx", for the skeleton and the new document in the staging folder.
/// </summary>
protected abstract string FileExtension { get; }
/// <summary>
/// Opens a document.
/// </summary>
/// <param name="stream">The file of the document.</param>
/// <param name="isEditable">Whether the document gets written.</param>
protected abstract TDocument Open(Stream stream, bool isEditable);
/// <summary>
/// Reads the paragraphs of a document which can be segments, in the order of the document.
/// </summary>
/// <param name="document">The document.</param>
protected abstract IReadOnlyList<TParagraph> ReadParagraphs(TDocument document);
/// <summary>
/// Gets the element of a paragraph, whose part the writer changes.
/// </summary>
/// <param name="paragraph">The paragraph, as ReadParagraphs returned it.</param>
protected abstract OpenXmlElement ElementOf(TParagraph paragraph);
/// <summary>
/// Gets the segment of a paragraph.
/// </summary>
/// <param name="paragraph">The paragraph, as ReadParagraphs returned it.</param>
protected abstract DocumentSegment SegmentOf(TParagraph paragraph);
/// <summary>
/// Replaces the words of a paragraph with its new words.
/// </summary>
/// <param name="paragraph">The paragraph, as ReadParagraphs returned it from the source read again.</param>
/// <param name="newText">The new words with tags, as the model wrote them.</param>
/// <param name="languageTag">The IETF tag of the language of the new words; empty to leave the languages as they are.</param>
/// <returns>Whether the paragraph kept all of its inline structure and formatting.</returns>
protected abstract bool Write(TParagraph paragraph, string newText, string languageTag);
/// <summary>
/// Writes the new words into the DOM of the source read again, and the new document into the given file.
/// </summary>
/// <remarks>
/// The SDK lets the DOM of a package opened for reading change in memory; it only refuses to save it, which the
/// skeleton does instead.
/// </remarks>
private SegmentWriteResult WriteInto(string sourcePath, string documentPath, SegmentResults results, string languageTag, ILogger logger, CancellationToken token)
{
this.RefuseTooLargeText(sourcePath);
using var skeleton = PackageSkeleton.Create(sourcePath, this.FileExtension, logger, token);
using var file = skeleton.OpenRead();
using var document = this.Open(file, isEditable: false);
var paragraphs = this.ReadParagraphs(document);
if (paragraphs.Any(paragraph => !results.Covers(this.SegmentOf(paragraph))))
return SegmentWriteResult.SOURCE_CHANGED;
var exactCount = 0;
var simplifiedCount = 0;
var changedParts = new HashSet<OpenXmlPart>();
foreach (var paragraph in paragraphs)
{
var segment = this.SegmentOf(paragraph);
if (!results.TryGetText(segment, out var newText) || newText == segment.Key)
continue;
// Taken before the writer puts the paragraph together again:
changedParts.Add(PartOf(this.ElementOf(paragraph)));
if (this.Write(paragraph, newText, languageTag))
exactCount++;
else
simplifiedCount++;
}
// False when the source changed since its skeleton was written, e.g., because Word saved it meanwhile:
return skeleton.TryWriteDocument(changedParts, ReadOnlyDictionary<string, string>.Empty, documentPath, token)
? new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount)
: SegmentWriteResult.SOURCE_CHANGED;
}
/// <summary>
/// Refuses a document whose text would not fit into the memory of this computer, before its DOM is read.
/// </summary>
/// <exception cref="DocumentTooLargeException">The text of the document is larger than MaxTextSize.</exception>
private void RefuseTooLargeText(string path)
{
var textSize = this.TextSizeOf(path);
var maxTextSize = this.MaxTextSize;
if (textSize > maxTextSize)
throw new DocumentTooLargeException(path, textSize, maxTextSize);
}
/// <summary>
/// Gets the part which holds an element of a document.
/// </summary>
private static OpenXmlPart PartOf(OpenXmlElement element) => element.Ancestors<OpenXmlPartRootElement>().FirstOrDefault()?.OpenXmlPart
?? throw new InvalidOperationException("A paragraph of the document belongs to no part.");
}