add Epub, Html, PowerPoint, RTF File Content Extractor and etc ...

This commit is contained in:
2026-10-22 19:06:51 +03:30
parent 877627714c
commit f39cde0d09
20 changed files with 1810 additions and 177 deletions
@@ -0,0 +1,231 @@
using System;
using System.IO;
using System.Linq;
using System.Text;
using VersOne.Epub;
using HtmlAgilityPack;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers.Extractors
{
/// <summary>
/// Extractor for EPUB electronic publication format
/// (application/epub+zip)
/// </summary>
public class XEpubFileContentExtractor : IXEpubFileContentExtractor
{
/// <summary>
/// Supported MIME Types ...
/// </summary>
private static readonly string[] SupportedMimeTypes =
[
"application/epub+zip"
];
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
/// <summary>
/// Extract text content from file stream ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await ExtractRichAsync(
fileStream,
"book.epub",
mimeType,
cancellationToken
);
//
return result.Text;
}
/// <summary>
/// Extract content from stream as Rich Result ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="fileName"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XFileExtractionResult> ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
//
try
{
//
result.Text = await ExtractEpubAsync(
fileStream,
cancellationToken
);
}
catch (Exception ex)
{
//
result.ErrorMessage =
$"EPUB extraction failed: {ex.Message}";
}
//
return result;
}
/// <summary>
/// Extract Epub Content ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> ExtractEpubAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
// Copy to MemoryStream (VersOne.Epub requires seekable stream) ...
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
//
// Load EPUB book ...
EpubBook book = await EpubReader.ReadBookAsync(ms);
var sb = new StringBuilder();
//
// Extract metadata ...
//
if (!book.Title.IsNullOrEmpty())
{
sb.AppendLine($"Title: {book.Title}");
}
//
if (!book.Author.IsNullOrEmpty())
{
sb.AppendLine($"Author: {book.Author}");
}
//
sb.AppendLine();
//
// Extract chapters in reading order ...
var chapterIndex = 0;
foreach (var textContentFile in book.ReadingOrder)
{
//
if (cancellationToken.IsCancellationRequested)
{
break;
}
//
chapterIndex++;
sb.AppendLine($"[Chapter {chapterIndex}]");
var plainText = ExtractTextFromHtml(
textContentFile.Content
);
if (!plainText.IsNullOrEmpty())
{
sb.AppendLine(plainText);
}
//
sb.AppendLine();
}
//
var result = sb.ToString().TrimEnd();
//
return result;
}
/// <summary>
/// Extract Text Content from HTML ...
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
private string ExtractTextFromHtml(string html)
{
//
var result = string.Empty;
//
if (html.IsNullOrEmpty())
{
return result;
}
//
var htmlDocument = new HtmlDocument();
htmlDocument.LoadHtml(html);
//
var sb = new StringBuilder();
var textNodes = htmlDocument.DocumentNode
.SelectNodes("//text()");
//
if (textNodes == null)
{
return result;
}
//
foreach (var node in textNodes)
{
//
var text = node.InnerText?.Trim();
if (!text.IsNullOrEmpty())
{
sb.AppendLine(text);
}
}
//
result = sb.ToString().TrimEnd();
//
return result;
}
}
}
@@ -0,0 +1,221 @@
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
{
/// <summary>
/// Extractor for HTML documents (text/html, application/xhtml+xml)
/// </summary>
public class XHtmlFileContentExtractor : IXHtmlFileContentExtractor
{
/// <summary>
/// Supported MIME Types ...
/// </summary>
private static readonly string[] SupportedMimeTypes =
[
"text/html",
"application/xhtml+xml"
];
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
/// <summary>
/// Extract text content from file stream ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await ExtractRichAsync(
fileStream,
"document.html",
mimeType,
cancellationToken
);
//
return result.Text;
}
/// <summary>
/// Extract content from stream as Rich Result ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="fileName"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XFileExtractionResult> 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;
}
/// <summary>
/// Extract Html Content as Text ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> 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();
}
/// <summary>
/// Remove Noisy Nodes ...
/// </summary>
/// <param name="html"></param>
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();
}
}
}
/// <summary>
/// Extract Title ...
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
private string ExtractTitle(HtmlDocument html)
{
//
var titleNode = html.DocumentNode
.SelectSingleNode("//title");
//
var result = titleNode?.InnerText?.Trim() ?? string.Empty;
//
return result;
}
/// <summary>
/// Clean Text ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
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;
}
}
}
@@ -0,0 +1,407 @@
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using OfficeIMO.OpenDocument;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
namespace xAiApi.Providers.Extractors
{
/// <summary>
/// Extractor for OpenDocument Format (ODF) documents
/// (ODT: OpenDocument Text, ODS: OpenDocument Spreadsheet, ODP: OpenDocument Presentation)
/// </summary>
public class XOpenDocumentFileContentExtractor : IXOpenDocumentFileContentExtractor
{
/// <summary>
/// Supported MIME Types ...
/// </summary>
private static readonly string[] SupportedMimeTypes =
[
"application/vnd.oasis.opendocument.text", // .odt
"application/vnd.oasis.opendocument.spreadsheet", // .ods
"application/vnd.oasis.opendocument.presentation" // .odp
];
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
/// <summary>
/// Extract text content from file stream ...
/// </summary>
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await ExtractRichAsync(
fileStream,
"document.rtf",
mimeType,
cancellationToken
);
//
return result.Text;
}
/// <summary>
/// Extract content from stream as Rich Result ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="fileName"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XFileExtractionResult> ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
//
try
{
//
if (IsOdt(mimeType))
{
result.Text = await ExtractOdtAsync(fileStream, cancellationToken);
}
else if (IsOds(mimeType))
{
result.Text = await ExtractOdsAsync(fileStream, cancellationToken);
}
else if (IsOdp(mimeType))
{
result.Text = await ExtractOdpAsync(fileStream, cancellationToken);
}
else
{
result.ErrorMessage =
$"Unsupported OpenDocument MIME type: {mimeType}";
}
}
catch (Exception ex)
{
//
result.ErrorMessage =
$"RTF extraction failed: {ex.Message}";
}
//
return result;
}
/// <summary>
/// Check Mime Type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
private bool IsOdt(string mimeType)
{
//
var result = mimeType?
.ToLowerInvariant() == "application/vnd.oasis.opendocument.text";
//
return result;
}
/// <summary>
/// Check Mime Type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
private bool IsOds(string mimeType)
{
//
var result = mimeType?
.ToLowerInvariant() == "application/vnd.oasis.opendocument.spreadsheet";
//
return result;
}
/// <summary>
/// Check Mime Type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
private bool IsOdp(string mimeType)
{
//
var result = mimeType?
.ToLowerInvariant() == "application/vnd.oasis.opendocument.presentation";
//
return result;
}
/// <summary>
/// Extract ODT File Content ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> ExtractOdtAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
//
var document = OdtDocument.Load(ms);
//
var sb = new StringBuilder();
foreach (var paragraph in document.Paragraphs)
{
//
if (cancellationToken.IsCancellationRequested)
{
break;
}
//
if (!paragraph.Text.IsNullOrEmpty())
{
sb.AppendLine(paragraph.Text.Trim());
}
}
//
// 4. استخراج جداول
var tableIndex = 0;
foreach (var table in document.Tables)
{
//
if (cancellationToken.IsCancellationRequested)
{
break;
}
//
tableIndex++;
sb.AppendLine();
sb.AppendLine($"[Table {tableIndex}]");
//
foreach (var row in table.Rows)
{
//
var cellTexts = new List<string>();
foreach (var cell in row.Cells)
{
//
var cellText = string.Join(
" ",
cell.Paragraphs
.Select(p => p.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t))
);
cellTexts.Add(cellText);
}
//
sb.AppendLine($" | {string.Join(" | ", cellTexts)} |");
}
//
sb.AppendLine();
}
//
var result = sb.ToString().TrimEnd();
//
return result;
}
/// <summary>
/// Extract ODS File Content ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> ExtractOdsAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
//
var document = OdsDocument.Load(ms);
var sb = new StringBuilder();
var sheetIndex = 0;
foreach (var sheet in document.Sheets)
{
//
if (cancellationToken.IsCancellationRequested)
{
break;
}
//
sheetIndex++;
sb.AppendLine($"--- Sheet: {sheet.Name} ---");
//
for (long row = 0; row < sheet.RowCount; row++)
{
//
if (cancellationToken.IsCancellationRequested)
{
break;
}
//
var cellValues = new List<string>();
var columnCount = sheet.ColumnRuns.Sum(r => r.RepeatCount);
for (long col = 0; col < columnCount; col++)
{
//
var value = sheet.GetValue(row, col);
if (!value.IsNull())
{
var text = value.LexicalValue?.Trim() ?? string.Empty;
cellValues.Add(text);
}
}
//
if (cellValues.Any(v => !string.IsNullOrWhiteSpace(v)))
{
sb.AppendLine(string.Join(" | ", cellValues));
}
}
//
sb.AppendLine();
}
//
var result = sb.ToString().TrimEnd();
//
return result;
}
/// <summary>
/// Extract ODS File Content ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> ExtractOdpAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
//
var presentation = OdpPresentation.Load(ms);
var sb = new StringBuilder();
var slideIndex = 0;
foreach (var slide in presentation.Slides)
{
//
if (cancellationToken.IsCancellationRequested)
{
break;
}
//
slideIndex++;
sb.AppendLine($"[Slide {slideIndex}]");
var textParts = new List<string>();
//
foreach (var shape in slide.Shapes)
{
//
if (shape is OdpTextBox textBox)
{
//
foreach (var paragraph in textBox.Paragraphs)
{
//
if (!paragraph.Text.IsNullOrEmpty())
{
textParts.Add(paragraph.Text.Trim());
}
}
}
else if (shape is OdpShape odpShape)
{
//
foreach (var paragraph in odpShape.TextParagraphs)
{
//
if (!paragraph.Text.IsNullOrEmpty())
{
textParts.Add(paragraph.Text.Trim());
}
}
}
}
//
if (textParts.Count > 0)
{
//
sb.AppendLine("Content:");
foreach (var text in textParts)
{
sb.AppendLine($" - {text}");
}
}
//
sb.AppendLine();
}
//
var result = sb.ToString().TrimEnd();
//
return result;
}
}
}
@@ -25,26 +25,6 @@ namespace xAiApi.Providers.Extractors
"application/pdf"
];
/// <summary>
/// Minimum Length for Fallback Using Images ...
/// </summary>
private const int MinTextLengthThreshold = 50;
/// <summary>
/// Max Pages for Falling Back Using Images ...
/// </summary>
private const int MaxPagesForImageFallback = 10;
/// <summary>
/// Default DPI for Rendering Images ...
/// </summary>
private const int RenderDpi = 150;
/// <summary>
/// Max Rendered Image Width ...
/// </summary>
private const int MaxImageWidth = 2000;
/// <summary>
/// Api Configuration ...
/// </summary>
@@ -58,6 +38,8 @@ namespace xAiApi.Providers.Extractors
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
public bool CanExtract(string mimeType)
{
//
@@ -69,6 +51,10 @@ namespace xAiApi.Providers.Extractors
/// <summary>
/// Extract text content from file stream ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
@@ -182,6 +168,8 @@ namespace xAiApi.Providers.Extractors
/// Check Extracted Content is Sufficient or not ...
/// if not try to Falling Back using Images ...
/// </summary>
/// <param name="text"></param>
/// <returns></returns>
private bool IsTextSufficient(string text)
{
//
@@ -195,12 +183,20 @@ namespace xAiApi.Providers.Extractors
var cleanText = new string(text.Where(c => !char.IsWhiteSpace(c)).ToArray());
//
return cleanText.Length >= MinTextLengthThreshold;
var result = cleanText.Length >= configuration.PDFToImageDescriptor.MinTextLengthThreshold;
//
return result;
}
/// <summary>
/// Fallback Converts PDF Pages to Images ...
/// </summary>
/// <param name="pdfStream"></param>
/// <param name="fileName"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<XFileExtractionResult> FallbackToImageExtractionAsync(
Stream pdfStream,
string fileName,
@@ -223,30 +219,48 @@ namespace xAiApi.Providers.Extractors
try
{
//
var images = Conversion.ToImages(
pdfStream: pdfStream,
options: new RenderOptions
{
Dpi = configuration.PDFToImageDescriptor.Dpi,
Width = configuration.PDFToImageDescriptor.Width,
Height = configuration.PDFToImageDescriptor.Height,
UseTiling = configuration.PDFToImageDescriptor.UseTiling,
WithFormFill = configuration.PDFToImageDescriptor.WithFormFill,
WithAspectRatio = configuration.PDFToImageDescriptor.WithAspectRatio,
WithAnnotations = configuration.PDFToImageDescriptor.WithAnnotations,
DpiRelativeToBounds = configuration.PDFToImageDescriptor.DpiRelativeToBounds,
}
).ToList();
// Calculating With ...
var width = configuration.PDFToImageDescriptor.Width;
if (width >= 0 && configuration.PDFToImageDescriptor.MaxImageWidth > 0)
{
//
width = Math.Min(
width,
configuration.PDFToImageDescriptor.MaxImageWidth
);
}
//
var allPagesCount = Conversion.GetPageCount(pdfStream);
var pageCount = Math.Min(
allPagesCount,
MaxPagesForImageFallback
);
//
// Preparing Render Options ...
var renderOptions = new RenderOptions
{
Width = width,
Dpi = configuration.PDFToImageDescriptor.Dpi,
Height = configuration.PDFToImageDescriptor.Height,
UseTiling = configuration.PDFToImageDescriptor.UseTiling,
WithFormFill = configuration.PDFToImageDescriptor.WithFormFill,
WithAspectRatio = configuration.PDFToImageDescriptor.WithAspectRatio,
WithAnnotations = configuration.PDFToImageDescriptor.WithAnnotations,
DpiRelativeToBounds = configuration.PDFToImageDescriptor.DpiRelativeToBounds,
};
//
// Preparing Images to Fallback ...
var pagesCount = Conversion.GetPageCount(pdfStream);
pdfStream.Position = 0;
//
if (configuration.PDFToImageDescriptor.MaxPagesForImageFallback > 0)
{
//
pagesCount = Math.Min(
pagesCount,
configuration.PDFToImageDescriptor.MaxPagesForImageFallback
);
}
//
for (int pageIndex = 0; pageIndex < allPagesCount; pageIndex++)
for (int pageIndex = 0; pageIndex < pagesCount; pageIndex++)
{
//
// Check Cancellation Token ...
@@ -259,7 +273,14 @@ namespace xAiApi.Providers.Extractors
try
{
//
var skBitmap = images[pageIndex];
var skBitmap = Conversion.ToImage(
page: pageIndex,
pdfStream: pdfStream,
options: renderOptions
);
pdfStream.Position = 0;
//
using (skBitmap)
using (var image = SKImage.FromBitmap(skBitmap))
using (var data = image.Encode(SKEncodedImageFormat.Png, 100))
@@ -271,7 +292,7 @@ namespace xAiApi.Providers.Extractors
{
Bytes = ms.ToArray(),
MimeType = "image/png",
Description = $"Page {pageIndex}, rendered from {fileName}"
Description = $"Page {pageIndex + 1}, rendered from {fileName}"
});
}
}
@@ -21,7 +21,6 @@ namespace xAiApi.Providers.Extractors
"text/plain",
"text/markdown",
"text/csv",
"text/html",
"text/xml",
"application/json",
"application/xml"
@@ -30,6 +29,8 @@ namespace xAiApi.Providers.Extractors
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
public bool CanExtract(string mimeType)
{
//
@@ -0,0 +1,477 @@
using System;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using OfficeIMO.PowerPoint;
using xExceptions.Constants;
using System.Threading.Tasks;
using System.Collections.Generic;
using xAiApi.Interfaces.Extractors;
using DocumentFormat.OpenXml.Packaging;
using DrawingText = DocumentFormat.OpenXml.Drawing.Text;
namespace xAiApi.Providers.Extractors
{
/// <summary>
/// Extracts content from all PowerPoint formats
/// (OpenXML: pptx/ppsx/potx/pptm/ppsm/potm | Legacy Binary: ppt/pps/pot)
/// </summary>
public class XPowerPointFileContentExtractor : IXPowerPointFileContentExtractor
{
/// <summary>
/// Supported MIME Types ...
/// </summary>
private static readonly string[] SupportedMimeTypes =
[
// OpenXML Formats
"application/vnd.openxmlformats-officedocument.presentationml.presentation", // .pptx
"application/vnd.openxmlformats-officedocument.presentationml.slideshow", // .ppsx
"application/vnd.openxmlformats-officedocument.presentationml.template", // .potx
"application/vnd.ms-powerpoint.presentation.macroEnabled.12", // .pptm
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12", // .ppsm
"application/vnd.ms-powerpoint.template.macroEnabled.12", // .potm
// Legacy Binary Formats (.ppt / .pps / .pot share same MIME)
"application/vnd.ms-powerpoint"
];
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
/// <summary>
/// Extract text content from file stream ...
/// </summary>
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await ExtractRichAsync(
fileStream: fileStream,
fileName: "presentation",
mimeType: mimeType,
cancellationToken: cancellationToken
);
return result.Text;
}
/// <summary>
/// Extract content from stream as Rich Result ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="fileName"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XFileExtractionResult> ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
//
try
{
//
if (IsOpenXmlFormat(mimeType))
{
//
result.Text = await ExtractOpenXmlAsync(
fileStream,
cancellationToken
);
}
else if (IsLegacyFormat(mimeType))
{
//
result.Text = await ExtractLegacyAsync(
fileStream,
cancellationToken
);
}
else
{
//
result.ErrorMessage =
$"Unsupported PowerPoint MIME type: {mimeType}";
}
}
catch (Exception ex)
{
result.ErrorMessage =
$"PowerPoint extraction failed: {ex.Message}";
}
//
return result;
}
/// <summary>
/// Check Open XML Format ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
private bool IsOpenXmlFormat(string mimeType)
{
//
var result = mimeType?.ToLowerInvariant() switch
{
"application/vnd.openxmlformats-officedocument.presentationml.presentation" => true,
"application/vnd.openxmlformats-officedocument.presentationml.slideshow" => true,
"application/vnd.openxmlformats-officedocument.presentationml.template" => true,
"application/vnd.ms-powerpoint.presentation.macroEnabled.12" => true,
"application/vnd.ms-powerpoint.slideshow.macroEnabled.12" => true,
"application/vnd.ms-powerpoint.template.macroEnabled.12" => true,
_ => false
};
//
return result;
}
/// <summary>
/// Check Legacy Format ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
private bool IsLegacyFormat(string mimeType)
{
//
var result = mimeType?.ToLowerInvariant() == "application/vnd.ms-powerpoint";
return result;
}
/// <summary>
/// Extract an Slide Title ...
/// </summary>
/// <param name="slidePart"></param>
/// <returns></returns>
private string GetSlideTitle(SlidePart slidePart)
{
//
var result = string.Empty;
//
// Title placeholder has specific type
var titleShape = slidePart.Slide
.Descendants<DocumentFormat.OpenXml.Presentation.Shape>()
.FirstOrDefault(s => s.NonVisualShapeProperties?
.NonVisualDrawingProperties?
.Name?.Value?
.StartsWith("Title", StringComparison.OrdinalIgnoreCase) == true
);
if (titleShape != null)
{
//
var titleText = titleShape
.Descendants<DrawingText>()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t));
result = string.Join(" ", titleText);
}
//
return result;
}
/// <summary>
/// Extract Speaker Notes ...
/// </summary>
/// <param name="slidePart"></param>
/// <returns></returns>
private string GetSpeakerNotes(SlidePart slidePart)
{
//
var result = string.Empty;
//
var notesSlidePart = slidePart.NotesSlidePart;
if (notesSlidePart?.NotesSlide == null)
{
return result;
}
//
var notesTexts = notesSlidePart.NotesSlide
.Descendants<DrawingText>()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t))
.ToList();
//
result = notesTexts.Count > 0
? string.Join(Environment.NewLine, notesTexts)
: null;
//
return result;
}
/// <summary>
/// Extract OpenXML Tables ...
/// </summary>
/// <param name="slidePart"></param>
/// <returns></returns>
private static string ExtractOpenXmlTables(SlidePart slidePart)
{
//
var sb = new StringBuilder();
//
var tableElements = slidePart.Slide
.Descendants<DocumentFormat.OpenXml.Drawing.Table>();
//
var tableIndex = 0;
foreach (var table in tableElements)
{
//
tableIndex++;
sb.AppendLine($" Table {tableIndex}:");
//
foreach (var row in table
.Descendants<DocumentFormat.OpenXml.Drawing.TableRow>())
{
//
var cells = row
.Descendants<DocumentFormat.OpenXml.Drawing.TableCell>()
.Select(c => string.Join(" ", c
.Descendants<DrawingText>()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t))))
.ToList();
//
if (cells.Count > 0)
{
sb.AppendLine($" | {string.Join(" | ", cells)} |");
}
}
//
sb.AppendLine();
}
//
var result = sb.ToString();
//
return result;
}
/// <summary>
/// Extract Open XML Format ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> ExtractOpenXmlAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
var sb = new StringBuilder();
//
// Copy to MemoryStream (OpenXml requires seekable stream)
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
//
using var presentationDocument = PresentationDocument.Open(ms, false);
var presentationPart = presentationDocument.PresentationPart;
if (presentationPart == null)
{
XException.InvalidData.Throw();
}
//
var slideParts = presentationPart.SlideParts.ToList();
var slideIndex = 0;
foreach (var slidePart in slideParts)
{
//
if (cancellationToken.IsCancellationRequested) break;
slideIndex++;
//
sb.AppendLine($"[Slide {slideIndex}]");
//
// 1. Extract slide title
var slideTitle = GetSlideTitle(slidePart);
if (!string.IsNullOrWhiteSpace(slideTitle))
{
sb.AppendLine($"Title: {slideTitle}");
}
//
// 2. Extract body texts
var bodyTexts = slidePart.Slide
.Descendants<DrawingText>()
.Select(t => t.Text?.Trim())
.Where(t => !string.IsNullOrWhiteSpace(t) && t != slideTitle)
.ToList();
if (bodyTexts.Count > 0)
{
//
sb.AppendLine("Content:");
foreach (var text in bodyTexts)
{
sb.AppendLine($" - {text}");
}
}
//
// 3. Extract tables
var tables = ExtractOpenXmlTables(slidePart);
if (!string.IsNullOrWhiteSpace(tables))
{
//
sb.AppendLine("[Tables]");
sb.AppendLine(tables);
}
//
// 4. Extract speaker notes
var notes = GetSpeakerNotes(slidePart);
if (!string.IsNullOrWhiteSpace(notes))
{
//
sb.AppendLine("[Speaker Notes]");
sb.AppendLine(notes);
}
//
// 5. Image count metadata
var imageCount = slidePart.ImageParts?.Count() ?? 0;
if (imageCount > 0)
{
sb.AppendLine($"[Images: {imageCount}]");
}
//
sb.AppendLine();
}
//
var result = sb.ToString().TrimEnd();
//
return result;
}
/// <summary>
/// Extract Legacy Format ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> ExtractLegacyAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
var sb = new StringBuilder();
//
await using var ms = new MemoryStream();
await fileStream.CopyToAsync(ms, cancellationToken);
ms.Position = 0;
//
using var presentation = PowerPointPresentation.Load(ms);
var slideIndex = 0;
foreach (var slide in presentation.Slides)
{
//
if (cancellationToken.IsCancellationRequested)
{
break;
}
slideIndex++;
//
sb.AppendLine($"[Slide {slideIndex}]");
//
var textParts = new List<string>();
var imageCount = 0;
foreach (var shape in slide.Shapes)
{
//
if (shape is PowerPointTextBox textBox)
{
//
if (!textBox.Text.IsNullOrEmpty())
{
textParts.Add(textBox.Text.Trim());
}
}
else if (shape is PowerPointAutoShape autoShape)
{
//
if (!autoShape.AltText.IsNullOrEmpty())
{
textParts.Add(autoShape.AltText.Trim());
}
}
else if (shape is PowerPointPicture picture)
{
imageCount++;
}
}
//
if (textParts.Count > 0)
{
//
sb.AppendLine("Content:");
foreach (var text in textParts)
{
sb.AppendLine($" - {text}");
}
}
//
if (imageCount > 0)
{
sb.AppendLine($"[Images: {imageCount}]");
}
//
sb.AppendLine();
}
//
var result = sb.ToString().TrimEnd();
//
return result;
}
}
}
@@ -0,0 +1,187 @@
using System;
using RtfPipe;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using xAiModels.Models;
using xCommons.Extensions;
using System.Threading.Tasks;
using xAiApi.Interfaces.Extractors;
using System.Text.RegularExpressions;
namespace xAiApi.Providers.Extractors
{
/// <summary>
/// Extractor for Rich Text Format (RTF) documents
/// (application/rtf, text/rtf)
/// </summary>
public class XRtfFileContentExtractor : IXRtfFileContentExtractor
{
/// <summary>
/// Supported MIME Types ...
/// </summary>
private static readonly string[] SupportedMimeTypes =
[
"text/rtf",
"application/rtf",
];
/// <summary>
/// Check if this extractor supports the specified MIME type ...
/// </summary>
/// <param name="mimeType"></param>
/// <returns></returns>
public bool CanExtract(string mimeType)
{
//
return SupportedMimeTypes.Contains(
mimeType?.ToLowerInvariant() ?? string.Empty
);
}
/// <summary>
/// Extract text content from file stream ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<string> ExtractAsync(
Stream fileStream,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = await ExtractRichAsync(
fileStream,
"document.rtf",
mimeType,
cancellationToken
);
//
return result.Text;
}
/// <summary>
/// Extract content from stream as Rich Result ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="fileName"></param>
/// <param name="mimeType"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
public async Task<XFileExtractionResult> ExtractRichAsync(
Stream fileStream,
string fileName,
string mimeType,
CancellationToken cancellationToken = default
)
{
//
var result = new XFileExtractionResult
{
FileName = fileName,
MimeType = mimeType
};
//
try
{
//
result.Text = await ExtractRtfAsync(
fileStream,
cancellationToken
);
}
catch (Exception ex)
{
//
result.ErrorMessage =
$"RTF extraction failed: {ex.Message}";
}
//
return result;
}
/// <summary>
/// Extract RTF Content ...
/// </summary>
/// <param name="fileStream"></param>
/// <param name="cancellationToken"></param>
/// <returns></returns>
private async Task<string> ExtractRtfAsync(
Stream fileStream,
CancellationToken cancellationToken
)
{
//
var result = string.Empty;
//
// Read RTF content as string ...
using var reader = new StreamReader(
fileStream,
Encoding.UTF8,
detectEncodingFromByteOrderMarks: true,
leaveOpen: true
);
var rtfContent = await reader.ReadToEndAsync();
if (rtfContent.IsNullOrEmpty())
{
result = string.Empty;
}
//
// Convert RTF to HTML using RtfPipe ...
var html = Rtf.ToHtml(rtfContent);
//
// Convert HTML to plain text ...
result = HtmlToPlainText(html);
//
return result;
}
/// <summary>
/// Converts Html to Text ...
/// </summary>
/// <param name="html"></param>
/// <returns></returns>
private string HtmlToPlainText(string html)
{
//
var result = string.Empty;
//
if (html.IsNullOrEmpty())
{
result = string.Empty;
}
//
// Remove HTML tags ...
result = Regex.Replace(
html,
"<.*?>",
string.Empty,
RegexOptions.Singleline
);
//
// Decode HTML entities ...
result = System.Net.WebUtility.HtmlDecode(result);
//
// Normalize whitespace ...
result = Regex.Replace(result, @"\s+", " ").Trim();
//
return result;
}
}
}