using System;
using System.IO;
using System.Linq;
using System.Text;
using HtmlAgilityPack;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers.Extractors
{
///
/// Extractor for HTML documents (text/html, application/xhtml+xml)
///
public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor
{
///
/// Supported MIME Types ...
///
private static readonly string[] SupportedMimeTypes =
[
"text/html",
"application/xhtml+xml"
];
///
/// Check if this extractor supports the specified MIME type ...
///
///
///
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
///
/// Extract text content from file stream ...
///
///
///
///
///
public async Task ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await ExtractRichAsync(
fileStream,
"document.html",
mimeType,
cancellationToken
);
//
return result.Text;
}
///
/// Extract content from stream as Rich Result ...
///
///
///
///
///
///
public async Task ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
//
try
{
//
result.Text = await ExtractHtmlAsync(
fileStream,
cancellationToken
);
}
catch (Exception ex)
{
result.ErrorMessage =
$"HTML extraction failed: {ex.Message}";
}
//
return result;
}
///
/// Extract Html Content as Text ...
///
///
///
///
private async Task ExtractHtmlAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
// Load HTML into HtmlDocument
var html = new HtmlDocument();
html.Load(fileStream);
// Remove noise nodes (script, style, etc.)
RemoveNoiseNodes(html);
// Extract title
var title = ExtractTitle(html);
// Extract body text
var body = html.DocumentNode
.SelectSingleNode("//body");
var bodyText = body?.InnerText ?? string.Empty;
// Clean and normalize text
var cleanedText = CleanText(bodyText);
// Build structured output
var sb = new StringBuilder();
if (!string.IsNullOrWhiteSpace(title))
{
sb.AppendLine($"Title: {title}");
sb.AppendLine();
}
sb.AppendLine(cleanedText);
return sb.ToString().TrimEnd();
}
///
/// Remove Noisy Nodes ...
///
///
private void RemoveNoiseNodes(HtmlDocument html)
{
//
// Remove script and style tags ...
var noiseTags = new[] { "script", "style", "noscript", "iframe" };
foreach (var tag in noiseTags)
{
//
var nodes = html.DocumentNode
.Descendants(tag)
.ToList();
foreach (var node in nodes)
{
node.Remove();
}
}
}
///
/// Extract Title ...
///
///
///
private string ExtractTitle(HtmlDocument html)
{
//
var titleNode = html.DocumentNode
.SelectSingleNode("//title");
//
var result = titleNode?.InnerText?.Trim() ?? string.Empty;
//
return result;
}
///
/// Clean Text ...
///
///
///
private string CleanText(string text)
{
//
var result = string.Empty;
//
if (text.IsNullOrEmpty())
{
result = string.Empty;
}
//
// Decode HTML entities ...
text = System.Net.WebUtility.HtmlDecode(text);
//
// Normalize whitespace ...
text = System.Text.RegularExpressions.Regex
.Replace(text, @"\s+", " ")
.Trim();
//
result = text;
//
return result;
}
}
}