using System.Text; namespace AIStudio.Tools.DocumentSegments; /// /// Writes the new texts of the segments into a document which is text itself, leaving everything around them /// as it is. /// public static class TextSegmentWriter { /// /// Replaces the segments of a source with their new texts. /// /// /// /// A new text whose tags do not fit those of its segment still gets written: its pairs whose both tags /// arrived go back, the others go, and the tags of their own which the model dropped follow the words, /// unless the segment names them optional, see TextSegment.OptionalPlaceholders. A segment whose new text /// equals its source stays exactly as the source holds it. /// /// /// White space at the inner edges of a pair goes outside of its markup, see TaggedText.WithWhiteSpaceOutsideOfPairs. /// /// /// The segments may come in any order, but must not overlap, since each one replaces its own part of the source. /// The words function gets one run of words between two tags at a time, so the start of what it gets may be the /// start of a line, e.g., right after an item of a list; a function which treats that start apart relies on it. /// /// /// The text of the document. /// The segments of the document, as the format reads them from this source. /// What became of the segments. /// Makes words fit the format, e.g., escapes the characters of markup; a segment may bring its own, see TextSegment.FormatWords. /// Two segments overlap. /// The text of the new document, or the source when the results do not cover it. /// How the segments were written, or SOURCE_CHANGED when the results miss one of them. public static SegmentWriteResult Apply(string source, IReadOnlyList segments, SegmentResults results, Func formatWords, out string text) { text = source; if (segments.Any(segment => !results.Covers(segment.Segment))) return SegmentWriteResult.SOURCE_CHANGED; var ordered = segments.OrderBy(segment => segment.Start).ToList(); for (var index = 1; index < ordered.Count; index++) { if (ordered[index].Start < ordered[index - 1].End) throw new ArgumentException($"The segments at {ordered[index - 1].Start} and {ordered[index].Start} overlap.", nameof(segments)); } var exactCount = 0; var simplifiedCount = 0; var builder = new StringBuilder(source.Length); var position = 0; foreach (var segment in ordered) { builder.Append(source, position, segment.Start - position); position = segment.End; if (!results.TryGetText(segment.Segment, out var newText) || newText == segment.Segment.Key) { builder.Append(source, segment.Start, segment.End - segment.Start); continue; } var newSegmentText = segment.FormatNewText is null ? builder : new StringBuilder(); var fits = Render(segment, newText, formatWords, newSegmentText); if (segment.FormatNewText is { } formatNewText) builder.Append(formatNewText(newSegmentText.ToString())); if (fits) exactCount++; else simplifiedCount++; } builder.Append(source, position, source.Length - position); text = builder.ToString(); return new(SegmentWriteOutcome.WRITTEN, exactCount, simplifiedCount); } /// /// Puts new words into one line, for formats in which a blank line would end a paragraph or a table row, e.g., Markdown or LaTeX. /// /// /// Every kind of line break becomes a space, those of Unicode included, such as U+2028 or U+0085. /// /// The new words. public static string InOneLine(string words) => words.ReplaceLineEndings(" "); /// /// Writes the new text of a segment with the markup of its tags. /// /// Whether the tags of the new text fit those of the segment. private static bool Render(TextSegment segment, string newText, Func formatWords, StringBuilder builder) { formatWords = segment.FormatWords ?? formatWords; if (!TaggedText.TryRead(newText, out var taggedText, out _)) { builder.Append(formatWords(TaggedText.RemoveTags(newText))); AppendMissingPlaceholders(segment, [], builder); return false; } var fits = taggedText.HasSameTagsAs(segment.Segment.Source, out _); 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 writtenPlaceholders = new HashSet(); foreach (var token in taggedText.WithWhiteSpaceOutsideOfPairs().Tokens) { switch (token.Kind) { case TaggedTokenKind.TEXT: builder.Append(formatWords(token.Text)); break; case TaggedTokenKind.OPEN when closeIds.Contains(token.Id) && segment.Openings.TryGetValue(token.Id, out var opening): builder.Append(opening); break; case TaggedTokenKind.CLOSE when openIds.Contains(token.Id) && segment.Closings.TryGetValue(token.Id, out var closing): builder.Append(closing); break; case TaggedTokenKind.PLACEHOLDER when segment.Placeholders.TryGetValue(token.Id, out var placeholder) && writtenPlaceholders.Add(token.Id): builder.Append(placeholder); break; } } AppendMissingPlaceholders(segment, writtenPlaceholders, builder); return fits; } /// /// Writes the tags of their own which the model dropped after the words, so that nothing of the source gets lost. /// private static void AppendMissingPlaceholders(TextSegment segment, HashSet writtenPlaceholders, StringBuilder builder) { foreach (var (id, placeholder) in segment.Placeholders.OrderBy(entry => entry.Key)) { if (writtenPlaceholders.Contains(id) || segment.OptionalPlaceholders?.Contains(id) is true) continue; if (builder.Length > 0 && !char.IsWhiteSpace(builder[^1])) builder.Append(' '); builder.Append(placeholder); } } }