using System.IO.Compression;
using AIStudio.Tools.OpenXml;
using AIStudio.Tools.Rust;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace AIStudio.Tools.DocumentSegments;
///
/// A format of Office documents, e.g., Word documents, whose paragraphs a model works on.
///
///
/// The source is read again, for reading only, and nothing is written when the results miss one of its paragraphs.
/// The writer changes the DOM of the paragraphs, and PackageRewrite writes a new document with the parts whose
/// paragraphs got new words, streaming every other entry through: the pictures and videos of a document never come
/// into memory. 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.
///
/// The kind of Office document, e.g., WordprocessingDocument.
/// A paragraph as the reader of the format returns it, with all its writer needs.
internal abstract class OpenXmlSegmentFormat : IDocumentSegmentFormat where TDocument : OpenXmlPackage
{
///
/// How many times the size of its XML an Office document takes in memory while it is read and written, see
/// DocumentMemoryBudget.
///
///
/// 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.
///
private const int MEMORY_FACTOR = 30;
#region Implementation of IDocumentSegmentFormat
///
public abstract FileTypeFilter FileType { get; }
///
public abstract string LimitsNotice { get; }
///
public long MaxTextSize => DocumentMemoryBudget.MaxTextSize(MEMORY_FACTOR);
///
///
/// The entries of XML and of relationships 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.
///
public long TextSizeOf(string path)
{
using var file = TemplateFile.OpenRead(path);
using var archive = new ZipArchive(file, ZipArchiveMode.Read);
return archive.Entries
.Where(entry => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase))
.Sum(entry => entry.Length);
}
///
public Task> ReadAsync(string path, CancellationToken token) => Task.Run>(() =>
{
this.RefuseTooLargeText(path);
using var file = TemplateFile.OpenRead(path);
using var document = this.Open(file, isEditable: false);
return this.ReadParagraphs(document).Select(this.SegmentOf).ToList();
}, token);
///
public async Task 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, token), token);
if (result.Outcome is SegmentWriteOutcome.WRITTEN)
await stagedDocument.WriteIntoAsync(targetPath, token);
return result;
}
#endregion
///
/// The extension of the documents, with its dot, e.g., ".docx", for the new document in the StagedDocument.
///
protected abstract string FileExtension { get; }
///
/// Opens a document.
///
/// The file of the document.
/// Whether the document gets written.
protected abstract TDocument Open(Stream stream, bool isEditable);
///
/// Reads the paragraphs of a document which can be segments, in the order of the document.
///
/// The document.
protected abstract IReadOnlyList ReadParagraphs(TDocument document);
///
/// Gets the element of a paragraph, whose part the writer changes.
///
/// The paragraph, as ReadParagraphs returned it.
protected abstract OpenXmlElement ElementOf(TParagraph paragraph);
///
/// Gets the segment of a paragraph.
///
/// The paragraph, as ReadParagraphs returned it.
protected abstract DocumentSegment SegmentOf(TParagraph paragraph);
///
/// Replaces the words of a paragraph with its new words.
///
/// The paragraph, as ReadParagraphs returned it from the source read again.
/// The new words with tags, as the model wrote them.
/// The IETF tag of the language of the new words; empty to leave the languages as they are.
/// Whether the paragraph kept all of its inline structure and formatting.
protected abstract bool Write(TParagraph paragraph, string newText, string languageTag);
///
/// Writes the new words into the DOM of the source read again, and the new document into the given file.
///
///
/// The SDK lets the DOM of a package opened for reading change in memory; it only refuses to save it, which
/// PackageRewrite does instead.
///
private SegmentWriteResult WriteInto(string sourcePath, string documentPath, SegmentResults results, string languageTag, CancellationToken token)
{
this.RefuseTooLargeText(sourcePath);
using var file = TemplateFile.OpenRead(sourcePath);
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();
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++;
}
PackageRewrite.Write(sourcePath, changedParts, documentPath, token);
return new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount);
}
///
/// Refuses a document whose text would not fit into the memory of this computer, before its DOM is read.
///
/// The text of the document is larger than MaxTextSize.
private void RefuseTooLargeText(string path)
{
var textSize = this.TextSizeOf(path);
var maxTextSize = this.MaxTextSize;
if (textSize > maxTextSize)
throw new DocumentTooLargeException(path, textSize, maxTextSize);
}
///
/// Gets the part which holds an element of a document.
///
private static OpenXmlPart PartOf(OpenXmlElement element) => element.Ancestors().FirstOrDefault()?.OpenXmlPart
?? throw new InvalidOperationException("A paragraph of the document belongs to no part.");
}