mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-03 03:54:24 +00:00
175 lines
8.0 KiB
C#
175 lines
8.0 KiB
C#
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.
|
||
|
|
/// 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.
|
||
|
|
/// </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 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(entry => entry.FullName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase) || entry.FullName.EndsWith(".rels", StringComparison.OrdinalIgnoreCase))
|
||
|
|
.Sum(entry => entry.Length);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <inheritdoc />
|
||
|
|
public Task<IReadOnlyList<DocumentSegment>> ReadAsync(string path, CancellationToken token) => Task.Run<IReadOnlyList<DocumentSegment>>(() =>
|
||
|
|
{
|
||
|
|
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);
|
||
|
|
|
||
|
|
/// <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, 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 new document in the StagedDocument.
|
||
|
|
/// </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
|
||
|
|
/// PackageRewrite does instead.
|
||
|
|
/// </remarks>
|
||
|
|
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<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++;
|
||
|
|
}
|
||
|
|
|
||
|
|
PackageRewrite.Write(sourcePath, changedParts, documentPath, token);
|
||
|
|
return new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount);
|
||
|
|
}
|
||
|
|
|
||
|
|
/// <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.");
|
||
|
|
}
|