using System.Collections.Frozen;
using System.Text.RegularExpressions;
using HtmlAgilityPack;
namespace AIStudio.Tools.DocumentSegments.Html;
///
/// 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.
///
///
///
/// 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.
///
///
/// 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.
///
///
internal static partial class HtmlSegmentReader
{
///
/// Elements which mark up words within a block.
///
private static readonly FrozenSet 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");
///
/// Elements within a block which stay as they are, with everything inside them.
///
private static readonly FrozenSet 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");
///
/// Blocks which stay as they are, with everything inside them.
///
private static readonly FrozenSet SKIPPED_BLOCKS = FrozenSet.Create(StringComparer.OrdinalIgnoreCase, "pre");
///
/// Elements whose attributes nobody reads, since they hold code or a graphic.
///
private static readonly FrozenSet UNREAD_ELEMENTS = FrozenSet.Create(StringComparer.OrdinalIgnoreCase, "math", "script", "style", "svg", "template");
///
/// The attributes whose texts people read, e.g., as a tooltip or instead of a picture.
///
private static readonly FrozenSet READABLE_ATTRIBUTES = FrozenSet.Create(StringComparer.OrdinalIgnoreCase, "alt", "aria-label", "placeholder", "title");
///
/// The meta elements whose content describes the page, e.g., in search results or in a preview of a link.
///
private static readonly FrozenSet DESCRIBING_META_NAMES = FrozenSet.Create(StringComparer.OrdinalIgnoreCase,
"description", "og:title", "og:description", "twitter:title", "twitter:description");
///
/// White space as HTML knows it; a no-break space is none.
///
private const string HTML_WHITE_SPACE = " \t\r\n\f";
///
/// 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.
///
private const int MAX_NESTING_DEPTH = 256;
///
/// 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.
///
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();
///
/// 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.
///
/// The page.
/// The name of the encoding, e.g., "iso-8859-1"; null when the page names none.
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;
}
///
/// Reads a page.
///
/// The page.
/// The page nests its elements deeper than MAX_PARSED_NESTING_DEPTH.
public static HtmlDocument Parse(string text)
{
var document = new HtmlDocument { OptionMaxNestedChildNodes = MAX_PARSED_NESTING_DEPTH };
document.LoadHtml(text);
return document;
}
///
/// Finds the elements below a node, in the order of the page, down to MAX_NESTING_DEPTH.
///
///
/// Use it instead of the Descendants of HtmlAgilityPack, whose recursion follows a page as deep as it goes.
///
/// The node, e.g., the document node of a page.
public static IEnumerable ElementsOf(HtmlNode node) => ElementsOf(node, 0);
///
/// Reads the segments of the blocks of a page, in the order of the page.
///
/// The page.
public static List BlockSegmentsOf(string text)
{
var segments = new List();
CollectBlock(Parse(text).DocumentNode, 0, text, segments);
return segments;
}
///
/// Reads the segments of the readable attributes of a page, in the order of the page.
///
/// The page.
public static List AttributeSegmentsOf(string text)
{
var segments = new List();
CollectAttributes(Parse(text).DocumentNode, 0, text, segments);
return segments;
}
///
/// Makes words fit into the text of a page.
///
public static string EncodedText(string words) => words.Replace("&", "&").Replace("<", "<").Replace(">", ">");
///
/// Makes words fit into the value of an attribute, whichever quotes enclose it.
///
public static string EncodedAttribute(string words) => EncodedText(words).Replace("\"", """).Replace("'", "'");
///
/// Puts quotes around the new value of an attribute which had none, e.g., alt=Mars: new words with a space would end it.
///
/// The whole new value, with its words encoded.
private static string Quoted(string value) => $"\"{value}\"";
private static IEnumerable 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;
}
}
///
/// Collects the segments of the readable attributes of the elements below a node, in the order of the page.
///
///
/// Nothing inside a script, a style, or a graphic is read by people, and elements deeper than MAX_NESTING_DEPTH
/// stay as they are.
///
private static void CollectAttributes(HtmlNode node, int depth, string text, List 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)));
}
///
/// Collects the segments within a block: each run of words between its blocks is one segment.
///
/// The block.
/// How deep the block lies in the page; 0 for the document node. A block below MAX_NESTING_DEPTH stays as it is.
/// The page.
/// Where the segments go.
private static void CollectBlock(HtmlNode block, int depth, string text, List segments)
{
var childDepth = depth + 1;
var run = new List();
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,
};
///
/// 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.
///
///
/// Below MAX_NESTING_DEPTH, an element counts as words, whose run then stays as it is, see InlineWalker.
///
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 run, int depth, string text, List 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;
///
/// Words as a browser shows them: entities decoded and white space collapsed.
///
private static string Collapsed(string html) => WhiteSpaceRegex().Replace(HtmlEntity.DeEntitize(html), " ");
///
/// Walks the nodes of one run of words and puts its segment together.
///
///
/// A run with an element below MAX_NESTING_DEPTH stays as it is.
///
/// The page.
/// How deep the nodes of the run lie in the page.
private sealed class InlineWalker(string text, int depth)
{
private readonly TextSegmentBuilder builder = new();
private int position;
private bool isConsistent = true;
public TextSegment? TryRead(List 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;
}
///
/// Takes what lies between the last node and the next one, which may only be white space.
///
/// Where the next node starts.
/// The next node; null for the end of an element.
/// Whether the next node follows right away or after white space, rather than overlapping the last one or leaving markup in between.
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;
}
}
}