mirror of
https://github.com/MindWorkAI/AI-Studio.git
synced 2026-12-05 16:51:36 +00:00
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:
1 parent
f7666861f1
commit
918572c158
150 files changed
+12850
-302
No files matched your search
@@ -0,0 +1,419 @@
|
||||
using System.Collections.Frozen;
|
||||
using System.Text.RegularExpressions;
|
||||
|
||||
using HtmlAgilityPack;
|
||||
|
||||
namespace AIStudio.Tools.DocumentSegments.Html;
|
||||
|
||||
/// <summary>
|
||||
/// Reads the segments of a web page: the words of its blocks, e.g., paragraphs, headings, list items, and table
|
||||
/// cells, and the texts of the attributes people read, e.g., the alternative texts of pictures.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// <para>
|
||||
/// The segments come from the positions HtmlAgilityPack reads for each part of the page, so the new page is the
|
||||
/// source with the words of each segment replaced, and everything else stays byte for byte.
|
||||
/// </para>
|
||||
/// <para>
|
||||
/// Elements which mark up words, e.g., links, emphasis, or spans, become pairs of tags, which stand for their start
|
||||
/// and end tags, so a model moves them with their words and never touches an address. Code, pictures, line breaks,
|
||||
/// form fields, scripts, and the like become tags of their own. Words go to the model with their entities decoded
|
||||
/// and their white space collapsed, as a browser shows them.
|
||||
/// </para>
|
||||
/// </remarks>
|
||||
internal static partial class HtmlSegmentReader
|
||||
{
|
||||
/// <summary>
|
||||
/// Elements which mark up words within a block.
|
||||
/// </summary>
|
||||
private static readonly FrozenSet<string> INLINE_ELEMENTS = FrozenSet.Create(StringComparer.OrdinalIgnoreCase,
|
||||
"a", "abbr", "acronym", "b", "bdi", "bdo", "big", "button", "cite", "data", "del", "dfn", "em", "font", "i", "ins",
|
||||
"label", "mark", "nobr", "output", "q", "s", "small", "span", "strike", "strong", "sub", "sup", "time", "tt", "u");
|
||||
|
||||
/// <summary>
|
||||
/// Elements within a block which stay as they are, with everything inside them.
|
||||
/// </summary>
|
||||
private static readonly FrozenSet<string> ATOMIC_ELEMENTS = FrozenSet.Create(StringComparer.OrdinalIgnoreCase,
|
||||
"audio", "br", "canvas", "code", "embed", "iframe", "img", "input", "kbd", "map", "math", "noscript", "object",
|
||||
"picture", "samp", "script", "select", "style", "svg", "template", "textarea", "var", "video", "wbr");
|
||||
|
||||
/// <summary>
|
||||
/// Blocks which stay as they are, with everything inside them.
|
||||
/// </summary>
|
||||
private static readonly FrozenSet<string> SKIPPED_BLOCKS = FrozenSet.Create(StringComparer.OrdinalIgnoreCase, "pre");
|
||||
|
||||
/// <summary>
|
||||
/// Elements whose attributes nobody reads, since they hold code or a graphic.
|
||||
/// </summary>
|
||||
private static readonly FrozenSet<string> UNREAD_ELEMENTS = FrozenSet.Create(StringComparer.OrdinalIgnoreCase, "math", "script", "style", "svg", "template");
|
||||
|
||||
/// <summary>
|
||||
/// The attributes whose texts people read, e.g., as a tooltip or instead of a picture.
|
||||
/// </summary>
|
||||
private static readonly FrozenSet<string> READABLE_ATTRIBUTES = FrozenSet.Create(StringComparer.OrdinalIgnoreCase, "alt", "aria-label", "placeholder", "title");
|
||||
|
||||
/// <summary>
|
||||
/// The meta elements whose content describes the page, e.g., in search results or in a preview of a link.
|
||||
/// </summary>
|
||||
private static readonly FrozenSet<string> DESCRIBING_META_NAMES = FrozenSet.Create(StringComparer.OrdinalIgnoreCase,
|
||||
"description", "og:title", "og:description", "twitter:title", "twitter:description");
|
||||
|
||||
/// <summary>
|
||||
/// White space as HTML knows it; a no-break space is none.
|
||||
/// </summary>
|
||||
private const string HTML_WHITE_SPACE = " \t\r\n\f";
|
||||
|
||||
/// <summary>
|
||||
/// How deep the reader follows elements at most; far deeper than any page needs, but shallow enough that its
|
||||
/// recursion stays within the stack of a thread. Deeper elements stay as they are, with the run of words around them.
|
||||
/// </summary>
|
||||
private const int MAX_NESTING_DEPTH = 256;
|
||||
|
||||
/// <summary>
|
||||
/// How deep HtmlAgilityPack reads elements at most; it refuses a page nested deeper, e.g., by thousands of elements
|
||||
/// without their end tags, whose recursion would otherwise exhaust the stack and end the app.
|
||||
/// </summary>
|
||||
private const int MAX_PARSED_NESTING_DEPTH = 1024;
|
||||
|
||||
[GeneratedRegex("[ \t\r\n\f]+")]
|
||||
private static partial Regex WhiteSpaceRegex();
|
||||
|
||||
[GeneratedRegex("""\A\s*<\?xml\b[^>]*\bencoding\s*=\s*["']([^"']*)["']""", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex XmlDeclarationEncodingRegex();
|
||||
|
||||
[GeneratedRegex("""\bcharset\s*=\s*["']?([^;"'\s]*)""", RegexOptions.IgnoreCase)]
|
||||
private static partial Regex ContentTypeCharsetRegex();
|
||||
|
||||
/// <summary>
|
||||
/// Finds the encoding which a page names for itself: by its XML declaration, by a meta element with a
|
||||
/// charset, or by one which stands for the HTTP header of the content type.
|
||||
/// </summary>
|
||||
/// <param name="text">The page.</param>
|
||||
/// <returns>The name of the encoding, e.g., "iso-8859-1"; null when the page names none.</returns>
|
||||
public static string? DeclaredEncodingOf(string text)
|
||||
{
|
||||
if (XmlDeclarationEncodingRegex().Match(text) is { Success: true } declaration && !string.IsNullOrWhiteSpace(declaration.Groups[1].Value))
|
||||
return declaration.Groups[1].Value;
|
||||
|
||||
foreach (var meta in ElementsOf(Parse(text).DocumentNode).Where(element => element.Name.Equals("meta", StringComparison.OrdinalIgnoreCase)))
|
||||
{
|
||||
var charset = meta.GetAttributeValue("charset", string.Empty);
|
||||
if (!string.IsNullOrWhiteSpace(charset))
|
||||
return HtmlEntity.DeEntitize(charset);
|
||||
|
||||
if (!string.Equals(meta.GetAttributeValue("http-equiv", string.Empty).Trim(), "content-type", StringComparison.OrdinalIgnoreCase))
|
||||
continue;
|
||||
|
||||
if (ContentTypeCharsetRegex().Match(HtmlEntity.DeEntitize(meta.GetAttributeValue("content", string.Empty))) is { Success: true } match && !string.IsNullOrWhiteSpace(match.Groups[1].Value))
|
||||
return match.Groups[1].Value;
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads a page.
|
||||
/// </summary>
|
||||
/// <param name="text">The page.</param>
|
||||
/// <exception cref="Exception">The page nests its elements deeper than MAX_PARSED_NESTING_DEPTH.</exception>
|
||||
public static HtmlDocument Parse(string text)
|
||||
{
|
||||
var document = new HtmlDocument { OptionMaxNestedChildNodes = MAX_PARSED_NESTING_DEPTH };
|
||||
document.LoadHtml(text);
|
||||
return document;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Finds the elements below a node, in the order of the page, down to MAX_NESTING_DEPTH.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Use it instead of the Descendants of HtmlAgilityPack, whose recursion follows a page as deep as it goes.
|
||||
/// </remarks>
|
||||
/// <param name="node">The node, e.g., the document node of a page.</param>
|
||||
public static IEnumerable<HtmlNode> ElementsOf(HtmlNode node) => ElementsOf(node, 0);
|
||||
|
||||
/// <summary>
|
||||
/// Reads the segments of the blocks of a page, in the order of the page.
|
||||
/// </summary>
|
||||
/// <param name="text">The page.</param>
|
||||
public static List<TextSegment> BlockSegmentsOf(string text)
|
||||
{
|
||||
var segments = new List<TextSegment>();
|
||||
CollectBlock(Parse(text).DocumentNode, 0, text, segments);
|
||||
return segments;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Reads the segments of the readable attributes of a page, in the order of the page.
|
||||
/// </summary>
|
||||
/// <param name="text">The page.</param>
|
||||
public static List<TextSegment> AttributeSegmentsOf(string text)
|
||||
{
|
||||
var segments = new List<TextSegment>();
|
||||
CollectAttributes(Parse(text).DocumentNode, 0, text, segments);
|
||||
return segments;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Makes words fit into the text of a page.
|
||||
/// </summary>
|
||||
public static string EncodedText(string words) => words.Replace("&", "&").Replace("<", "<").Replace(">", ">");
|
||||
|
||||
/// <summary>
|
||||
/// Makes words fit into the value of an attribute, whichever quotes enclose it.
|
||||
/// </summary>
|
||||
public static string EncodedAttribute(string words) => EncodedText(words).Replace("\"", """).Replace("'", "'");
|
||||
|
||||
/// <summary>
|
||||
/// Puts quotes around the new value of an attribute which had none, e.g., alt=Mars: new words with a space would end it.
|
||||
/// </summary>
|
||||
/// <param name="value">The whole new value, with its words encoded.</param>
|
||||
private static string Quoted(string value) => $"\"{value}\"";
|
||||
|
||||
private static IEnumerable<HtmlNode> ElementsOf(HtmlNode node, int depth)
|
||||
{
|
||||
if (depth >= MAX_NESTING_DEPTH)
|
||||
yield break;
|
||||
|
||||
foreach (var child in node.ChildNodes.Where(child => child.NodeType is HtmlNodeType.Element))
|
||||
{
|
||||
yield return child;
|
||||
foreach (var element in ElementsOf(child, depth + 1))
|
||||
yield return element;
|
||||
}
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collects the segments of the readable attributes of the elements below a node, in the order of the page.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Nothing inside a script, a style, or a graphic is read by people, and elements deeper than MAX_NESTING_DEPTH
|
||||
/// stay as they are.
|
||||
/// </remarks>
|
||||
private static void CollectAttributes(HtmlNode node, int depth, string text, List<TextSegment> segments)
|
||||
{
|
||||
if (depth >= MAX_NESTING_DEPTH)
|
||||
return;
|
||||
|
||||
foreach (var element in node.ChildNodes.Where(child => child.NodeType is HtmlNodeType.Element && !UNREAD_ELEMENTS.Contains(child.Name)))
|
||||
{
|
||||
foreach (var attribute in element.Attributes)
|
||||
{
|
||||
if (!IsReadable(element, attribute) || attribute.ValueLength <= 0 || attribute.ValueStartIndex < 0 || attribute.ValueStartIndex + attribute.ValueLength > text.Length)
|
||||
continue;
|
||||
|
||||
var builder = new TextSegmentBuilder();
|
||||
builder.Words(Collapsed(text.Substring(attribute.ValueStartIndex, attribute.ValueLength)));
|
||||
if (builder.TryBuild(attribute.ValueStartIndex, attribute.ValueStartIndex + attribute.ValueLength) is { } segment)
|
||||
segments.Add(attribute.QuoteType is AttributeValueQuote.None ? segment with { FormatNewText = Quoted } : segment);
|
||||
}
|
||||
|
||||
CollectAttributes(element, depth + 1, text, segments);
|
||||
}
|
||||
}
|
||||
|
||||
private static bool IsReadable(HtmlNode element, HtmlAttribute attribute)
|
||||
{
|
||||
if (READABLE_ATTRIBUTES.Contains(attribute.Name))
|
||||
return true;
|
||||
|
||||
return element.Name.Equals("meta", StringComparison.OrdinalIgnoreCase)
|
||||
&& attribute.Name.Equals("content", StringComparison.OrdinalIgnoreCase)
|
||||
&& (DESCRIBING_META_NAMES.Contains(element.GetAttributeValue("name", string.Empty)) || DESCRIBING_META_NAMES.Contains(element.GetAttributeValue("property", string.Empty)));
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Collects the segments within a block: each run of words between its blocks is one segment.
|
||||
/// </summary>
|
||||
/// <param name="block">The block.</param>
|
||||
/// <param name="depth">How deep the block lies in the page; 0 for the document node. A block below MAX_NESTING_DEPTH stays as it is.</param>
|
||||
/// <param name="text">The page.</param>
|
||||
/// <param name="segments">Where the segments go.</param>
|
||||
private static void CollectBlock(HtmlNode block, int depth, string text, List<TextSegment> segments)
|
||||
{
|
||||
var childDepth = depth + 1;
|
||||
var run = new List<HtmlNode>();
|
||||
foreach (var child in block.ChildNodes)
|
||||
{
|
||||
if (IsWithinWords(child, childDepth))
|
||||
{
|
||||
run.Add(child);
|
||||
continue;
|
||||
}
|
||||
|
||||
AddRun(run, childDepth, text, segments);
|
||||
run.Clear();
|
||||
if (child.NodeType is HtmlNodeType.Element && !SKIPPED_BLOCKS.Contains(child.Name) && childDepth < MAX_NESTING_DEPTH)
|
||||
CollectBlock(child, childDepth, text, segments);
|
||||
}
|
||||
|
||||
AddRun(run, childDepth, text, segments);
|
||||
}
|
||||
|
||||
private static bool IsWithinWords(HtmlNode node, int depth) => node.NodeType switch
|
||||
{
|
||||
HtmlNodeType.Text or HtmlNodeType.Comment => true,
|
||||
HtmlNodeType.Element => ATOMIC_ELEMENTS.Contains(node.Name) || (INLINE_ELEMENTS.Contains(node.Name) && !HoldsBlocks(node, depth)),
|
||||
|
||||
_ => false,
|
||||
};
|
||||
|
||||
/// <summary>
|
||||
/// Whether an element which marks up words holds blocks, e.g., a link around a whole card with a heading and a
|
||||
/// paragraph. Such an element counts as a block, so that the runs of words within it are read: as a part of a run,
|
||||
/// its blocks would become one tag of their own, and their words would never reach the model.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// Below MAX_NESTING_DEPTH, an element counts as words, whose run then stays as it is, see InlineWalker.
|
||||
/// </remarks>
|
||||
private static bool HoldsBlocks(HtmlNode element, int depth) => depth < MAX_NESTING_DEPTH && element.ChildNodes.Any(child =>
|
||||
child.NodeType is HtmlNodeType.Element &&
|
||||
!ATOMIC_ELEMENTS.Contains(child.Name) &&
|
||||
(!INLINE_ELEMENTS.Contains(child.Name) || HoldsBlocks(child, depth + 1)));
|
||||
|
||||
private static void AddRun(List<HtmlNode> run, int depth, string text, List<TextSegment> segments)
|
||||
{
|
||||
// The white space around the words stays outside of the segment, e.g., the indentation of the source:
|
||||
var first = run.FindIndex(node => !IsBlank(node, text));
|
||||
if (first < 0)
|
||||
return;
|
||||
|
||||
var last = run.FindLastIndex(node => !IsBlank(node, text));
|
||||
if (new InlineWalker(text, depth).TryRead(run.GetRange(first, last - first + 1)) is { } segment)
|
||||
segments.Add(segment);
|
||||
}
|
||||
|
||||
private static bool IsBlank(HtmlNode node, string text) => node.NodeType is HtmlNodeType.Text && OuterOf(node, text).AsSpan().Trim(HTML_WHITE_SPACE).IsEmpty;
|
||||
|
||||
private static string OuterOf(HtmlNode node, string text) => node.OuterStartIndex >= 0 && node.OuterStartIndex + node.OuterLength <= text.Length
|
||||
? text.Substring(node.OuterStartIndex, node.OuterLength)
|
||||
: string.Empty;
|
||||
|
||||
/// <summary>
|
||||
/// Words as a browser shows them: entities decoded and white space collapsed.
|
||||
/// </summary>
|
||||
private static string Collapsed(string html) => WhiteSpaceRegex().Replace(HtmlEntity.DeEntitize(html), " ");
|
||||
|
||||
/// <summary>
|
||||
/// Walks the nodes of one run of words and puts its segment together.
|
||||
/// </summary>
|
||||
/// <remarks>
|
||||
/// A run with an element below MAX_NESTING_DEPTH stays as it is.
|
||||
/// </remarks>
|
||||
/// <param name="text">The page.</param>
|
||||
/// <param name="depth">How deep the nodes of the run lie in the page.</param>
|
||||
private sealed class InlineWalker(string text, int depth)
|
||||
{
|
||||
private readonly TextSegmentBuilder builder = new();
|
||||
private int position;
|
||||
private bool isConsistent = true;
|
||||
|
||||
public TextSegment? TryRead(List<HtmlNode> nodes)
|
||||
{
|
||||
var start = nodes[0].OuterStartIndex;
|
||||
if (nodes[0].NodeType is HtmlNodeType.Text)
|
||||
{
|
||||
var firstWords = OuterOf(nodes[0], text).AsSpan();
|
||||
start += firstWords.Length - firstWords.TrimStart(HTML_WHITE_SPACE).Length;
|
||||
}
|
||||
|
||||
var end = nodes[^1].OuterStartIndex + nodes[^1].OuterLength;
|
||||
if (nodes[^1].NodeType is HtmlNodeType.Text)
|
||||
{
|
||||
var lastWords = OuterOf(nodes[^1], text).AsSpan();
|
||||
end -= lastWords.Length - lastWords.TrimEnd(HTML_WHITE_SPACE).Length;
|
||||
}
|
||||
|
||||
if (start < 0 || end > text.Length || end <= start)
|
||||
return null;
|
||||
|
||||
this.position = start;
|
||||
foreach (var node in nodes)
|
||||
this.Visit(node, end, depth);
|
||||
|
||||
return this.isConsistent && this.position == end ? this.builder.TryBuild(start, end) : null;
|
||||
}
|
||||
|
||||
private void Visit(HtmlNode node, int limit, int nodeDepth)
|
||||
{
|
||||
if (!this.isConsistent)
|
||||
return;
|
||||
|
||||
if (nodeDepth > MAX_NESTING_DEPTH)
|
||||
{
|
||||
this.isConsistent = false;
|
||||
return;
|
||||
}
|
||||
|
||||
var outerStart = node.OuterStartIndex;
|
||||
var outerEnd = outerStart + node.OuterLength;
|
||||
if (outerStart < 0 || outerEnd > text.Length || !this.TakeGapUntil(outerStart, node))
|
||||
{
|
||||
this.isConsistent = false;
|
||||
return;
|
||||
}
|
||||
|
||||
// The first words of a run start behind their leading white space, the last ones end before their trailing one:
|
||||
var nodeStart = Math.Max(outerStart, this.position);
|
||||
var nodeEnd = Math.Min(outerEnd, limit);
|
||||
if (nodeEnd < nodeStart)
|
||||
{
|
||||
this.isConsistent = false;
|
||||
return;
|
||||
}
|
||||
|
||||
switch (node.NodeType)
|
||||
{
|
||||
case HtmlNodeType.Text:
|
||||
this.builder.Words(Collapsed(text[nodeStart..nodeEnd]));
|
||||
break;
|
||||
|
||||
case HtmlNodeType.Element when INLINE_ELEMENTS.Contains(node.Name) && node.HasChildNodes && node.InnerStartIndex > nodeStart && node.InnerStartIndex + node.InnerLength <= nodeEnd:
|
||||
var innerEnd = node.InnerStartIndex + node.InnerLength;
|
||||
var pair = this.builder.Open(text[nodeStart..node.InnerStartIndex]);
|
||||
this.position = node.InnerStartIndex;
|
||||
foreach (var child in node.ChildNodes)
|
||||
this.Visit(child, innerEnd, nodeDepth + 1);
|
||||
|
||||
if (!this.isConsistent || this.position > innerEnd || !this.TakeGapUntil(innerEnd, null))
|
||||
{
|
||||
this.isConsistent = false;
|
||||
return;
|
||||
}
|
||||
|
||||
this.builder.Close(pair, text[innerEnd..nodeEnd]);
|
||||
break;
|
||||
|
||||
// Code, pictures, scripts, comments, and markup without words:
|
||||
default:
|
||||
this.builder.Placeholder(text[nodeStart..nodeEnd]);
|
||||
break;
|
||||
}
|
||||
|
||||
this.position = nodeEnd;
|
||||
}
|
||||
|
||||
/// <summary>
|
||||
/// Takes what lies between the last node and the next one, which may only be white space.
|
||||
/// </summary>
|
||||
/// <param name="next">Where the next node starts.</param>
|
||||
/// <param name="nextNode">The next node; null for the end of an element.</param>
|
||||
/// <returns>Whether the next node follows right away or after white space, rather than overlapping the last one or leaving markup in between.</returns>
|
||||
private bool TakeGapUntil(int next, HtmlNode? nextNode)
|
||||
{
|
||||
// Only the first words of a run start before it, by the white space left out:
|
||||
if (next < this.position)
|
||||
return nextNode is { NodeType: HtmlNodeType.Text };
|
||||
|
||||
if (next == this.position)
|
||||
return true;
|
||||
|
||||
if (!text.AsSpan(this.position, next - this.position).Trim(HTML_WHITE_SPACE).IsEmpty)
|
||||
return false;
|
||||
|
||||
this.builder.Words(" ");
|
||||
this.position = next;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user