Added whole documents to the Translation, Grammar & Spelling, and Rewrite & Improve assistants (#1179)

Co-authored-by: Thorsten Sommer <SommerEngineering@users.noreply.github.com>
This commit is contained in:
Sabrina-devopsandThorsten Sommer authored and GitHub committed 2026-11-28 20:27:23 +01:00
1 parent f7666861f1
commit 918572c158
150 files changed
+12850 -302

No files matched your search

@@ -0,0 +1,27 @@
using DocumentFormat.OpenXml;
namespace AIStudio.Tools.OpenXml;
internal static class OpenXmlElementExtensions
{
/// <param name="element">The element.</param>
/// <typeparam name="T">The type of the element.</typeparam>
extension<T>(T element) where T : OpenXmlElement
{
/// <summary>
/// Takes the element out of its parent, if it has one, so that it can move to another place.
/// </summary>
/// <remarks>
/// Moving keeps everything within the element, e.g., a text box with the new words of its own paragraphs,
/// which a copy made before those were written would lack.
/// </remarks>
/// <returns>The element, without a parent.</returns>
public T Detached()
{
if (element.Parent is not null)
element.Remove();
return element;
}
}
}
@@ -0,0 +1,37 @@
using System.Text;
using System.Xml;
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// Prepares texts for the Office documents AI Studio writes.
/// </summary>
internal static class OpenXmlText
{
/// <summary>
/// Leaves out the characters XML cannot carry, which a model may produce now and then. The file
/// could not be saved with them.
/// </summary>
/// <remarks>
/// A character outside the Basic Multilingual Plane, such as an emoji, takes two chars; such a
/// pair stays, whereas a half of one alone goes.
/// </remarks>
/// <param name="text">The text.</param>
/// <returns>The text without the characters XML cannot carry.</returns>
public static string XmlSafe(string text)
{
if (text.All(XmlConvert.IsXmlChar))
return text;
var result = new StringBuilder(text.Length);
for (var index = 0; index < text.Length; index++)
{
if (XmlConvert.IsXmlChar(text[index]))
result.Append(text[index]);
else if (index + 1 < text.Length && XmlConvert.IsXmlSurrogatePair(text[index + 1], text[index]))
result.Append(text[index]).Append(text[++index]);
}
return result.ToString();
}
}
@@ -0,0 +1,80 @@
using System.IO.Compression;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// Writes a copy of an Office document in which some parts have a changed DOM, without holding the rest of the
/// document in memory.
/// </summary>
/// <remarks>
/// <para>
/// The Open XML SDK saves a package in the update mode of ZipArchive, which loads every entry behind the first changed
/// one into memory, e.g., all pictures and videos behind the first slide, often hundreds of megabytes. So the source
/// stays open for reading only, and a new archive comes about entry by entry: each entry of the source is streamed
/// through in its order, and each changed part is written from its DOM instead.
/// </para>
/// <para>
/// This serves only changes within the XML of existing parts. Whoever adds or removes parts or relationships, as the
/// Slide Assistant does, needs the SDK to save the package.
/// </para>
/// </remarks>
internal static class PackageRewrite
{
/// <summary>
/// Writes a copy of the source with the DOM of the changed parts.
/// </summary>
/// <param name="sourcePath">The source, which stays as it is.</param>
/// <param name="changedParts">The parts of the source, opened by the SDK, whose DOM changed.</param>
/// <param name="documentPath">The new document, which must not exist yet.</param>
/// <param name="token">The cancellation token, checked between entries.</param>
/// <exception cref="InvalidOperationException">A changed part has no entry in the source, e.g., because the source changed.</exception>
public static void Write(string sourcePath, IReadOnlyCollection<OpenXmlPart> changedParts, string documentPath, CancellationToken token)
{
var partsByEntry = changedParts.ToDictionary(EntryNameOf, StringComparer.OrdinalIgnoreCase);
using var sourceFile = TemplateFile.OpenRead(sourcePath);
using var source = new ZipArchive(sourceFile, ZipArchiveMode.Read);
using var documentFile = new FileStream(documentPath, FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None);
using var document = new ZipArchive(documentFile, ZipArchiveMode.Create);
var written = 0;
foreach (var entry in source.Entries)
{
token.ThrowIfCancellationRequested();
if (partsByEntry.TryGetValue(entry.FullName, out var part))
{
var newEntry = CreateEntryLike(document, entry, CompressionLevel.Optimal);
using var stream = newEntry.Open();
RootElementOf(part).Save(stream);
written++;
continue;
}
// A stored entry, such as a video, stays stored; deflating it once more would take time and gain nothing:
var copy = CreateEntryLike(document, entry, entry.CompressedLength >= entry.Length ? CompressionLevel.NoCompression : CompressionLevel.Optimal);
using var from = entry.Open();
using var to = copy.Open();
from.CopyTo(to);
}
if (written != partsByEntry.Count)
throw new InvalidOperationException($"{partsByEntry.Count - written} changed part(s) have no entry in the document '{sourcePath}'.");
}
/// <summary>
/// The name of the entry which holds a part, e.g., "ppt/slides/slide1.xml" for the part "/ppt/slides/slide1.xml".
/// </summary>
private static string EntryNameOf(OpenXmlPart part) => Uri.UnescapeDataString(part.Uri.OriginalString).TrimStart('/');
private static OpenXmlPartRootElement RootElementOf(OpenXmlPart part) => part.RootElement ?? throw new InvalidOperationException($"The changed part '{part.Uri}' has no XML.");
private static ZipArchiveEntry CreateEntryLike(ZipArchive archive, ZipArchiveEntry entry, CompressionLevel compressionLevel)
{
var newEntry = archive.CreateEntry(entry.FullName, compressionLevel);
newEntry.LastWriteTime = entry.LastWriteTime;
newEntry.ExternalAttributes = entry.ExternalAttributes;
return newEntry;
}
}
@@ -0,0 +1,81 @@
using AIStudio.Settings;
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// A file below the data directory, in which a new Office document comes about before it goes into the file the
/// user chose, see TargetFile.
/// </summary>
/// <remarks>
/// <para>
/// The folder lies below the data directory rather than in the temporary folder of the system: on many Linux
/// systems, the temporary folder lives in memory (tmpfs), and a document with videos takes hundreds of megabytes.
/// A backup leaves the folder out, see DataBackupContents.
/// </para>
/// <para>
/// Disposing the file removes it. A file left behind, e.g., after a crash, is removed by the next document which
/// comes about here, once it is a day old. Tests, which have no data directory, use the temporary folder.
/// </para>
/// </remarks>
internal sealed class StagedDocument : IDisposable
{
/// <summary>
/// The folder below the data directory, see DataBackupContents.
/// </summary>
public const string DIRECTORY = ".document-staging/";
private static readonly TimeSpan AGE_OF_LEFTOVERS = TimeSpan.FromDays(1);
private readonly ILogger logger;
private StagedDocument(string filePath, ILogger logger)
{
this.FilePath = filePath;
this.logger = logger;
}
/// <summary>
/// The path of the file, which does not exist until the document is written into it.
/// </summary>
public string FilePath { get; }
/// <summary>
/// Reserves a file for a new document and removes what earlier documents left behind.
/// </summary>
/// <param name="fileExtension">The extension of the document, including the leading dot.</param>
/// <param name="logger">Where to report a file which cannot be removed.</param>
/// <returns>The file, which does not exist yet.</returns>
public static StagedDocument Create(string fileExtension, ILogger logger)
{
var directory = Path.Join(SettingsManager.DataDirectory ?? Path.GetTempPath(), DIRECTORY);
Directory.CreateDirectory(directory);
RemoveLeftovers(directory, logger);
return new StagedDocument(Path.Join(directory, $"{Guid.NewGuid():N}{fileExtension}"), logger);
}
/// <summary>
/// Streams the complete document into the file the user chose, see TargetFile.WriteOverAsync.
/// </summary>
/// <param name="targetPath">The path of the file the user chose.</param>
/// <param name="token">The cancellation token.</param>
public Task WriteIntoAsync(string targetPath, CancellationToken token) => TargetFile.WriteOverAsync(this.FilePath, targetPath, this.logger, token);
/// <summary>
/// Removes the file.
/// </summary>
public void Dispose() => TargetFile.DeleteQuietly(this.FilePath, this.logger);
/// <summary>
/// Removes the files which are older than a day, e.g., after a crash.
/// </summary>
private static void RemoveLeftovers(string directory, ILogger logger)
{
var oldest = DateTime.UtcNow - AGE_OF_LEFTOVERS;
foreach (var file in new DirectoryInfo(directory).EnumerateFiles())
{
if (file.LastWriteTimeUtc < oldest)
TargetFile.DeleteQuietly(file.FullName, logger);
}
}
}
@@ -0,0 +1,58 @@
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// Writes a complete Office document into the file the user chose.
/// </summary>
/// <remarks>
/// The document comes about in a file of its own first, and only the complete document is streamed into the target.
/// Nothing is created next to the target: inside the Flatpak, the save dialog grants access to exactly the chosen
/// file, and to nothing next to it. A failure before the document is complete therefore leaves the target untouched.
/// </remarks>
internal static class TargetFile
{
/// <summary>
/// Streams a complete document into the file the user chose.
/// </summary>
/// <remarks>
/// The file is written over rather than removed and created anew, which the Flatpak would not allow. Once writing
/// has begun, a failure removes the file: a half-written document is worse than none. A file which cannot even be
/// opened, e.g., because PowerPoint or Word shows it, stays as it is.
/// </remarks>
/// <param name="documentPath">The complete document.</param>
/// <param name="targetPath">The path of the file the user chose. It may exist; the save dialog asked about overwriting it.</param>
/// <param name="logger">Where to report a half-written target which cannot be removed.</param>
/// <param name="token">The cancellation token.</param>
public static async Task WriteOverAsync(string documentPath, string targetPath, ILogger logger, CancellationToken token)
{
await using var document = new FileStream(documentPath, FileMode.Open, FileAccess.Read, FileShare.Read);
var target = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None);
try
{
await using (target)
await document.CopyToAsync(target, token);
}
catch
{
DeleteQuietly(targetPath, logger);
throw;
}
}
/// <summary>
/// Removes a file which is of no use anymore, and only reports when that fails.
/// </summary>
/// <param name="path">The file.</param>
/// <param name="logger">Where to report a file which cannot be removed.</param>
public static void DeleteQuietly(string path, ILogger logger)
{
try
{
if (File.Exists(path))
File.Delete(path);
}
catch (Exception e)
{
logger.LogWarning(e, "The file '{FilePath}' cannot be deleted.", path);
}
}
}
@@ -0,0 +1,88 @@
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// A copy of a template in the temporary folder, in which an Office document comes about before it
/// goes into the file the user chose.
/// </summary>
/// <remarks>
/// <para>
/// Only the complete document is streamed into the file the user chose, see TargetFile, so a failure
/// before the document is complete leaves the target untouched. Disposing the copy removes it.
/// </para>
/// <para>
/// The writer edits the copy with the Open XML SDK, which saves it in the update mode of ZipArchive.
/// That mode loads every entry behind the first changed one into memory, e.g., the pictures and videos
/// behind the first slide. The Slide Assistant needs it all the same, since it adds and removes parts.
/// A writer which only changes the XML of existing parts uses PackageRewrite instead, as the document
/// segments do.
/// </para>
/// </remarks>
internal sealed class TemplateCopy : IDisposable
{
private readonly ILogger logger;
private TemplateCopy(string filePath, ILogger logger)
{
this.FilePath = filePath;
this.logger = logger;
}
/// <summary>
/// The path of the copy.
/// </summary>
public string FilePath { get; }
/// <summary>
/// Copies the template into a folder below the temporary folder of the system.
/// </summary>
/// <param name="templatePath">The path of the template.</param>
/// <param name="temporaryDirectory">The name of the folder below the temporary folder, one per
/// kind of document.</param>
/// <param name="fileExtension">The extension of the document which comes about, including the
/// leading dot.</param>
/// <param name="logger">Where to report a temporary file which cannot be removed.</param>
/// <param name="token">The cancellation token.</param>
/// <returns>The copy.</returns>
public static async Task<TemplateCopy> CreateAsync(string templatePath, string temporaryDirectory, string fileExtension, ILogger logger, CancellationToken token)
{
var directory = Path.Join(Path.GetTempPath(), temporaryDirectory);
Directory.CreateDirectory(directory);
var copy = new TemplateCopy(Path.Join(directory, $"{Guid.NewGuid():N}{fileExtension}"), logger);
try
{
await using var templateFile = TemplateFile.OpenRead(templatePath);
await using var copyFile = new FileStream(copy.FilePath, FileMode.CreateNew, FileAccess.Write, FileShare.None);
await templateFile.CopyToAsync(copyFile, token);
}
catch
{
copy.Dispose();
throw;
}
return copy;
}
/// <summary>
/// Opens the copy for the writer to edit it.
/// </summary>
/// <returns>The copy, opened for reading and writing.</returns>
public FileStream OpenForEditing() => new(this.FilePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
/// <summary>
/// Streams the complete document into the file the user chose, see TargetFile.WriteOverAsync.
/// </summary>
/// <param name="targetPath">The path of the file the user chose. It may exist; the save dialog
/// asked about overwriting it.</param>
/// <param name="token">The cancellation token.</param>
public Task WriteIntoAsync(string targetPath, CancellationToken token) => TargetFile.WriteOverAsync(this.FilePath, targetPath, this.logger, token);
/// <summary>
/// Removes the copy.
/// </summary>
/// <remarks>
/// A copy of the template left behind would pile up in the temporary folder with every attempt.
/// </remarks>
public void Dispose() => TargetFile.DeleteQuietly(this.FilePath, this.logger);
}
@@ -0,0 +1,28 @@
namespace AIStudio.Tools.OpenXml;
/// <summary>
/// Opens the template of an Office document, such as a PowerPoint or a Word template.
/// </summary>
internal static class TemplateFile
{
/// <summary>
/// How a template file is opened for reading.
/// </summary>
/// <remarks>
/// Other programs may go on writing or deleting the file meanwhile. PowerPoint and Word keep a
/// file open for writing as long as they show it, and a template which is still open there has
/// to be readable all the same.
/// </remarks>
private const FileShare FILE_SHARE = FileShare.ReadWrite | FileShare.Delete;
/// <summary>
/// Opens the template file at the given path for reading.
/// </summary>
/// <remarks>
/// Throws when the file is missing or cannot be opened; the caller decides what the user hears
/// about it.
/// </remarks>
/// <param name="path">The path of the template file.</param>
/// <returns>The file, opened for reading.</returns>
public static FileStream OpenRead(string path) => new(path, FileMode.Open, FileAccess.Read, FILE_SHARE);
}