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

@@ -17,7 +17,9 @@ to `app/AGENTS.md`, which apply here as well.
which gets one repair round.
5. `SlideDeckSpec.ToMarkdownOutline` shows the result as an outline, and `PresentationWriter.WriteAsync`
writes the file: a copy of the template, with its slides replaced. `PresentationFile.CreateAsync` makes
that copy in the temporary folder and streams it into the target once it is complete.
that copy in the temporary folder and streams it into the target once it is complete, both with
`TemplateCopy` from `app/MindWork AI Studio/Tools/OpenXml/`, which every Office document written from
a template shares.
## Rules which are easy to break
@@ -64,11 +66,16 @@ to `app/AGENTS.md`, which apply here as well.
(`PresentationWriteOptions.KeepEmptyPicturePlaceholders`), for pictures of their own.
- **No copy of a file in memory.** Templates of organizations carry pictures and videos and easily reach
a hundred megabytes, and AI Studio also runs on small devices. Read templates from their file, and
let the writer edit a copy on disk. The Open XML SDK holds the compressed parts of the file in memory
while it saves, which is all it costs; a `MemoryStream` with the whole file multiplies that.
let the writer edit a copy on disk; a `MemoryStream` with the whole file would hold it once more. The
Open XML SDK saves the copy in the update mode of ZipArchive, which loads every entry behind the first
changed one into memory, compressed, e.g., the pictures and videos behind the first slide. The Slide
Assistant accepts that because it adds and removes parts; a writer which only changes the XML of existing
parts writes with `PackageRewrite` instead, as the document segments do.
- **Write only into the file the user chose.** Inside the Flatpak, the save dialog grants access to
exactly that file, so nothing may be created, renamed, or moved next to it. Temporary files go into
the temporary folder, and the finished presentation is written over the chosen file, never moved there.
`TemplateCopy` keeps both rules, and `TemplateFile.OpenRead` opens a template which PowerPoint still
shows; use them rather than a `FileStream` of your own.
- **Removing a shape removes what only it used:** its image, chart, or diagram parts, and the animations
of its slide, see `PresentationWriter.RemoveShape`. Otherwise PowerPoint offers to repair the file.
@@ -1,14 +1,13 @@
using AIStudio.Tools.OpenXml;
namespace AIStudio.Tools.PowerPoint;
/// <summary>
/// Creates a presentation file from a template and a slide deck.
/// </summary>
/// <remarks>
/// The presentation comes about in a copy of the template in the temporary folder, and only the
/// complete presentation is streamed into the file the user chose. Nothing is created next to that
/// file: inside the Flatpak, the save dialog grants access to exactly the chosen file, and to nothing
/// next to it. A failure before the presentation is complete therefore leaves the target untouched,
/// and neither the template nor the presentation has to be held in memory.
/// The presentation comes about in a TemplateCopy, and only the complete presentation is streamed
/// into the file the user chose; TemplateCopy says why.
/// </remarks>
internal static class PresentationFile
{
@@ -35,77 +34,20 @@ internal static class PresentationFile
/// <returns>Whether the presentation was written, and which pictures it lacks.</returns>
public static async Task<PresentationFileResult> CreateAsync(string templatePath, string targetPath, SlideDeckSpec deck, IReadOnlyDictionary<string, string> basis, PresentationWriteOptions options, IPictureSource pictures, ILogger logger, CancellationToken token)
{
var temporaryDirectory = Path.Join(Path.GetTempPath(), TEMPORARY_DIRECTORY);
Directory.CreateDirectory(temporaryDirectory);
using var copy = await TemplateCopy.CreateAsync(templatePath, TEMPORARY_DIRECTORY, ".pptx", logger, token);
var temporaryPath = Path.Join(temporaryDirectory, $"{Guid.NewGuid():N}.pptx");
try
PresentationWriteResult written;
await using (var presentationFile = copy.OpenForEditing())
{
await using (var templateFile = new FileStream(templatePath, FileMode.Open, FileAccess.Read, PresentationTemplate.FILE_SHARE))
await using (var copy = new FileStream(temporaryPath, FileMode.CreateNew, FileAccess.Write, FileShare.None))
await templateFile.CopyToAsync(copy, token);
var currentTemplate = PresentationTemplate.Read(presentationFile);
presentationFile.Position = 0;
if (!SlideDeckSpecValidator.StillFits(deck, currentTemplate, basis))
return PresentationFileResult.TEMPLATE_CHANGED;
PresentationWriteResult written;
await using (var presentationFile = new FileStream(temporaryPath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
var currentTemplate = PresentationTemplate.Read(presentationFile);
presentationFile.Position = 0;
if (!SlideDeckSpecValidator.StillFits(deck, currentTemplate, basis))
return PresentationFileResult.TEMPLATE_CHANGED;
written = await PresentationWriter.WriteAsync(presentationFile, currentTemplate, deck, options, pictures, token);
}
written = await PresentationWriter.WriteAsync(presentationFile, currentTemplate, deck, options, pictures, token);
}
await CopyIntoTargetAsync(temporaryPath, targetPath, logger, token);
return new PresentationFileResult(true, written.SkippedPictures);
}
finally
{
DeleteQuietly(temporaryPath, logger);
}
}
/// <summary>
/// Streams the complete presentation 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 presentation is
/// worse than none. A file which cannot even be opened, e.g., because PowerPoint shows it, stays
/// as it is.
/// </remarks>
private static async Task CopyIntoTargetAsync(string presentationPath, string targetPath, ILogger logger, CancellationToken token)
{
await using var presentation = new FileStream(presentationPath, FileMode.Open, FileAccess.Read, FileShare.Read);
var target = new FileStream(targetPath, FileMode.Create, FileAccess.Write, FileShare.None);
try
{
await using (target)
await presentation.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>
/// <remarks>
/// A copy of the template left behind would pile up in the temporary folder with every attempt.
/// </remarks>
private 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);
}
await copy.WriteIntoAsync(targetPath, token);
return new PresentationFileResult(true, written.SkippedPictures);
}
}
@@ -1,3 +1,5 @@
using AIStudio.Tools.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using A = DocumentFormat.OpenXml.Drawing;
@@ -56,16 +58,6 @@ internal sealed partial class PresentationTemplate
/// </summary>
private const int READING_ROWS = 50;
/// <summary>
/// How a template file is opened for reading.
/// </summary>
/// <remarks>
/// Other programs may go on writing or deleting the file meanwhile. PowerPoint keeps a file open
/// for writing as long as it shows it, and a template which is still open there has to be
/// readable all the same.
/// </remarks>
public const FileShare FILE_SHARE = FileShare.ReadWrite | FileShare.Delete;
/// <summary>
/// Reads the template file at the given path, as Read does with a stream.
/// </summary>
@@ -77,7 +69,7 @@ internal sealed partial class PresentationTemplate
/// <returns>The template.</returns>
public static PresentationTemplate ReadFile(string path)
{
using var stream = new FileStream(path, FileMode.Open, FileAccess.Read, FILE_SHARE);
using var stream = TemplateFile.OpenRead(path);
return Read(stream);
}
@@ -1,5 +1,4 @@
using System.Text;
using System.Xml;
using AIStudio.Tools.OpenXml;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
@@ -233,7 +232,7 @@ internal static partial class PresentationWriter
var row = new A.TableRow { Height = TABLE_ROW_HEIGHT };
for (var column = 0; column < columns; column++)
{
var text = column < cells.Count ? XmlSafe(cells[column]) : string.Empty;
var text = column < cells.Count ? OpenXmlText.XmlSafe(cells[column]) : string.Empty;
var paragraph = text.Length > 0 ? new A.Paragraph(new A.Run(new A.Text(text))) : new A.Paragraph();
row.Append(new A.TableCell(new A.TextBody(new A.BodyProperties(), new A.ListStyle(), paragraph), new A.TableCellProperties()));
}
@@ -247,7 +246,7 @@ internal static partial class PresentationWriter
if (paragraph.Level > 0)
result.Append(new A.ParagraphProperties { Level = paragraph.Level });
result.Append(new A.Run(new A.Text(XmlSafe(paragraph.Text))));
result.Append(new A.Run(new A.Text(OpenXmlText.XmlSafe(paragraph.Text))));
return result;
}
@@ -260,27 +259,6 @@ internal static partial class PresentationWriter
.Select(line => ParagraphOf(new SlideParagraph(line, 0)))
.ToList();
/// <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>
private 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();
}
/// <summary>
/// A copy of a layout placeholder, for a slide to refer to it.
/// </summary>