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,44 @@
using AIStudio.Tools.PluginSystem;
using AIStudio.Tools.Rust;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
namespace AIStudio.Tools.DocumentSegments.PowerPoint;
/// <summary>
/// PowerPoint presentations (.pptx), whose slides and notes a model works on, while the design, the pictures, the
/// animations, and the masters and layouts of the slides stay as they are.
/// </summary>
/// <remarks>
/// How the new presentation comes about is the same for every Office document, see OpenXmlSegmentFormat. See
/// SlideSegmentReader for what becomes a segment.
/// </remarks>
internal sealed class PowerPointSegmentFormat : OpenXmlSegmentFormat<PresentationDocument, SlideTextParagraph>
{
private static string TA(string fallbackEN) => I18N.I.TA(fallbackEN, typeof(PowerPointSegmentFormat).Namespace, nameof(PowerPointSegmentFormat));
/// <inheritdoc />
public override FileTypeFilter FileType => FileTypes.POWER_POINT_PRESENTATION;
/// <inheritdoc />
public override string LimitsNotice => TA("Charts, SmartArt, the alternative texts of pictures, the properties of the presentation, such as its title, and the masters and layouts of the slides stay as they are. Paragraphs keep their direction, so new text in a language written from right to left, such as Arabic or Hebrew, may need adjustments. New text often needs more room than the original, so please check the text boxes on your slides.");
/// <inheritdoc />
protected override string FileExtension => ".pptx";
/// <inheritdoc />
protected override PresentationDocument Open(Stream stream, bool isEditable) => PresentationDocument.Open(stream, isEditable);
/// <inheritdoc />
protected override IReadOnlyList<SlideTextParagraph> ReadParagraphs(PresentationDocument document) => SlideSegmentReader.Read(document);
/// <inheritdoc />
protected override OpenXmlElement ElementOf(SlideTextParagraph paragraph) => paragraph.Paragraph;
/// <inheritdoc />
protected override DocumentSegment SegmentOf(SlideTextParagraph paragraph) => paragraph.Segment;
/// <inheritdoc />
protected override bool Write(SlideTextParagraph paragraph, string newText, string languageTag) => SlideParagraphWriter.Write(paragraph, newText, languageTag);
}
@@ -0,0 +1,121 @@
using AIStudio.Tools.OpenXml;
using DocumentFormat.OpenXml;
using A = DocumentFormat.OpenXml.Drawing;
namespace AIStudio.Tools.DocumentSegments.PowerPoint;
/// <summary>
/// Puts a paragraph of a slide together again around its new words.
/// </summary>
/// <remarks>
/// The properties of the paragraph and those of its end stay, the latter as its last element, as the schema
/// demands. The elements its tags stand for, e.g., line breaks and fields, move into the new paragraph. New words
/// get the formatting of their pair, or the most common formatting of the paragraph outside of any pair.
/// </remarks>
internal static class SlideParagraphWriter
{
/// <summary>
/// Replaces the content of a paragraph with its new words.
/// </summary>
/// <param name="paragraph">The paragraph, as the reader read it from this presentation.</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>
public static bool Write(SlideTextParagraph paragraph, string newText, string languageTag)
{
var element = paragraph.Paragraph;
var end = element.GetFirstChild<A.EndParagraphRunProperties>();
foreach (var child in element.ChildElements.Where(child => child is not (A.ParagraphProperties or A.EndParagraphRunProperties)).ToList())
child.Remove();
var writtenPlaceholders = new HashSet<int>();
bool keepsTags;
if (TaggedText.TryRead(newText, out var taggedText, out _))
{
keepsTags = taggedText.HasSameTagsAs(paragraph.Segment.Source, out _);
// Only pairs whose both tags arrived go back; TryRead made sure that they nest:
var openIds = taggedText.Tokens.Where(token => token.Kind is TaggedTokenKind.OPEN).Select(token => token.Id).ToHashSet();
var closeIds = taggedText.Tokens.Where(token => token.Kind is TaggedTokenKind.CLOSE).Select(token => token.Id).ToHashSet();
var openPairs = new Stack<int>();
foreach (var token in taggedText.Tokens)
{
switch (token.Kind)
{
case TaggedTokenKind.TEXT:
AppendWords(element, end, token.Text, openPairs.Count == 0 ? paragraph.BaseFormat : paragraph.FormatPairs[openPairs.Peek()], languageTag);
break;
case TaggedTokenKind.OPEN when closeIds.Contains(token.Id) && paragraph.FormatPairs.ContainsKey(token.Id):
openPairs.Push(token.Id);
break;
case TaggedTokenKind.CLOSE when openIds.Contains(token.Id) && paragraph.FormatPairs.ContainsKey(token.Id):
openPairs.Pop();
break;
case TaggedTokenKind.PLACEHOLDER when paragraph.Placeholders.TryGetValue(token.Id, out var placeholder) && writtenPlaceholders.Add(token.Id):
Insert(element, end, placeholder.Detached());
break;
}
}
}
else
{
keepsTags = false;
AppendWords(element, end, TaggedText.RemoveTags(newText), paragraph.BaseFormat, languageTag);
}
// What the model dropped follows its words, so that no line break or field gets lost:
foreach (var (id, placeholder) in paragraph.Placeholders.OrderBy(entry => entry.Key))
{
if (!writtenPlaceholders.Contains(id))
Insert(element, end, placeholder.Detached());
}
return keepsTags && !paragraph.HasMixedFormatting;
}
/// <summary>
/// Appends words as runs, with line breaks as PowerPoint writes them.
/// </summary>
private static void AppendWords(A.Paragraph paragraph, A.EndParagraphRunProperties? end, string words, A.RunProperties? format, string languageTag)
{
var lines = words.Replace("\r", string.Empty).Split('\n');
for (var index = 0; index < lines.Length; index++)
{
if (index > 0)
Insert(paragraph, end, new A.Break { RunProperties = FormatOf(format, languageTag) });
if (lines[index].Length > 0)
Insert(paragraph, end, new A.Run(FormatOf(format, languageTag), new A.Text(OpenXmlText.XmlSafe(lines[index]))));
}
}
/// <summary>
/// Copies the formatting for new words, in their language, and without the marks of an earlier spell check.
/// </summary>
private static A.RunProperties FormatOf(A.RunProperties? format, string languageTag)
{
var properties = format?.CloneNode(true) as A.RunProperties ?? new A.RunProperties();
properties.SpellingError = null;
properties.Dirty = null;
if (languageTag.Length > 0)
properties.Language = languageTag;
return properties;
}
/// <summary>
/// Adds an element before the properties of the end of the paragraph, which have to come last.
/// </summary>
private static void Insert(A.Paragraph paragraph, A.EndParagraphRunProperties? end, OpenXmlElement element)
{
if (end is null)
paragraph.AppendChild(element);
else
paragraph.InsertBefore(element, end);
}
}
@@ -0,0 +1,145 @@
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using A = DocumentFormat.OpenXml.Drawing;
using P = DocumentFormat.OpenXml.Presentation;
namespace AIStudio.Tools.DocumentSegments.PowerPoint;
/// <summary>
/// Reads the paragraphs of a presentation as segments: those of the shapes, groups, and tables of each slide,
/// and those of its notes, slide by slide in the order of the presentation.
/// </summary>
/// <remarks>
/// <para>
/// The paragraphs of PowerPoint hold runs, line breaks, and fields side by side, without anything that encloses
/// runs. A link is part of the properties of its run, so it is a change of formatting like bold: such a change
/// becomes a pair of tags, see FormatSpans. Line breaks, fields such as the number of the slide, and everything
/// else become tags of their own.
/// </para>
/// <para>
/// The masters and layouts of the slides stay as they are: their texts are prompts for the authors, such as
/// "Click to add title", which a slide replaces with its own. Charts and SmartArt keep their texts in parts of
/// their own, which this reader leaves alone as well.
/// </para>
/// </remarks>
internal static class SlideSegmentReader
{
/// <summary>
/// Reads the paragraphs which can be segments, in the order of the presentation.
/// </summary>
/// <param name="document">The presentation.</param>
public static IReadOnlyList<SlideTextParagraph> Read(PresentationDocument document)
{
var paragraphs = new List<SlideTextParagraph>();
foreach (var root in RootsOf(document))
{
foreach (var paragraph in root.Descendants<A.Paragraph>())
{
if (ReadParagraph(paragraph) is { } read)
paragraphs.Add(read);
}
}
return paragraphs;
}
private static IEnumerable<OpenXmlElement> RootsOf(PresentationDocument document)
{
if (document.PresentationPart is not { Presentation.SlideIdList: { } slideIds } presentationPart)
yield break;
foreach (var slideId in slideIds.Elements<P.SlideId>())
{
if (slideId.RelationshipId?.Value is not { } relationshipId || !presentationPart.TryGetPartById(relationshipId, out var part) || part is not SlidePart slidePart)
continue;
if (slidePart.Slide is { } slide)
yield return slide;
if (slidePart.NotesSlidePart?.NotesSlide is { } notes)
yield return notes;
}
}
/// <summary>
/// Reads a paragraph, with its changes of formatting as pairs as long as they are few, see FormatSpans.MAX_PAIRS.
/// </summary>
private static SlideTextParagraph? ReadParagraph(A.Paragraph paragraph)
{
var reader = new ParagraphReader(usesFormatPairs: true);
var read = reader.TryRead(paragraph);
return reader.FormatPairCount <= FormatSpans.MAX_PAIRS ? read : new ParagraphReader(usesFormatPairs: false).TryRead(paragraph);
}
/// <summary>
/// Reads one paragraph.
/// </summary>
private sealed class ParagraphReader
{
private readonly TaggedTextBuilder builder = new();
private readonly FormatSpanReader<A.RunProperties> spans;
private readonly Dictionary<int, A.RunProperties?> formatPairs = [];
private readonly Dictionary<int, OpenXmlElement> placeholders = [];
public ParagraphReader(bool usesFormatPairs) => this.spans = new(this.builder, usesFormatPairs, FormatKeyOf);
/// <summary>
/// How many changes of formatting became pairs.
/// </summary>
public int FormatPairCount => this.spans.FormatPairCount;
public SlideTextParagraph? TryRead(A.Paragraph paragraph)
{
var children = paragraph.ChildElements.Where(child => child is not (A.ParagraphProperties or A.EndParagraphRunProperties)).ToList();
var baseFormatKey = this.spans.BaseKeyOf(children.OfType<A.Run>().Select(WordsOf));
var words = new List<A.Run>();
foreach (var child in children)
{
if (child is A.Run run)
{
words.Add(run);
continue;
}
this.AddWords(words, baseFormatKey);
words.Clear();
this.placeholders[this.builder.Placeholder()] = child;
}
this.AddWords(words, baseFormatKey);
// Words which read as a tag could not be told apart from the tags of the paragraph:
var text = this.builder.Build();
if (text.HasTagLikeWords)
return null;
return new(paragraph, new DocumentSegment(text), this.formatPairs, this.placeholders, this.spans.BaseFormats.GetValueOrDefault(0), this.spans.HasMixedFormatting);
}
private static FormattedWords<A.RunProperties?> WordsOf(A.Run run) => new(TextOf(run), run.RunProperties);
private void AddWords(List<A.Run> runs, string baseFormatKey) => this.spans.AddWords(runs.Select(WordsOf), 0, baseFormatKey, (formatPair, format) => this.formatPairs[formatPair] = format);
/// <summary>
/// Tells the formatting of runs apart, leaving out what changes nothing about how words look, e.g.,
/// their language or whether PowerPoint checked their spelling.
/// </summary>
private static string FormatKeyOf(A.RunProperties format)
{
var copy = (A.RunProperties)format.CloneNode(true);
copy.Language = null;
copy.AlternativeLanguage = null;
copy.SpellingError = null;
copy.Dirty = null;
copy.NoProof = null;
copy.SmartTagClean = null;
// A run without anything that changes its look counts as having no properties at all:
return copy.HasAttributes || copy.HasChildren ? copy.OuterXml : string.Empty;
}
private static string TextOf(A.Run run) => run.Text?.Text ?? string.Empty;
}
}
@@ -0,0 +1,22 @@
using DocumentFormat.OpenXml;
using A = DocumentFormat.OpenXml.Drawing;
namespace AIStudio.Tools.DocumentSegments.PowerPoint;
/// <summary>
/// A paragraph of a slide or of its notes as a segment, with all the writer needs to put it together again.
/// </summary>
/// <param name="Paragraph">The paragraph.</param>
/// <param name="Segment">Its words with tags.</param>
/// <param name="FormatPairs">The formatting of the words within each pair, e.g., bold or a link.</param>
/// <param name="Placeholders">The element each tag of its own stands for, e.g., a line break or the field of the slide number.</param>
/// <param name="BaseFormat">The most common formatting of the words, which new words outside of any pair get.</param>
/// <param name="HasMixedFormatting">Whether the words differ in their formatting more often than pairs of formatting allow, so that the new words keep only the most common one.</param>
internal sealed record SlideTextParagraph(
A.Paragraph Paragraph,
DocumentSegment Segment,
IReadOnlyDictionary<int, A.RunProperties?> FormatPairs,
IReadOnlyDictionary<int, OpenXmlElement> Placeholders,
A.RunProperties? BaseFormat,
bool HasMixedFormatting);